blob: 736118e067915b2a7de485b430e4470dd096a664 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006-2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.am;
18
Jeff Sharkey110a6b62012-03-12 11:12:41 -070019import static android.content.pm.PackageManager.PERMISSION_GRANTED;
20
Dianne Hackborn860755f2010-06-03 18:47:52 -070021import com.android.internal.R;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080022import com.android.internal.os.BatteryStatsImpl;
Dianne Hackborn45ce8642011-07-14 16:10:16 -070023import com.android.internal.os.ProcessStats;
Dianne Hackbornde7faf62009-06-30 13:27:30 -070024import com.android.server.AttributeCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025import com.android.server.IntentResolver;
26import com.android.server.ProcessMap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080027import com.android.server.SystemServer;
28import com.android.server.Watchdog;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070029import com.android.server.am.ActivityStack.ActivityState;
Dianne Hackborna924dc0d2011-02-17 14:22:17 -080030import com.android.server.wm.WindowManagerService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031
Dianne Hackborndd71fc82009-12-16 19:24:32 -080032import dalvik.system.Zygote;
33
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080034import android.app.Activity;
35import android.app.ActivityManager;
36import android.app.ActivityManagerNative;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -070037import android.app.ActivityOptions;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038import android.app.ActivityThread;
39import android.app.AlertDialog;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070040import android.app.AppGlobals;
Jacek Surazskif5b9c722009-05-18 12:09:59 +020041import android.app.ApplicationErrorReport;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import android.app.Dialog;
Dianne Hackbornb06ea702009-07-13 13:07:51 -070043import android.app.IActivityController;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044import android.app.IApplicationThread;
45import android.app.IInstrumentationWatcher;
Dianne Hackborn860755f2010-06-03 18:47:52 -070046import android.app.INotificationManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -070047import android.app.IProcessObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048import android.app.IServiceConnection;
49import android.app.IThumbnailReceiver;
50import android.app.Instrumentation;
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070051import android.app.Notification;
Dianne Hackborn860755f2010-06-03 18:47:52 -070052import android.app.NotificationManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080053import android.app.PendingIntent;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070054import android.app.Service;
Christopher Tate45281862010-03-05 15:46:30 -080055import android.app.backup.IBackupManager;
Jacek Surazskif5b9c722009-05-18 12:09:59 +020056import android.content.ActivityNotFoundException;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -080057import android.content.BroadcastReceiver;
Dianne Hackborn21c241e2012-03-08 13:57:23 -080058import android.content.ClipData;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070059import android.content.ComponentCallbacks2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060import android.content.ComponentName;
Jeff Sharkey110a6b62012-03-12 11:12:41 -070061import android.content.ContentProvider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062import android.content.ContentResolver;
63import android.content.Context;
Christian Mehlmauer7664e202010-07-20 08:46:17 +020064import android.content.DialogInterface;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070065import android.content.IIntentReceiver;
66import android.content.IIntentSender;
Adam Powelldd8fab22012-03-22 17:47:27 -070067import android.content.Intent;
68import android.content.IntentFilter;
Dianne Hackbornfa82f222009-09-17 15:14:12 -070069import android.content.IntentSender;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070import android.content.pm.ActivityInfo;
71import android.content.pm.ApplicationInfo;
72import android.content.pm.ConfigurationInfo;
73import android.content.pm.IPackageDataObserver;
74import android.content.pm.IPackageManager;
75import android.content.pm.InstrumentationInfo;
Dan Egnor66c40e72010-01-26 16:23:11 -080076import android.content.pm.PackageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077import android.content.pm.PackageManager;
Adam Powelldd8fab22012-03-22 17:47:27 -070078import android.content.pm.PackageManager.NameNotFoundException;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070079import android.content.pm.PathPermission;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080080import android.content.pm.ProviderInfo;
81import android.content.pm.ResolveInfo;
82import android.content.pm.ServiceInfo;
Amith Yamasani742a6712011-05-04 14:49:28 -070083import android.content.pm.UserInfo;
Dianne Hackborne2515ee2011-04-27 18:52:56 -040084import android.content.res.CompatibilityInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085import android.content.res.Configuration;
86import android.graphics.Bitmap;
Robert Greenwalt434203a2010-10-11 16:00:27 -070087import android.net.Proxy;
88import android.net.ProxyProperties;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080089import android.net.Uri;
90import android.os.Binder;
Dan Egnor60d87622009-12-16 16:32:58 -080091import android.os.Build;
Dan Egnor42471dd2010-01-07 17:25:22 -080092import android.os.Bundle;
Dianne Hackborn3025ef32009-08-31 21:31:47 -070093import android.os.Debug;
Dan Egnor60d87622009-12-16 16:32:58 -080094import android.os.DropBoxManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080095import android.os.Environment;
Dan Egnor42471dd2010-01-07 17:25:22 -080096import android.os.FileObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080097import android.os.FileUtils;
98import android.os.Handler;
99import android.os.IBinder;
100import android.os.IPermissionController;
101import android.os.Looper;
102import android.os.Message;
103import android.os.Parcel;
104import android.os.ParcelFileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800105import android.os.Process;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700106import android.os.RemoteCallbackList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107import android.os.RemoteException;
108import android.os.ServiceManager;
Brad Fitzpatrick46d42382010-06-11 13:57:58 -0700109import android.os.StrictMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110import android.os.SystemClock;
111import android.os.SystemProperties;
Amith Yamasani742a6712011-05-04 14:49:28 -0700112import android.os.UserId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113import android.provider.Settings;
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700114import android.text.format.Time;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800115import android.util.EventLog;
Joe Onorato5d3bea62010-03-01 13:44:29 -0800116import android.util.Log;
Adam Powelldd8fab22012-03-22 17:47:27 -0700117import android.util.Pair;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118import android.util.PrintWriterPrinter;
Adam Powelldd8fab22012-03-22 17:47:27 -0700119import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800120import android.util.SparseArray;
Amith Yamasani742a6712011-05-04 14:49:28 -0700121import android.util.SparseIntArray;
Dianne Hackborn1ebccf52010-08-15 13:04:34 -0700122import android.util.TimeUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800123import android.view.Gravity;
124import android.view.LayoutInflater;
125import android.view.View;
126import android.view.WindowManager;
127import android.view.WindowManagerPolicy;
128
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700129import java.io.BufferedInputStream;
130import java.io.BufferedOutputStream;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700131import java.io.BufferedReader;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700132import java.io.DataInputStream;
133import java.io.DataOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800134import java.io.File;
135import java.io.FileDescriptor;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700136import java.io.FileInputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800137import java.io.FileNotFoundException;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700138import java.io.FileOutputStream;
Jacek Surazskif5b9c722009-05-18 12:09:59 +0200139import java.io.IOException;
Dan Egnora455d192010-03-12 08:52:28 -0800140import java.io.InputStreamReader;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800141import java.io.PrintWriter;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700142import java.io.StringWriter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800143import java.lang.ref.WeakReference;
144import java.util.ArrayList;
Amith Yamasani742a6712011-05-04 14:49:28 -0700145import java.util.Collection;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700146import java.util.Collections;
147import java.util.Comparator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800148import java.util.HashMap;
149import java.util.HashSet;
150import java.util.Iterator;
151import java.util.List;
152import java.util.Locale;
153import java.util.Map;
Amith Yamasani13593602012-03-22 16:16:17 -0700154import java.util.Map.Entry;
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -0700155import java.util.Set;
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700156import java.util.concurrent.atomic.AtomicBoolean;
157import java.util.concurrent.atomic.AtomicLong;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800158
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700159public final class ActivityManagerService extends ActivityManagerNative
160 implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
Amith Yamasani742a6712011-05-04 14:49:28 -0700161 private static final String USER_DATA_DIR = "/data/user/";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800162 static final String TAG = "ActivityManager";
Amith Yamasani742a6712011-05-04 14:49:28 -0700163 static final String TAG_MU = "ActivityManagerServiceMU";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800164 static final boolean DEBUG = false;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400165 static final boolean localLOGV = DEBUG;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800166 static final boolean DEBUG_SWITCH = localLOGV || false;
167 static final boolean DEBUG_TASKS = localLOGV || false;
168 static final boolean DEBUG_PAUSE = localLOGV || false;
169 static final boolean DEBUG_OOM_ADJ = localLOGV || false;
170 static final boolean DEBUG_TRANSITION = localLOGV || false;
171 static final boolean DEBUG_BROADCAST = localLOGV || false;
Christopher Tatef46723b2012-01-26 14:19:24 -0800172 static final boolean DEBUG_BACKGROUND_BROADCAST = DEBUG_BROADCAST || false;
Dianne Hackborn82f3f002009-06-16 18:49:05 -0700173 static final boolean DEBUG_BROADCAST_LIGHT = DEBUG_BROADCAST || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800174 static final boolean DEBUG_SERVICE = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700175 static final boolean DEBUG_SERVICE_EXECUTING = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800176 static final boolean DEBUG_VISBILITY = localLOGV || false;
177 static final boolean DEBUG_PROCESSES = localLOGV || false;
Dianne Hackborna1e989b2009-09-01 19:54:29 -0700178 static final boolean DEBUG_PROVIDER = localLOGV || false;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800179 static final boolean DEBUG_URI_PERMISSION = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800180 static final boolean DEBUG_USER_LEAVING = localLOGV || false;
The Android Open Source Project10592532009-03-18 17:39:46 -0700181 static final boolean DEBUG_RESULTS = localLOGV || false;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -0700182 static final boolean DEBUG_BACKUP = localLOGV || false;
Dianne Hackborndc6b6352009-09-30 14:20:09 -0700183 static final boolean DEBUG_CONFIGURATION = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700184 static final boolean DEBUG_POWER = localLOGV || false;
185 static final boolean DEBUG_POWER_QUICK = DEBUG_POWER || false;
Amith Yamasani742a6712011-05-04 14:49:28 -0700186 static final boolean DEBUG_MU = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800187 static final boolean VALIDATE_TOKENS = false;
188 static final boolean SHOW_ACTIVITY_START_TIME = true;
189
190 // Control over CPU and battery monitoring.
191 static final long BATTERY_STATS_TIME = 30*60*1000; // write battery stats every 30 minutes.
192 static final boolean MONITOR_CPU_USAGE = true;
193 static final long MONITOR_CPU_MIN_TIME = 5*1000; // don't sample cpu less than every 5 seconds.
194 static final long MONITOR_CPU_MAX_TIME = 0x0fffffff; // wait possibly forever for next cpu sample.
195 static final boolean MONITOR_THREAD_CPU_USAGE = false;
196
Dianne Hackborn1655be42009-05-08 14:29:01 -0700197 // The flags that are set for all calls we make to the package manager.
Dianne Hackborn11b822d2009-07-21 20:03:02 -0700198 static final int STOCK_PM_FLAGS = PackageManager.GET_SHARED_LIBRARY_FILES;
Dianne Hackborn1655be42009-05-08 14:29:01 -0700199
Dianne Hackbornf02e57b2011-03-01 22:21:04 -0800200 private static final String SYSTEM_DEBUGGABLE = "ro.debuggable";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800201
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700202 static final boolean IS_USER_BUILD = "user".equals(Build.TYPE);
203
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800204 // Maximum number of recent tasks that we can remember.
205 static final int MAX_RECENT_TASKS = 20;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700206
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700207 // Amount of time after a call to stopAppSwitches() during which we will
208 // prevent further untrusted switches from happening.
209 static final long APP_SWITCH_DELAY_TIME = 5*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800210
211 // How long we wait for a launched process to attach to the activity manager
212 // before we decide it's never going to come up for real.
213 static final int PROC_START_TIMEOUT = 10*1000;
214
Jeff Brown3f9dd282011-07-08 20:02:19 -0700215 // How long we wait for a launched process to attach to the activity manager
216 // before we decide it's never going to come up for real, when the process was
217 // started with a wrapper for instrumentation (such as Valgrind) because it
218 // could take much longer than usual.
219 static final int PROC_START_TIMEOUT_WITH_WRAPPER = 300*1000;
220
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800221 // How long to wait after going idle before forcing apps to GC.
222 static final int GC_TIMEOUT = 5*1000;
223
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700224 // The minimum amount of time between successive GC requests for a process.
225 static final int GC_MIN_INTERVAL = 60*1000;
226
Dianne Hackborn287952c2010-09-22 22:34:31 -0700227 // The rate at which we check for apps using excessive power -- 15 mins.
228 static final int POWER_CHECK_DELAY = (DEBUG_POWER_QUICK ? 2 : 15) * 60*1000;
229
230 // The minimum sample duration we will allow before deciding we have
231 // enough data on wake locks to start killing things.
232 static final int WAKE_LOCK_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
233
234 // The minimum sample duration we will allow before deciding we have
235 // enough data on CPU usage to start killing things.
236 static final int CPU_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700237
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800238 // How long we allow a receiver to run before giving up on it.
Christopher Tatef46723b2012-01-26 14:19:24 -0800239 static final int BROADCAST_FG_TIMEOUT = 10*1000;
240 static final int BROADCAST_BG_TIMEOUT = 60*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800241
242 // How long we wait for a service to finish executing.
243 static final int SERVICE_TIMEOUT = 20*1000;
244
245 // How long a service needs to be running until restarting its process
246 // is no longer considered to be a relaunch of the service.
247 static final int SERVICE_RESTART_DURATION = 5*1000;
248
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700249 // How long a service needs to be running until it will start back at
250 // SERVICE_RESTART_DURATION after being killed.
251 static final int SERVICE_RESET_RUN_DURATION = 60*1000;
252
253 // Multiplying factor to increase restart duration time by, for each time
254 // a service is killed before it has run for SERVICE_RESET_RUN_DURATION.
255 static final int SERVICE_RESTART_DURATION_FACTOR = 4;
256
257 // The minimum amount of time between restarting services that we allow.
258 // That is, when multiple services are restarting, we won't allow each
259 // to restart less than this amount of time from the last one.
260 static final int SERVICE_MIN_RESTART_TIME_BETWEEN = 10*1000;
261
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800262 // Maximum amount of time for there to be no activity on a service before
263 // we consider it non-essential and allow its process to go on the
264 // LRU background list.
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700265 static final int MAX_SERVICE_INACTIVITY = 30*60*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800266
267 // How long we wait until we timeout on key dispatching.
268 static final int KEY_DISPATCHING_TIMEOUT = 5*1000;
269
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800270 // How long we wait until we timeout on key dispatching during instrumentation.
271 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT = 60*1000;
272
Dan Egnor42471dd2010-01-07 17:25:22 -0800273 static final int MY_PID = Process.myPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800274
275 static final String[] EMPTY_STRING_ARRAY = new String[0];
276
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700277 public ActivityStack mMainStack;
Mike Lockwood3a74bd32011-08-12 13:55:22 -0700278
279 private final boolean mHeadless;
280
Joe Onorato54a4a412011-11-02 20:50:08 -0700281 // Whether we should show our dialogs (ANR, crash, etc) or just perform their
282 // default actuion automatically. Important for devices without direct input
283 // devices.
284 private boolean mShowDialogs = true;
285
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800286 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700287 * Description of a request to start a new activity, which has been held
288 * due to app switches being disabled.
289 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700290 static class PendingActivityLaunch {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700291 ActivityRecord r;
292 ActivityRecord sourceRecord;
Dianne Hackborna4972e92012-03-14 10:38:05 -0700293 int startFlags;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700294 }
295
296 final ArrayList<PendingActivityLaunch> mPendingActivityLaunches
297 = new ArrayList<PendingActivityLaunch>();
298
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800299
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800300 BroadcastQueue mFgBroadcastQueue;
301 BroadcastQueue mBgBroadcastQueue;
Christopher Tatef46723b2012-01-26 14:19:24 -0800302 // Convenient for easy iteration over the queues. Foreground is first
303 // so that dispatch of foreground broadcasts gets precedence.
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800304 final BroadcastQueue[] mBroadcastQueues = new BroadcastQueue[2];
Christopher Tatef46723b2012-01-26 14:19:24 -0800305
306 BroadcastQueue broadcastQueueForIntent(Intent intent) {
307 final boolean isFg = (intent.getFlags() & Intent.FLAG_RECEIVER_FOREGROUND) != 0;
308 if (DEBUG_BACKGROUND_BROADCAST) {
309 Slog.i(TAG, "Broadcast intent " + intent + " on "
310 + (isFg ? "foreground" : "background")
311 + " queue");
312 }
313 return (isFg) ? mFgBroadcastQueue : mBgBroadcastQueue;
314 }
315
316 BroadcastRecord broadcastRecordForReceiverLocked(IBinder receiver) {
317 for (BroadcastQueue queue : mBroadcastQueues) {
318 BroadcastRecord r = queue.getMatchingOrderedReceiver(receiver);
319 if (r != null) {
320 return r;
321 }
322 }
323 return null;
324 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800325
326 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800327 * Activity we have told the window manager to have key focus.
328 */
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700329 ActivityRecord mFocusedActivity = null;
Dianne Hackbornbfe319e2009-09-21 00:34:05 -0700330 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800331 * List of intents that were used to start the most recent tasks.
332 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700333 final ArrayList<TaskRecord> mRecentTasks = new ArrayList<TaskRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800334
335 /**
Dianne Hackborn7d608422011-08-07 16:24:18 -0700336 * Process management.
337 */
338 final ProcessList mProcessList = new ProcessList();
339
340 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800341 * All of the applications we currently have running organized by name.
342 * The keys are strings of the application package name (as
343 * returned by the package manager), and the keys are ApplicationRecord
344 * objects.
345 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700346 final ProcessMap<ProcessRecord> mProcessNames = new ProcessMap<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800347
348 /**
Dianne Hackborna0c283e2012-02-09 10:47:01 -0800349 * The currently running isolated processes.
350 */
351 final SparseArray<ProcessRecord> mIsolatedProcesses = new SparseArray<ProcessRecord>();
352
353 /**
354 * Counter for assigning isolated process uids, to avoid frequently reusing the
355 * same ones.
356 */
357 int mNextIsolatedProcessUid = 0;
358
359 /**
Dianne Hackborn860755f2010-06-03 18:47:52 -0700360 * The currently running heavy-weight process, if any.
361 */
362 ProcessRecord mHeavyWeightProcess = null;
363
364 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800365 * The last time that various processes have crashed.
366 */
367 final ProcessMap<Long> mProcessCrashTimes = new ProcessMap<Long>();
368
369 /**
370 * Set of applications that we consider to be bad, and will reject
371 * incoming broadcasts from (which the user has no control over).
372 * Processes are added to this set when they have crashed twice within
373 * a minimum amount of time; they are removed from it when they are
374 * later restarted (hopefully due to some user action). The value is the
375 * time it was added to the list.
376 */
377 final ProcessMap<Long> mBadProcesses = new ProcessMap<Long>();
378
379 /**
380 * All of the processes we currently have running organized by pid.
381 * The keys are the pid running the application.
382 *
383 * <p>NOTE: This object is protected by its own lock, NOT the global
384 * activity manager lock!
385 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700386 final SparseArray<ProcessRecord> mPidsSelfLocked = new SparseArray<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800387
388 /**
389 * All of the processes that have been forced to be foreground. The key
390 * is the pid of the caller who requested it (we hold a death
391 * link on it).
392 */
393 abstract class ForegroundToken implements IBinder.DeathRecipient {
394 int pid;
395 IBinder token;
396 }
397 final SparseArray<ForegroundToken> mForegroundProcesses
398 = new SparseArray<ForegroundToken>();
399
400 /**
401 * List of records for processes that someone had tried to start before the
402 * system was ready. We don't start them at that point, but ensure they
403 * are started by the time booting is complete.
404 */
405 final ArrayList<ProcessRecord> mProcessesOnHold
406 = new ArrayList<ProcessRecord>();
407
408 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800409 * List of persistent applications that are in the process
410 * of being started.
411 */
412 final ArrayList<ProcessRecord> mPersistentStartingProcesses
413 = new ArrayList<ProcessRecord>();
414
415 /**
416 * Processes that are being forcibly torn down.
417 */
418 final ArrayList<ProcessRecord> mRemovedProcesses
419 = new ArrayList<ProcessRecord>();
420
421 /**
422 * List of running applications, sorted by recent usage.
423 * The first entry in the list is the least recently used.
424 * It contains ApplicationRecord objects. This list does NOT include
425 * any persistent application records (since we never want to exit them).
426 */
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800427 final ArrayList<ProcessRecord> mLruProcesses
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800428 = new ArrayList<ProcessRecord>();
429
430 /**
431 * List of processes that should gc as soon as things are idle.
432 */
433 final ArrayList<ProcessRecord> mProcessesToGc
434 = new ArrayList<ProcessRecord>();
435
436 /**
The Android Open Source Project4df24232009-03-05 14:34:35 -0800437 * This is the process holding what we currently consider to be
438 * the "home" activity.
439 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700440 ProcessRecord mHomeProcess;
The Android Open Source Project4df24232009-03-05 14:34:35 -0800441
442 /**
Dianne Hackbornf35fe232011-11-01 19:25:20 -0700443 * This is the process holding the activity the user last visited that
444 * is in a different process from the one they are currently in.
445 */
446 ProcessRecord mPreviousProcess;
Dianne Hackborn50685602011-12-01 12:23:37 -0800447
448 /**
449 * The time at which the previous process was last visible.
450 */
451 long mPreviousProcessVisibleTime;
452
Dianne Hackbornf35fe232011-11-01 19:25:20 -0700453 /**
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400454 * Packages that the user has asked to have run in screen size
455 * compatibility mode instead of filling the screen.
456 */
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -0700457 final CompatModePackages mCompatModePackages;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400458
459 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800460 * Set of PendingResultRecord objects that are currently active.
461 */
462 final HashSet mPendingResultRecords = new HashSet();
463
464 /**
465 * Set of IntentSenderRecord objects that are currently active.
466 */
467 final HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>> mIntentSenderRecords
468 = new HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>>();
469
470 /**
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -0800471 * Fingerprints (hashCode()) of stack traces that we've
Brad Fitzpatrick143666f2010-06-14 12:40:21 -0700472 * already logged DropBox entries for. Guarded by itself. If
473 * something (rogue user app) forces this over
474 * MAX_DUP_SUPPRESSED_STACKS entries, the contents are cleared.
475 */
476 private final HashSet<Integer> mAlreadyLoggedViolatedStacks = new HashSet<Integer>();
477 private static final int MAX_DUP_SUPPRESSED_STACKS = 5000;
478
479 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -0700480 * Strict Mode background batched logging state.
481 *
482 * The string buffer is guarded by itself, and its lock is also
483 * used to determine if another batched write is already
484 * in-flight.
485 */
486 private final StringBuilder mStrictModeBuffer = new StringBuilder();
487
488 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800489 * Keeps track of all IIntentReceivers that have been registered for
490 * broadcasts. Hash keys are the receiver IBinder, hash value is
491 * a ReceiverList.
492 */
493 final HashMap mRegisteredReceivers = new HashMap();
494
495 /**
496 * Resolver for broadcast intents to registered receivers.
497 * Holds BroadcastFilter (subclass of IntentFilter).
498 */
499 final IntentResolver<BroadcastFilter, BroadcastFilter> mReceiverResolver
500 = new IntentResolver<BroadcastFilter, BroadcastFilter>() {
501 @Override
502 protected boolean allowFilterResult(
503 BroadcastFilter filter, List<BroadcastFilter> dest) {
504 IBinder target = filter.receiverList.receiver.asBinder();
505 for (int i=dest.size()-1; i>=0; i--) {
506 if (dest.get(i).receiverList.receiver.asBinder() == target) {
507 return false;
508 }
509 }
510 return true;
511 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700512
513 @Override
514 protected String packageForFilter(BroadcastFilter filter) {
515 return filter.packageName;
516 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800517 };
518
519 /**
520 * State of all active sticky broadcasts. Keys are the action of the
521 * sticky Intent, values are an ArrayList of all broadcasted intents with
522 * that action (which should usually be one).
523 */
524 final HashMap<String, ArrayList<Intent>> mStickyBroadcasts =
525 new HashMap<String, ArrayList<Intent>>();
526
Amith Yamasani742a6712011-05-04 14:49:28 -0700527 final ServiceMap mServiceMap = new ServiceMap();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800528
529 /**
530 * All currently bound service connections. Keys are the IBinder of
531 * the client's IServiceConnection.
532 */
Dianne Hackborn43d9ac82010-08-25 15:06:25 -0700533 final HashMap<IBinder, ArrayList<ConnectionRecord>> mServiceConnections
534 = new HashMap<IBinder, ArrayList<ConnectionRecord>>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800535
536 /**
537 * List of services that we have been asked to start,
538 * but haven't yet been able to. It is used to hold start requests
539 * while waiting for their corresponding application thread to get
540 * going.
541 */
542 final ArrayList<ServiceRecord> mPendingServices
543 = new ArrayList<ServiceRecord>();
544
545 /**
546 * List of services that are scheduled to restart following a crash.
547 */
548 final ArrayList<ServiceRecord> mRestartingServices
549 = new ArrayList<ServiceRecord>();
550
551 /**
552 * List of services that are in the process of being stopped.
553 */
554 final ArrayList<ServiceRecord> mStoppingServices
555 = new ArrayList<ServiceRecord>();
556
557 /**
Christopher Tate181fafa2009-05-14 11:12:14 -0700558 * Backup/restore process management
559 */
560 String mBackupAppName = null;
561 BackupRecord mBackupTarget = null;
562
563 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800564 * List of PendingThumbnailsRecord objects of clients who are still
565 * waiting to receive all of the thumbnails for a task.
566 */
567 final ArrayList mPendingThumbnails = new ArrayList();
568
569 /**
570 * List of HistoryRecord objects that have been finished and must
571 * still report back to a pending thumbnail receiver.
572 */
573 final ArrayList mCancelledThumbnails = new ArrayList();
574
Amith Yamasani742a6712011-05-04 14:49:28 -0700575 final ProviderMap mProviderMap = new ProviderMap();
576
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800577 /**
578 * List of content providers who have clients waiting for them. The
579 * application is currently being launched and the provider will be
580 * removed from this list once it is published.
581 */
Dianne Hackborn860755f2010-06-03 18:47:52 -0700582 final ArrayList<ContentProviderRecord> mLaunchingProviders
583 = new ArrayList<ContentProviderRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800584
585 /**
586 * Global set of specific Uri permissions that have been granted.
587 */
588 final private SparseArray<HashMap<Uri, UriPermission>> mGrantedUriPermissions
589 = new SparseArray<HashMap<Uri, UriPermission>>();
590
Svetoslav Ganov54d068e2011-03-02 12:58:40 -0800591 CoreSettingsObserver mCoreSettingsObserver;
592
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800593 /**
594 * Thread-local storage used to carry caller permissions over through
595 * indirect content-provider access.
596 * @see #ActivityManagerService.openContentUri()
597 */
598 private class Identity {
599 public int pid;
600 public int uid;
601
602 Identity(int _pid, int _uid) {
603 pid = _pid;
604 uid = _uid;
605 }
606 }
Amith Yamasani742a6712011-05-04 14:49:28 -0700607
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800608 private static ThreadLocal<Identity> sCallerIdentity = new ThreadLocal<Identity>();
609
610 /**
611 * All information we have collected about the runtime performance of
612 * any user id that can impact battery performance.
613 */
614 final BatteryStatsService mBatteryStatsService;
615
616 /**
617 * information about component usage
618 */
619 final UsageStatsService mUsageStatsService;
620
621 /**
622 * Current configuration information. HistoryRecord objects are given
623 * a reference to this object to indicate which configuration they are
624 * currently running in, so this object must be kept immutable.
625 */
626 Configuration mConfiguration = new Configuration();
627
628 /**
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800629 * Current sequencing integer of the configuration, for skipping old
630 * configurations.
631 */
632 int mConfigurationSeq = 0;
633
634 /**
Jack Palevichb90d28c2009-07-22 15:35:24 -0700635 * Hardware-reported OpenGLES version.
636 */
637 final int GL_ES_VERSION;
638
639 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800640 * List of initialization arguments to pass to all processes when binding applications to them.
641 * For example, references to the commonly used services.
642 */
643 HashMap<String, IBinder> mAppBindArgs;
644
645 /**
Dianne Hackbornf210d6b2009-04-13 18:42:49 -0700646 * Temporary to avoid allocations. Protected by main lock.
647 */
648 final StringBuilder mStringBuilder = new StringBuilder(256);
649
650 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800651 * Used to control how we initialize the service.
652 */
653 boolean mStartRunning = false;
654 ComponentName mTopComponent;
655 String mTopAction;
656 String mTopData;
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700657 boolean mProcessesReady = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800658 boolean mSystemReady = false;
659 boolean mBooting = false;
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700660 boolean mWaitingUpdate = false;
661 boolean mDidUpdate = false;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700662 boolean mOnBattery = false;
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700663 boolean mLaunchWarningShown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800664
665 Context mContext;
666
667 int mFactoryTest;
668
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -0700669 boolean mCheckedForSetup;
670
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800671 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700672 * The time at which we will allow normal application switches again,
673 * after a call to {@link #stopAppSwitches()}.
674 */
675 long mAppSwitchesAllowedTime;
676
677 /**
678 * This is set to true after the first switch after mAppSwitchesAllowedTime
679 * is set; any switches after that will clear the time.
680 */
681 boolean mDidAppSwitch;
682
683 /**
Dianne Hackborn287952c2010-09-22 22:34:31 -0700684 * Last time (in realtime) at which we checked for power usage.
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700685 */
Dianne Hackborn287952c2010-09-22 22:34:31 -0700686 long mLastPowerCheckRealtime;
687
688 /**
689 * Last time (in uptime) at which we checked for power usage.
690 */
691 long mLastPowerCheckUptime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700692
693 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800694 * Set while we are wanting to sleep, to prevent any
695 * activities from being started/resumed.
696 */
697 boolean mSleeping = false;
698
699 /**
Dianne Hackbornff5b1582012-04-12 17:24:07 -0700700 * State of external calls telling us if the device is asleep.
701 */
702 boolean mWentToSleep = false;
703
704 /**
705 * State of external call telling us if the lock screen is shown.
706 */
707 boolean mLockScreenShown = false;
708
709 /**
Dianne Hackborn55280a92009-05-07 15:53:46 -0700710 * Set if we are shutting down the system, similar to sleeping.
711 */
712 boolean mShuttingDown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800713
714 /**
715 * Task identifier that activities are currently being started
716 * in. Incremented each time a new task is created.
717 * todo: Replace this with a TokenSpace class that generates non-repeating
718 * integers that won't wrap.
719 */
720 int mCurTask = 1;
721
722 /**
723 * Current sequence id for oom_adj computation traversal.
724 */
725 int mAdjSeq = 0;
726
727 /**
Dianne Hackborn906497c2010-05-10 15:57:38 -0700728 * Current sequence id for process LRU updating.
729 */
730 int mLruSeq = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800731
732 /**
Dianne Hackborne02c88a2011-10-28 13:58:15 -0700733 * Keep track of the number of service processes we last found, to
734 * determine on the next iteration which should be B services.
735 */
736 int mNumServiceProcs = 0;
737 int mNewNumServiceProcs = 0;
738
739 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800740 * System monitoring: number of processes that died since the last
741 * N procs were started.
742 */
743 int[] mProcDeaths = new int[20];
744
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700745 /**
746 * This is set if we had to do a delayed dexopt of an app before launching
747 * it, to increasing the ANR timeouts in that case.
748 */
749 boolean mDidDexOpt;
750
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800751 String mDebugApp = null;
752 boolean mWaitForDebugger = false;
753 boolean mDebugTransient = false;
754 String mOrigDebugApp = null;
755 boolean mOrigWaitForDebugger = false;
756 boolean mAlwaysFinishActivities = false;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700757 IActivityController mController = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700758 String mProfileApp = null;
759 ProcessRecord mProfileProc = null;
760 String mProfileFile;
761 ParcelFileDescriptor mProfileFd;
762 int mProfileType = 0;
763 boolean mAutoStopProfiler = false;
Siva Velusamy92a8b222012-03-09 16:24:04 -0800764 String mOpenGlTraceApp = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800765
Jeff Sharkeya4620792011-05-20 15:29:23 -0700766 final RemoteCallbackList<IProcessObserver> mProcessObservers
767 = new RemoteCallbackList<IProcessObserver>();
768
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800769 /**
770 * Callback of last caller to {@link #requestPss}.
771 */
772 Runnable mRequestPssCallback;
773
774 /**
775 * Remaining processes for which we are waiting results from the last
776 * call to {@link #requestPss}.
777 */
778 final ArrayList<ProcessRecord> mRequestPssList
779 = new ArrayList<ProcessRecord>();
780
781 /**
782 * Runtime statistics collection thread. This object's lock is used to
783 * protect all related state.
784 */
785 final Thread mProcessStatsThread;
786
787 /**
788 * Used to collect process stats when showing not responding dialog.
789 * Protected by mProcessStatsThread.
790 */
791 final ProcessStats mProcessStats = new ProcessStats(
792 MONITOR_THREAD_CPU_USAGE);
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700793 final AtomicLong mLastCpuTime = new AtomicLong(0);
794 final AtomicBoolean mProcessStatsMutexFree = new AtomicBoolean(true);
795
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800796 long mLastWriteTime = 0;
797
798 /**
799 * Set to true after the system has finished booting.
800 */
801 boolean mBooted = false;
802
Dianne Hackborn7d608422011-08-07 16:24:18 -0700803 int mProcessLimit = ProcessList.MAX_HIDDEN_APPS;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700804 int mProcessLimitOverride = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800805
806 WindowManagerService mWindowManager;
807
808 static ActivityManagerService mSelf;
809 static ActivityThread mSystemThread;
810
811 private final class AppDeathRecipient implements IBinder.DeathRecipient {
812 final ProcessRecord mApp;
813 final int mPid;
814 final IApplicationThread mAppThread;
815
816 AppDeathRecipient(ProcessRecord app, int pid,
817 IApplicationThread thread) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800818 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800819 TAG, "New death recipient " + this
820 + " for thread " + thread.asBinder());
821 mApp = app;
822 mPid = pid;
823 mAppThread = thread;
824 }
825
826 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800827 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800828 TAG, "Death received in " + this
829 + " for thread " + mAppThread.asBinder());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800830 synchronized(ActivityManagerService.this) {
831 appDiedLocked(mApp, mPid, mAppThread);
832 }
833 }
834 }
835
836 static final int SHOW_ERROR_MSG = 1;
837 static final int SHOW_NOT_RESPONDING_MSG = 2;
838 static final int SHOW_FACTORY_ERROR_MSG = 3;
839 static final int UPDATE_CONFIGURATION_MSG = 4;
840 static final int GC_BACKGROUND_PROCESSES_MSG = 5;
841 static final int WAIT_FOR_DEBUGGER_MSG = 6;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800842 static final int SERVICE_TIMEOUT_MSG = 12;
843 static final int UPDATE_TIME_ZONE = 13;
844 static final int SHOW_UID_ERROR_MSG = 14;
845 static final int IM_FEELING_LUCKY_MSG = 15;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800846 static final int PROC_START_TIMEOUT_MSG = 20;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700847 static final int DO_PENDING_ACTIVITY_LAUNCHES_MSG = 21;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -0700848 static final int KILL_APPLICATION_MSG = 22;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800849 static final int FINALIZE_PENDING_INTENT_MSG = 23;
Dianne Hackborn860755f2010-06-03 18:47:52 -0700850 static final int POST_HEAVY_NOTIFICATION_MSG = 24;
851 static final int CANCEL_HEAVY_NOTIFICATION_MSG = 25;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700852 static final int SHOW_STRICT_MODE_VIOLATION_MSG = 26;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700853 static final int CHECK_EXCESSIVE_WAKE_LOCKS_MSG = 27;
Robert Greenwalt03595d02010-11-02 14:08:23 -0700854 static final int CLEAR_DNS_CACHE = 28;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700855 static final int UPDATE_HTTP_PROXY = 29;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700856 static final int SHOW_COMPAT_MODE_DIALOG_MSG = 30;
Dianne Hackborn36f80f32011-05-31 18:26:45 -0700857 static final int DISPATCH_FOREGROUND_ACTIVITIES_CHANGED = 31;
858 static final int DISPATCH_PROCESS_DIED = 32;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700859 static final int REPORT_MEM_USAGE = 33;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800860
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800861 static final int FIRST_ACTIVITY_STACK_MSG = 100;
862 static final int FIRST_BROADCAST_QUEUE_MSG = 200;
863 static final int FIRST_COMPAT_MODE_MSG = 300;
864
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800865 AlertDialog mUidAlert;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700866 CompatModeDialog mCompatModeDialog;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700867 long mLastMemUsageReportTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800868
869 final Handler mHandler = new Handler() {
870 //public Handler() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800871 // if (localLOGV) Slog.v(TAG, "Handler started!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800872 //}
873
874 public void handleMessage(Message msg) {
875 switch (msg.what) {
876 case SHOW_ERROR_MSG: {
877 HashMap data = (HashMap) msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800878 synchronized (ActivityManagerService.this) {
879 ProcessRecord proc = (ProcessRecord)data.get("app");
880 if (proc != null && proc.crashDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800881 Slog.e(TAG, "App already has crash dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800882 return;
883 }
884 AppErrorResult res = (AppErrorResult) data.get("result");
Joe Onorato54a4a412011-11-02 20:50:08 -0700885 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Dan Egnorb7f03672009-12-09 16:22:32 -0800886 Dialog d = new AppErrorDialog(mContext, res, proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800887 d.show();
888 proc.crashDialog = d;
889 } else {
890 // The device is asleep, so just pretend that the user
891 // saw a crash dialog and hit "force quit".
892 res.set(0);
893 }
894 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700895
896 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800897 } break;
898 case SHOW_NOT_RESPONDING_MSG: {
899 synchronized (ActivityManagerService.this) {
900 HashMap data = (HashMap) msg.obj;
901 ProcessRecord proc = (ProcessRecord)data.get("app");
902 if (proc != null && proc.anrDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800903 Slog.e(TAG, "App already has anr dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800904 return;
905 }
The Android Open Source Project4df24232009-03-05 14:34:35 -0800906
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700907 Intent intent = new Intent("android.intent.action.ANR");
908 if (!mProcessesReady) {
Christopher Tatef46723b2012-01-26 14:19:24 -0800909 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
910 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700911 }
912 broadcastIntentLocked(null, null, intent,
The Android Open Source Project4df24232009-03-05 14:34:35 -0800913 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -0700914 false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
The Android Open Source Project4df24232009-03-05 14:34:35 -0800915
Justin Kohbc52ca22012-03-29 15:11:44 -0700916 if (mShowDialogs) {
917 Dialog d = new AppNotRespondingDialog(ActivityManagerService.this,
Mike Lockwood69ccdbd2012-04-03 11:53:47 -0700918 mContext, proc, (ActivityRecord)data.get("activity"));
Justin Kohbc52ca22012-03-29 15:11:44 -0700919 d.show();
920 proc.anrDialog = d;
921 } else {
922 // Just kill the app if there is no dialog to be shown.
923 killAppAtUsersRequest(proc, null);
924 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800925 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700926
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700927 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800928 } break;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700929 case SHOW_STRICT_MODE_VIOLATION_MSG: {
930 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj;
931 synchronized (ActivityManagerService.this) {
932 ProcessRecord proc = (ProcessRecord) data.get("app");
933 if (proc == null) {
934 Slog.e(TAG, "App not found when showing strict mode dialog.");
935 break;
936 }
937 if (proc.crashDialog != null) {
938 Slog.e(TAG, "App already has strict mode dialog: " + proc);
939 return;
940 }
941 AppErrorResult res = (AppErrorResult) data.get("result");
Joe Onorato54a4a412011-11-02 20:50:08 -0700942 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700943 Dialog d = new StrictModeViolationDialog(mContext, res, proc);
944 d.show();
945 proc.crashDialog = d;
946 } else {
947 // The device is asleep, so just pretend that the user
948 // saw a crash dialog and hit "force quit".
949 res.set(0);
950 }
951 }
952 ensureBootCompleted();
953 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800954 case SHOW_FACTORY_ERROR_MSG: {
955 Dialog d = new FactoryErrorDialog(
956 mContext, msg.getData().getCharSequence("msg"));
957 d.show();
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700958 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800959 } break;
960 case UPDATE_CONFIGURATION_MSG: {
961 final ContentResolver resolver = mContext.getContentResolver();
962 Settings.System.putConfiguration(resolver, (Configuration)msg.obj);
963 } break;
964 case GC_BACKGROUND_PROCESSES_MSG: {
965 synchronized (ActivityManagerService.this) {
966 performAppGcsIfAppropriateLocked();
967 }
968 } break;
969 case WAIT_FOR_DEBUGGER_MSG: {
970 synchronized (ActivityManagerService.this) {
971 ProcessRecord app = (ProcessRecord)msg.obj;
972 if (msg.arg1 != 0) {
973 if (!app.waitedForDebugger) {
974 Dialog d = new AppWaitingForDebuggerDialog(
975 ActivityManagerService.this,
976 mContext, app);
977 app.waitDialog = d;
978 app.waitedForDebugger = true;
979 d.show();
980 }
981 } else {
982 if (app.waitDialog != null) {
983 app.waitDialog.dismiss();
984 app.waitDialog = null;
985 }
986 }
987 }
988 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800989 case SERVICE_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700990 if (mDidDexOpt) {
991 mDidDexOpt = false;
992 Message nmsg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
993 nmsg.obj = msg.obj;
994 mHandler.sendMessageDelayed(nmsg, SERVICE_TIMEOUT);
995 return;
996 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800997 serviceTimeout((ProcessRecord)msg.obj);
998 } break;
999 case UPDATE_TIME_ZONE: {
1000 synchronized (ActivityManagerService.this) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001001 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1002 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001003 if (r.thread != null) {
1004 try {
1005 r.thread.updateTimeZone();
1006 } catch (RemoteException ex) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001007 Slog.w(TAG, "Failed to update time zone for: " + r.info.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001008 }
1009 }
1010 }
1011 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001012 } break;
Robert Greenwalt03595d02010-11-02 14:08:23 -07001013 case CLEAR_DNS_CACHE: {
1014 synchronized (ActivityManagerService.this) {
1015 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1016 ProcessRecord r = mLruProcesses.get(i);
1017 if (r.thread != null) {
1018 try {
1019 r.thread.clearDnsCache();
1020 } catch (RemoteException ex) {
1021 Slog.w(TAG, "Failed to clear dns cache for: " + r.info.processName);
1022 }
1023 }
1024 }
1025 }
1026 } break;
Robert Greenwalt434203a2010-10-11 16:00:27 -07001027 case UPDATE_HTTP_PROXY: {
1028 ProxyProperties proxy = (ProxyProperties)msg.obj;
1029 String host = "";
1030 String port = "";
1031 String exclList = "";
1032 if (proxy != null) {
1033 host = proxy.getHost();
1034 port = Integer.toString(proxy.getPort());
1035 exclList = proxy.getExclusionList();
1036 }
1037 synchronized (ActivityManagerService.this) {
1038 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1039 ProcessRecord r = mLruProcesses.get(i);
1040 if (r.thread != null) {
1041 try {
1042 r.thread.setHttpProxy(host, port, exclList);
1043 } catch (RemoteException ex) {
1044 Slog.w(TAG, "Failed to update http proxy for: " +
1045 r.info.processName);
1046 }
1047 }
1048 }
1049 }
1050 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001051 case SHOW_UID_ERROR_MSG: {
Joe Onorato54a4a412011-11-02 20:50:08 -07001052 String title = "System UIDs Inconsistent";
1053 String text = "UIDs on the system are inconsistent, you need to wipe your"
1054 + " data partition or your device will be unstable.";
1055 Log.e(TAG, title + ": " + text);
1056 if (mShowDialogs) {
1057 // XXX This is a temporary dialog, no need to localize.
1058 AlertDialog d = new BaseErrorDialog(mContext);
1059 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
1060 d.setCancelable(false);
1061 d.setTitle(title);
1062 d.setMessage(text);
1063 d.setButton(DialogInterface.BUTTON_POSITIVE, "I'm Feeling Lucky",
1064 mHandler.obtainMessage(IM_FEELING_LUCKY_MSG));
1065 mUidAlert = d;
1066 d.show();
1067 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001068 } break;
1069 case IM_FEELING_LUCKY_MSG: {
1070 if (mUidAlert != null) {
1071 mUidAlert.dismiss();
1072 mUidAlert = null;
1073 }
1074 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001075 case PROC_START_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001076 if (mDidDexOpt) {
1077 mDidDexOpt = false;
1078 Message nmsg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
1079 nmsg.obj = msg.obj;
1080 mHandler.sendMessageDelayed(nmsg, PROC_START_TIMEOUT);
1081 return;
1082 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001083 ProcessRecord app = (ProcessRecord)msg.obj;
1084 synchronized (ActivityManagerService.this) {
1085 processStartTimedOutLocked(app);
1086 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001087 } break;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07001088 case DO_PENDING_ACTIVITY_LAUNCHES_MSG: {
1089 synchronized (ActivityManagerService.this) {
1090 doPendingActivityLaunchesLocked(true);
1091 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001092 } break;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001093 case KILL_APPLICATION_MSG: {
1094 synchronized (ActivityManagerService.this) {
1095 int uid = msg.arg1;
1096 boolean restart = (msg.arg2 == 1);
1097 String pkg = (String) msg.obj;
Amith Yamasani483f3b02012-03-13 16:08:00 -07001098 forceStopPackageLocked(pkg, uid, restart, false, true, false,
1099 UserId.getUserId(uid));
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001100 }
1101 } break;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001102 case FINALIZE_PENDING_INTENT_MSG: {
1103 ((PendingIntentRecord)msg.obj).completeFinalize();
1104 } break;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001105 case POST_HEAVY_NOTIFICATION_MSG: {
1106 INotificationManager inm = NotificationManager.getService();
1107 if (inm == null) {
1108 return;
1109 }
1110
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001111 ActivityRecord root = (ActivityRecord)msg.obj;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001112 ProcessRecord process = root.app;
1113 if (process == null) {
1114 return;
1115 }
1116
1117 try {
1118 Context context = mContext.createPackageContext(process.info.packageName, 0);
1119 String text = mContext.getString(R.string.heavy_weight_notification,
1120 context.getApplicationInfo().loadLabel(context.getPackageManager()));
1121 Notification notification = new Notification();
1122 notification.icon = com.android.internal.R.drawable.stat_sys_adb; //context.getApplicationInfo().icon;
1123 notification.when = 0;
1124 notification.flags = Notification.FLAG_ONGOING_EVENT;
1125 notification.tickerText = text;
1126 notification.defaults = 0; // please be quiet
1127 notification.sound = null;
1128 notification.vibrate = null;
1129 notification.setLatestEventInfo(context, text,
1130 mContext.getText(R.string.heavy_weight_notification_detail),
1131 PendingIntent.getActivity(mContext, 0, root.intent,
1132 PendingIntent.FLAG_CANCEL_CURRENT));
1133
1134 try {
1135 int[] outId = new int[1];
1136 inm.enqueueNotification("android", R.string.heavy_weight_notification,
1137 notification, outId);
1138 } catch (RuntimeException e) {
1139 Slog.w(ActivityManagerService.TAG,
1140 "Error showing notification for heavy-weight app", e);
1141 } catch (RemoteException e) {
1142 }
1143 } catch (NameNotFoundException e) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07001144 Slog.w(TAG, "Unable to create context for heavy notification", e);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001145 }
1146 } break;
1147 case CANCEL_HEAVY_NOTIFICATION_MSG: {
1148 INotificationManager inm = NotificationManager.getService();
1149 if (inm == null) {
1150 return;
1151 }
1152 try {
1153 inm.cancelNotification("android",
1154 R.string.heavy_weight_notification);
1155 } catch (RuntimeException e) {
1156 Slog.w(ActivityManagerService.TAG,
1157 "Error canceling notification for service", e);
1158 } catch (RemoteException e) {
1159 }
1160 } break;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001161 case CHECK_EXCESSIVE_WAKE_LOCKS_MSG: {
1162 synchronized (ActivityManagerService.this) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001163 checkExcessivePowerUsageLocked(true);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07001164 removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001165 Message nmsg = obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
1166 sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001167 }
1168 } break;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001169 case SHOW_COMPAT_MODE_DIALOG_MSG: {
1170 synchronized (ActivityManagerService.this) {
1171 ActivityRecord ar = (ActivityRecord)msg.obj;
1172 if (mCompatModeDialog != null) {
1173 if (mCompatModeDialog.mAppInfo.packageName.equals(
1174 ar.info.applicationInfo.packageName)) {
1175 return;
1176 }
1177 mCompatModeDialog.dismiss();
1178 mCompatModeDialog = null;
1179 }
Dianne Hackborn29478262011-06-07 15:44:22 -07001180 if (ar != null && false) {
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001181 if (mCompatModePackages.getPackageAskCompatModeLocked(
1182 ar.packageName)) {
1183 int mode = mCompatModePackages.computeCompatModeLocked(
1184 ar.info.applicationInfo);
1185 if (mode == ActivityManager.COMPAT_MODE_DISABLED
1186 || mode == ActivityManager.COMPAT_MODE_ENABLED) {
1187 mCompatModeDialog = new CompatModeDialog(
1188 ActivityManagerService.this, mContext,
1189 ar.info.applicationInfo);
1190 mCompatModeDialog.show();
1191 }
1192 }
1193 }
1194 }
Dianne Hackborn36f80f32011-05-31 18:26:45 -07001195 break;
1196 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001197 case DISPATCH_FOREGROUND_ACTIVITIES_CHANGED: {
Jeff Sharkey287bd832011-05-28 19:36:26 -07001198 final int pid = msg.arg1;
1199 final int uid = msg.arg2;
1200 final boolean foregroundActivities = (Boolean) msg.obj;
1201 dispatchForegroundActivitiesChanged(pid, uid, foregroundActivities);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001202 break;
1203 }
1204 case DISPATCH_PROCESS_DIED: {
Jeff Sharkey287bd832011-05-28 19:36:26 -07001205 final int pid = msg.arg1;
1206 final int uid = msg.arg2;
1207 dispatchProcessDied(pid, uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001208 break;
1209 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001210 case REPORT_MEM_USAGE: {
1211 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
1212 if (!isDebuggable) {
1213 return;
1214 }
1215 synchronized (ActivityManagerService.this) {
1216 long now = SystemClock.uptimeMillis();
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001217 if (now < (mLastMemUsageReportTime+5*60*1000)) {
1218 // Don't report more than every 5 minutes to somewhat
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001219 // avoid spamming.
1220 return;
1221 }
1222 mLastMemUsageReportTime = now;
1223 }
1224 Thread thread = new Thread() {
1225 @Override public void run() {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001226 StringBuilder dropBuilder = new StringBuilder(1024);
1227 StringBuilder logBuilder = new StringBuilder(1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -08001228 StringWriter oomSw = new StringWriter();
1229 PrintWriter oomPw = new PrintWriter(oomSw);
1230 StringWriter catSw = new StringWriter();
1231 PrintWriter catPw = new PrintWriter(catSw);
1232 String[] emptyArgs = new String[] { };
1233 StringBuilder tag = new StringBuilder(128);
1234 StringBuilder stack = new StringBuilder(128);
1235 tag.append("Low on memory -- ");
1236 dumpApplicationMemoryUsage(null, oomPw, " ", emptyArgs, true, catPw,
1237 tag, stack);
1238 dropBuilder.append(stack);
1239 dropBuilder.append('\n');
1240 dropBuilder.append('\n');
1241 String oomString = oomSw.toString();
1242 dropBuilder.append(oomString);
1243 dropBuilder.append('\n');
1244 logBuilder.append(oomString);
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001245 try {
1246 java.lang.Process proc = Runtime.getRuntime().exec(new String[] {
1247 "procrank", });
1248 final InputStreamReader converter = new InputStreamReader(
1249 proc.getInputStream());
1250 BufferedReader in = new BufferedReader(converter);
1251 String line;
1252 while (true) {
1253 line = in.readLine();
1254 if (line == null) {
1255 break;
1256 }
1257 if (line.length() > 0) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001258 logBuilder.append(line);
1259 logBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001260 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001261 dropBuilder.append(line);
1262 dropBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001263 }
1264 converter.close();
1265 } catch (IOException e) {
1266 }
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001267 synchronized (ActivityManagerService.this) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08001268 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001269 dumpProcessesLocked(null, catPw, emptyArgs, 0, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001270 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001271 dumpServicesLocked(null, catPw, emptyArgs, 0, false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001272 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001273 dumpActivitiesLocked(null, catPw, emptyArgs, 0, false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001274 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001275 dropBuilder.append(catSw.toString());
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001276 addErrorToDropBox("lowmem", null, "system_server", null,
1277 null, tag.toString(), dropBuilder.toString(), null, null);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001278 Slog.i(TAG, logBuilder.toString());
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001279 synchronized (ActivityManagerService.this) {
1280 long now = SystemClock.uptimeMillis();
1281 if (mLastMemUsageReportTime < now) {
1282 mLastMemUsageReportTime = now;
1283 }
1284 }
1285 }
1286 };
1287 thread.start();
1288 break;
1289 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001290 }
1291 }
1292 };
1293
1294 public static void setSystemProcess() {
1295 try {
1296 ActivityManagerService m = mSelf;
1297
Dianne Hackborna573f6a2012-02-09 16:12:18 -08001298 ServiceManager.addService("activity", m, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001299 ServiceManager.addService("meminfo", new MemBinder(m));
Chet Haase9c1e23b2011-03-24 10:51:31 -07001300 ServiceManager.addService("gfxinfo", new GraphicsBinder(m));
Jeff Brown6754ba22011-12-14 20:20:01 -08001301 ServiceManager.addService("dbinfo", new DbBinder(m));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001302 if (MONITOR_CPU_USAGE) {
1303 ServiceManager.addService("cpuinfo", new CpuBinder(m));
1304 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001305 ServiceManager.addService("permission", new PermissionController(m));
1306
1307 ApplicationInfo info =
1308 mSelf.mContext.getPackageManager().getApplicationInfo(
Amith Yamasani483f3b02012-03-13 16:08:00 -07001309 "android", STOCK_PM_FLAGS);
Mike Cleron432b7132009-09-24 15:28:29 -07001310 mSystemThread.installSystemApplicationInfo(info);
1311
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001312 synchronized (mSelf) {
1313 ProcessRecord app = mSelf.newProcessRecordLocked(
1314 mSystemThread.getApplicationThread(), info,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001315 info.processName, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001316 app.persistent = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08001317 app.pid = MY_PID;
Dianne Hackborn7d608422011-08-07 16:24:18 -07001318 app.maxAdj = ProcessList.SYSTEM_ADJ;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001319 mSelf.mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001320 synchronized (mSelf.mPidsSelfLocked) {
1321 mSelf.mPidsSelfLocked.put(app.pid, app);
1322 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001323 mSelf.updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001324 }
1325 } catch (PackageManager.NameNotFoundException e) {
1326 throw new RuntimeException(
1327 "Unable to find android system package", e);
1328 }
1329 }
1330
1331 public void setWindowManager(WindowManagerService wm) {
1332 mWindowManager = wm;
1333 }
1334
1335 public static final Context main(int factoryTest) {
1336 AThread thr = new AThread();
1337 thr.start();
1338
1339 synchronized (thr) {
1340 while (thr.mService == null) {
1341 try {
1342 thr.wait();
1343 } catch (InterruptedException e) {
1344 }
1345 }
1346 }
1347
1348 ActivityManagerService m = thr.mService;
1349 mSelf = m;
1350 ActivityThread at = ActivityThread.systemMain();
1351 mSystemThread = at;
1352 Context context = at.getSystemContext();
Dianne Hackborn247fe742011-01-08 17:25:57 -08001353 context.setTheme(android.R.style.Theme_Holo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001354 m.mContext = context;
1355 m.mFactoryTest = factoryTest;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001356 m.mMainStack = new ActivityStack(m, context, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001357
1358 m.mBatteryStatsService.publish(context);
1359 m.mUsageStatsService.publish(context);
1360
1361 synchronized (thr) {
1362 thr.mReady = true;
1363 thr.notifyAll();
1364 }
1365
1366 m.startRunning(null, null, null, null);
1367
1368 return context;
1369 }
1370
1371 public static ActivityManagerService self() {
1372 return mSelf;
1373 }
1374
1375 static class AThread extends Thread {
1376 ActivityManagerService mService;
1377 boolean mReady = false;
1378
1379 public AThread() {
1380 super("ActivityManager");
1381 }
1382
1383 public void run() {
1384 Looper.prepare();
1385
1386 android.os.Process.setThreadPriority(
1387 android.os.Process.THREAD_PRIORITY_FOREGROUND);
Christopher Tate160edb32010-06-30 17:46:30 -07001388 android.os.Process.setCanSelfBackground(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001389
1390 ActivityManagerService m = new ActivityManagerService();
1391
1392 synchronized (this) {
1393 mService = m;
1394 notifyAll();
1395 }
1396
1397 synchronized (this) {
1398 while (!mReady) {
1399 try {
1400 wait();
1401 } catch (InterruptedException e) {
1402 }
1403 }
1404 }
1405
Brad Fitzpatrickec062f62010-11-03 09:56:54 -07001406 // For debug builds, log event loop stalls to dropbox for analysis.
1407 if (StrictMode.conditionallyEnableDebugLogging()) {
1408 Slog.i(TAG, "Enabled StrictMode logging for AThread's Looper");
1409 }
1410
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001411 Looper.loop();
1412 }
1413 }
1414
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001415 static class MemBinder extends Binder {
1416 ActivityManagerService mActivityManagerService;
1417 MemBinder(ActivityManagerService activityManagerService) {
1418 mActivityManagerService = activityManagerService;
1419 }
1420
1421 @Override
1422 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001423 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1424 != PackageManager.PERMISSION_GRANTED) {
1425 pw.println("Permission Denial: can't dump meminfo from from pid="
1426 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1427 + " without permission " + android.Manifest.permission.DUMP);
1428 return;
1429 }
1430
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001431 mActivityManagerService.dumpApplicationMemoryUsage(fd, pw, " ", args,
Dianne Hackborn672342c2011-11-29 11:29:02 -08001432 false, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001433 }
1434 }
1435
Chet Haase9c1e23b2011-03-24 10:51:31 -07001436 static class GraphicsBinder extends Binder {
1437 ActivityManagerService mActivityManagerService;
1438 GraphicsBinder(ActivityManagerService activityManagerService) {
1439 mActivityManagerService = activityManagerService;
1440 }
1441
1442 @Override
1443 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001444 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1445 != PackageManager.PERMISSION_GRANTED) {
1446 pw.println("Permission Denial: can't dump gfxinfo from from pid="
1447 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1448 + " without permission " + android.Manifest.permission.DUMP);
1449 return;
1450 }
1451
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001452 mActivityManagerService.dumpGraphicsHardwareUsage(fd, pw, args);
Chet Haase9c1e23b2011-03-24 10:51:31 -07001453 }
1454 }
1455
Jeff Brown6754ba22011-12-14 20:20:01 -08001456 static class DbBinder extends Binder {
1457 ActivityManagerService mActivityManagerService;
1458 DbBinder(ActivityManagerService activityManagerService) {
1459 mActivityManagerService = activityManagerService;
1460 }
1461
1462 @Override
1463 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1464 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1465 != PackageManager.PERMISSION_GRANTED) {
1466 pw.println("Permission Denial: can't dump dbinfo from from pid="
1467 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1468 + " without permission " + android.Manifest.permission.DUMP);
1469 return;
1470 }
1471
1472 mActivityManagerService.dumpDbInfo(fd, pw, args);
1473 }
1474 }
1475
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001476 static class CpuBinder extends Binder {
1477 ActivityManagerService mActivityManagerService;
1478 CpuBinder(ActivityManagerService activityManagerService) {
1479 mActivityManagerService = activityManagerService;
1480 }
1481
1482 @Override
1483 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001484 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1485 != PackageManager.PERMISSION_GRANTED) {
1486 pw.println("Permission Denial: can't dump cpuinfo from from pid="
1487 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1488 + " without permission " + android.Manifest.permission.DUMP);
1489 return;
1490 }
1491
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001492 synchronized (mActivityManagerService.mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07001493 pw.print(mActivityManagerService.mProcessStats.printCurrentLoad());
1494 pw.print(mActivityManagerService.mProcessStats.printCurrentState(
1495 SystemClock.uptimeMillis()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001496 }
1497 }
1498 }
1499
1500 private ActivityManagerService() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001501 Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
Dianne Hackborn2c6c5e62009-10-08 17:55:49 -07001502
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001503 mFgBroadcastQueue = new BroadcastQueue(this, "foreground", BROADCAST_FG_TIMEOUT);
1504 mBgBroadcastQueue = new BroadcastQueue(this, "background", BROADCAST_BG_TIMEOUT);
1505 mBroadcastQueues[0] = mFgBroadcastQueue;
1506 mBroadcastQueues[1] = mBgBroadcastQueue;
1507
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001508 File dataDir = Environment.getDataDirectory();
1509 File systemDir = new File(dataDir, "system");
1510 systemDir.mkdirs();
1511 mBatteryStatsService = new BatteryStatsService(new File(
1512 systemDir, "batterystats.bin").toString());
1513 mBatteryStatsService.getActiveStatistics().readLocked();
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001514 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
Dianne Hackborn287952c2010-09-22 22:34:31 -07001515 mOnBattery = DEBUG_POWER ? true
1516 : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001517 mBatteryStatsService.getActiveStatistics().setCallback(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001518
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001519 mUsageStatsService = new UsageStatsService(new File(
Dianne Hackborn6447ca32009-04-07 19:50:08 -07001520 systemDir, "usagestats").toString());
Mike Lockwood3a74bd32011-08-12 13:55:22 -07001521 mHeadless = "1".equals(SystemProperties.get("ro.config.headless", "0"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001522
Jack Palevichb90d28c2009-07-22 15:35:24 -07001523 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",
1524 ConfigurationInfo.GL_ES_VERSION_UNDEFINED);
1525
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001526 mConfiguration.setToDefaults();
1527 mConfiguration.locale = Locale.getDefault();
Dianne Hackborn813075a62011-11-14 17:45:19 -08001528 mConfigurationSeq = mConfiguration.seq = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001529 mProcessStats.init();
1530
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07001531 mCompatModePackages = new CompatModePackages(this, systemDir);
1532
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001533 // Add ourself to the Watchdog monitors.
1534 Watchdog.getInstance().addMonitor(this);
1535
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001536 mProcessStatsThread = new Thread("ProcessStats") {
1537 public void run() {
1538 while (true) {
1539 try {
1540 try {
1541 synchronized(this) {
1542 final long now = SystemClock.uptimeMillis();
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001543 long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001544 long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001545 //Slog.i(TAG, "Cpu delay=" + nextCpuDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001546 // + ", write delay=" + nextWriteDelay);
1547 if (nextWriteDelay < nextCpuDelay) {
1548 nextCpuDelay = nextWriteDelay;
1549 }
1550 if (nextCpuDelay > 0) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001551 mProcessStatsMutexFree.set(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001552 this.wait(nextCpuDelay);
1553 }
1554 }
1555 } catch (InterruptedException e) {
1556 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001557 updateCpuStatsNow();
1558 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001559 Slog.e(TAG, "Unexpected exception collecting process stats", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001560 }
1561 }
1562 }
1563 };
1564 mProcessStatsThread.start();
1565 }
1566
1567 @Override
1568 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1569 throws RemoteException {
1570 try {
1571 return super.onTransact(code, data, reply, flags);
1572 } catch (RuntimeException e) {
1573 // The activity manager only throws security exceptions, so let's
1574 // log all others.
1575 if (!(e instanceof SecurityException)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001576 Slog.e(TAG, "Activity Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001577 }
1578 throw e;
1579 }
1580 }
1581
1582 void updateCpuStats() {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001583 final long now = SystemClock.uptimeMillis();
1584 if (mLastCpuTime.get() >= now - MONITOR_CPU_MIN_TIME) {
1585 return;
1586 }
1587 if (mProcessStatsMutexFree.compareAndSet(true, false)) {
1588 synchronized (mProcessStatsThread) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001589 mProcessStatsThread.notify();
1590 }
1591 }
1592 }
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001593
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001594 void updateCpuStatsNow() {
1595 synchronized (mProcessStatsThread) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001596 mProcessStatsMutexFree.set(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001597 final long now = SystemClock.uptimeMillis();
1598 boolean haveNewCpuStats = false;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07001599
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001600 if (MONITOR_CPU_USAGE &&
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001601 mLastCpuTime.get() < (now-MONITOR_CPU_MIN_TIME)) {
1602 mLastCpuTime.set(now);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001603 haveNewCpuStats = true;
1604 mProcessStats.update();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001605 //Slog.i(TAG, mProcessStats.printCurrentState());
1606 //Slog.i(TAG, "Total CPU usage: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001607 // + mProcessStats.getTotalCpuPercent() + "%");
1608
Joe Onorato8a9b2202010-02-26 18:56:32 -08001609 // Slog the cpu usage if the property is set.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001610 if ("true".equals(SystemProperties.get("events.cpu"))) {
1611 int user = mProcessStats.getLastUserTime();
1612 int system = mProcessStats.getLastSystemTime();
1613 int iowait = mProcessStats.getLastIoWaitTime();
1614 int irq = mProcessStats.getLastIrqTime();
1615 int softIrq = mProcessStats.getLastSoftIrqTime();
1616 int idle = mProcessStats.getLastIdleTime();
1617
1618 int total = user + system + iowait + irq + softIrq + idle;
1619 if (total == 0) total = 1;
1620
Doug Zongker2bec3d42009-12-04 12:52:44 -08001621 EventLog.writeEvent(EventLogTags.CPU,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001622 ((user+system+iowait+irq+softIrq) * 100) / total,
1623 (user * 100) / total,
1624 (system * 100) / total,
1625 (iowait * 100) / total,
1626 (irq * 100) / total,
1627 (softIrq * 100) / total);
1628 }
1629 }
1630
Amith Yamasanie43530a2009-08-21 13:11:37 -07001631 long[] cpuSpeedTimes = mProcessStats.getLastCpuSpeedTimes();
Amith Yamasani819f9282009-06-24 23:18:15 -07001632 final BatteryStatsImpl bstats = mBatteryStatsService.getActiveStatistics();
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001633 synchronized(bstats) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001634 synchronized(mPidsSelfLocked) {
1635 if (haveNewCpuStats) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001636 if (mOnBattery) {
1637 int perc = bstats.startAddingCpuLocked();
1638 int totalUTime = 0;
1639 int totalSTime = 0;
Dianne Hackborn287952c2010-09-22 22:34:31 -07001640 final int N = mProcessStats.countStats();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001641 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001642 ProcessStats.Stats st = mProcessStats.getStats(i);
1643 if (!st.working) {
1644 continue;
1645 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001646 ProcessRecord pr = mPidsSelfLocked.get(st.pid);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001647 int otherUTime = (st.rel_utime*perc)/100;
1648 int otherSTime = (st.rel_stime*perc)/100;
1649 totalUTime += otherUTime;
1650 totalSTime += otherSTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001651 if (pr != null) {
1652 BatteryStatsImpl.Uid.Proc ps = pr.batteryStats;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001653 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1654 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001655 ps.addSpeedStepTimes(cpuSpeedTimes);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001656 pr.curCpuTime += (st.rel_utime+st.rel_stime) * 10;
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001657 } else {
1658 BatteryStatsImpl.Uid.Proc ps =
Amith Yamasani819f9282009-06-24 23:18:15 -07001659 bstats.getProcessStatsLocked(st.name, st.pid);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001660 if (ps != null) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001661 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1662 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001663 ps.addSpeedStepTimes(cpuSpeedTimes);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001664 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001665 }
1666 }
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001667 bstats.finishAddingCpuLocked(perc, totalUTime,
1668 totalSTime, cpuSpeedTimes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001669 }
1670 }
1671 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001672
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001673 if (mLastWriteTime < (now-BATTERY_STATS_TIME)) {
1674 mLastWriteTime = now;
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001675 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001676 }
1677 }
1678 }
1679 }
1680
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001681 @Override
1682 public void batteryNeedsCpuUpdate() {
1683 updateCpuStatsNow();
1684 }
1685
1686 @Override
1687 public void batteryPowerChanged(boolean onBattery) {
1688 // When plugging in, update the CPU stats first before changing
1689 // the plug state.
1690 updateCpuStatsNow();
1691 synchronized (this) {
1692 synchronized(mPidsSelfLocked) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001693 mOnBattery = DEBUG_POWER ? true : onBattery;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001694 }
1695 }
1696 }
1697
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001698 /**
1699 * Initialize the application bind args. These are passed to each
1700 * process when the bindApplication() IPC is sent to the process. They're
1701 * lazily setup to make sure the services are running when they're asked for.
1702 */
1703 private HashMap<String, IBinder> getCommonServicesLocked() {
1704 if (mAppBindArgs == null) {
1705 mAppBindArgs = new HashMap<String, IBinder>();
1706
1707 // Setup the application init args
1708 mAppBindArgs.put("package", ServiceManager.getService("package"));
1709 mAppBindArgs.put("window", ServiceManager.getService("window"));
1710 mAppBindArgs.put(Context.ALARM_SERVICE,
1711 ServiceManager.getService(Context.ALARM_SERVICE));
1712 }
1713 return mAppBindArgs;
1714 }
1715
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001716 final void setFocusedActivityLocked(ActivityRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001717 if (mFocusedActivity != r) {
1718 mFocusedActivity = r;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001719 if (r != null) {
1720 mWindowManager.setFocusedApp(r.appToken, true);
1721 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001722 }
1723 }
1724
Dianne Hackborn906497c2010-05-10 15:57:38 -07001725 private final void updateLruProcessInternalLocked(ProcessRecord app,
1726 boolean oomAdj, boolean updateActivityTime, int bestPos) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001727 // put it on the LRU to keep track of when it should be exited.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001728 int lrui = mLruProcesses.indexOf(app);
1729 if (lrui >= 0) mLruProcesses.remove(lrui);
1730
1731 int i = mLruProcesses.size()-1;
1732 int skipTop = 0;
1733
Dianne Hackborn906497c2010-05-10 15:57:38 -07001734 app.lruSeq = mLruSeq;
1735
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001736 // compute the new weight for this process.
1737 if (updateActivityTime) {
1738 app.lastActivityTime = SystemClock.uptimeMillis();
1739 }
1740 if (app.activities.size() > 0) {
1741 // If this process has activities, we more strongly want to keep
1742 // it around.
1743 app.lruWeight = app.lastActivityTime;
1744 } else if (app.pubProviders.size() > 0) {
1745 // If this process contains content providers, we want to keep
1746 // it a little more strongly.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001747 app.lruWeight = app.lastActivityTime - ProcessList.CONTENT_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001748 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001749 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001750 } else {
1751 // If this process doesn't have activities, we less strongly
1752 // want to keep it around, and generally want to avoid getting
1753 // in front of any very recently used activities.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001754 app.lruWeight = app.lastActivityTime - ProcessList.EMPTY_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001755 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001756 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001757 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001758
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001759 while (i >= 0) {
1760 ProcessRecord p = mLruProcesses.get(i);
1761 // If this app shouldn't be in front of the first N background
1762 // apps, then skip over that many that are currently hidden.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001763 if (skipTop > 0 && p.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001764 skipTop--;
1765 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001766 if (p.lruWeight <= app.lruWeight || i < bestPos) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001767 mLruProcesses.add(i+1, app);
1768 break;
1769 }
1770 i--;
1771 }
1772 if (i < 0) {
1773 mLruProcesses.add(0, app);
1774 }
1775
Dianne Hackborn906497c2010-05-10 15:57:38 -07001776 // If the app is currently using a content provider or service,
1777 // bump those processes as well.
1778 if (app.connections.size() > 0) {
1779 for (ConnectionRecord cr : app.connections) {
1780 if (cr.binding != null && cr.binding.service != null
1781 && cr.binding.service.app != null
1782 && cr.binding.service.app.lruSeq != mLruSeq) {
1783 updateLruProcessInternalLocked(cr.binding.service.app, oomAdj,
1784 updateActivityTime, i+1);
1785 }
1786 }
1787 }
1788 if (app.conProviders.size() > 0) {
1789 for (ContentProviderRecord cpr : app.conProviders.keySet()) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07001790 if (cpr.proc != null && cpr.proc.lruSeq != mLruSeq) {
1791 updateLruProcessInternalLocked(cpr.proc, oomAdj,
Dianne Hackborn906497c2010-05-10 15:57:38 -07001792 updateActivityTime, i+1);
1793 }
1794 }
1795 }
1796
Joe Onorato8a9b2202010-02-26 18:56:32 -08001797 //Slog.i(TAG, "Putting proc to front: " + app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001798 if (oomAdj) {
1799 updateOomAdjLocked();
1800 }
1801 }
1802
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001803 final void updateLruProcessLocked(ProcessRecord app,
Dianne Hackborn906497c2010-05-10 15:57:38 -07001804 boolean oomAdj, boolean updateActivityTime) {
1805 mLruSeq++;
1806 updateLruProcessInternalLocked(app, oomAdj, updateActivityTime, 0);
1807 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001808
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001809 final ProcessRecord getProcessRecordLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001810 String processName, int uid) {
Amith Yamasania4a54e22012-04-16 15:44:19 -07001811 if (uid == Process.SYSTEM_UID) {
Amith Yamasani0184ce92012-03-28 22:41:41 -07001812 // The system gets to run in any process. If there are multiple
1813 // processes with the same uid, just pick the first (this
1814 // should never happen).
1815 SparseArray<ProcessRecord> procs = mProcessNames.getMap().get(
1816 processName);
Amith Yamasania4a54e22012-04-16 15:44:19 -07001817 if (procs == null) return null;
1818 final int N = procs.size();
1819 for (int i = 0; i < N; i++) {
1820 if (UserId.isSameUser(procs.keyAt(i), uid)) return procs.valueAt(i);
1821 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001822 }
1823 ProcessRecord proc = mProcessNames.get(processName, uid);
1824 return proc;
1825 }
1826
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001827 void ensurePackageDexOpt(String packageName) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001828 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001829 try {
1830 if (pm.performDexOpt(packageName)) {
1831 mDidDexOpt = true;
1832 }
1833 } catch (RemoteException e) {
1834 }
1835 }
1836
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001837 boolean isNextTransitionForward() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001838 int transit = mWindowManager.getPendingAppTransition();
1839 return transit == WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
1840 || transit == WindowManagerPolicy.TRANSIT_TASK_OPEN
1841 || transit == WindowManagerPolicy.TRANSIT_TASK_TO_FRONT;
1842 }
1843
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001844 final ProcessRecord startProcessLocked(String processName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001845 ApplicationInfo info, boolean knownToBeDead, int intentFlags,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001846 String hostingType, ComponentName hostingName, boolean allowWhileBooting,
1847 boolean isolated) {
1848 ProcessRecord app;
1849 if (!isolated) {
1850 app = getProcessRecordLocked(processName, info.uid);
1851 } else {
1852 // If this is an isolated process, it can't re-use an existing process.
1853 app = null;
1854 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001855 // We don't have to do anything more if:
1856 // (1) There is an existing application record; and
1857 // (2) The caller doesn't think it is dead, OR there is no thread
1858 // object attached to it so we know it couldn't have crashed; and
1859 // (3) There is a pid assigned to it, so it is either starting or
1860 // already running.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001861 if (DEBUG_PROCESSES) Slog.v(TAG, "startProcess: name=" + processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001862 + " app=" + app + " knownToBeDead=" + knownToBeDead
1863 + " thread=" + (app != null ? app.thread : null)
1864 + " pid=" + (app != null ? app.pid : -1));
Magnus Edlund7bb25812010-02-24 15:45:06 +01001865 if (app != null && app.pid > 0) {
1866 if (!knownToBeDead || app.thread == null) {
Dianne Hackborn20cb56e2010-03-04 00:58:29 -08001867 // We already have the app running, or are waiting for it to
1868 // come up (we have a pid but not yet its thread), so keep it.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001869 if (DEBUG_PROCESSES) Slog.v(TAG, "App already running: " + app);
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001870 // If this is a new package in the process, add the package to the list
1871 app.addPackage(info.packageName);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001872 return app;
1873 } else {
1874 // An application record is attached to a previous process,
1875 // clean it up now.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001876 if (DEBUG_PROCESSES) Slog.v(TAG, "App died: " + app);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07001877 handleAppDiedLocked(app, true, true);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001878 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001879 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01001880
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001881 String hostingNameStr = hostingName != null
1882 ? hostingName.flattenToShortString() : null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001883
1884 if (!isolated) {
1885 if ((intentFlags&Intent.FLAG_FROM_BACKGROUND) != 0) {
1886 // If we are in the background, then check to see if this process
1887 // is bad. If so, we will just silently fail.
1888 if (mBadProcesses.get(info.processName, info.uid) != null) {
1889 if (DEBUG_PROCESSES) Slog.v(TAG, "Bad process: " + info.uid
1890 + "/" + info.processName);
1891 return null;
1892 }
1893 } else {
1894 // When the user is explicitly starting a process, then clear its
1895 // crash count so that we won't make it bad until they see at
1896 // least one crash dialog again, and make the process good again
1897 // if it had been bad.
1898 if (DEBUG_PROCESSES) Slog.v(TAG, "Clearing bad process: " + info.uid
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001899 + "/" + info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001900 mProcessCrashTimes.remove(info.processName, info.uid);
1901 if (mBadProcesses.get(info.processName, info.uid) != null) {
1902 EventLog.writeEvent(EventLogTags.AM_PROC_GOOD, info.uid,
1903 info.processName);
1904 mBadProcesses.remove(info.processName, info.uid);
1905 if (app != null) {
1906 app.bad = false;
1907 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001908 }
1909 }
1910 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001911
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001912 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001913 app = newProcessRecordLocked(null, info, processName, isolated);
1914 if (app == null) {
1915 Slog.w(TAG, "Failed making new process record for "
1916 + processName + "/" + info.uid + " isolated=" + isolated);
1917 return null;
1918 }
1919 mProcessNames.put(processName, app.uid, app);
1920 if (isolated) {
1921 mIsolatedProcesses.put(app.uid, app);
1922 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001923 } else {
1924 // If this is a new package in the process, add the package to the list
1925 app.addPackage(info.packageName);
1926 }
1927
1928 // If the system is not ready yet, then hold off on starting this
1929 // process until it is.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001930 if (!mProcessesReady
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001931 && !isAllowedWhileBooting(info)
1932 && !allowWhileBooting) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001933 if (!mProcessesOnHold.contains(app)) {
1934 mProcessesOnHold.add(app);
1935 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001936 if (DEBUG_PROCESSES) Slog.v(TAG, "System not ready, putting on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001937 return app;
1938 }
1939
1940 startProcessLocked(app, hostingType, hostingNameStr);
1941 return (app.pid != 0) ? app : null;
1942 }
1943
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001944 boolean isAllowedWhileBooting(ApplicationInfo ai) {
1945 return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0;
1946 }
1947
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001948 private final void startProcessLocked(ProcessRecord app,
1949 String hostingType, String hostingNameStr) {
1950 if (app.pid > 0 && app.pid != MY_PID) {
1951 synchronized (mPidsSelfLocked) {
1952 mPidsSelfLocked.remove(app.pid);
1953 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
1954 }
1955 app.pid = 0;
1956 }
1957
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001958 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
1959 "startProcessLocked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001960 mProcessesOnHold.remove(app);
1961
1962 updateCpuStats();
1963
1964 System.arraycopy(mProcDeaths, 0, mProcDeaths, 1, mProcDeaths.length-1);
1965 mProcDeaths[0] = 0;
1966
1967 try {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001968 int uid = app.uid;
Amith Yamasani742a6712011-05-04 14:49:28 -07001969
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001970 int[] gids = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001971 if (!app.isolated) {
1972 try {
1973 gids = mContext.getPackageManager().getPackageGids(
1974 app.info.packageName);
1975 } catch (PackageManager.NameNotFoundException e) {
1976 Slog.w(TAG, "Unable to retrieve gids", e);
1977 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001978 }
1979 if (mFactoryTest != SystemServer.FACTORY_TEST_OFF) {
1980 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
1981 && mTopComponent != null
1982 && app.processName.equals(mTopComponent.getPackageName())) {
1983 uid = 0;
1984 }
1985 if (mFactoryTest == SystemServer.FACTORY_TEST_HIGH_LEVEL
1986 && (app.info.flags&ApplicationInfo.FLAG_FACTORY_TEST) != 0) {
1987 uid = 0;
1988 }
1989 }
1990 int debugFlags = 0;
1991 if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
1992 debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;
Elliott Hughesfa36aee2011-06-17 14:39:41 -07001993 // Also turn on CheckJNI for debuggable apps. It's quite
1994 // awkward to turn on otherwise.
1995 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001996 }
Ben Cheng6c0afff2010-02-14 16:18:56 -08001997 // Run the app in safe mode if its manifest requests so or the
1998 // system is booted in safe mode.
1999 if ((app.info.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0 ||
2000 Zygote.systemInSafeMode == true) {
Ben Cheng23085b72010-02-08 16:06:32 -08002001 debugFlags |= Zygote.DEBUG_ENABLE_SAFEMODE;
2002 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002003 if ("1".equals(SystemProperties.get("debug.checkjni"))) {
2004 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
2005 }
Elliott Hughesae07ecf2011-07-06 17:33:27 -07002006 if ("1".equals(SystemProperties.get("debug.jni.logging"))) {
2007 debugFlags |= Zygote.DEBUG_ENABLE_JNI_LOGGING;
2008 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002009 if ("1".equals(SystemProperties.get("debug.assert"))) {
2010 debugFlags |= Zygote.DEBUG_ENABLE_ASSERT;
2011 }
Jeff Brown3f9dd282011-07-08 20:02:19 -07002012
2013 // Start the process. It will either succeed and return a result containing
2014 // the PID of the new process, or else throw a RuntimeException.
2015 Process.ProcessStartResult startResult = Process.start("android.app.ActivityThread",
Elliott Hughese1dfcb72011-07-08 11:08:07 -07002016 app.processName, uid, uid, gids, debugFlags,
2017 app.info.targetSdkVersion, null);
Jeff Brown3f9dd282011-07-08 20:02:19 -07002018
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002019 BatteryStatsImpl bs = app.batteryStats.getBatteryStats();
2020 synchronized (bs) {
2021 if (bs.isOnBattery()) {
2022 app.batteryStats.incStartsLocked();
2023 }
2024 }
2025
Jeff Brown3f9dd282011-07-08 20:02:19 -07002026 EventLog.writeEvent(EventLogTags.AM_PROC_START, startResult.pid, uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002027 app.processName, hostingType,
2028 hostingNameStr != null ? hostingNameStr : "");
2029
2030 if (app.persistent) {
Jeff Brown3f9dd282011-07-08 20:02:19 -07002031 Watchdog.getInstance().processStarted(app.processName, startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002032 }
2033
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07002034 StringBuilder buf = mStringBuilder;
2035 buf.setLength(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002036 buf.append("Start proc ");
2037 buf.append(app.processName);
2038 buf.append(" for ");
2039 buf.append(hostingType);
2040 if (hostingNameStr != null) {
2041 buf.append(" ");
2042 buf.append(hostingNameStr);
2043 }
2044 buf.append(": pid=");
Jeff Brown3f9dd282011-07-08 20:02:19 -07002045 buf.append(startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002046 buf.append(" uid=");
2047 buf.append(uid);
2048 buf.append(" gids={");
2049 if (gids != null) {
2050 for (int gi=0; gi<gids.length; gi++) {
2051 if (gi != 0) buf.append(", ");
2052 buf.append(gids[gi]);
2053
2054 }
2055 }
2056 buf.append("}");
Joe Onorato8a9b2202010-02-26 18:56:32 -08002057 Slog.i(TAG, buf.toString());
Jeff Brown3f9dd282011-07-08 20:02:19 -07002058 app.pid = startResult.pid;
2059 app.usingWrapper = startResult.usingWrapper;
2060 app.removed = false;
2061 synchronized (mPidsSelfLocked) {
2062 this.mPidsSelfLocked.put(startResult.pid, app);
2063 Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
2064 msg.obj = app;
2065 mHandler.sendMessageDelayed(msg, startResult.usingWrapper
2066 ? PROC_START_TIMEOUT_WITH_WRAPPER : PROC_START_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002067 }
2068 } catch (RuntimeException e) {
2069 // XXX do better error recovery.
2070 app.pid = 0;
Joe Onorato8a9b2202010-02-26 18:56:32 -08002071 Slog.e(TAG, "Failure starting process " + app.processName, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002072 }
2073 }
2074
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002075 void updateUsageStats(ActivityRecord resumedComponent, boolean resumed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002076 if (resumed) {
2077 mUsageStatsService.noteResumeComponent(resumedComponent.realActivity);
2078 } else {
2079 mUsageStatsService.notePauseComponent(resumedComponent.realActivity);
2080 }
2081 }
2082
Amith Yamasani742a6712011-05-04 14:49:28 -07002083 boolean startHomeActivityLocked(int userId) {
Mike Lockwooda8f767a2011-08-31 14:32:37 -04002084 if (mHeadless) {
2085 // Added because none of the other calls to ensureBootCompleted seem to fire
2086 // when running headless.
2087 ensureBootCompleted();
2088 return false;
2089 }
2090
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002091 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2092 && mTopAction == null) {
2093 // We are running in factory test mode, but unable to find
2094 // the factory test app, so just sit around displaying the
2095 // error message and don't try to start anything.
2096 return false;
2097 }
2098 Intent intent = new Intent(
2099 mTopAction,
2100 mTopData != null ? Uri.parse(mTopData) : null);
2101 intent.setComponent(mTopComponent);
2102 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
2103 intent.addCategory(Intent.CATEGORY_HOME);
2104 }
2105 ActivityInfo aInfo =
2106 intent.resolveActivityInfo(mContext.getPackageManager(),
2107 STOCK_PM_FLAGS);
2108 if (aInfo != null) {
2109 intent.setComponent(new ComponentName(
2110 aInfo.applicationInfo.packageName, aInfo.name));
2111 // Don't do this if the home app is currently being
2112 // instrumented.
Amith Yamasani742a6712011-05-04 14:49:28 -07002113 aInfo = new ActivityInfo(aInfo);
2114 aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002115 ProcessRecord app = getProcessRecordLocked(aInfo.processName,
2116 aInfo.applicationInfo.uid);
2117 if (app == null || app.instrumentationClass == null) {
2118 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002119 mMainStack.startActivityLocked(null, intent, null, aInfo,
2120 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002121 }
2122 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002123
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002124 return true;
2125 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002126
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002127 /**
2128 * Starts the "new version setup screen" if appropriate.
2129 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002130 void startSetupActivityLocked() {
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002131 // Only do this once per boot.
2132 if (mCheckedForSetup) {
2133 return;
2134 }
2135
2136 // We will show this screen if the current one is a different
2137 // version than the last one shown, and we are not running in
2138 // low-level factory test mode.
2139 final ContentResolver resolver = mContext.getContentResolver();
2140 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL &&
2141 Settings.Secure.getInt(resolver,
2142 Settings.Secure.DEVICE_PROVISIONED, 0) != 0) {
2143 mCheckedForSetup = true;
2144
2145 // See if we should be showing the platform update setup UI.
2146 Intent intent = new Intent(Intent.ACTION_UPGRADE_SETUP);
2147 List<ResolveInfo> ris = mSelf.mContext.getPackageManager()
2148 .queryIntentActivities(intent, PackageManager.GET_META_DATA);
2149
2150 // We don't allow third party apps to replace this.
2151 ResolveInfo ri = null;
2152 for (int i=0; ris != null && i<ris.size(); i++) {
2153 if ((ris.get(i).activityInfo.applicationInfo.flags
2154 & ApplicationInfo.FLAG_SYSTEM) != 0) {
2155 ri = ris.get(i);
2156 break;
2157 }
2158 }
2159
2160 if (ri != null) {
2161 String vers = ri.activityInfo.metaData != null
2162 ? ri.activityInfo.metaData.getString(Intent.METADATA_SETUP_VERSION)
2163 : null;
2164 if (vers == null && ri.activityInfo.applicationInfo.metaData != null) {
2165 vers = ri.activityInfo.applicationInfo.metaData.getString(
2166 Intent.METADATA_SETUP_VERSION);
2167 }
2168 String lastVers = Settings.Secure.getString(
2169 resolver, Settings.Secure.LAST_SETUP_SHOWN);
2170 if (vers != null && !vers.equals(lastVers)) {
2171 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2172 intent.setComponent(new ComponentName(
2173 ri.activityInfo.packageName, ri.activityInfo.name));
Dianne Hackborna4972e92012-03-14 10:38:05 -07002174 mMainStack.startActivityLocked(null, intent, null, ri.activityInfo,
2175 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002176 }
2177 }
2178 }
2179 }
2180
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002181 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002182 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002183 }
2184
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002185 void enforceNotIsolatedCaller(String caller) {
2186 if (UserId.isIsolated(Binder.getCallingUid())) {
2187 throw new SecurityException("Isolated process not allowed to call " + caller);
2188 }
2189 }
2190
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002191 public int getFrontActivityScreenCompatMode() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002192 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002193 synchronized (this) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002194 return mCompatModePackages.getFrontActivityScreenCompatModeLocked();
2195 }
2196 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002197
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002198 public void setFrontActivityScreenCompatMode(int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002199 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2200 "setFrontActivityScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002201 synchronized (this) {
2202 mCompatModePackages.setFrontActivityScreenCompatModeLocked(mode);
2203 }
2204 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002205
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002206 public int getPackageScreenCompatMode(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002207 enforceNotIsolatedCaller("getPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002208 synchronized (this) {
2209 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
2210 }
2211 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002212
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002213 public void setPackageScreenCompatMode(String packageName, int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002214 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2215 "setPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002216 synchronized (this) {
2217 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002218 }
2219 }
2220
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002221 public boolean getPackageAskScreenCompat(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002222 enforceNotIsolatedCaller("getPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002223 synchronized (this) {
2224 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
2225 }
2226 }
2227
2228 public void setPackageAskScreenCompat(String packageName, boolean ask) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002229 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2230 "setPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002231 synchronized (this) {
2232 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
2233 }
2234 }
2235
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002236 void reportResumedActivityLocked(ActivityRecord r) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002237 //Slog.i(TAG, "**** REPORT RESUME: " + r);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002238
2239 final int identHash = System.identityHashCode(r);
2240 updateUsageStats(r, true);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002241 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002242
Jeff Sharkeya4620792011-05-20 15:29:23 -07002243 private void dispatchForegroundActivitiesChanged(int pid, int uid, boolean foregroundActivities) {
2244 int i = mProcessObservers.beginBroadcast();
2245 while (i > 0) {
2246 i--;
2247 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2248 if (observer != null) {
2249 try {
2250 observer.onForegroundActivitiesChanged(pid, uid, foregroundActivities);
2251 } catch (RemoteException e) {
2252 }
2253 }
2254 }
2255 mProcessObservers.finishBroadcast();
2256 }
2257
2258 private void dispatchProcessDied(int pid, int uid) {
2259 int i = mProcessObservers.beginBroadcast();
2260 while (i > 0) {
2261 i--;
2262 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2263 if (observer != null) {
2264 try {
2265 observer.onProcessDied(pid, uid);
2266 } catch (RemoteException e) {
2267 }
2268 }
2269 }
2270 mProcessObservers.finishBroadcast();
2271 }
2272
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002273 final void doPendingActivityLaunchesLocked(boolean doResume) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002274 final int N = mPendingActivityLaunches.size();
2275 if (N <= 0) {
2276 return;
2277 }
2278 for (int i=0; i<N; i++) {
2279 PendingActivityLaunch pal = mPendingActivityLaunches.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002280 mMainStack.startActivityUncheckedLocked(pal.r, pal.sourceRecord,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002281 pal.startFlags, doResume && i == (N-1), null);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002282 }
2283 mPendingActivityLaunches.clear();
2284 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002285
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002286 public final int startActivity(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002287 Intent intent, String resolvedType, IBinder resultTo,
2288 String resultWho, int requestCode, int startFlags,
2289 String profileFile, ParcelFileDescriptor profileFd, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002290 enforceNotIsolatedCaller("startActivity");
Amith Yamasani742a6712011-05-04 14:49:28 -07002291 int userId = 0;
2292 if (intent.getCategories() != null && intent.getCategories().contains(Intent.CATEGORY_HOME)) {
2293 // Requesting home, set the identity to the current user
2294 // HACK!
2295 userId = mCurrentUserId;
2296 } else {
2297 // TODO: Fix this in a better way - calls coming from SystemUI should probably carry
2298 // the current user's userId
2299 if (Binder.getCallingUid() < Process.FIRST_APPLICATION_UID) {
2300 userId = 0;
2301 } else {
2302 userId = Binder.getOrigCallingUser();
2303 }
2304 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002305 return mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002306 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
2307 null, null, options, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002308 }
2309
2310 public final WaitResult startActivityAndWait(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002311 Intent intent, String resolvedType, IBinder resultTo,
2312 String resultWho, int requestCode, int startFlags, String profileFile,
2313 ParcelFileDescriptor profileFd, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002314 enforceNotIsolatedCaller("startActivityAndWait");
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002315 WaitResult res = new WaitResult();
Amith Yamasani742a6712011-05-04 14:49:28 -07002316 int userId = Binder.getOrigCallingUser();
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002317 mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002318 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
2319 res, null, options, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002320 return res;
2321 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08002322
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002323 public final int startActivityWithConfig(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002324 Intent intent, String resolvedType, IBinder resultTo,
2325 String resultWho, int requestCode, int startFlags, Configuration config,
2326 Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002327 enforceNotIsolatedCaller("startActivityWithConfig");
Amith Yamasani742a6712011-05-04 14:49:28 -07002328 int ret = mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002329 resultTo, resultWho, requestCode, startFlags,
2330 null, null, null, config, options, Binder.getOrigCallingUser());
Amith Yamasani742a6712011-05-04 14:49:28 -07002331 return ret;
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002332 }
2333
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002334 public int startActivityIntentSender(IApplicationThread caller,
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002335 IntentSender intent, Intent fillInIntent, String resolvedType,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002336 IBinder resultTo, String resultWho, int requestCode,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002337 int flagsMask, int flagsValues, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002338 enforceNotIsolatedCaller("startActivityIntentSender");
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002339 // Refuse possible leaked file descriptors
2340 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
2341 throw new IllegalArgumentException("File descriptors passed in Intent");
2342 }
2343
2344 IIntentSender sender = intent.getTarget();
2345 if (!(sender instanceof PendingIntentRecord)) {
2346 throw new IllegalArgumentException("Bad PendingIntent object");
2347 }
2348
2349 PendingIntentRecord pir = (PendingIntentRecord)sender;
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002350
2351 synchronized (this) {
2352 // If this is coming from the currently resumed activity, it is
2353 // effectively saying that app switches are allowed at this point.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002354 if (mMainStack.mResumedActivity != null
2355 && mMainStack.mResumedActivity.info.applicationInfo.uid ==
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002356 Binder.getCallingUid()) {
2357 mAppSwitchesAllowedTime = 0;
2358 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002359 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002360 int ret = pir.sendInner(0, fillInIntent, resolvedType, null, null,
2361 resultTo, resultWho, requestCode, flagsMask, flagsValues, options);
Amith Yamasani742a6712011-05-04 14:49:28 -07002362 return ret;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002363 }
2364
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002365 public boolean startNextMatchingActivity(IBinder callingActivity,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002366 Intent intent, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002367 // Refuse possible leaked file descriptors
2368 if (intent != null && intent.hasFileDescriptors() == true) {
2369 throw new IllegalArgumentException("File descriptors passed in Intent");
2370 }
2371
2372 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002373 ActivityRecord r = mMainStack.isInStackLocked(callingActivity);
2374 if (r == null) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002375 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002376 return false;
2377 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002378 if (r.app == null || r.app.thread == null) {
2379 // The caller is not running... d'oh!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002380 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002381 return false;
2382 }
2383 intent = new Intent(intent);
2384 // The caller is not allowed to change the data.
2385 intent.setDataAndType(r.intent.getData(), r.intent.getType());
2386 // And we are resetting to find the next component...
2387 intent.setComponent(null);
2388
2389 ActivityInfo aInfo = null;
2390 try {
2391 List<ResolveInfo> resolves =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002392 AppGlobals.getPackageManager().queryIntentActivities(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002393 intent, r.resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002394 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
2395 UserId.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002396
2397 // Look for the original activity in the list...
2398 final int N = resolves != null ? resolves.size() : 0;
2399 for (int i=0; i<N; i++) {
2400 ResolveInfo rInfo = resolves.get(i);
2401 if (rInfo.activityInfo.packageName.equals(r.packageName)
2402 && rInfo.activityInfo.name.equals(r.info.name)) {
2403 // We found the current one... the next matching is
2404 // after it.
2405 i++;
2406 if (i<N) {
2407 aInfo = resolves.get(i).activityInfo;
2408 }
2409 break;
2410 }
2411 }
2412 } catch (RemoteException e) {
2413 }
2414
2415 if (aInfo == null) {
2416 // Nobody who is next!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002417 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002418 return false;
2419 }
2420
2421 intent.setComponent(new ComponentName(
2422 aInfo.applicationInfo.packageName, aInfo.name));
2423 intent.setFlags(intent.getFlags()&~(
2424 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
2425 Intent.FLAG_ACTIVITY_CLEAR_TOP|
2426 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
2427 Intent.FLAG_ACTIVITY_NEW_TASK));
2428
2429 // Okay now we need to start the new activity, replacing the
2430 // currently running activity. This is a little tricky because
2431 // we want to start the new one as if the current one is finished,
2432 // but not finish the current one first so that there is no flicker.
2433 // And thus...
2434 final boolean wasFinishing = r.finishing;
2435 r.finishing = true;
2436
2437 // Propagate reply information over to the new activity.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002438 final ActivityRecord resultTo = r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002439 final String resultWho = r.resultWho;
2440 final int requestCode = r.requestCode;
2441 r.resultTo = null;
2442 if (resultTo != null) {
2443 resultTo.removeResultsLocked(r, resultWho, requestCode);
2444 }
2445
2446 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002447 int res = mMainStack.startActivityLocked(r.app.thread, intent,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002448 r.resolvedType, aInfo, resultTo != null ? resultTo.appToken : null,
2449 resultWho, requestCode, -1, r.launchedFromUid, 0,
2450 options, false, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002451 Binder.restoreCallingIdentity(origId);
2452
2453 r.finishing = wasFinishing;
Dianne Hackborna4972e92012-03-14 10:38:05 -07002454 if (res != ActivityManager.START_SUCCESS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002455 return false;
2456 }
2457 return true;
2458 }
2459 }
2460
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002461 public final int startActivityInPackage(int uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002462 Intent intent, String resolvedType, IBinder resultTo,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002463 String resultWho, int requestCode, int startFlags, Bundle options) {
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002464
2465 // This is so super not safe, that only the system (or okay root)
2466 // can do it.
Amith Yamasani742a6712011-05-04 14:49:28 -07002467 int userId = Binder.getOrigCallingUser();
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002468 final int callingUid = Binder.getCallingUid();
2469 if (callingUid != 0 && callingUid != Process.myUid()) {
2470 throw new SecurityException(
2471 "startActivityInPackage only available to the system");
2472 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002473
Amith Yamasani742a6712011-05-04 14:49:28 -07002474 int ret = mMainStack.startActivityMayWait(null, uid, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002475 resultTo, resultWho, requestCode, startFlags,
2476 null, null, null, null, options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002477 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002478 }
2479
2480 public final int startActivities(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002481 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002482 enforceNotIsolatedCaller("startActivities");
Amith Yamasani742a6712011-05-04 14:49:28 -07002483 int ret = mMainStack.startActivities(caller, -1, intents, resolvedTypes, resultTo,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002484 options, Binder.getOrigCallingUser());
Amith Yamasani742a6712011-05-04 14:49:28 -07002485 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002486 }
2487
2488 public final int startActivitiesInPackage(int uid,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002489 Intent[] intents, String[] resolvedTypes, IBinder resultTo,
2490 Bundle options) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002491
2492 // This is so super not safe, that only the system (or okay root)
2493 // can do it.
2494 final int callingUid = Binder.getCallingUid();
2495 if (callingUid != 0 && callingUid != Process.myUid()) {
2496 throw new SecurityException(
2497 "startActivityInPackage only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002498 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002499 int ret = mMainStack.startActivities(null, uid, intents, resolvedTypes, resultTo,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002500 options, UserId.getUserId(uid));
Amith Yamasani742a6712011-05-04 14:49:28 -07002501 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002502 }
2503
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002504 final void addRecentTaskLocked(TaskRecord task) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002505 int N = mRecentTasks.size();
Dianne Hackborn7c0e75e2010-12-21 19:15:40 -08002506 // Quick case: check if the top-most recent task is the same.
2507 if (N > 0 && mRecentTasks.get(0) == task) {
2508 return;
2509 }
2510 // Remove any existing entries that are the same kind of task.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002511 for (int i=0; i<N; i++) {
2512 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07002513 if (task.userId == tr.userId
2514 && ((task.affinity != null && task.affinity.equals(tr.affinity))
2515 || (task.intent != null && task.intent.filterEquals(tr.intent)))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002516 mRecentTasks.remove(i);
2517 i--;
2518 N--;
2519 if (task.intent == null) {
2520 // If the new recent task we are adding is not fully
2521 // specified, then replace it with the existing recent task.
2522 task = tr;
2523 }
2524 }
2525 }
2526 if (N >= MAX_RECENT_TASKS) {
2527 mRecentTasks.remove(N-1);
2528 }
2529 mRecentTasks.add(0, task);
2530 }
2531
2532 public void setRequestedOrientation(IBinder token,
2533 int requestedOrientation) {
2534 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002535 ActivityRecord r = mMainStack.isInStackLocked(token);
2536 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002537 return;
2538 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002539 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornbe707852011-11-11 14:32:10 -08002540 mWindowManager.setAppOrientation(r.appToken, requestedOrientation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002541 Configuration config = mWindowManager.updateOrientationFromAppTokens(
The Android Open Source Project10592532009-03-18 17:39:46 -07002542 mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -08002543 r.mayFreezeScreenLocked(r.app) ? r.appToken : null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002544 if (config != null) {
2545 r.frozenBeforeDestroy = true;
Dianne Hackborn813075a62011-11-14 17:45:19 -08002546 if (!updateConfigurationLocked(config, r, false, false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002547 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002548 }
2549 }
2550 Binder.restoreCallingIdentity(origId);
2551 }
2552 }
2553
2554 public int getRequestedOrientation(IBinder token) {
2555 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002556 ActivityRecord r = mMainStack.isInStackLocked(token);
2557 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002558 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
2559 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08002560 return mWindowManager.getAppOrientation(r.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002561 }
2562 }
2563
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002564 /**
2565 * This is the internal entry point for handling Activity.finish().
2566 *
2567 * @param token The Binder token referencing the Activity we want to finish.
2568 * @param resultCode Result code, if any, from this Activity.
2569 * @param resultData Result data (Intent), if any, from this Activity.
2570 *
Alexey Tarasov83bad3d2009-08-12 15:05:43 +11002571 * @return Returns true if the activity successfully finished, or false if it is still running.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002572 */
2573 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData) {
2574 // Refuse possible leaked file descriptors
2575 if (resultData != null && resultData.hasFileDescriptors() == true) {
2576 throw new IllegalArgumentException("File descriptors passed in Intent");
2577 }
2578
2579 synchronized(this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002580 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002581 // Find the first activity that is not finishing.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002582 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002583 if (next != null) {
2584 // ask watcher if this is allowed
2585 boolean resumeOK = true;
2586 try {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002587 resumeOK = mController.activityResuming(next.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002588 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002589 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002590 }
2591
2592 if (!resumeOK) {
2593 return false;
2594 }
2595 }
2596 }
2597 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002598 boolean res = mMainStack.requestFinishActivityLocked(token, resultCode,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002599 resultData, "app-request");
2600 Binder.restoreCallingIdentity(origId);
2601 return res;
2602 }
2603 }
2604
Dianne Hackborn860755f2010-06-03 18:47:52 -07002605 public final void finishHeavyWeightApp() {
2606 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2607 != PackageManager.PERMISSION_GRANTED) {
2608 String msg = "Permission Denial: finishHeavyWeightApp() from pid="
2609 + Binder.getCallingPid()
2610 + ", uid=" + Binder.getCallingUid()
2611 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2612 Slog.w(TAG, msg);
2613 throw new SecurityException(msg);
2614 }
2615
2616 synchronized(this) {
2617 if (mHeavyWeightProcess == null) {
2618 return;
2619 }
2620
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002621 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>(
Dianne Hackborn860755f2010-06-03 18:47:52 -07002622 mHeavyWeightProcess.activities);
2623 for (int i=0; i<activities.size(); i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002624 ActivityRecord r = activities.get(i);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002625 if (!r.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002626 int index = mMainStack.indexOfTokenLocked(r.appToken);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002627 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002628 mMainStack.finishActivityLocked(r, index, Activity.RESULT_CANCELED,
Dianne Hackborn860755f2010-06-03 18:47:52 -07002629 null, "finish-heavy");
2630 }
2631 }
2632 }
2633
2634 mHeavyWeightProcess = null;
2635 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
2636 }
2637 }
2638
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002639 public void crashApplication(int uid, int initialPid, String packageName,
2640 String message) {
2641 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2642 != PackageManager.PERMISSION_GRANTED) {
2643 String msg = "Permission Denial: crashApplication() from pid="
2644 + Binder.getCallingPid()
2645 + ", uid=" + Binder.getCallingUid()
2646 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2647 Slog.w(TAG, msg);
2648 throw new SecurityException(msg);
2649 }
2650
2651 synchronized(this) {
2652 ProcessRecord proc = null;
2653
2654 // Figure out which process to kill. We don't trust that initialPid
2655 // still has any relation to current pids, so must scan through the
2656 // list.
2657 synchronized (mPidsSelfLocked) {
2658 for (int i=0; i<mPidsSelfLocked.size(); i++) {
2659 ProcessRecord p = mPidsSelfLocked.valueAt(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002660 if (p.uid != uid) {
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002661 continue;
2662 }
2663 if (p.pid == initialPid) {
2664 proc = p;
2665 break;
2666 }
2667 for (String str : p.pkgList) {
2668 if (str.equals(packageName)) {
2669 proc = p;
2670 }
2671 }
2672 }
2673 }
2674
2675 if (proc == null) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07002676 Slog.w(TAG, "crashApplication: nothing for uid=" + uid
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002677 + " initialPid=" + initialPid
2678 + " packageName=" + packageName);
2679 return;
2680 }
2681
2682 if (proc.thread != null) {
Dianne Hackborn9f531192010-08-04 17:48:03 -07002683 if (proc.pid == Process.myPid()) {
2684 Log.w(TAG, "crashApplication: trying to crash self!");
2685 return;
2686 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002687 long ident = Binder.clearCallingIdentity();
2688 try {
2689 proc.thread.scheduleCrash(message);
2690 } catch (RemoteException e) {
2691 }
2692 Binder.restoreCallingIdentity(ident);
2693 }
2694 }
2695 }
2696
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002697 public final void finishSubActivity(IBinder token, String resultWho,
2698 int requestCode) {
2699 synchronized(this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002700 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07002701 mMainStack.finishSubActivityLocked(token, resultWho, requestCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002702 Binder.restoreCallingIdentity(origId);
2703 }
2704 }
2705
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07002706 public boolean finishActivityAffinity(IBinder token) {
2707 synchronized(this) {
2708 final long origId = Binder.clearCallingIdentity();
2709 boolean res = mMainStack.finishActivityAffinityLocked(token);
2710 Binder.restoreCallingIdentity(origId);
2711 return res;
2712 }
2713 }
2714
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002715 public boolean willActivityBeVisible(IBinder token) {
2716 synchronized(this) {
2717 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002718 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2719 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08002720 if (r.appToken == token) {
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002721 return true;
2722 }
2723 if (r.fullscreen && !r.finishing) {
2724 return false;
2725 }
2726 }
2727 return true;
2728 }
2729 }
2730
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002731 public void overridePendingTransition(IBinder token, String packageName,
2732 int enterAnim, int exitAnim) {
2733 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002734 ActivityRecord self = mMainStack.isInStackLocked(token);
2735 if (self == null) {
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002736 return;
2737 }
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002738
2739 final long origId = Binder.clearCallingIdentity();
2740
2741 if (self.state == ActivityState.RESUMED
2742 || self.state == ActivityState.PAUSING) {
2743 mWindowManager.overridePendingAppTransition(packageName,
2744 enterAnim, exitAnim);
2745 }
2746
2747 Binder.restoreCallingIdentity(origId);
2748 }
2749 }
2750
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002751 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002752 * Main function for removing an existing process from the activity manager
2753 * as a result of that process going away. Clears out all connections
2754 * to the process.
2755 */
2756 private final void handleAppDiedLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002757 boolean restarting, boolean allowRestart) {
2758 cleanUpApplicationRecordLocked(app, restarting, allowRestart, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002759 if (!restarting) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002760 mLruProcesses.remove(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002761 }
2762
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002763 if (mProfileProc == app) {
2764 clearProfilerLocked();
2765 }
2766
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002767 // Just in case...
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002768 if (mMainStack.mPausingActivity != null && mMainStack.mPausingActivity.app == app) {
2769 if (DEBUG_PAUSE) Slog.v(TAG, "App died while pausing: " +mMainStack.mPausingActivity);
2770 mMainStack.mPausingActivity = null;
2771 }
2772 if (mMainStack.mLastPausedActivity != null && mMainStack.mLastPausedActivity.app == app) {
2773 mMainStack.mLastPausedActivity = null;
2774 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002775
2776 // Remove this application's activities from active lists.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002777 mMainStack.removeHistoryRecordsForAppLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002778
2779 boolean atTop = true;
2780 boolean hasVisibleActivities = false;
2781
2782 // Clean out the history list.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002783 int i = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08002784 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002785 TAG, "Removing app " + app + " from history with " + i + " entries");
2786 while (i > 0) {
2787 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002788 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002789 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002790 TAG, "Record #" + i + " " + r + ": app=" + r.app);
2791 if (r.app == app) {
2792 if ((!r.haveState && !r.stateNotNeeded) || r.finishing) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002793 if (ActivityStack.DEBUG_ADD_REMOVE) {
2794 RuntimeException here = new RuntimeException("here");
2795 here.fillInStackTrace();
2796 Slog.i(TAG, "Removing activity " + r + " from stack at " + i
2797 + ": haveState=" + r.haveState
2798 + " stateNotNeeded=" + r.stateNotNeeded
2799 + " finishing=" + r.finishing
2800 + " state=" + r.state, here);
2801 }
2802 if (!r.finishing) {
2803 Slog.w(TAG, "Force removing " + r + ": app died, no saved state");
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -08002804 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
2805 System.identityHashCode(r),
2806 r.task.taskId, r.shortComponentName,
2807 "proc died without state saved");
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002808 }
Dianne Hackborn5c607432012-02-28 14:44:19 -08002809 mMainStack.removeActivityFromHistoryLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002810
2811 } else {
2812 // We have the current state for this activity, so
2813 // it can be restarted later when needed.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002814 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002815 TAG, "Keeping entry, setting app to null");
2816 if (r.visible) {
2817 hasVisibleActivities = true;
2818 }
2819 r.app = null;
2820 r.nowVisible = false;
2821 if (!r.haveState) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002822 if (ActivityStack.DEBUG_SAVED_STATE) Slog.i(TAG,
2823 "App died, clearing saved state of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002824 r.icicle = null;
2825 }
2826 }
2827
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002828 r.stack.cleanUpActivityLocked(r, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002829 }
2830 atTop = false;
2831 }
2832
2833 app.activities.clear();
2834
2835 if (app.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002836 Slog.w(TAG, "Crash of app " + app.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002837 + " running instrumentation " + app.instrumentationClass);
2838 Bundle info = new Bundle();
2839 info.putString("shortMsg", "Process crashed.");
2840 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
2841 }
2842
2843 if (!restarting) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002844 if (!mMainStack.resumeTopActivityLocked(null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002845 // If there was nothing to resume, and we are not already
2846 // restarting this process, but there is a visible activity that
2847 // is hosted by the process... then make sure all visible
2848 // activities are running, taking care of restarting this
2849 // process.
2850 if (hasVisibleActivities) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002851 mMainStack.ensureActivitiesVisibleLocked(null, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002852 }
2853 }
2854 }
2855 }
2856
2857 private final int getLRURecordIndexForAppLocked(IApplicationThread thread) {
2858 IBinder threadBinder = thread.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002859 // Find the application record.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002860 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2861 ProcessRecord rec = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002862 if (rec.thread != null && rec.thread.asBinder() == threadBinder) {
2863 return i;
2864 }
2865 }
2866 return -1;
2867 }
2868
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002869 final ProcessRecord getRecordForAppLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002870 IApplicationThread thread) {
2871 if (thread == null) {
2872 return null;
2873 }
2874
2875 int appIndex = getLRURecordIndexForAppLocked(thread);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002876 return appIndex >= 0 ? mLruProcesses.get(appIndex) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002877 }
2878
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002879 final void appDiedLocked(ProcessRecord app, int pid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002880 IApplicationThread thread) {
2881
2882 mProcDeaths[0]++;
2883
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002884 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
2885 synchronized (stats) {
2886 stats.noteProcessDiedLocked(app.info.uid, pid);
2887 }
2888
Magnus Edlund7bb25812010-02-24 15:45:06 +01002889 // Clean up already done if the process has been re-started.
2890 if (app.pid == pid && app.thread != null &&
2891 app.thread.asBinder() == thread.asBinder()) {
Dianne Hackborn906497c2010-05-10 15:57:38 -07002892 if (!app.killedBackground) {
2893 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
2894 + ") has died.");
2895 }
Doug Zongker2bec3d42009-12-04 12:52:44 -08002896 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002897 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002898 TAG, "Dying app: " + app + ", pid: " + pid
2899 + ", thread: " + thread.asBinder());
2900 boolean doLowMem = app.instrumentationClass == null;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002901 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002902
2903 if (doLowMem) {
2904 // If there are no longer any background processes running,
2905 // and the app that died was not running instrumentation,
2906 // then tell everyone we are now low on memory.
2907 boolean haveBg = false;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002908 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2909 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -07002910 if (rec.thread != null && rec.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002911 haveBg = true;
2912 break;
2913 }
2914 }
2915
2916 if (!haveBg) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002917 EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mLruProcesses.size());
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002918 long now = SystemClock.uptimeMillis();
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002919 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2920 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn36124872009-10-08 16:22:03 -07002921 if (rec != app && rec.thread != null &&
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002922 (rec.lastLowMemory+GC_MIN_INTERVAL) <= now) {
2923 // The low memory report is overriding any current
2924 // state for a GC request. Make sure to do
Dianne Hackborn32907cf2010-06-10 17:50:20 -07002925 // heavy/important/visible/foreground processes first.
Dianne Hackborn7d608422011-08-07 16:24:18 -07002926 if (rec.setAdj <= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002927 rec.lastRequestedGc = 0;
2928 } else {
2929 rec.lastRequestedGc = rec.lastLowMemory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002930 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002931 rec.reportLowMemory = true;
2932 rec.lastLowMemory = now;
2933 mProcessesToGc.remove(rec);
2934 addProcessToGcListLocked(rec);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002935 }
2936 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07002937 mHandler.sendEmptyMessage(REPORT_MEM_USAGE);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002938 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002939 }
2940 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01002941 } else if (app.pid != pid) {
2942 // A new process has already been started.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002943 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
Magnus Edlund7bb25812010-02-24 15:45:06 +01002944 + ") has died and restarted (pid " + app.pid + ").");
Dianne Hackborn28a8c2b2010-03-01 11:30:02 -08002945 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08002946 } else if (DEBUG_PROCESSES) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002947 Slog.d(TAG, "Received spurious death notification for thread "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002948 + thread.asBinder());
2949 }
2950 }
2951
Dan Egnor42471dd2010-01-07 17:25:22 -08002952 /**
2953 * If a stack trace dump file is configured, dump process stack traces.
Christopher Tate6ee412d2010-05-28 12:01:56 -07002954 * @param clearTraces causes the dump file to be erased prior to the new
2955 * traces being written, if true; when false, the new traces will be
2956 * appended to any existing file content.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002957 * @param firstPids of dalvik VM processes to dump stack traces for first
2958 * @param lastPids of dalvik VM processes to dump stack traces for last
Dan Egnor42471dd2010-01-07 17:25:22 -08002959 * @return file containing stack traces, or null if no dump file is configured
2960 */
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002961 public static File dumpStackTraces(boolean clearTraces, ArrayList<Integer> firstPids,
2962 ProcessStats processStats, SparseArray<Boolean> lastPids) {
Dan Egnor42471dd2010-01-07 17:25:22 -08002963 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
2964 if (tracesPath == null || tracesPath.length() == 0) {
2965 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002966 }
Dan Egnor42471dd2010-01-07 17:25:22 -08002967
2968 File tracesFile = new File(tracesPath);
2969 try {
2970 File tracesDir = tracesFile.getParentFile();
2971 if (!tracesDir.exists()) tracesFile.mkdirs();
2972 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
2973
Christopher Tate6ee412d2010-05-28 12:01:56 -07002974 if (clearTraces && tracesFile.exists()) tracesFile.delete();
Dan Egnor42471dd2010-01-07 17:25:22 -08002975 tracesFile.createNewFile();
2976 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
2977 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002978 Slog.w(TAG, "Unable to prepare ANR traces file: " + tracesPath, e);
Dan Egnor42471dd2010-01-07 17:25:22 -08002979 return null;
2980 }
2981
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07002982 dumpStackTraces(tracesPath, firstPids, processStats, lastPids);
2983 return tracesFile;
2984 }
2985
2986 private static void dumpStackTraces(String tracesPath, ArrayList<Integer> firstPids,
2987 ProcessStats processStats, SparseArray<Boolean> lastPids) {
Dan Egnor42471dd2010-01-07 17:25:22 -08002988 // Use a FileObserver to detect when traces finish writing.
2989 // The order of traces is considered important to maintain for legibility.
2990 FileObserver observer = new FileObserver(tracesPath, FileObserver.CLOSE_WRITE) {
2991 public synchronized void onEvent(int event, String path) { notify(); }
2992 };
2993
2994 try {
2995 observer.startWatching();
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002996
2997 // First collect all of the stacks of the most important pids.
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07002998 if (firstPids != null) {
2999 try {
3000 int num = firstPids.size();
3001 for (int i = 0; i < num; i++) {
3002 synchronized (observer) {
3003 Process.sendSignal(firstPids.get(i), Process.SIGNAL_QUIT);
3004 observer.wait(200); // Wait for write-close, give up after 200msec
3005 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003006 }
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003007 } catch (InterruptedException e) {
3008 Log.wtf(TAG, e);
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003009 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003010 }
3011
3012 // Next measure CPU usage.
3013 if (processStats != null) {
3014 processStats.init();
3015 System.gc();
3016 processStats.update();
3017 try {
3018 synchronized (processStats) {
3019 processStats.wait(500); // measure over 1/2 second.
3020 }
3021 } catch (InterruptedException e) {
3022 }
3023 processStats.update();
3024
3025 // We'll take the stack crawls of just the top apps using CPU.
3026 final int N = processStats.countWorkingStats();
3027 int numProcs = 0;
3028 for (int i=0; i<N && numProcs<5; i++) {
3029 ProcessStats.Stats stats = processStats.getWorkingStats(i);
3030 if (lastPids.indexOfKey(stats.pid) >= 0) {
3031 numProcs++;
3032 try {
3033 synchronized (observer) {
3034 Process.sendSignal(stats.pid, Process.SIGNAL_QUIT);
3035 observer.wait(200); // Wait for write-close, give up after 200msec
3036 }
3037 } catch (InterruptedException e) {
3038 Log.wtf(TAG, e);
3039 }
3040
3041 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003042 }
3043 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003044
Dan Egnor42471dd2010-01-07 17:25:22 -08003045 } finally {
3046 observer.stopWatching();
3047 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003048 }
3049
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003050 final void logAppTooSlow(ProcessRecord app, long startTime, String msg) {
Dianne Hackborn69dc66e2012-03-26 10:50:54 -07003051 if (true || IS_USER_BUILD) {
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003052 return;
3053 }
3054 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
3055 if (tracesPath == null || tracesPath.length() == 0) {
3056 return;
3057 }
3058
3059 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
3060 StrictMode.allowThreadDiskWrites();
3061 try {
3062 final File tracesFile = new File(tracesPath);
3063 final File tracesDir = tracesFile.getParentFile();
3064 final File tracesTmp = new File(tracesDir, "__tmp__");
3065 try {
3066 if (!tracesDir.exists()) tracesFile.mkdirs();
3067 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
3068
3069 if (tracesFile.exists()) {
3070 tracesTmp.delete();
3071 tracesFile.renameTo(tracesTmp);
3072 }
3073 StringBuilder sb = new StringBuilder();
3074 Time tobj = new Time();
3075 tobj.set(System.currentTimeMillis());
3076 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
3077 sb.append(": ");
3078 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
3079 sb.append(" since ");
3080 sb.append(msg);
3081 FileOutputStream fos = new FileOutputStream(tracesFile);
3082 fos.write(sb.toString().getBytes());
3083 if (app == null) {
3084 fos.write("\n*** No application process!".getBytes());
3085 }
3086 fos.close();
3087 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
3088 } catch (IOException e) {
3089 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesPath, e);
3090 return;
3091 }
3092
3093 if (app != null) {
3094 ArrayList<Integer> firstPids = new ArrayList<Integer>();
3095 firstPids.add(app.pid);
3096 dumpStackTraces(tracesPath, firstPids, null, null);
3097 }
3098
3099 File lastTracesFile = null;
3100 File curTracesFile = null;
3101 for (int i=9; i>=0; i--) {
3102 String name = String.format("slow%02d.txt", i);
3103 curTracesFile = new File(tracesDir, name);
3104 if (curTracesFile.exists()) {
3105 if (lastTracesFile != null) {
3106 curTracesFile.renameTo(lastTracesFile);
3107 } else {
3108 curTracesFile.delete();
3109 }
3110 }
3111 lastTracesFile = curTracesFile;
3112 }
3113 tracesFile.renameTo(curTracesFile);
3114 if (tracesTmp.exists()) {
3115 tracesTmp.renameTo(tracesFile);
3116 }
3117 } finally {
3118 StrictMode.setThreadPolicy(oldPolicy);
3119 }
3120 }
3121
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003122 final void appNotResponding(ProcessRecord app, ActivityRecord activity,
3123 ActivityRecord parent, final String annotation) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003124 ArrayList<Integer> firstPids = new ArrayList<Integer>(5);
3125 SparseArray<Boolean> lastPids = new SparseArray<Boolean>(20);
3126
Dianne Hackborn287952c2010-09-22 22:34:31 -07003127 if (mController != null) {
3128 try {
3129 // 0 == continue, -1 = kill process immediately
3130 int res = mController.appEarlyNotResponding(app.processName, app.pid, annotation);
3131 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3132 } catch (RemoteException e) {
3133 mController = null;
3134 }
3135 }
3136
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003137 long anrTime = SystemClock.uptimeMillis();
3138 if (MONITOR_CPU_USAGE) {
3139 updateCpuStatsNow();
3140 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003141
3142 synchronized (this) {
3143 // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down.
3144 if (mShuttingDown) {
3145 Slog.i(TAG, "During shutdown skipping ANR: " + app + " " + annotation);
3146 return;
3147 } else if (app.notResponding) {
3148 Slog.i(TAG, "Skipping duplicate ANR: " + app + " " + annotation);
3149 return;
3150 } else if (app.crashing) {
3151 Slog.i(TAG, "Crashing app skipping ANR: " + app + " " + annotation);
3152 return;
3153 }
3154
3155 // In case we come through here for the same app before completing
3156 // this one, mark as anring now so we will bail out.
3157 app.notResponding = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08003158
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003159 // Log the ANR to the event log.
3160 EventLog.writeEvent(EventLogTags.AM_ANR, app.pid, app.processName, app.info.flags,
3161 annotation);
Dan Egnor42471dd2010-01-07 17:25:22 -08003162
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003163 // Dump thread traces as quickly as we can, starting with "interesting" processes.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003164 firstPids.add(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003165
3166 int parentPid = app.pid;
3167 if (parent != null && parent.app != null && parent.app.pid > 0) parentPid = parent.app.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003168 if (parentPid != app.pid) firstPids.add(parentPid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003169
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003170 if (MY_PID != app.pid && MY_PID != parentPid) firstPids.add(MY_PID);
Dan Egnor42471dd2010-01-07 17:25:22 -08003171
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003172 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
3173 ProcessRecord r = mLruProcesses.get(i);
3174 if (r != null && r.thread != null) {
3175 int pid = r.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003176 if (pid > 0 && pid != app.pid && pid != parentPid && pid != MY_PID) {
3177 if (r.persistent) {
3178 firstPids.add(pid);
3179 } else {
3180 lastPids.put(pid, Boolean.TRUE);
3181 }
3182 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003183 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003184 }
3185 }
3186
Dan Egnor42471dd2010-01-07 17:25:22 -08003187 // Log the ANR to the main log.
Jeff Browndeb6ed82012-04-10 14:26:26 -07003188 StringBuilder info = new StringBuilder();
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07003189 info.setLength(0);
Dan Egnor42471dd2010-01-07 17:25:22 -08003190 info.append("ANR in ").append(app.processName);
3191 if (activity != null && activity.shortComponentName != null) {
3192 info.append(" (").append(activity.shortComponentName).append(")");
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07003193 }
Eric Rowe6f4f6192010-02-17 18:29:04 -08003194 info.append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003195 if (annotation != null) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003196 info.append("Reason: ").append(annotation).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003197 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003198 if (parent != null && parent != activity) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003199 info.append("Parent: ").append(parent.shortComponentName).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003200 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003201
Dianne Hackborn287952c2010-09-22 22:34:31 -07003202 final ProcessStats processStats = new ProcessStats(true);
3203
3204 File tracesFile = dumpStackTraces(true, firstPids, processStats, lastPids);
3205
Dan Egnor42471dd2010-01-07 17:25:22 -08003206 String cpuInfo = null;
3207 if (MONITOR_CPU_USAGE) {
3208 updateCpuStatsNow();
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003209 synchronized (mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003210 cpuInfo = mProcessStats.printCurrentState(anrTime);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003211 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003212 info.append(processStats.printCurrentLoad());
Dan Egnor42471dd2010-01-07 17:25:22 -08003213 info.append(cpuInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003214 }
3215
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003216 info.append(processStats.printCurrentState(anrTime));
3217
Joe Onorato8a9b2202010-02-26 18:56:32 -08003218 Slog.e(TAG, info.toString());
Dan Egnor42471dd2010-01-07 17:25:22 -08003219 if (tracesFile == null) {
3220 // There is no trace file, so dump (only) the alleged culprit's threads to the log
3221 Process.sendSignal(app.pid, Process.SIGNAL_QUIT);
3222 }
3223
Jeff Sharkeya353d262011-10-28 11:12:06 -07003224 addErrorToDropBox("anr", app, app.processName, activity, parent, annotation,
3225 cpuInfo, tracesFile, null);
Dan Egnor42471dd2010-01-07 17:25:22 -08003226
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003227 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003228 try {
Dan Egnor42471dd2010-01-07 17:25:22 -08003229 // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately
3230 int res = mController.appNotResponding(app.processName, app.pid, info.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003231 if (res != 0) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003232 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3233 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003234 }
3235 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003236 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003237 }
3238 }
3239
Dan Egnor42471dd2010-01-07 17:25:22 -08003240 // Unless configured otherwise, swallow ANRs in background processes & kill the process.
3241 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
3242 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003243
3244 synchronized (this) {
3245 if (!showBackground && !app.isInterestingToUserLocked() && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003246 Slog.w(TAG, "Killing " + app + ": background ANR");
3247 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
3248 app.processName, app.setAdj, "background ANR");
3249 Process.killProcessQuiet(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003250 return;
3251 }
3252
3253 // Set the app's notResponding state, and look up the errorReportReceiver
3254 makeAppNotRespondingLocked(app,
3255 activity != null ? activity.shortComponentName : null,
3256 annotation != null ? "ANR " + annotation : "ANR",
3257 info.toString());
3258
3259 // Bring up the infamous App Not Responding dialog
3260 Message msg = Message.obtain();
3261 HashMap map = new HashMap();
3262 msg.what = SHOW_NOT_RESPONDING_MSG;
3263 msg.obj = map;
3264 map.put("app", app);
3265 if (activity != null) {
3266 map.put("activity", activity);
3267 }
3268
3269 mHandler.sendMessage(msg);
Dan Egnor42471dd2010-01-07 17:25:22 -08003270 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003271 }
3272
Dianne Hackborn0dad3642010-09-09 21:25:35 -07003273 final void showLaunchWarningLocked(final ActivityRecord cur, final ActivityRecord next) {
3274 if (!mLaunchWarningShown) {
3275 mLaunchWarningShown = true;
3276 mHandler.post(new Runnable() {
3277 @Override
3278 public void run() {
3279 synchronized (ActivityManagerService.this) {
3280 final Dialog d = new LaunchWarningWindow(mContext, cur, next);
3281 d.show();
3282 mHandler.postDelayed(new Runnable() {
3283 @Override
3284 public void run() {
3285 synchronized (ActivityManagerService.this) {
3286 d.dismiss();
3287 mLaunchWarningShown = false;
3288 }
3289 }
3290 }, 4000);
3291 }
3292 }
3293 });
3294 }
3295 }
3296
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003297 public boolean clearApplicationUserData(final String packageName,
Amith Yamasani742a6712011-05-04 14:49:28 -07003298 final IPackageDataObserver observer, final int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003299 enforceNotIsolatedCaller("clearApplicationUserData");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003300 int uid = Binder.getCallingUid();
3301 int pid = Binder.getCallingPid();
3302 long callingId = Binder.clearCallingIdentity();
3303 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003304 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003305 int pkgUid = -1;
3306 synchronized(this) {
3307 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003308 pkgUid = pm.getPackageUid(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003309 } catch (RemoteException e) {
3310 }
3311 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003312 Slog.w(TAG, "Invalid packageName:" + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003313 return false;
3314 }
3315 if (uid == pkgUid || checkComponentPermission(
3316 android.Manifest.permission.CLEAR_APP_USER_DATA,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08003317 pid, uid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003318 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003319 forceStopPackageLocked(packageName, pkgUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003320 } else {
3321 throw new SecurityException(pid+" does not have permission:"+
3322 android.Manifest.permission.CLEAR_APP_USER_DATA+" to clear data" +
3323 "for process:"+packageName);
3324 }
3325 }
3326
3327 try {
3328 //clear application user data
Amith Yamasani483f3b02012-03-13 16:08:00 -07003329 pm.clearApplicationUserData(packageName, observer, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003330 Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED,
3331 Uri.fromParts("package", packageName, null));
3332 intent.putExtra(Intent.EXTRA_UID, pkgUid);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003333 broadcastIntentInPackage("android", Process.SYSTEM_UID, intent,
Amith Yamasani742a6712011-05-04 14:49:28 -07003334 null, null, 0, null, null, null, false, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003335 } catch (RemoteException e) {
3336 }
3337 } finally {
3338 Binder.restoreCallingIdentity(callingId);
3339 }
3340 return true;
3341 }
3342
Dianne Hackborn03abb812010-01-04 18:43:19 -08003343 public void killBackgroundProcesses(final String packageName) {
3344 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3345 != PackageManager.PERMISSION_GRANTED &&
3346 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES)
3347 != PackageManager.PERMISSION_GRANTED) {
3348 String msg = "Permission Denial: killBackgroundProcesses() from pid="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003349 + Binder.getCallingPid()
3350 + ", uid=" + Binder.getCallingUid()
Dianne Hackborn03abb812010-01-04 18:43:19 -08003351 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003352 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003353 throw new SecurityException(msg);
3354 }
3355
Amith Yamasani483f3b02012-03-13 16:08:00 -07003356 int userId = UserId.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003357 long callingId = Binder.clearCallingIdentity();
3358 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003359 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003360 int pkgUid = -1;
3361 synchronized(this) {
3362 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003363 pkgUid = pm.getPackageUid(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003364 } catch (RemoteException e) {
3365 }
3366 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003367 Slog.w(TAG, "Invalid packageName: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003368 return;
3369 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003370 killPackageProcessesLocked(packageName, pkgUid,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003371 ProcessList.SERVICE_ADJ, false, true, true, false, "kill background");
3372 }
3373 } finally {
3374 Binder.restoreCallingIdentity(callingId);
3375 }
3376 }
3377
3378 public void killAllBackgroundProcesses() {
3379 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3380 != PackageManager.PERMISSION_GRANTED) {
3381 String msg = "Permission Denial: killAllBackgroundProcesses() from pid="
3382 + Binder.getCallingPid()
3383 + ", uid=" + Binder.getCallingUid()
3384 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
3385 Slog.w(TAG, msg);
3386 throw new SecurityException(msg);
3387 }
3388
3389 long callingId = Binder.clearCallingIdentity();
3390 try {
3391 synchronized(this) {
3392 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
3393 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3394 final int NA = apps.size();
3395 for (int ia=0; ia<NA; ia++) {
3396 ProcessRecord app = apps.valueAt(ia);
3397 if (app.persistent) {
3398 // we don't kill persistent processes
3399 continue;
3400 }
3401 if (app.removed) {
3402 procs.add(app);
3403 } else if (app.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
3404 app.removed = true;
3405 procs.add(app);
3406 }
3407 }
3408 }
3409
3410 int N = procs.size();
3411 for (int i=0; i<N; i++) {
3412 removeProcessLocked(procs.get(i), false, true, "kill all background");
3413 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003414 }
3415 } finally {
3416 Binder.restoreCallingIdentity(callingId);
3417 }
3418 }
3419
3420 public void forceStopPackage(final String packageName) {
3421 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3422 != PackageManager.PERMISSION_GRANTED) {
3423 String msg = "Permission Denial: forceStopPackage() from pid="
3424 + Binder.getCallingPid()
3425 + ", uid=" + Binder.getCallingUid()
3426 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003427 Slog.w(TAG, msg);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003428 throw new SecurityException(msg);
3429 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07003430 final int userId = UserId.getCallingUserId();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003431 long callingId = Binder.clearCallingIdentity();
3432 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003433 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003434 int pkgUid = -1;
3435 synchronized(this) {
3436 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003437 pkgUid = pm.getPackageUid(packageName, userId);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003438 } catch (RemoteException e) {
3439 }
3440 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003441 Slog.w(TAG, "Invalid packageName: " + packageName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003442 return;
3443 }
3444 forceStopPackageLocked(packageName, pkgUid);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003445 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003446 pm.setPackageStoppedState(packageName, true, userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003447 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08003448 } catch (IllegalArgumentException e) {
3449 Slog.w(TAG, "Failed trying to unstop package "
3450 + packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003451 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003452 }
3453 } finally {
3454 Binder.restoreCallingIdentity(callingId);
3455 }
3456 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003457
3458 /*
3459 * The pkg name and uid have to be specified.
3460 * @see android.app.IActivityManager#killApplicationWithUid(java.lang.String, int)
3461 */
3462 public void killApplicationWithUid(String pkg, int uid) {
3463 if (pkg == null) {
3464 return;
3465 }
3466 // Make sure the uid is valid.
3467 if (uid < 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003468 Slog.w(TAG, "Invalid uid specified for pkg : " + pkg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003469 return;
3470 }
3471 int callerUid = Binder.getCallingUid();
3472 // Only the system server can kill an application
3473 if (callerUid == Process.SYSTEM_UID) {
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07003474 // Post an aysnc message to kill the application
3475 Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG);
3476 msg.arg1 = uid;
3477 msg.arg2 = 0;
3478 msg.obj = pkg;
Suchi Amalapurapud50066f2009-08-18 16:57:41 -07003479 mHandler.sendMessage(msg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003480 } else {
3481 throw new SecurityException(callerUid + " cannot kill pkg: " +
3482 pkg);
3483 }
3484 }
3485
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003486 public void closeSystemDialogs(String reason) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003487 enforceNotIsolatedCaller("closeSystemDialogs");
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003488 Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003489 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003490 if (reason != null) {
3491 intent.putExtra("reason", reason);
3492 }
3493
3494 final int uid = Binder.getCallingUid();
3495 final long origId = Binder.clearCallingIdentity();
3496 synchronized (this) {
Dianne Hackbornffa42482009-09-23 22:20:11 -07003497 mWindowManager.closeSystemDialogs(reason);
3498
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08003499 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003500 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornffa42482009-09-23 22:20:11 -07003501 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003502 r.stack.finishActivityLocked(r, i,
Dianne Hackbornffa42482009-09-23 22:20:11 -07003503 Activity.RESULT_CANCELED, null, "close-sys");
3504 }
3505 }
3506
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003507 broadcastIntentLocked(null, null, intent, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07003508 null, 0, null, null, null, false, false, -1, uid, 0 /* TODO: Verify */);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003509 }
3510 Binder.restoreCallingIdentity(origId);
3511 }
3512
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003513 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids)
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003514 throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003515 enforceNotIsolatedCaller("getProcessMemoryInfo");
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003516 Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length];
3517 for (int i=pids.length-1; i>=0; i--) {
3518 infos[i] = new Debug.MemoryInfo();
3519 Debug.getMemoryInfo(pids[i], infos[i]);
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003520 }
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003521 return infos;
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003522 }
Christopher Tate5e1ab332009-09-01 20:32:49 -07003523
Dianne Hackbornb437e092011-08-05 17:50:29 -07003524 public long[] getProcessPss(int[] pids) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003525 enforceNotIsolatedCaller("getProcessPss");
Dianne Hackbornb437e092011-08-05 17:50:29 -07003526 long[] pss = new long[pids.length];
3527 for (int i=pids.length-1; i>=0; i--) {
3528 pss[i] = Debug.getPss(pids[i]);
3529 }
3530 return pss;
3531 }
3532
Christopher Tate5e1ab332009-09-01 20:32:49 -07003533 public void killApplicationProcess(String processName, int uid) {
3534 if (processName == null) {
3535 return;
3536 }
3537
3538 int callerUid = Binder.getCallingUid();
3539 // Only the system server can kill an application
3540 if (callerUid == Process.SYSTEM_UID) {
3541 synchronized (this) {
3542 ProcessRecord app = getProcessRecordLocked(processName, uid);
Christopher Tate4a627c72011-04-01 14:43:32 -07003543 if (app != null && app.thread != null) {
Christopher Tate5e1ab332009-09-01 20:32:49 -07003544 try {
3545 app.thread.scheduleSuicide();
3546 } catch (RemoteException e) {
3547 // If the other end already died, then our work here is done.
3548 }
3549 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003550 Slog.w(TAG, "Process/uid not found attempting kill of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07003551 + processName + " / " + uid);
3552 }
3553 }
3554 } else {
3555 throw new SecurityException(callerUid + " cannot kill app process: " +
3556 processName);
3557 }
3558 }
3559
Dianne Hackborn03abb812010-01-04 18:43:19 -08003560 private void forceStopPackageLocked(final String packageName, int uid) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003561 forceStopPackageLocked(packageName, uid, false, false, true, false, UserId.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003562 Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED,
3563 Uri.fromParts("package", packageName, null));
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003564 if (!mProcessesReady) {
3565 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3566 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003567 intent.putExtra(Intent.EXTRA_UID, uid);
3568 broadcastIntentLocked(null, null, intent,
3569 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07003570 false, false,
3571 MY_PID, Process.SYSTEM_UID, UserId.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003572 }
3573
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003574 private final boolean killPackageProcessesLocked(String packageName, int uid,
Christopher Tate3dacd842011-08-19 14:56:15 -07003575 int minOomAdj, boolean callerWillRestart, boolean allowRestart, boolean doit,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003576 boolean evenPersistent, String reason) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003577 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003578
Dianne Hackborn03abb812010-01-04 18:43:19 -08003579 // Remove all processes this package may have touched: all with the
3580 // same UID (except for the system or root user), and all whose name
3581 // matches the package name.
3582 final String procNamePrefix = packageName + ":";
3583 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3584 final int NA = apps.size();
3585 for (int ia=0; ia<NA; ia++) {
3586 ProcessRecord app = apps.valueAt(ia);
Christopher Tate3dacd842011-08-19 14:56:15 -07003587 if (app.persistent && !evenPersistent) {
Christopher Tate064d8422011-07-26 15:38:07 -07003588 // we don't kill persistent processes
3589 continue;
3590 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003591 if (app.removed) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003592 if (doit) {
3593 procs.add(app);
3594 }
Amith Yamasani13593602012-03-22 16:16:17 -07003595 // If uid is specified and the uid and process name match
3596 // Or, the uid is not specified and the process name matches
3597 } else if (((uid > 0 && uid != Process.SYSTEM_UID && app.info.uid == uid)
Amith Yamasani34db3d62012-04-02 16:35:19 -07003598 || ((app.processName.equals(packageName)
3599 || app.processName.startsWith(procNamePrefix))
3600 && uid < 0))) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003601 if (app.setAdj >= minOomAdj) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003602 if (!doit) {
3603 return true;
3604 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003605 app.removed = true;
3606 procs.add(app);
3607 }
3608 }
3609 }
3610 }
3611
3612 int N = procs.size();
3613 for (int i=0; i<N; i++) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003614 removeProcessLocked(procs.get(i), callerWillRestart, allowRestart, reason);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003615 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003616 return N > 0;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003617 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003618
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003619 private final boolean forceStopPackageLocked(String name, int uid,
Christopher Tate3dacd842011-08-19 14:56:15 -07003620 boolean callerWillRestart, boolean purgeCache, boolean doit,
Amith Yamasani483f3b02012-03-13 16:08:00 -07003621 boolean evenPersistent, int userId) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003622 int i;
3623 int N;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003624
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003625 if (uid < 0) {
3626 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003627 uid = AppGlobals.getPackageManager().getPackageUid(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003628 } catch (RemoteException e) {
3629 }
3630 }
3631
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003632 if (doit) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003633 Slog.i(TAG, "Force stopping package " + name + " uid=" + uid);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003634
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003635 Iterator<SparseArray<Long>> badApps = mProcessCrashTimes.getMap().values().iterator();
3636 while (badApps.hasNext()) {
3637 SparseArray<Long> ba = badApps.next();
3638 if (ba.get(uid) != null) {
3639 badApps.remove();
3640 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003641 }
3642 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003643
3644 boolean didSomething = killPackageProcessesLocked(name, uid, -100,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003645 callerWillRestart, false, doit, evenPersistent, "force stop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003646
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003647 TaskRecord lastTask = null;
3648 for (i=0; i<mMainStack.mHistory.size(); i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003649 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003650 final boolean samePackage = r.packageName.equals(name);
Amith Yamasani13593602012-03-22 16:16:17 -07003651 if (r.userId == userId
3652 && (samePackage || r.task == lastTask)
Christopher Tate3dacd842011-08-19 14:56:15 -07003653 && (r.app == null || evenPersistent || !r.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003654 if (!doit) {
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003655 if (r.finishing) {
3656 // If this activity is just finishing, then it is not
3657 // interesting as far as something to stop.
3658 continue;
3659 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003660 return true;
3661 }
3662 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003663 Slog.i(TAG, " Force finishing activity " + r);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003664 if (samePackage) {
3665 if (r.app != null) {
3666 r.app.removed = true;
3667 }
3668 r.app = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003669 }
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003670 lastTask = r.task;
3671 if (r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003672 null, "force-stop", true)) {
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003673 i--;
3674 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003675 }
3676 }
3677
3678 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
Amith Yamasani742a6712011-05-04 14:49:28 -07003679 for (ServiceRecord service : mServiceMap.getAllServices(userId)) {
Christopher Tate064d8422011-07-26 15:38:07 -07003680 if (service.packageName.equals(name)
Christopher Tate3dacd842011-08-19 14:56:15 -07003681 && (service.app == null || evenPersistent || !service.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003682 if (!doit) {
3683 return true;
3684 }
3685 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003686 Slog.i(TAG, " Force stopping service " + service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003687 if (service.app != null) {
3688 service.app.removed = true;
3689 }
3690 service.app = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003691 service.isolatedProc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003692 services.add(service);
3693 }
3694 }
3695
3696 N = services.size();
3697 for (i=0; i<N; i++) {
3698 bringDownServiceLocked(services.get(i), true);
3699 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003700
3701 ArrayList<ContentProviderRecord> providers = new ArrayList<ContentProviderRecord>();
Amith Yamasani13593602012-03-22 16:16:17 -07003702 for (ContentProviderRecord provider : mProviderMap.getProvidersByClass(userId).values()) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003703 if (provider.info.packageName.equals(name)
3704 && (provider.proc == null || evenPersistent || !provider.proc.persistent)) {
3705 if (!doit) {
3706 return true;
3707 }
3708 didSomething = true;
3709 providers.add(provider);
3710 }
3711 }
3712
3713 N = providers.size();
3714 for (i=0; i<N; i++) {
3715 removeDyingProviderLocked(null, providers.get(i));
3716 }
3717
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003718 if (doit) {
3719 if (purgeCache) {
3720 AttributeCache ac = AttributeCache.instance();
3721 if (ac != null) {
3722 ac.removePackage(name);
3723 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003724 }
Dianne Hackborn38cc8962011-10-13 11:33:55 -07003725 if (mBooted) {
3726 mMainStack.resumeTopActivityLocked(null);
3727 mMainStack.scheduleIdleLocked();
3728 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003729 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003730
3731 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003732 }
3733
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003734 private final boolean removeProcessLocked(ProcessRecord app,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003735 boolean callerWillRestart, boolean allowRestart, String reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003736 final String name = app.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003737 final int uid = app.uid;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003738 if (DEBUG_PROCESSES) Slog.d(
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003739 TAG, "Force removing proc " + app.toShortString() + " (" + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003740 + "/" + uid + ")");
3741
3742 mProcessNames.remove(name, uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003743 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003744 if (mHeavyWeightProcess == app) {
3745 mHeavyWeightProcess = null;
3746 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3747 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003748 boolean needRestart = false;
3749 if (app.pid > 0 && app.pid != MY_PID) {
3750 int pid = app.pid;
3751 synchronized (mPidsSelfLocked) {
3752 mPidsSelfLocked.remove(pid);
3753 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3754 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003755 Slog.i(TAG, "Killing proc " + app.toShortString() + ": " + reason);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003756 handleAppDiedLocked(app, true, allowRestart);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003757 mLruProcesses.remove(app);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003758 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003759
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003760 if (app.persistent && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003761 if (!callerWillRestart) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003762 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003763 } else {
3764 needRestart = true;
3765 }
3766 }
3767 } else {
3768 mRemovedProcesses.add(app);
3769 }
3770
3771 return needRestart;
3772 }
3773
3774 private final void processStartTimedOutLocked(ProcessRecord app) {
3775 final int pid = app.pid;
3776 boolean gone = false;
3777 synchronized (mPidsSelfLocked) {
3778 ProcessRecord knownApp = mPidsSelfLocked.get(pid);
3779 if (knownApp != null && knownApp.thread == null) {
3780 mPidsSelfLocked.remove(pid);
3781 gone = true;
3782 }
3783 }
3784
3785 if (gone) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003786 Slog.w(TAG, "Process " + app + " failed to attach");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003787 EventLog.writeEvent(EventLogTags.AM_PROCESS_START_TIMEOUT, pid, app.uid,
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003788 app.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003789 mProcessNames.remove(app.processName, app.uid);
3790 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003791 if (mHeavyWeightProcess == app) {
3792 mHeavyWeightProcess = null;
3793 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3794 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003795 // Take care of any launching providers waiting for this process.
3796 checkAppInLaunchingProvidersLocked(app, true);
3797 // Take care of any services that are waiting for the process.
3798 for (int i=0; i<mPendingServices.size(); i++) {
3799 ServiceRecord sr = mPendingServices.get(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003800 if ((app.uid == sr.appInfo.uid
3801 && app.processName.equals(sr.processName))
3802 || sr.isolatedProc == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003803 Slog.w(TAG, "Forcing bringing down service: " + sr);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003804 sr.isolatedProc = null;
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003805 mPendingServices.remove(i);
3806 i--;
3807 bringDownServiceLocked(sr, true);
3808 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003809 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003810 EventLog.writeEvent(EventLogTags.AM_KILL, pid,
3811 app.processName, app.setAdj, "start timeout");
3812 Process.killProcessQuiet(pid);
Christopher Tate181fafa2009-05-14 11:12:14 -07003813 if (mBackupTarget != null && mBackupTarget.app.pid == pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003814 Slog.w(TAG, "Unattached app died before backup, skipping");
Christopher Tate181fafa2009-05-14 11:12:14 -07003815 try {
3816 IBackupManager bm = IBackupManager.Stub.asInterface(
3817 ServiceManager.getService(Context.BACKUP_SERVICE));
3818 bm.agentDisconnected(app.info.packageName);
3819 } catch (RemoteException e) {
3820 // Can't happen; the backup manager is local
3821 }
3822 }
Christopher Tatef46723b2012-01-26 14:19:24 -08003823 if (isPendingBroadcastProcessLocked(pid)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003824 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
Christopher Tatef46723b2012-01-26 14:19:24 -08003825 skipPendingBroadcastLocked(pid);
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003826 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003827 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003828 Slog.w(TAG, "Spurious process start timeout - pid not known for " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003829 }
3830 }
3831
3832 private final boolean attachApplicationLocked(IApplicationThread thread,
3833 int pid) {
3834
3835 // Find the application record that is being attached... either via
3836 // the pid if we are running in multiple processes, or just pull the
3837 // next app record if we are emulating process with anonymous threads.
3838 ProcessRecord app;
3839 if (pid != MY_PID && pid >= 0) {
3840 synchronized (mPidsSelfLocked) {
3841 app = mPidsSelfLocked.get(pid);
3842 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003843 } else {
3844 app = null;
3845 }
3846
3847 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003848 Slog.w(TAG, "No pending application record for pid " + pid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003849 + " (IApplicationThread " + thread + "); dropping process");
Doug Zongker2bec3d42009-12-04 12:52:44 -08003850 EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003851 if (pid > 0 && pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003852 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003853 } else {
3854 try {
3855 thread.scheduleExit();
3856 } catch (Exception e) {
3857 // Ignore exceptions.
3858 }
3859 }
3860 return false;
3861 }
3862
3863 // If this application record is still attached to a previous
3864 // process, clean it up now.
3865 if (app.thread != null) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003866 handleAppDiedLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003867 }
3868
3869 // Tell the process all about itself.
3870
Joe Onorato8a9b2202010-02-26 18:56:32 -08003871 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003872 TAG, "Binding process pid " + pid + " to record " + app);
3873
3874 String processName = app.processName;
3875 try {
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07003876 AppDeathRecipient adr = new AppDeathRecipient(
3877 app, pid, thread);
3878 thread.asBinder().linkToDeath(adr, 0);
3879 app.deathRecipient = adr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003880 } catch (RemoteException e) {
3881 app.resetPackageList();
3882 startProcessLocked(app, "link fail", processName);
3883 return false;
3884 }
3885
Doug Zongker2bec3d42009-12-04 12:52:44 -08003886 EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.pid, app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003887
3888 app.thread = thread;
3889 app.curAdj = app.setAdj = -100;
Dianne Hackborn09c916b2009-12-08 14:50:51 -08003890 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
3891 app.setSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003892 app.forcingToForeground = null;
3893 app.foregroundServices = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07003894 app.hasShownUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003895 app.debugging = false;
3896
3897 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3898
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003899 boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003900 List providers = normalMode ? generateApplicationProvidersLocked(app) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003901
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003902 if (!normalMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003903 Slog.i(TAG, "Launching preboot mode app: " + app);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003904 }
3905
Joe Onorato8a9b2202010-02-26 18:56:32 -08003906 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003907 TAG, "New app record " + app
3908 + " thread=" + thread.asBinder() + " pid=" + pid);
3909 try {
3910 int testMode = IApplicationThread.DEBUG_OFF;
3911 if (mDebugApp != null && mDebugApp.equals(processName)) {
3912 testMode = mWaitForDebugger
3913 ? IApplicationThread.DEBUG_WAIT
3914 : IApplicationThread.DEBUG_ON;
3915 app.debugging = true;
3916 if (mDebugTransient) {
3917 mDebugApp = mOrigDebugApp;
3918 mWaitForDebugger = mOrigWaitForDebugger;
3919 }
3920 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003921 String profileFile = app.instrumentationProfileFile;
3922 ParcelFileDescriptor profileFd = null;
3923 boolean profileAutoStop = false;
3924 if (mProfileApp != null && mProfileApp.equals(processName)) {
3925 mProfileProc = app;
3926 profileFile = mProfileFile;
3927 profileFd = mProfileFd;
3928 profileAutoStop = mAutoStopProfiler;
3929 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08003930 boolean enableOpenGlTrace = false;
3931 if (mOpenGlTraceApp != null && mOpenGlTraceApp.equals(processName)) {
3932 enableOpenGlTrace = true;
3933 mOpenGlTraceApp = null;
3934 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003935
Christopher Tate181fafa2009-05-14 11:12:14 -07003936 // If the app is being launched for restore or full backup, set it up specially
3937 boolean isRestrictedBackupMode = false;
3938 if (mBackupTarget != null && mBackupAppName.equals(processName)) {
3939 isRestrictedBackupMode = (mBackupTarget.backupMode == BackupRecord.RESTORE)
Christopher Tate75a99702011-05-18 16:28:19 -07003940 || (mBackupTarget.backupMode == BackupRecord.RESTORE_FULL)
Christopher Tate181fafa2009-05-14 11:12:14 -07003941 || (mBackupTarget.backupMode == BackupRecord.BACKUP_FULL);
3942 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003943
Dianne Hackbornd7f6daa2009-06-22 17:06:35 -07003944 ensurePackageDexOpt(app.instrumentationInfo != null
3945 ? app.instrumentationInfo.packageName
3946 : app.info.packageName);
3947 if (app.instrumentationClass != null) {
3948 ensurePackageDexOpt(app.instrumentationClass.getPackageName());
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003949 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08003950 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Binding proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003951 + processName + " with config " + mConfiguration);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003952 ApplicationInfo appInfo = app.instrumentationInfo != null
3953 ? app.instrumentationInfo : app.info;
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -07003954 app.compat = compatibilityInfoForPackageLocked(appInfo);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003955 if (profileFd != null) {
3956 profileFd = profileFd.dup();
3957 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003958 thread.bindApplication(processName, appInfo, providers,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003959 app.instrumentationClass, profileFile, profileFd, profileAutoStop,
Siva Velusamy92a8b222012-03-09 16:24:04 -08003960 app.instrumentationArguments, app.instrumentationWatcher, testMode,
3961 enableOpenGlTrace, isRestrictedBackupMode || !normalMode, app.persistent,
Dianne Hackborn813075a62011-11-14 17:45:19 -08003962 new Configuration(mConfiguration), app.compat, getCommonServicesLocked(),
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08003963 mCoreSettingsObserver.getCoreSettingsLocked());
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003964 updateLruProcessLocked(app, false, true);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003965 app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003966 } catch (Exception e) {
3967 // todo: Yikes! What should we do? For now we will try to
3968 // start another process, but that could easily get us in
3969 // an infinite loop of restarting processes...
Joe Onorato8a9b2202010-02-26 18:56:32 -08003970 Slog.w(TAG, "Exception thrown during bind!", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003971
3972 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07003973 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003974 startProcessLocked(app, "bind fail", processName);
3975 return false;
3976 }
3977
3978 // Remove this record from the list of starting applications.
3979 mPersistentStartingProcesses.remove(app);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003980 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
3981 "Attach application locked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003982 mProcessesOnHold.remove(app);
3983
3984 boolean badApp = false;
3985 boolean didSomething = false;
3986
3987 // See if the top visible activity is waiting to run in this process...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003988 ActivityRecord hr = mMainStack.topRunningActivityLocked(null);
Christopher Tate04c0af82010-06-07 18:35:20 -07003989 if (hr != null && normalMode) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003990 if (hr.app == null && app.uid == hr.info.applicationInfo.uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003991 && processName.equals(hr.processName)) {
3992 try {
Mike Lockwood3a74bd32011-08-12 13:55:22 -07003993 if (mHeadless) {
3994 Slog.e(TAG, "Starting activities not supported on headless device: " + hr);
3995 } else if (mMainStack.realStartActivityLocked(hr, app, true, true)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003996 didSomething = true;
3997 }
3998 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003999 Slog.w(TAG, "Exception in new application when starting activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004000 + hr.intent.getComponent().flattenToShortString(), e);
4001 badApp = true;
4002 }
4003 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004004 mMainStack.ensureActivitiesVisibleLocked(hr, null, processName, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004005 }
4006 }
4007
4008 // Find any services that should be running in this process...
4009 if (!badApp && mPendingServices.size() > 0) {
4010 ServiceRecord sr = null;
4011 try {
4012 for (int i=0; i<mPendingServices.size(); i++) {
4013 sr = mPendingServices.get(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004014 if (app != sr.isolatedProc && (app.uid != sr.appInfo.uid
4015 || !processName.equals(sr.processName))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004016 continue;
4017 }
4018
4019 mPendingServices.remove(i);
4020 i--;
4021 realStartServiceLocked(sr, app);
4022 didSomething = true;
4023 }
4024 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004025 Slog.w(TAG, "Exception in new application when starting service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004026 + sr.shortName, e);
4027 badApp = true;
4028 }
4029 }
4030
Christopher Tatef46723b2012-01-26 14:19:24 -08004031 // Check if a next-broadcast receiver is in this process...
4032 if (!badApp && isPendingBroadcastProcessLocked(pid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004033 try {
Christopher Tatef46723b2012-01-26 14:19:24 -08004034 didSomething = sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004035 } catch (Exception e) {
Christopher Tatef46723b2012-01-26 14:19:24 -08004036 // If the app died trying to launch the receiver we declare it 'bad'
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004037 badApp = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004038 }
4039 }
4040
Christopher Tate181fafa2009-05-14 11:12:14 -07004041 // Check whether the next backup agent is in this process...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004042 if (!badApp && mBackupTarget != null && mBackupTarget.appInfo.uid == app.uid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004043 if (DEBUG_BACKUP) Slog.v(TAG, "New app is backup target, launching agent for " + app);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004044 ensurePackageDexOpt(mBackupTarget.appInfo.packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07004045 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004046 thread.scheduleCreateBackupAgent(mBackupTarget.appInfo,
4047 compatibilityInfoForPackageLocked(mBackupTarget.appInfo),
4048 mBackupTarget.backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -07004049 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004050 Slog.w(TAG, "Exception scheduling backup agent creation: ");
Christopher Tate181fafa2009-05-14 11:12:14 -07004051 e.printStackTrace();
4052 }
4053 }
4054
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004055 if (badApp) {
4056 // todo: Also need to kill application to deal with all
4057 // kinds of exceptions.
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004058 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004059 return false;
4060 }
4061
4062 if (!didSomething) {
4063 updateOomAdjLocked();
4064 }
4065
4066 return true;
4067 }
4068
4069 public final void attachApplication(IApplicationThread thread) {
4070 synchronized (this) {
4071 int callingPid = Binder.getCallingPid();
4072 final long origId = Binder.clearCallingIdentity();
4073 attachApplicationLocked(thread, callingPid);
4074 Binder.restoreCallingIdentity(origId);
4075 }
4076 }
4077
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004078 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004079 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004080 ActivityRecord r = mMainStack.activityIdleInternal(token, false, config);
4081 if (stopProfiling) {
4082 synchronized (this) {
4083 if (mProfileProc == r.app) {
4084 if (mProfileFd != null) {
4085 try {
4086 mProfileFd.close();
4087 } catch (IOException e) {
4088 }
4089 clearProfilerLocked();
4090 }
4091 }
4092 }
4093 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004094 Binder.restoreCallingIdentity(origId);
4095 }
4096
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004097 void enableScreenAfterBoot() {
Doug Zongker2bec3d42009-12-04 12:52:44 -08004098 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004099 SystemClock.uptimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004100 mWindowManager.enableScreenAfterBoot();
Jeff Brownc042ee22012-05-08 13:03:42 -07004101
4102 synchronized (this) {
4103 updateEventDispatchingLocked();
4104 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004105 }
4106
Dianne Hackborn661cd522011-08-22 00:26:20 -07004107 public void showBootMessage(final CharSequence msg, final boolean always) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004108 enforceNotIsolatedCaller("showBootMessage");
Dianne Hackborn661cd522011-08-22 00:26:20 -07004109 mWindowManager.showBootMessage(msg, always);
4110 }
4111
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004112 public void dismissKeyguardOnNextActivity() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004113 enforceNotIsolatedCaller("dismissKeyguardOnNextActivity");
Jeff Sharkey7ffaa982012-04-30 16:59:05 -07004114 final long token = Binder.clearCallingIdentity();
4115 try {
4116 synchronized (this) {
4117 if (mLockScreenShown) {
4118 mLockScreenShown = false;
4119 comeOutOfSleepIfNeededLocked();
4120 }
4121 mMainStack.dismissKeyguardOnNextActivityLocked();
Dianne Hackborn1e88e982012-04-24 18:35:55 -07004122 }
Jeff Sharkey7ffaa982012-04-30 16:59:05 -07004123 } finally {
4124 Binder.restoreCallingIdentity(token);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004125 }
4126 }
4127
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004128 final void finishBooting() {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004129 IntentFilter pkgFilter = new IntentFilter();
4130 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
4131 pkgFilter.addDataScheme("package");
4132 mContext.registerReceiver(new BroadcastReceiver() {
4133 @Override
4134 public void onReceive(Context context, Intent intent) {
4135 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
4136 if (pkgs != null) {
4137 for (String pkg : pkgs) {
Vairavan Srinivasan61f07652010-07-22 13:36:40 -07004138 synchronized (ActivityManagerService.this) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07004139 if (forceStopPackageLocked(pkg, -1, false, false, false, false, 0)) {
4140 setResultCode(Activity.RESULT_OK);
4141 return;
4142 }
4143 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004144 }
4145 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004146 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004147 }, pkgFilter);
Amith Yamasani13593602012-03-22 16:16:17 -07004148
4149 IntentFilter userFilter = new IntentFilter();
4150 userFilter.addAction(Intent.ACTION_USER_REMOVED);
4151 mContext.registerReceiver(new BroadcastReceiver() {
4152 @Override
4153 public void onReceive(Context context, Intent intent) {
4154 onUserRemoved(intent);
4155 }
4156 }, userFilter);
4157
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004158 synchronized (this) {
4159 // Ensure that any processes we had put on hold are now started
4160 // up.
4161 final int NP = mProcessesOnHold.size();
4162 if (NP > 0) {
4163 ArrayList<ProcessRecord> procs =
4164 new ArrayList<ProcessRecord>(mProcessesOnHold);
4165 for (int ip=0; ip<NP; ip++) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004166 if (DEBUG_PROCESSES) Slog.v(TAG, "Starting process on hold: "
4167 + procs.get(ip));
4168 startProcessLocked(procs.get(ip), "on-hold", null);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004169 }
4170 }
4171
4172 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004173 // Start looking for apps that are abusing wake locks.
4174 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07004175 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004176 // Tell anyone interested that we are done booting!
Dianne Hackbornf4c454b2010-08-11 12:47:41 -07004177 SystemProperties.set("sys.boot_completed", "1");
Guang Zhu191713a2012-01-12 12:02:22 -08004178 SystemProperties.set("dev.bootcomplete", "1");
Amith Yamasani742a6712011-05-04 14:49:28 -07004179 /* TODO: Send this to all users that are to be logged in on startup */
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004180 broadcastIntentLocked(null, null,
4181 new Intent(Intent.ACTION_BOOT_COMPLETED, null),
4182 null, null, 0, null, null,
4183 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
Amith Yamasani742a6712011-05-04 14:49:28 -07004184 false, false, MY_PID, Process.SYSTEM_UID, Binder.getOrigCallingUser());
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004185 }
4186 }
4187 }
4188
4189 final void ensureBootCompleted() {
4190 boolean booting;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004191 boolean enableScreen;
4192 synchronized (this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004193 booting = mBooting;
4194 mBooting = false;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004195 enableScreen = !mBooted;
4196 mBooted = true;
4197 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004198
4199 if (booting) {
4200 finishBooting();
4201 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004202
4203 if (enableScreen) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004204 enableScreenAfterBoot();
4205 }
4206 }
4207
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004208 public final void activityPaused(IBinder token) {
4209 final long origId = Binder.clearCallingIdentity();
4210 mMainStack.activityPaused(token, false);
4211 Binder.restoreCallingIdentity(origId);
4212 }
4213
4214 public final void activityStopped(IBinder token, Bundle icicle, Bitmap thumbnail,
4215 CharSequence description) {
4216 if (localLOGV) Slog.v(
4217 TAG, "Activity stopped: token=" + token);
4218
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004219 // Refuse possible leaked file descriptors
4220 if (icicle != null && icicle.hasFileDescriptors()) {
4221 throw new IllegalArgumentException("File descriptors passed in Bundle");
4222 }
4223
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004224 ActivityRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004225
4226 final long origId = Binder.clearCallingIdentity();
4227
4228 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004229 r = mMainStack.isInStackLocked(token);
4230 if (r != null) {
4231 r.stack.activityStoppedLocked(r, icicle, thumbnail, description);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004232 }
4233 }
4234
4235 if (r != null) {
4236 sendPendingThumbnail(r, null, null, null, false);
4237 }
4238
4239 trimApplications();
4240
4241 Binder.restoreCallingIdentity(origId);
4242 }
4243
4244 public final void activityDestroyed(IBinder token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004245 if (DEBUG_SWITCH) Slog.v(TAG, "ACTIVITY DESTROYED: " + token);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004246 mMainStack.activityDestroyed(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004247 }
4248
4249 public String getCallingPackage(IBinder token) {
4250 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004251 ActivityRecord r = getCallingRecordLocked(token);
Dianne Hackborn9bbcb912009-10-20 15:42:38 -07004252 return r != null && r.app != null ? r.info.packageName : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004253 }
4254 }
4255
4256 public ComponentName getCallingActivity(IBinder token) {
4257 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004258 ActivityRecord r = getCallingRecordLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004259 return r != null ? r.intent.getComponent() : null;
4260 }
4261 }
4262
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004263 private ActivityRecord getCallingRecordLocked(IBinder token) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004264 ActivityRecord r = mMainStack.isInStackLocked(token);
4265 if (r == null) {
4266 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004267 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004268 return r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004269 }
4270
4271 public ComponentName getActivityClassForToken(IBinder token) {
4272 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004273 ActivityRecord r = mMainStack.isInStackLocked(token);
4274 if (r == null) {
4275 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004276 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004277 return r.intent.getComponent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004278 }
4279 }
4280
4281 public String getPackageForToken(IBinder token) {
4282 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004283 ActivityRecord r = mMainStack.isInStackLocked(token);
4284 if (r == null) {
4285 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004286 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004287 return r.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004288 }
4289 }
4290
4291 public IIntentSender getIntentSender(int type,
4292 String packageName, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004293 int requestCode, Intent[] intents, String[] resolvedTypes,
4294 int flags, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004295 enforceNotIsolatedCaller("getIntentSender");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004296 // Refuse possible leaked file descriptors
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004297 if (intents != null) {
4298 if (intents.length < 1) {
4299 throw new IllegalArgumentException("Intents array length must be >= 1");
4300 }
4301 for (int i=0; i<intents.length; i++) {
4302 Intent intent = intents[i];
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004303 if (intent != null) {
4304 if (intent.hasFileDescriptors()) {
4305 throw new IllegalArgumentException("File descriptors passed in Intent");
4306 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07004307 if (type == ActivityManager.INTENT_SENDER_BROADCAST &&
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004308 (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
4309 throw new IllegalArgumentException(
4310 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
4311 }
4312 intents[i] = new Intent(intent);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004313 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004314 }
4315 if (resolvedTypes != null && resolvedTypes.length != intents.length) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004316 throw new IllegalArgumentException(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004317 "Intent array length does not match resolvedTypes length");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004318 }
4319 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004320 if (options != null) {
4321 if (options.hasFileDescriptors()) {
4322 throw new IllegalArgumentException("File descriptors passed in options");
4323 }
4324 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004325
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004326 synchronized(this) {
4327 int callingUid = Binder.getCallingUid();
4328 try {
Jeff Brown10e89712011-07-08 18:52:57 -07004329 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004330 int uid = AppGlobals.getPackageManager()
Amith Yamasani483f3b02012-03-13 16:08:00 -07004331 .getPackageUid(packageName, UserId.getUserId(callingUid));
4332 if (!UserId.isSameApp(callingUid, uid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004333 String msg = "Permission Denial: getIntentSender() from pid="
4334 + Binder.getCallingPid()
4335 + ", uid=" + Binder.getCallingUid()
4336 + ", (need uid=" + uid + ")"
4337 + " is not allowed to send as package " + packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004338 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004339 throw new SecurityException(msg);
4340 }
4341 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004342
Amith Yamasani742a6712011-05-04 14:49:28 -07004343 if (DEBUG_MU)
4344 Slog.i(TAG_MU, "Getting intent sender for origCallingUid="
4345 + Binder.getOrigCallingUid());
4346 return getIntentSenderLocked(type, packageName, Binder.getOrigCallingUid(),
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004347 token, resultWho, requestCode, intents, resolvedTypes, flags, options);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004348
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004349 } catch (RemoteException e) {
4350 throw new SecurityException(e);
4351 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004352 }
4353 }
4354
4355 IIntentSender getIntentSenderLocked(int type,
4356 String packageName, int callingUid, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004357 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
4358 Bundle options) {
Amith Yamasani742a6712011-05-04 14:49:28 -07004359 if (DEBUG_MU)
4360 Slog.v(TAG_MU, "getIntentSenderLocked(): uid=" + callingUid);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004361 ActivityRecord activity = null;
Dianne Hackborna4972e92012-03-14 10:38:05 -07004362 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004363 activity = mMainStack.isInStackLocked(token);
4364 if (activity == null) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004365 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004366 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004367 if (activity.finishing) {
4368 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004369 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004370 }
4371
4372 final boolean noCreate = (flags&PendingIntent.FLAG_NO_CREATE) != 0;
4373 final boolean cancelCurrent = (flags&PendingIntent.FLAG_CANCEL_CURRENT) != 0;
4374 final boolean updateCurrent = (flags&PendingIntent.FLAG_UPDATE_CURRENT) != 0;
4375 flags &= ~(PendingIntent.FLAG_NO_CREATE|PendingIntent.FLAG_CANCEL_CURRENT
4376 |PendingIntent.FLAG_UPDATE_CURRENT);
4377
4378 PendingIntentRecord.Key key = new PendingIntentRecord.Key(
4379 type, packageName, activity, resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004380 requestCode, intents, resolvedTypes, flags, options);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004381 WeakReference<PendingIntentRecord> ref;
4382 ref = mIntentSenderRecords.get(key);
4383 PendingIntentRecord rec = ref != null ? ref.get() : null;
4384 if (rec != null) {
4385 if (!cancelCurrent) {
4386 if (updateCurrent) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004387 if (rec.key.requestIntent != null) {
Adam Powell501d4a52012-04-30 15:03:57 -07004388 rec.key.requestIntent.replaceExtras(intents != null ?
4389 intents[intents.length - 1] : null);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004390 }
4391 if (intents != null) {
4392 intents[intents.length-1] = rec.key.requestIntent;
4393 rec.key.allIntents = intents;
4394 rec.key.allResolvedTypes = resolvedTypes;
4395 } else {
4396 rec.key.allIntents = null;
4397 rec.key.allResolvedTypes = null;
4398 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004399 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004400 return rec;
4401 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004402 rec.canceled = true;
4403 mIntentSenderRecords.remove(key);
4404 }
4405 if (noCreate) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004406 return rec;
4407 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004408 rec = new PendingIntentRecord(this, key, callingUid);
4409 mIntentSenderRecords.put(key, rec.ref);
Dianne Hackborna4972e92012-03-14 10:38:05 -07004410 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004411 if (activity.pendingResults == null) {
4412 activity.pendingResults
4413 = new HashSet<WeakReference<PendingIntentRecord>>();
4414 }
4415 activity.pendingResults.add(rec.ref);
4416 }
4417 return rec;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004418 }
4419
4420 public void cancelIntentSender(IIntentSender sender) {
4421 if (!(sender instanceof PendingIntentRecord)) {
4422 return;
4423 }
4424 synchronized(this) {
4425 PendingIntentRecord rec = (PendingIntentRecord)sender;
4426 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004427 int uid = AppGlobals.getPackageManager()
Amith Yamasani483f3b02012-03-13 16:08:00 -07004428 .getPackageUid(rec.key.packageName, UserId.getCallingUserId());
Amith Yamasani04e0d262012-02-14 11:50:53 -08004429 if (!UserId.isSameApp(uid, Binder.getCallingUid())) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004430 String msg = "Permission Denial: cancelIntentSender() from pid="
4431 + Binder.getCallingPid()
4432 + ", uid=" + Binder.getCallingUid()
4433 + " is not allowed to cancel packges "
4434 + rec.key.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004435 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004436 throw new SecurityException(msg);
4437 }
4438 } catch (RemoteException e) {
4439 throw new SecurityException(e);
4440 }
4441 cancelIntentSenderLocked(rec, true);
4442 }
4443 }
4444
4445 void cancelIntentSenderLocked(PendingIntentRecord rec, boolean cleanActivity) {
4446 rec.canceled = true;
4447 mIntentSenderRecords.remove(rec.key);
4448 if (cleanActivity && rec.key.activity != null) {
4449 rec.key.activity.pendingResults.remove(rec.ref);
4450 }
4451 }
4452
4453 public String getPackageForIntentSender(IIntentSender pendingResult) {
4454 if (!(pendingResult instanceof PendingIntentRecord)) {
4455 return null;
4456 }
Brad Fitzpatrickb213d102010-04-19 11:58:52 -07004457 try {
4458 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4459 return res.key.packageName;
4460 } catch (ClassCastException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004461 }
4462 return null;
4463 }
4464
Christopher Tatec4a07d12012-04-06 14:19:13 -07004465 public int getUidForIntentSender(IIntentSender sender) {
4466 if (sender instanceof PendingIntentRecord) {
4467 try {
4468 PendingIntentRecord res = (PendingIntentRecord)sender;
4469 return res.uid;
4470 } catch (ClassCastException e) {
4471 }
4472 }
4473 return -1;
4474 }
4475
Dianne Hackborn6c418d52011-06-29 14:05:33 -07004476 public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) {
4477 if (!(pendingResult instanceof PendingIntentRecord)) {
4478 return false;
4479 }
4480 try {
4481 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4482 if (res.key.allIntents == null) {
4483 return false;
4484 }
4485 for (int i=0; i<res.key.allIntents.length; i++) {
4486 Intent intent = res.key.allIntents[i];
4487 if (intent.getPackage() != null && intent.getComponent() != null) {
4488 return false;
4489 }
4490 }
4491 return true;
4492 } catch (ClassCastException e) {
4493 }
4494 return false;
4495 }
4496
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004497 public void setProcessLimit(int max) {
4498 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4499 "setProcessLimit()");
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004500 synchronized (this) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07004501 mProcessLimit = max < 0 ? ProcessList.MAX_HIDDEN_APPS : max;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004502 mProcessLimitOverride = max;
4503 }
4504 trimApplications();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004505 }
4506
4507 public int getProcessLimit() {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004508 synchronized (this) {
4509 return mProcessLimitOverride;
4510 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004511 }
4512
4513 void foregroundTokenDied(ForegroundToken token) {
4514 synchronized (ActivityManagerService.this) {
4515 synchronized (mPidsSelfLocked) {
4516 ForegroundToken cur
4517 = mForegroundProcesses.get(token.pid);
4518 if (cur != token) {
4519 return;
4520 }
4521 mForegroundProcesses.remove(token.pid);
4522 ProcessRecord pr = mPidsSelfLocked.get(token.pid);
4523 if (pr == null) {
4524 return;
4525 }
4526 pr.forcingToForeground = null;
4527 pr.foregroundServices = false;
4528 }
4529 updateOomAdjLocked();
4530 }
4531 }
4532
4533 public void setProcessForeground(IBinder token, int pid, boolean isForeground) {
4534 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4535 "setProcessForeground()");
4536 synchronized(this) {
4537 boolean changed = false;
4538
4539 synchronized (mPidsSelfLocked) {
4540 ProcessRecord pr = mPidsSelfLocked.get(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004541 if (pr == null && isForeground) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004542 Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004543 return;
4544 }
4545 ForegroundToken oldToken = mForegroundProcesses.get(pid);
4546 if (oldToken != null) {
4547 oldToken.token.unlinkToDeath(oldToken, 0);
4548 mForegroundProcesses.remove(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004549 if (pr != null) {
4550 pr.forcingToForeground = null;
4551 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004552 changed = true;
4553 }
4554 if (isForeground && token != null) {
4555 ForegroundToken newToken = new ForegroundToken() {
4556 public void binderDied() {
4557 foregroundTokenDied(this);
4558 }
4559 };
4560 newToken.pid = pid;
4561 newToken.token = token;
4562 try {
4563 token.linkToDeath(newToken, 0);
4564 mForegroundProcesses.put(pid, newToken);
4565 pr.forcingToForeground = token;
4566 changed = true;
4567 } catch (RemoteException e) {
4568 // If the process died while doing this, we will later
4569 // do the cleanup with the process death link.
4570 }
4571 }
4572 }
4573
4574 if (changed) {
4575 updateOomAdjLocked();
4576 }
4577 }
4578 }
4579
4580 // =========================================================
4581 // PERMISSIONS
4582 // =========================================================
4583
4584 static class PermissionController extends IPermissionController.Stub {
4585 ActivityManagerService mActivityManagerService;
4586 PermissionController(ActivityManagerService activityManagerService) {
4587 mActivityManagerService = activityManagerService;
4588 }
4589
4590 public boolean checkPermission(String permission, int pid, int uid) {
4591 return mActivityManagerService.checkPermission(permission, pid,
4592 uid) == PackageManager.PERMISSION_GRANTED;
4593 }
4594 }
4595
4596 /**
4597 * This can be called with or without the global lock held.
4598 */
4599 int checkComponentPermission(String permission, int pid, int uid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004600 int owningUid, boolean exported) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004601 // We might be performing an operation on behalf of an indirect binder
4602 // invocation, e.g. via {@link #openContentUri}. Check and adjust the
4603 // client identity accordingly before proceeding.
4604 Identity tlsIdentity = sCallerIdentity.get();
4605 if (tlsIdentity != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004606 Slog.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004607 + tlsIdentity.pid + "," + tlsIdentity.uid + "}");
4608 uid = tlsIdentity.uid;
4609 pid = tlsIdentity.pid;
4610 }
4611
4612 // Root, system server and our own process get to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07004613 if (uid == 0 || uid == Process.SYSTEM_UID || pid == MY_PID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004614 return PackageManager.PERMISSION_GRANTED;
4615 }
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004616 // Isolated processes don't get any permissions.
4617 if (UserId.isIsolated(uid)) {
4618 return PackageManager.PERMISSION_DENIED;
4619 }
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004620 // If there is a uid that owns whatever is being accessed, it has
4621 // blanket access to it regardless of the permissions it requires.
Amith Yamasani742a6712011-05-04 14:49:28 -07004622 if (owningUid >= 0 && UserId.isSameApp(uid, owningUid)) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004623 return PackageManager.PERMISSION_GRANTED;
4624 }
4625 // If the target is not exported, then nobody else can get to it.
4626 if (!exported) {
4627 Slog.w(TAG, "Permission denied: checkComponentPermission() owningUid=" + owningUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004628 return PackageManager.PERMISSION_DENIED;
4629 }
4630 if (permission == null) {
4631 return PackageManager.PERMISSION_GRANTED;
4632 }
4633 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004634 return AppGlobals.getPackageManager()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004635 .checkUidPermission(permission, uid);
4636 } catch (RemoteException e) {
4637 // Should never happen, but if it does... deny!
Joe Onorato8a9b2202010-02-26 18:56:32 -08004638 Slog.e(TAG, "PackageManager is dead?!?", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004639 }
4640 return PackageManager.PERMISSION_DENIED;
4641 }
4642
4643 /**
4644 * As the only public entry point for permissions checking, this method
4645 * can enforce the semantic that requesting a check on a null global
4646 * permission is automatically denied. (Internally a null permission
4647 * string is used when calling {@link #checkComponentPermission} in cases
4648 * when only uid-based security is needed.)
4649 *
4650 * This can be called with or without the global lock held.
4651 */
4652 public int checkPermission(String permission, int pid, int uid) {
4653 if (permission == null) {
4654 return PackageManager.PERMISSION_DENIED;
4655 }
Amith Yamasani742a6712011-05-04 14:49:28 -07004656 return checkComponentPermission(permission, pid, UserId.getAppId(uid), -1, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004657 }
4658
4659 /**
4660 * Binder IPC calls go through the public entry point.
4661 * This can be called with or without the global lock held.
4662 */
4663 int checkCallingPermission(String permission) {
4664 return checkPermission(permission,
4665 Binder.getCallingPid(),
Amith Yamasani742a6712011-05-04 14:49:28 -07004666 UserId.getAppId(Binder.getCallingUid()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004667 }
4668
4669 /**
4670 * This can be called with or without the global lock held.
4671 */
4672 void enforceCallingPermission(String permission, String func) {
4673 if (checkCallingPermission(permission)
4674 == PackageManager.PERMISSION_GRANTED) {
4675 return;
4676 }
4677
4678 String msg = "Permission Denial: " + func + " from pid="
4679 + Binder.getCallingPid()
4680 + ", uid=" + Binder.getCallingUid()
4681 + " requires " + permission;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004682 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004683 throw new SecurityException(msg);
4684 }
4685
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004686 /**
4687 * Determine if UID is holding permissions required to access {@link Uri} in
4688 * the given {@link ProviderInfo}. Final permission checking is always done
4689 * in {@link ContentProvider}.
4690 */
4691 private final boolean checkHoldingPermissionsLocked(
4692 IPackageManager pm, ProviderInfo pi, Uri uri, int uid, int modeFlags) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004693 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4694 "checkHoldingPermissionsLocked: uri=" + uri + " uid=" + uid);
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004695
4696 if (pi.applicationInfo.uid == uid) {
4697 return true;
4698 } else if (!pi.exported) {
4699 return false;
4700 }
4701
4702 boolean readMet = (modeFlags & Intent.FLAG_GRANT_READ_URI_PERMISSION) == 0;
4703 boolean writeMet = (modeFlags & Intent.FLAG_GRANT_WRITE_URI_PERMISSION) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004704 try {
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004705 // check if target holds top-level <provider> permissions
4706 if (!readMet && pi.readPermission != null
4707 && (pm.checkUidPermission(pi.readPermission, uid) == PERMISSION_GRANTED)) {
4708 readMet = true;
4709 }
4710 if (!writeMet && pi.writePermission != null
4711 && (pm.checkUidPermission(pi.writePermission, uid) == PERMISSION_GRANTED)) {
4712 writeMet = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004713 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004714
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004715 // track if unprotected read/write is allowed; any denied
4716 // <path-permission> below removes this ability
4717 boolean allowDefaultRead = pi.readPermission == null;
4718 boolean allowDefaultWrite = pi.writePermission == null;
Dianne Hackborn48058e82010-09-27 16:53:23 -07004719
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004720 // check if target holds any <path-permission> that match uri
4721 final PathPermission[] pps = pi.pathPermissions;
4722 if (pps != null) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004723 final String path = uri.getPath();
4724 int i = pps.length;
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004725 while (i > 0 && (!readMet || !writeMet)) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004726 i--;
4727 PathPermission pp = pps[i];
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004728 if (pp.match(path)) {
4729 if (!readMet) {
4730 final String pprperm = pp.getReadPermission();
4731 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking read perm for "
4732 + pprperm + " for " + pp.getPath()
4733 + ": match=" + pp.match(path)
4734 + " check=" + pm.checkUidPermission(pprperm, uid));
4735 if (pprperm != null) {
4736 if (pm.checkUidPermission(pprperm, uid) == PERMISSION_GRANTED) {
4737 readMet = true;
4738 } else {
4739 allowDefaultRead = false;
4740 }
4741 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004742 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004743 if (!writeMet) {
4744 final String ppwperm = pp.getWritePermission();
4745 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking write perm "
4746 + ppwperm + " for " + pp.getPath()
4747 + ": match=" + pp.match(path)
4748 + " check=" + pm.checkUidPermission(ppwperm, uid));
4749 if (ppwperm != null) {
4750 if (pm.checkUidPermission(ppwperm, uid) == PERMISSION_GRANTED) {
4751 writeMet = true;
4752 } else {
4753 allowDefaultWrite = false;
4754 }
4755 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004756 }
4757 }
4758 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07004759 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004760
4761 // grant unprotected <provider> read/write, if not blocked by
4762 // <path-permission> above
4763 if (allowDefaultRead) readMet = true;
4764 if (allowDefaultWrite) writeMet = true;
4765
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004766 } catch (RemoteException e) {
4767 return false;
4768 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004769
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004770 return readMet && writeMet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004771 }
4772
4773 private final boolean checkUriPermissionLocked(Uri uri, int uid,
4774 int modeFlags) {
4775 // Root gets to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07004776 if (uid == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004777 return true;
4778 }
4779 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(uid);
4780 if (perms == null) return false;
4781 UriPermission perm = perms.get(uri);
4782 if (perm == null) return false;
4783 return (modeFlags&perm.modeFlags) == modeFlags;
4784 }
4785
4786 public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004787 enforceNotIsolatedCaller("checkUriPermission");
4788
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004789 // Another redirected-binder-call permissions check as in
4790 // {@link checkComponentPermission}.
4791 Identity tlsIdentity = sCallerIdentity.get();
4792 if (tlsIdentity != null) {
4793 uid = tlsIdentity.uid;
4794 pid = tlsIdentity.pid;
4795 }
4796
Amith Yamasani742a6712011-05-04 14:49:28 -07004797 uid = UserId.getAppId(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004798 // Our own process gets to do everything.
4799 if (pid == MY_PID) {
4800 return PackageManager.PERMISSION_GRANTED;
4801 }
4802 synchronized(this) {
4803 return checkUriPermissionLocked(uri, uid, modeFlags)
4804 ? PackageManager.PERMISSION_GRANTED
4805 : PackageManager.PERMISSION_DENIED;
4806 }
4807 }
4808
Dianne Hackborn39792d22010-08-19 18:01:52 -07004809 /**
4810 * Check if the targetPkg can be granted permission to access uri by
4811 * the callingUid using the given modeFlags. Throws a security exception
4812 * if callingUid is not allowed to do this. Returns the uid of the target
4813 * if the URI permission grant should be performed; returns -1 if it is not
4814 * needed (for example targetPkg already has permission to access the URI).
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004815 * If you already know the uid of the target, you can supply it in
4816 * lastTargetUid else set that to -1.
Dianne Hackborn39792d22010-08-19 18:01:52 -07004817 */
4818 int checkGrantUriPermissionLocked(int callingUid, String targetPkg,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004819 Uri uri, int modeFlags, int lastTargetUid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004820 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4821 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4822 if (modeFlags == 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004823 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004824 }
4825
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004826 if (targetPkg != null) {
4827 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4828 "Checking grant " + targetPkg + " permission to " + uri);
4829 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004830
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004831 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004832
4833 // If this is not a content: uri, we can't do anything with it.
4834 if (!ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004835 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004836 "Can't grant URI permission for non-content URI: " + uri);
Dianne Hackborn39792d22010-08-19 18:01:52 -07004837 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004838 }
4839
4840 String name = uri.getAuthority();
4841 ProviderInfo pi = null;
Amith Yamasani742a6712011-05-04 14:49:28 -07004842 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
4843 UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004844 if (cpr != null) {
4845 pi = cpr.info;
4846 } else {
4847 try {
4848 pi = pm.resolveContentProvider(name,
Amith Yamasani483f3b02012-03-13 16:08:00 -07004849 PackageManager.GET_URI_PERMISSION_PATTERNS, UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004850 } catch (RemoteException ex) {
4851 }
4852 }
4853 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07004854 Slog.w(TAG, "No content provider found for permission check: " + uri.toSafeString());
Dianne Hackborn39792d22010-08-19 18:01:52 -07004855 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004856 }
4857
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004858 int targetUid = lastTargetUid;
4859 if (targetUid < 0 && targetPkg != null) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004860 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07004861 targetUid = pm.getPackageUid(targetPkg, UserId.getUserId(callingUid));
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004862 if (targetUid < 0) {
4863 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4864 "Can't grant URI permission no uid for: " + targetPkg);
4865 return -1;
4866 }
4867 } catch (RemoteException ex) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004868 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004869 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004870 }
4871
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004872 if (targetUid >= 0) {
4873 // First... does the target actually need this permission?
4874 if (checkHoldingPermissionsLocked(pm, pi, uri, targetUid, modeFlags)) {
4875 // No need to grant the target this permission.
4876 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4877 "Target " + targetPkg + " already has full permission to " + uri);
4878 return -1;
4879 }
4880 } else {
4881 // First... there is no target package, so can anyone access it?
4882 boolean allowed = pi.exported;
4883 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
4884 if (pi.readPermission != null) {
4885 allowed = false;
4886 }
4887 }
4888 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
4889 if (pi.writePermission != null) {
4890 allowed = false;
4891 }
4892 }
4893 if (allowed) {
4894 return -1;
4895 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004896 }
4897
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004898 // Second... is the provider allowing granting of URI permissions?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004899 if (!pi.grantUriPermissions) {
4900 throw new SecurityException("Provider " + pi.packageName
4901 + "/" + pi.name
4902 + " does not allow granting of Uri permissions (uri "
4903 + uri + ")");
4904 }
4905 if (pi.uriPermissionPatterns != null) {
4906 final int N = pi.uriPermissionPatterns.length;
4907 boolean allowed = false;
4908 for (int i=0; i<N; i++) {
4909 if (pi.uriPermissionPatterns[i] != null
4910 && pi.uriPermissionPatterns[i].match(uri.getPath())) {
4911 allowed = true;
4912 break;
4913 }
4914 }
4915 if (!allowed) {
4916 throw new SecurityException("Provider " + pi.packageName
4917 + "/" + pi.name
4918 + " does not allow granting of permission to path of Uri "
4919 + uri);
4920 }
4921 }
4922
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004923 // Third... does the caller itself have permission to access
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004924 // this uri?
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004925 if (callingUid != Process.myUid()) {
4926 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
4927 if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
4928 throw new SecurityException("Uid " + callingUid
4929 + " does not have permission to uri " + uri);
4930 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004931 }
4932 }
4933
Dianne Hackborn39792d22010-08-19 18:01:52 -07004934 return targetUid;
4935 }
4936
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004937 public int checkGrantUriPermission(int callingUid, String targetPkg,
4938 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004939 enforceNotIsolatedCaller("checkGrantUriPermission");
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004940 synchronized(this) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004941 return checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004942 }
4943 }
4944
Dianne Hackborn39792d22010-08-19 18:01:52 -07004945 void grantUriPermissionUncheckedLocked(int targetUid, String targetPkg,
4946 Uri uri, int modeFlags, UriPermissionOwner owner) {
4947 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4948 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4949 if (modeFlags == 0) {
4950 return;
4951 }
4952
4953 // So here we are: the caller has the assumed permission
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004954 // to the uri, and the target doesn't. Let's now give this to
4955 // the target.
4956
Joe Onorato8a9b2202010-02-26 18:56:32 -08004957 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn39792d22010-08-19 18:01:52 -07004958 "Granting " + targetPkg + "/" + targetUid + " permission to " + uri);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004959
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004960 HashMap<Uri, UriPermission> targetUris
4961 = mGrantedUriPermissions.get(targetUid);
4962 if (targetUris == null) {
4963 targetUris = new HashMap<Uri, UriPermission>();
4964 mGrantedUriPermissions.put(targetUid, targetUris);
4965 }
4966
4967 UriPermission perm = targetUris.get(uri);
4968 if (perm == null) {
4969 perm = new UriPermission(targetUid, uri);
4970 targetUris.put(uri, perm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004971 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07004972
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004973 perm.modeFlags |= modeFlags;
Dianne Hackborn39792d22010-08-19 18:01:52 -07004974 if (owner == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004975 perm.globalModeFlags |= modeFlags;
Vairavan Srinivasan91c12c22011-01-21 18:26:06 -08004976 } else {
4977 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
4978 perm.readOwners.add(owner);
4979 owner.addReadPermission(perm);
4980 }
4981 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
4982 perm.writeOwners.add(owner);
4983 owner.addWritePermission(perm);
4984 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004985 }
4986 }
4987
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004988 void grantUriPermissionLocked(int callingUid, String targetPkg, Uri uri,
4989 int modeFlags, UriPermissionOwner owner) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004990 if (targetPkg == null) {
4991 throw new NullPointerException("targetPkg");
4992 }
4993
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004994 int targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn39792d22010-08-19 18:01:52 -07004995 if (targetUid < 0) {
4996 return;
4997 }
4998
4999 grantUriPermissionUncheckedLocked(targetUid, targetPkg, uri, modeFlags, owner);
5000 }
5001
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005002 static class NeededUriGrants extends ArrayList<Uri> {
5003 final String targetPkg;
5004 final int targetUid;
5005 final int flags;
5006
5007 NeededUriGrants(String _targetPkg, int _targetUid, int _flags) {
5008 targetPkg = _targetPkg;
5009 targetUid = _targetUid;
5010 flags = _flags;
5011 }
5012 }
5013
Dianne Hackborn39792d22010-08-19 18:01:52 -07005014 /**
5015 * Like checkGrantUriPermissionLocked, but takes an Intent.
5016 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005017 NeededUriGrants checkGrantUriPermissionFromIntentLocked(int callingUid,
5018 String targetPkg, Intent intent, int mode, NeededUriGrants needed) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07005019 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005020 "Checking URI perm to data=" + (intent != null ? intent.getData() : null)
5021 + " clip=" + (intent != null ? intent.getClipData() : null)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005022 + " from " + intent + "; flags=0x"
5023 + Integer.toHexString(intent != null ? intent.getFlags() : 0));
5024
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005025 if (targetPkg == null) {
5026 throw new NullPointerException("targetPkg");
5027 }
5028
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005029 if (intent == null) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005030 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005031 }
5032 Uri data = intent.getData();
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005033 ClipData clip = intent.getClipData();
5034 if (data == null && clip == null) {
5035 return null;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005036 }
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005037 if (data != null) {
5038 int target = checkGrantUriPermissionLocked(callingUid, targetPkg, data,
5039 mode, needed != null ? needed.targetUid : -1);
5040 if (target > 0) {
5041 if (needed == null) {
5042 needed = new NeededUriGrants(targetPkg, target, mode);
5043 }
5044 needed.add(data);
5045 }
5046 }
5047 if (clip != null) {
5048 for (int i=0; i<clip.getItemCount(); i++) {
5049 Uri uri = clip.getItemAt(i).getUri();
5050 if (uri != null) {
5051 int target = -1;
5052 target = checkGrantUriPermissionLocked(callingUid, targetPkg, uri,
5053 mode, needed != null ? needed.targetUid : -1);
5054 if (target > 0) {
5055 if (needed == null) {
5056 needed = new NeededUriGrants(targetPkg, target, mode);
5057 }
5058 needed.add(uri);
5059 }
5060 } else {
5061 Intent clipIntent = clip.getItemAt(i).getIntent();
5062 if (clipIntent != null) {
5063 NeededUriGrants newNeeded = checkGrantUriPermissionFromIntentLocked(
5064 callingUid, targetPkg, clipIntent, mode, needed);
5065 if (newNeeded != null) {
5066 needed = newNeeded;
5067 }
5068 }
5069 }
5070 }
5071 }
5072
5073 return needed;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005074 }
5075
5076 /**
5077 * Like grantUriPermissionUncheckedLocked, but takes an Intent.
5078 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005079 void grantUriPermissionUncheckedFromIntentLocked(NeededUriGrants needed,
5080 UriPermissionOwner owner) {
5081 if (needed != null) {
5082 for (int i=0; i<needed.size(); i++) {
5083 grantUriPermissionUncheckedLocked(needed.targetUid, needed.targetPkg,
5084 needed.get(i), needed.flags, owner);
5085 }
5086 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005087 }
5088
5089 void grantUriPermissionFromIntentLocked(int callingUid,
5090 String targetPkg, Intent intent, UriPermissionOwner owner) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005091 NeededUriGrants needed = checkGrantUriPermissionFromIntentLocked(callingUid, targetPkg,
Dianne Hackbornd9781fe2012-03-08 18:04:18 -08005092 intent, intent != null ? intent.getFlags() : 0, null);
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005093 if (needed == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005094 return;
5095 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005096
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005097 grantUriPermissionUncheckedFromIntentLocked(needed, owner);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005098 }
5099
5100 public void grantUriPermission(IApplicationThread caller, String targetPkg,
5101 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005102 enforceNotIsolatedCaller("grantUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005103 synchronized(this) {
5104 final ProcessRecord r = getRecordForAppLocked(caller);
5105 if (r == null) {
5106 throw new SecurityException("Unable to find app for caller "
5107 + caller
5108 + " when granting permission to uri " + uri);
5109 }
5110 if (targetPkg == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005111 throw new IllegalArgumentException("null target");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005112 }
5113 if (uri == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005114 throw new IllegalArgumentException("null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005115 }
5116
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005117 grantUriPermissionLocked(r.uid, targetPkg, uri, modeFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005118 null);
5119 }
5120 }
5121
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005122 void removeUriPermissionIfNeededLocked(UriPermission perm) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005123 if ((perm.modeFlags&(Intent.FLAG_GRANT_READ_URI_PERMISSION
5124 |Intent.FLAG_GRANT_WRITE_URI_PERMISSION)) == 0) {
5125 HashMap<Uri, UriPermission> perms
5126 = mGrantedUriPermissions.get(perm.uid);
5127 if (perms != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005128 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005129 "Removing " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005130 perms.remove(perm.uri);
5131 if (perms.size() == 0) {
5132 mGrantedUriPermissions.remove(perm.uid);
5133 }
5134 }
5135 }
5136 }
5137
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005138 private void revokeUriPermissionLocked(int callingUid, Uri uri,
5139 int modeFlags) {
5140 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5141 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5142 if (modeFlags == 0) {
5143 return;
5144 }
5145
Joe Onorato8a9b2202010-02-26 18:56:32 -08005146 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005147 "Revoking all granted permissions to " + uri);
5148
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005149 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005150
5151 final String authority = uri.getAuthority();
5152 ProviderInfo pi = null;
Amith Yamasani483f3b02012-03-13 16:08:00 -07005153 int userId = UserId.getUserId(callingUid);
5154 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005155 if (cpr != null) {
5156 pi = cpr.info;
5157 } else {
5158 try {
5159 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005160 PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005161 } catch (RemoteException ex) {
5162 }
5163 }
5164 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005165 Slog.w(TAG, "No content provider found for permission revoke: " + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005166 return;
5167 }
5168
5169 // Does the caller have this permission on the URI?
Dianne Hackborn48058e82010-09-27 16:53:23 -07005170 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005171 // Right now, if you are not the original owner of the permission,
5172 // you are not allowed to revoke it.
5173 //if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5174 throw new SecurityException("Uid " + callingUid
5175 + " does not have permission to uri " + uri);
5176 //}
5177 }
5178
5179 // Go through all of the permissions and remove any that match.
5180 final List<String> SEGMENTS = uri.getPathSegments();
5181 if (SEGMENTS != null) {
5182 final int NS = SEGMENTS.size();
5183 int N = mGrantedUriPermissions.size();
5184 for (int i=0; i<N; i++) {
5185 HashMap<Uri, UriPermission> perms
5186 = mGrantedUriPermissions.valueAt(i);
5187 Iterator<UriPermission> it = perms.values().iterator();
5188 toploop:
5189 while (it.hasNext()) {
5190 UriPermission perm = it.next();
5191 Uri targetUri = perm.uri;
5192 if (!authority.equals(targetUri.getAuthority())) {
5193 continue;
5194 }
5195 List<String> targetSegments = targetUri.getPathSegments();
5196 if (targetSegments == null) {
5197 continue;
5198 }
5199 if (targetSegments.size() < NS) {
5200 continue;
5201 }
5202 for (int j=0; j<NS; j++) {
5203 if (!SEGMENTS.get(j).equals(targetSegments.get(j))) {
5204 continue toploop;
5205 }
5206 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08005207 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005208 "Revoking " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005209 perm.clearModes(modeFlags);
5210 if (perm.modeFlags == 0) {
5211 it.remove();
5212 }
5213 }
5214 if (perms.size() == 0) {
5215 mGrantedUriPermissions.remove(
5216 mGrantedUriPermissions.keyAt(i));
5217 N--;
5218 i--;
5219 }
5220 }
5221 }
5222 }
5223
5224 public void revokeUriPermission(IApplicationThread caller, Uri uri,
5225 int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005226 enforceNotIsolatedCaller("revokeUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005227 synchronized(this) {
5228 final ProcessRecord r = getRecordForAppLocked(caller);
5229 if (r == null) {
5230 throw new SecurityException("Unable to find app for caller "
5231 + caller
5232 + " when revoking permission to uri " + uri);
5233 }
5234 if (uri == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005235 Slog.w(TAG, "revokeUriPermission: null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005236 return;
5237 }
5238
5239 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5240 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5241 if (modeFlags == 0) {
5242 return;
5243 }
5244
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005245 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005246
5247 final String authority = uri.getAuthority();
5248 ProviderInfo pi = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005249 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005250 if (cpr != null) {
5251 pi = cpr.info;
5252 } else {
5253 try {
5254 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005255 PackageManager.GET_URI_PERMISSION_PATTERNS, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005256 } catch (RemoteException ex) {
5257 }
5258 }
5259 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005260 Slog.w(TAG, "No content provider found for permission revoke: "
5261 + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005262 return;
5263 }
5264
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005265 revokeUriPermissionLocked(r.uid, uri, modeFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005266 }
5267 }
5268
Dianne Hackborn7e269642010-08-25 19:50:20 -07005269 @Override
5270 public IBinder newUriPermissionOwner(String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005271 enforceNotIsolatedCaller("newUriPermissionOwner");
Dianne Hackborn7e269642010-08-25 19:50:20 -07005272 synchronized(this) {
5273 UriPermissionOwner owner = new UriPermissionOwner(this, name);
5274 return owner.getExternalTokenLocked();
5275 }
5276 }
5277
5278 @Override
5279 public void grantUriPermissionFromOwner(IBinder token, int fromUid, String targetPkg,
5280 Uri uri, int modeFlags) {
5281 synchronized(this) {
5282 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5283 if (owner == null) {
5284 throw new IllegalArgumentException("Unknown owner: " + token);
5285 }
5286 if (fromUid != Binder.getCallingUid()) {
5287 if (Binder.getCallingUid() != Process.myUid()) {
5288 // Only system code can grant URI permissions on behalf
5289 // of other users.
5290 throw new SecurityException("nice try");
5291 }
5292 }
5293 if (targetPkg == null) {
5294 throw new IllegalArgumentException("null target");
5295 }
5296 if (uri == null) {
5297 throw new IllegalArgumentException("null uri");
5298 }
5299
5300 grantUriPermissionLocked(fromUid, targetPkg, uri, modeFlags, owner);
5301 }
5302 }
5303
5304 @Override
5305 public void revokeUriPermissionFromOwner(IBinder token, Uri uri, int mode) {
5306 synchronized(this) {
5307 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5308 if (owner == null) {
5309 throw new IllegalArgumentException("Unknown owner: " + token);
5310 }
5311
5312 if (uri == null) {
5313 owner.removeUriPermissionsLocked(mode);
5314 } else {
5315 owner.removeUriPermissionLocked(uri, mode);
5316 }
5317 }
5318 }
5319
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005320 public void showWaitingForDebugger(IApplicationThread who, boolean waiting) {
5321 synchronized (this) {
5322 ProcessRecord app =
5323 who != null ? getRecordForAppLocked(who) : null;
5324 if (app == null) return;
5325
5326 Message msg = Message.obtain();
5327 msg.what = WAIT_FOR_DEBUGGER_MSG;
5328 msg.obj = app;
5329 msg.arg1 = waiting ? 1 : 0;
5330 mHandler.sendMessage(msg);
5331 }
5332 }
5333
5334 public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07005335 final long homeAppMem = mProcessList.getMemLevel(ProcessList.HOME_APP_ADJ);
5336 final long hiddenAppMem = mProcessList.getMemLevel(ProcessList.HIDDEN_APP_MIN_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005337 outInfo.availMem = Process.getFreeMemory();
Dianne Hackborn7d608422011-08-07 16:24:18 -07005338 outInfo.threshold = homeAppMem;
5339 outInfo.lowMemory = outInfo.availMem < (homeAppMem + ((hiddenAppMem-homeAppMem)/2));
5340 outInfo.hiddenAppThreshold = hiddenAppMem;
5341 outInfo.secondaryServerThreshold = mProcessList.getMemLevel(
Dianne Hackborne02c88a2011-10-28 13:58:15 -07005342 ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07005343 outInfo.visibleAppThreshold = mProcessList.getMemLevel(
5344 ProcessList.VISIBLE_APP_ADJ);
5345 outInfo.foregroundAppThreshold = mProcessList.getMemLevel(
5346 ProcessList.FOREGROUND_APP_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005347 }
5348
5349 // =========================================================
5350 // TASK MANAGEMENT
5351 // =========================================================
5352
5353 public List getTasks(int maxNum, int flags,
5354 IThumbnailReceiver receiver) {
5355 ArrayList list = new ArrayList();
5356
5357 PendingThumbnailsRecord pending = null;
5358 IApplicationThread topThumbnail = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005359 ActivityRecord topRecord = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005360
5361 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005362 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005363 TAG, "getTasks: max=" + maxNum + ", flags=" + flags
5364 + ", receiver=" + receiver);
5365
5366 if (checkCallingPermission(android.Manifest.permission.GET_TASKS)
5367 != PackageManager.PERMISSION_GRANTED) {
5368 if (receiver != null) {
5369 // If the caller wants to wait for pending thumbnails,
5370 // it ain't gonna get them.
5371 try {
5372 receiver.finished();
5373 } catch (RemoteException ex) {
5374 }
5375 }
5376 String msg = "Permission Denial: getTasks() from pid="
5377 + Binder.getCallingPid()
5378 + ", uid=" + Binder.getCallingUid()
5379 + " requires " + android.Manifest.permission.GET_TASKS;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005380 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005381 throw new SecurityException(msg);
5382 }
5383
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005384 int pos = mMainStack.mHistory.size()-1;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005385 ActivityRecord next =
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005386 pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005387 ActivityRecord top = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005388 TaskRecord curTask = null;
5389 int numActivities = 0;
5390 int numRunning = 0;
5391 while (pos >= 0 && maxNum > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005392 final ActivityRecord r = next;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005393 pos--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005394 next = pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005395
5396 // Initialize state for next task if needed.
5397 if (top == null ||
5398 (top.state == ActivityState.INITIALIZING
5399 && top.task == r.task)) {
5400 top = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005401 curTask = r.task;
5402 numActivities = numRunning = 0;
5403 }
5404
5405 // Add 'r' into the current task.
5406 numActivities++;
5407 if (r.app != null && r.app.thread != null) {
5408 numRunning++;
5409 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005410
Joe Onorato8a9b2202010-02-26 18:56:32 -08005411 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005412 TAG, r.intent.getComponent().flattenToShortString()
5413 + ": task=" + r.task);
5414
5415 // If the next one is a different task, generate a new
5416 // TaskInfo entry for what we have.
5417 if (next == null || next.task != curTask) {
5418 ActivityManager.RunningTaskInfo ci
5419 = new ActivityManager.RunningTaskInfo();
5420 ci.id = curTask.taskId;
5421 ci.baseActivity = r.intent.getComponent();
5422 ci.topActivity = top.intent.getComponent();
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005423 if (top.thumbHolder != null) {
5424 ci.description = top.thumbHolder.lastDescription;
5425 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005426 ci.numActivities = numActivities;
5427 ci.numRunning = numRunning;
5428 //System.out.println(
5429 // "#" + maxNum + ": " + " descr=" + ci.description);
5430 if (ci.thumbnail == null && receiver != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005431 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005432 TAG, "State=" + top.state + "Idle=" + top.idle
5433 + " app=" + top.app
5434 + " thr=" + (top.app != null ? top.app.thread : null));
5435 if (top.state == ActivityState.RESUMED
5436 || top.state == ActivityState.PAUSING) {
5437 if (top.idle && top.app != null
5438 && top.app.thread != null) {
5439 topRecord = top;
5440 topThumbnail = top.app.thread;
5441 } else {
5442 top.thumbnailNeeded = true;
5443 }
5444 }
5445 if (pending == null) {
5446 pending = new PendingThumbnailsRecord(receiver);
5447 }
5448 pending.pendingRecords.add(top);
5449 }
5450 list.add(ci);
5451 maxNum--;
5452 top = null;
5453 }
5454 }
5455
5456 if (pending != null) {
5457 mPendingThumbnails.add(pending);
5458 }
5459 }
5460
Joe Onorato8a9b2202010-02-26 18:56:32 -08005461 if (localLOGV) Slog.v(TAG, "We have pending thumbnails: " + pending);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005462
5463 if (topThumbnail != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005464 if (localLOGV) Slog.v(TAG, "Requesting top thumbnail");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005465 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08005466 topThumbnail.requestThumbnail(topRecord.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005467 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005468 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005469 sendPendingThumbnail(null, topRecord.appToken, null, null, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005470 }
5471 }
5472
5473 if (pending == null && receiver != null) {
5474 // In this case all thumbnails were available and the client
5475 // is being asked to be told when the remaining ones come in...
5476 // which is unusually, since the top-most currently running
5477 // activity should never have a canned thumbnail! Oh well.
5478 try {
5479 receiver.finished();
5480 } catch (RemoteException ex) {
5481 }
5482 }
5483
5484 return list;
5485 }
5486
5487 public List<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum,
5488 int flags) {
Amith Yamasani742a6712011-05-04 14:49:28 -07005489 final int callingUid = Binder.getCallingUid();
5490 // If it's the system uid asking, then use the current user id.
5491 // TODO: Make sure that there aren't any other legitimate calls from the system uid that
5492 // require the entire list.
5493 final int callingUserId = callingUid == Process.SYSTEM_UID
5494 ? mCurrentUserId : UserId.getUserId(callingUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005495 synchronized (this) {
5496 enforceCallingPermission(android.Manifest.permission.GET_TASKS,
5497 "getRecentTasks()");
Dianne Hackborn8238e712012-04-24 11:15:40 -07005498 final boolean detailed = checkCallingPermission(
5499 android.Manifest.permission.GET_DETAILED_TASKS)
5500 == PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005501
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005502 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005503
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005504 final int N = mRecentTasks.size();
5505 ArrayList<ActivityManager.RecentTaskInfo> res
5506 = new ArrayList<ActivityManager.RecentTaskInfo>(
5507 maxNum < N ? maxNum : N);
5508 for (int i=0; i<N && maxNum > 0; i++) {
5509 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005510 // Only add calling user's recent tasks
5511 if (tr.userId != callingUserId) continue;
Dianne Hackborn905577f2011-09-07 18:31:28 -07005512 // Return the entry if desired by the caller. We always return
5513 // the first entry, because callers always expect this to be the
Amith Yamasani742a6712011-05-04 14:49:28 -07005514 // foreground app. We may filter others if the caller has
Dianne Hackborn905577f2011-09-07 18:31:28 -07005515 // not supplied RECENT_WITH_EXCLUDED and there is some reason
5516 // we should exclude the entry.
Amith Yamasani742a6712011-05-04 14:49:28 -07005517
Dianne Hackborn905577f2011-09-07 18:31:28 -07005518 if (i == 0
5519 || ((flags&ActivityManager.RECENT_WITH_EXCLUDED) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005520 || (tr.intent == null)
5521 || ((tr.intent.getFlags()
5522 &Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) == 0)) {
5523 ActivityManager.RecentTaskInfo rti
5524 = new ActivityManager.RecentTaskInfo();
5525 rti.id = tr.numActivities > 0 ? tr.taskId : -1;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005526 rti.persistentId = tr.taskId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005527 rti.baseIntent = new Intent(
5528 tr.intent != null ? tr.intent : tr.affinityIntent);
Dianne Hackborn8238e712012-04-24 11:15:40 -07005529 if (!detailed) {
5530 rti.baseIntent.replaceExtras((Bundle)null);
5531 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005532 rti.origActivity = tr.origActivity;
Dianne Hackbornd2835932010-12-13 16:28:46 -08005533 rti.description = tr.lastDescription;
5534
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005535 if ((flags&ActivityManager.RECENT_IGNORE_UNAVAILABLE) != 0) {
5536 // Check whether this activity is currently available.
5537 try {
5538 if (rti.origActivity != null) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07005539 if (pm.getActivityInfo(rti.origActivity, 0, callingUserId)
5540 == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005541 continue;
5542 }
5543 } else if (rti.baseIntent != null) {
5544 if (pm.queryIntentActivities(rti.baseIntent,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005545 null, 0, callingUserId) == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005546 continue;
5547 }
5548 }
5549 } catch (RemoteException e) {
5550 // Will never happen.
5551 }
5552 }
5553
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005554 res.add(rti);
5555 maxNum--;
5556 }
5557 }
5558 return res;
5559 }
5560 }
5561
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005562 private TaskRecord taskForIdLocked(int id) {
5563 final int N = mRecentTasks.size();
5564 for (int i=0; i<N; i++) {
5565 TaskRecord tr = mRecentTasks.get(i);
5566 if (tr.taskId == id) {
5567 return tr;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005568 }
5569 }
5570 return null;
5571 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005572
5573 public ActivityManager.TaskThumbnails getTaskThumbnails(int id) {
5574 synchronized (this) {
5575 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
5576 "getTaskThumbnails()");
5577 TaskRecord tr = taskForIdLocked(id);
5578 if (tr != null) {
5579 return mMainStack.getTaskThumbnailsLocked(tr);
5580 }
5581 }
5582 return null;
5583 }
5584
5585 public boolean removeSubTask(int taskId, int subTaskIndex) {
5586 synchronized (this) {
5587 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5588 "removeSubTask()");
5589 long ident = Binder.clearCallingIdentity();
5590 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005591 return mMainStack.removeTaskActivitiesLocked(taskId, subTaskIndex,
5592 true) != null;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005593 } finally {
5594 Binder.restoreCallingIdentity(ident);
5595 }
5596 }
5597 }
5598
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005599 private void cleanUpRemovedTaskLocked(TaskRecord tr, int flags) {
5600 final boolean killProcesses = (flags&ActivityManager.REMOVE_TASK_KILL_PROCESS) != 0;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005601 Intent baseIntent = new Intent(
5602 tr.intent != null ? tr.intent : tr.affinityIntent);
5603 ComponentName component = baseIntent.getComponent();
5604 if (component == null) {
5605 Slog.w(TAG, "Now component for base intent of task: " + tr);
5606 return;
5607 }
5608
5609 // Find any running services associated with this app.
5610 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005611 for (ServiceRecord sr : mServiceMap.getAllServices(tr.userId)) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005612 if (sr.packageName.equals(component.getPackageName())) {
5613 services.add(sr);
5614 }
5615 }
5616
5617 // Take care of any running services associated with the app.
5618 for (int i=0; i<services.size(); i++) {
5619 ServiceRecord sr = services.get(i);
5620 if (sr.startRequested) {
5621 if ((sr.serviceInfo.flags&ServiceInfo.FLAG_STOP_WITH_TASK) != 0) {
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005622 Slog.i(TAG, "Stopping service " + sr.shortName + ": remove task");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005623 stopServiceLocked(sr);
5624 } else {
5625 sr.pendingStarts.add(new ServiceRecord.StartItem(sr, true,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005626 sr.makeNextStartId(), baseIntent, null));
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005627 if (sr.app != null && sr.app.thread != null) {
5628 sendServiceArgsLocked(sr, false);
5629 }
5630 }
5631 }
5632 }
5633
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005634 if (killProcesses) {
5635 // Find any running processes associated with this app.
5636 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
5637 SparseArray<ProcessRecord> appProcs
5638 = mProcessNames.getMap().get(component.getPackageName());
5639 if (appProcs != null) {
5640 for (int i=0; i<appProcs.size(); i++) {
5641 procs.add(appProcs.valueAt(i));
5642 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005643 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005644
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005645 // Kill the running processes.
5646 for (int i=0; i<procs.size(); i++) {
5647 ProcessRecord pr = procs.get(i);
5648 if (pr.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
5649 Slog.i(TAG, "Killing " + pr.toShortString() + ": remove task");
5650 EventLog.writeEvent(EventLogTags.AM_KILL, pr.pid,
5651 pr.processName, pr.setAdj, "remove task");
5652 Process.killProcessQuiet(pr.pid);
5653 } else {
5654 pr.waitingToKill = "remove task";
5655 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005656 }
5657 }
5658 }
5659
5660 public boolean removeTask(int taskId, int flags) {
5661 synchronized (this) {
5662 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5663 "removeTask()");
5664 long ident = Binder.clearCallingIdentity();
5665 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005666 ActivityRecord r = mMainStack.removeTaskActivitiesLocked(taskId, -1,
5667 false);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005668 if (r != null) {
5669 mRecentTasks.remove(r.task);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005670 cleanUpRemovedTaskLocked(r.task, flags);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005671 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005672 } else {
5673 TaskRecord tr = null;
5674 int i=0;
5675 while (i < mRecentTasks.size()) {
5676 TaskRecord t = mRecentTasks.get(i);
5677 if (t.taskId == taskId) {
5678 tr = t;
5679 break;
5680 }
5681 i++;
5682 }
5683 if (tr != null) {
5684 if (tr.numActivities <= 0) {
5685 // Caller is just removing a recent task that is
5686 // not actively running. That is easy!
5687 mRecentTasks.remove(i);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005688 cleanUpRemovedTaskLocked(tr, flags);
5689 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005690 } else {
5691 Slog.w(TAG, "removeTask: task " + taskId
5692 + " does not have activities to remove, "
5693 + " but numActivities=" + tr.numActivities
5694 + ": " + tr);
5695 }
5696 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005697 }
5698 } finally {
5699 Binder.restoreCallingIdentity(ident);
5700 }
5701 }
5702 return false;
5703 }
Dianne Hackbornd94df452011-02-16 18:53:31 -08005704
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005705 private final int findAffinityTaskTopLocked(int startIndex, String affinity) {
5706 int j;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005707 TaskRecord startTask = ((ActivityRecord)mMainStack.mHistory.get(startIndex)).task;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005708 TaskRecord jt = startTask;
5709
5710 // First look backwards
5711 for (j=startIndex-1; j>=0; j--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005712 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005713 if (r.task != jt) {
5714 jt = r.task;
5715 if (affinity.equals(jt.affinity)) {
5716 return j;
5717 }
5718 }
5719 }
5720
5721 // Now look forwards
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005722 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005723 jt = startTask;
5724 for (j=startIndex+1; j<N; j++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005725 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005726 if (r.task != jt) {
5727 if (affinity.equals(jt.affinity)) {
5728 return j;
5729 }
5730 jt = r.task;
5731 }
5732 }
5733
5734 // Might it be at the top?
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005735 if (affinity.equals(((ActivityRecord)mMainStack.mHistory.get(N-1)).task.affinity)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005736 return N-1;
5737 }
5738
5739 return -1;
5740 }
5741
5742 /**
Dianne Hackbornb06ea702009-07-13 13:07:51 -07005743 * TODO: Add mController hook
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005744 */
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005745 public void moveTaskToFront(int task, int flags, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005746 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5747 "moveTaskToFront()");
5748
5749 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005750 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5751 Binder.getCallingUid(), "Task to front")) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005752 ActivityOptions.abort(options);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005753 return;
5754 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005755 final long origId = Binder.clearCallingIdentity();
5756 try {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005757 TaskRecord tr = taskForIdLocked(task);
5758 if (tr != null) {
5759 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5760 mMainStack.mUserLeaving = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005761 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005762 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5763 // Caller wants the home activity moved with it. To accomplish this,
5764 // we'll just move the home task to the top first.
5765 mMainStack.moveHomeToFrontLocked();
5766 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005767 mMainStack.moveTaskToFrontLocked(tr, null, options);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005768 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005769 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005770 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
5771 ActivityRecord hr = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005772 if (hr.task.taskId == task) {
Dianne Hackbornd94df452011-02-16 18:53:31 -08005773 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5774 mMainStack.mUserLeaving = true;
5775 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005776 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5777 // Caller wants the home activity moved with it. To accomplish this,
5778 // we'll just move the home task to the top first.
5779 mMainStack.moveHomeToFrontLocked();
5780 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005781 mMainStack.moveTaskToFrontLocked(hr.task, null, options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005782 return;
5783 }
5784 }
5785 } finally {
5786 Binder.restoreCallingIdentity(origId);
5787 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005788 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005789 }
5790 }
5791
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005792 public void moveTaskToBack(int task) {
5793 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5794 "moveTaskToBack()");
5795
5796 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005797 if (mMainStack.mResumedActivity != null
5798 && mMainStack.mResumedActivity.task.taskId == task) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005799 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5800 Binder.getCallingUid(), "Task to back")) {
5801 return;
5802 }
5803 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005804 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005805 mMainStack.moveTaskToBackLocked(task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005806 Binder.restoreCallingIdentity(origId);
5807 }
5808 }
5809
5810 /**
5811 * Moves an activity, and all of the other activities within the same task, to the bottom
5812 * of the history stack. The activity's order within the task is unchanged.
5813 *
5814 * @param token A reference to the activity we wish to move
5815 * @param nonRoot If false then this only works if the activity is the root
5816 * of a task; if true it will work for any activity in a task.
5817 * @return Returns true if the move completed, false if not.
5818 */
5819 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005820 enforceNotIsolatedCaller("moveActivityTaskToBack");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005821 synchronized(this) {
5822 final long origId = Binder.clearCallingIdentity();
5823 int taskId = getTaskForActivityLocked(token, !nonRoot);
5824 if (taskId >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005825 return mMainStack.moveTaskToBackLocked(taskId, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005826 }
5827 Binder.restoreCallingIdentity(origId);
5828 }
5829 return false;
5830 }
5831
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005832 public void moveTaskBackwards(int task) {
5833 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5834 "moveTaskBackwards()");
5835
5836 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005837 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5838 Binder.getCallingUid(), "Task backwards")) {
5839 return;
5840 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005841 final long origId = Binder.clearCallingIdentity();
5842 moveTaskBackwardsLocked(task);
5843 Binder.restoreCallingIdentity(origId);
5844 }
5845 }
5846
5847 private final void moveTaskBackwardsLocked(int task) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005848 Slog.e(TAG, "moveTaskBackwards not yet implemented!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005849 }
5850
5851 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
5852 synchronized(this) {
5853 return getTaskForActivityLocked(token, onlyRoot);
5854 }
5855 }
5856
5857 int getTaskForActivityLocked(IBinder token, boolean onlyRoot) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005858 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005859 TaskRecord lastTask = null;
5860 for (int i=0; i<N; i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005861 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005862 if (r.appToken == token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005863 if (!onlyRoot || lastTask != r.task) {
5864 return r.task.taskId;
5865 }
5866 return -1;
5867 }
5868 lastTask = r.task;
5869 }
5870
5871 return -1;
5872 }
5873
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005874 // =========================================================
5875 // THUMBNAILS
5876 // =========================================================
5877
5878 public void reportThumbnail(IBinder token,
5879 Bitmap thumbnail, CharSequence description) {
5880 //System.out.println("Report thumbnail for " + token + ": " + thumbnail);
5881 final long origId = Binder.clearCallingIdentity();
5882 sendPendingThumbnail(null, token, thumbnail, description, true);
5883 Binder.restoreCallingIdentity(origId);
5884 }
5885
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005886 final void sendPendingThumbnail(ActivityRecord r, IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005887 Bitmap thumbnail, CharSequence description, boolean always) {
5888 TaskRecord task = null;
5889 ArrayList receivers = null;
5890
5891 //System.out.println("Send pending thumbnail: " + r);
5892
5893 synchronized(this) {
5894 if (r == null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07005895 r = mMainStack.isInStackLocked(token);
5896 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005897 return;
5898 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005899 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005900 if (thumbnail == null && r.thumbHolder != null) {
5901 thumbnail = r.thumbHolder.lastThumbnail;
5902 description = r.thumbHolder.lastDescription;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005903 }
5904 if (thumbnail == null && !always) {
5905 // If there is no thumbnail, and this entry is not actually
5906 // going away, then abort for now and pick up the next
5907 // thumbnail we get.
5908 return;
5909 }
5910 task = r.task;
5911
5912 int N = mPendingThumbnails.size();
5913 int i=0;
5914 while (i<N) {
5915 PendingThumbnailsRecord pr =
5916 (PendingThumbnailsRecord)mPendingThumbnails.get(i);
5917 //System.out.println("Looking in " + pr.pendingRecords);
5918 if (pr.pendingRecords.remove(r)) {
5919 if (receivers == null) {
5920 receivers = new ArrayList();
5921 }
5922 receivers.add(pr);
5923 if (pr.pendingRecords.size() == 0) {
5924 pr.finished = true;
5925 mPendingThumbnails.remove(i);
5926 N--;
5927 continue;
5928 }
5929 }
5930 i++;
5931 }
5932 }
5933
5934 if (receivers != null) {
5935 final int N = receivers.size();
5936 for (int i=0; i<N; i++) {
5937 try {
5938 PendingThumbnailsRecord pr =
5939 (PendingThumbnailsRecord)receivers.get(i);
5940 pr.receiver.newThumbnail(
5941 task != null ? task.taskId : -1, thumbnail, description);
5942 if (pr.finished) {
5943 pr.receiver.finished();
5944 }
5945 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005946 Slog.w(TAG, "Exception thrown when sending thumbnail", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005947 }
5948 }
5949 }
5950 }
5951
5952 // =========================================================
5953 // CONTENT PROVIDERS
5954 // =========================================================
5955
Jeff Brown10e89712011-07-08 18:52:57 -07005956 private final List<ProviderInfo> generateApplicationProvidersLocked(ProcessRecord app) {
5957 List<ProviderInfo> providers = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005958 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005959 providers = AppGlobals.getPackageManager().
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005960 queryContentProviders(app.processName, app.uid,
Dianne Hackborn1655be42009-05-08 14:29:01 -07005961 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005962 } catch (RemoteException ex) {
5963 }
Amith Yamasani742a6712011-05-04 14:49:28 -07005964 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005965 Slog.v(TAG_MU, "generateApplicationProvidersLocked, app.info.uid = " + app.uid);
5966 int userId = app.userId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005967 if (providers != null) {
5968 final int N = providers.size();
5969 for (int i=0; i<N; i++) {
5970 ProviderInfo cpi =
5971 (ProviderInfo)providers.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005972
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07005973 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07005974 ContentProviderRecord cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005975 if (cpr == null) {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08005976 cpr = new ContentProviderRecord(this, cpi, app.info, comp);
Amith Yamasani742a6712011-05-04 14:49:28 -07005977 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005978 }
Amith Yamasani742a6712011-05-04 14:49:28 -07005979 if (DEBUG_MU)
5980 Slog.v(TAG_MU, "generateApplicationProvidersLocked, cpi.uid = " + cpr.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005981 app.pubProviders.put(cpi.name, cpr);
5982 app.addPackage(cpi.applicationInfo.packageName);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07005983 ensurePackageDexOpt(cpi.applicationInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005984 }
5985 }
5986 return providers;
5987 }
5988
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005989 /**
5990 * Check if {@link ProcessRecord} has a possible chance at accessing the
5991 * given {@link ProviderInfo}. Final permission checking is always done
5992 * in {@link ContentProvider}.
5993 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005994 private final String checkContentProviderPermissionLocked(
Dianne Hackbornb424b632010-08-18 15:59:05 -07005995 ProviderInfo cpi, ProcessRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005996 final int callingPid = (r != null) ? r.pid : Binder.getCallingPid();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005997 final int callingUid = (r != null) ? r.uid : Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005998 if (checkComponentPermission(cpi.readPermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005999 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006000 == PackageManager.PERMISSION_GRANTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006001 return null;
6002 }
6003 if (checkComponentPermission(cpi.writePermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006004 cpi.applicationInfo.uid, cpi.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006005 == PackageManager.PERMISSION_GRANTED) {
6006 return null;
6007 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006008
6009 PathPermission[] pps = cpi.pathPermissions;
6010 if (pps != null) {
6011 int i = pps.length;
6012 while (i > 0) {
6013 i--;
6014 PathPermission pp = pps[i];
6015 if (checkComponentPermission(pp.getReadPermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006016 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006017 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006018 return null;
6019 }
6020 if (checkComponentPermission(pp.getWritePermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006021 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006022 == PackageManager.PERMISSION_GRANTED) {
6023 return null;
6024 }
6025 }
6026 }
6027
Dianne Hackbornb424b632010-08-18 15:59:05 -07006028 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(callingUid);
6029 if (perms != null) {
6030 for (Map.Entry<Uri, UriPermission> uri : perms.entrySet()) {
6031 if (uri.getKey().getAuthority().equals(cpi.authority)) {
6032 return null;
6033 }
6034 }
6035 }
6036
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006037 String msg;
6038 if (!cpi.exported) {
6039 msg = "Permission Denial: opening provider " + cpi.name
6040 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6041 + ", uid=" + callingUid + ") that is not exported from uid "
6042 + cpi.applicationInfo.uid;
6043 } else {
6044 msg = "Permission Denial: opening provider " + cpi.name
6045 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6046 + ", uid=" + callingUid + ") requires "
6047 + cpi.readPermission + " or " + cpi.writePermission;
6048 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08006049 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006050 return msg;
6051 }
6052
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006053 boolean incProviderCount(ProcessRecord r, final ContentProviderRecord cpr,
6054 IBinder externalProcessToken) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006055 if (r != null) {
6056 Integer cnt = r.conProviders.get(cpr);
6057 if (DEBUG_PROVIDER) Slog.v(TAG,
6058 "Adding provider requested by "
6059 + r.processName + " from process "
6060 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
6061 + " cnt=" + (cnt == null ? 1 : cnt));
6062 if (cnt == null) {
6063 cpr.clients.add(r);
6064 r.conProviders.put(cpr, new Integer(1));
6065 return true;
6066 } else {
6067 r.conProviders.put(cpr, new Integer(cnt.intValue()+1));
6068 }
6069 } else {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006070 cpr.addExternalProcessHandleLocked(externalProcessToken);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006071 }
6072 return false;
6073 }
6074
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006075 boolean decProviderCount(ProcessRecord r, final ContentProviderRecord cpr,
6076 IBinder externalProcessToken) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006077 if (r != null) {
6078 Integer cnt = r.conProviders.get(cpr);
6079 if (DEBUG_PROVIDER) Slog.v(TAG,
6080 "Removing provider requested by "
6081 + r.processName + " from process "
6082 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
6083 + " cnt=" + cnt);
6084 if (cnt == null || cnt.intValue() <= 1) {
6085 cpr.clients.remove(r);
6086 r.conProviders.remove(cpr);
6087 return true;
6088 } else {
6089 r.conProviders.put(cpr, new Integer(cnt.intValue()-1));
6090 }
6091 } else {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006092 cpr.removeExternalProcessHandleLocked(externalProcessToken);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006093 }
6094 return false;
6095 }
6096
Amith Yamasani742a6712011-05-04 14:49:28 -07006097 private final ContentProviderHolder getContentProviderImpl(IApplicationThread caller,
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006098 String name, IBinder token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006099 ContentProviderRecord cpr;
6100 ProviderInfo cpi = null;
6101
6102 synchronized(this) {
6103 ProcessRecord r = null;
6104 if (caller != null) {
6105 r = getRecordForAppLocked(caller);
6106 if (r == null) {
6107 throw new SecurityException(
6108 "Unable to find app for caller " + caller
6109 + " (pid=" + Binder.getCallingPid()
6110 + ") when getting content provider " + name);
6111 }
6112 }
6113
6114 // First check if this content provider has been published...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006115 int userId = UserId.getUserId(r != null ? r.uid : Binder.getCallingUid());
Amith Yamasani742a6712011-05-04 14:49:28 -07006116 cpr = mProviderMap.getProviderByName(name, userId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006117 boolean providerRunning = cpr != null;
6118 if (providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006119 cpi = cpr.info;
Dianne Hackbornb424b632010-08-18 15:59:05 -07006120 String msg;
6121 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6122 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006123 }
6124
6125 if (r != null && cpr.canRunHere(r)) {
6126 // This provider has been published or is in the process
6127 // of being published... but it is also allowed to run
6128 // in the caller's process, so don't make a connection
6129 // and just let the caller instantiate its own instance.
6130 if (cpr.provider != null) {
6131 // don't give caller the provider object, it needs
6132 // to make its own.
6133 cpr = new ContentProviderRecord(cpr);
6134 }
6135 return cpr;
6136 }
6137
6138 final long origId = Binder.clearCallingIdentity();
6139
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006140 // In this case the provider instance already exists, so we can
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006141 // return it right away.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006142 final boolean countChanged = incProviderCount(r, cpr, token);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006143 if (countChanged) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006144 if (cpr.proc != null && r.setAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006145 // If this is a perceptible app accessing the provider,
Dianne Hackborn906497c2010-05-10 15:57:38 -07006146 // make sure to count it as being accessed and thus
6147 // back up on the LRU list. This is good because
6148 // content providers are often expensive to start.
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006149 updateLruProcessLocked(cpr.proc, false, true);
Dianne Hackborn906497c2010-05-10 15:57:38 -07006150 }
Dianne Hackborn6f86c0e2010-05-11 14:20:52 -07006151 }
6152
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006153 if (cpr.proc != null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006154 if (false) {
6155 if (cpr.name.flattenToShortString().equals(
6156 "com.android.providers.calendar/.CalendarProvider2")) {
6157 Slog.v(TAG, "****************** KILLING "
6158 + cpr.name.flattenToShortString());
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006159 Process.killProcess(cpr.proc.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006160 }
6161 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006162 boolean success = updateOomAdjLocked(cpr.proc);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006163 if (DEBUG_PROVIDER) Slog.i(TAG, "Adjust success: " + success);
6164 // NOTE: there is still a race here where a signal could be
6165 // pending on the process even though we managed to update its
6166 // adj level. Not sure what to do about this, but at least
6167 // the race is now smaller.
6168 if (!success) {
6169 // Uh oh... it looks like the provider's process
6170 // has been killed on us. We need to wait for a new
6171 // process to be started, and make sure its death
6172 // doesn't kill our process.
6173 Slog.i(TAG,
6174 "Existing provider " + cpr.name.flattenToShortString()
6175 + " is crashing; detaching " + r);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006176 boolean lastRef = decProviderCount(r, cpr, token);
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006177 appDiedLocked(cpr.proc, cpr.proc.pid, cpr.proc.thread);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006178 if (!lastRef) {
6179 // This wasn't the last ref our process had on
6180 // the provider... we have now been killed, bail.
6181 return null;
6182 }
6183 providerRunning = false;
6184 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006185 }
6186
6187 Binder.restoreCallingIdentity(origId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006188 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006189
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006190 if (!providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006191 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006192 cpi = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07006193 resolveContentProvider(name,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006194 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006195 } catch (RemoteException ex) {
6196 }
6197 if (cpi == null) {
6198 return null;
6199 }
Amith Yamasania4a54e22012-04-16 15:44:19 -07006200 if (isSingleton(cpi.processName, cpi.applicationInfo)) {
6201 userId = 0;
6202 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006203 cpi.applicationInfo = getAppInfoForUser(cpi.applicationInfo, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07006204
Dianne Hackbornb424b632010-08-18 15:59:05 -07006205 String msg;
6206 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6207 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006208 }
6209
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07006210 if (!mProcessesReady && !mDidUpdate && !mWaitingUpdate
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006211 && !cpi.processName.equals("system")) {
6212 // If this content provider does not run in the system
6213 // process, and the system is not yet ready to run other
6214 // processes, then fail fast instead of hanging.
6215 throw new IllegalArgumentException(
6216 "Attempt to launch content provider before system ready");
6217 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006218
6219 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani483f3b02012-03-13 16:08:00 -07006220 cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006221 final boolean firstClass = cpr == null;
6222 if (firstClass) {
6223 try {
6224 ApplicationInfo ai =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006225 AppGlobals.getPackageManager().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006226 getApplicationInfo(
6227 cpi.applicationInfo.packageName,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006228 STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006229 if (ai == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006230 Slog.w(TAG, "No package info for content provider "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006231 + cpi.name);
6232 return null;
6233 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006234 ai = getAppInfoForUser(ai, userId);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006235 cpr = new ContentProviderRecord(this, cpi, ai, comp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006236 } catch (RemoteException ex) {
6237 // pm is in same process, this will never happen.
6238 }
6239 }
6240
6241 if (r != null && cpr.canRunHere(r)) {
6242 // If this is a multiprocess provider, then just return its
6243 // info and allow the caller to instantiate it. Only do
6244 // this if the provider is the same user as the caller's
6245 // process, or can run as root (so can be in any process).
6246 return cpr;
6247 }
6248
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006249 if (DEBUG_PROVIDER) {
6250 RuntimeException e = new RuntimeException("here");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006251 Slog.w(TAG, "LAUNCHING REMOTE PROVIDER (myuid " + r.uid
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006252 + " pruid " + cpr.appInfo.uid + "): " + cpr.info.name, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006253 }
6254
6255 // This is single process, and our app is now connecting to it.
6256 // See if we are already in the process of launching this
6257 // provider.
6258 final int N = mLaunchingProviders.size();
6259 int i;
6260 for (i=0; i<N; i++) {
6261 if (mLaunchingProviders.get(i) == cpr) {
6262 break;
6263 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006264 }
6265
6266 // If the provider is not already being launched, then get it
6267 // started.
6268 if (i >= N) {
6269 final long origId = Binder.clearCallingIdentity();
Dianne Hackborne7f97212011-02-24 14:40:20 -08006270
6271 try {
6272 // Content provider is now in use, its package can't be stopped.
6273 try {
6274 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07006275 cpr.appInfo.packageName, false, userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006276 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006277 } catch (IllegalArgumentException e) {
6278 Slog.w(TAG, "Failed trying to unstop package "
6279 + cpr.appInfo.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006280 }
6281
6282 ProcessRecord proc = startProcessLocked(cpi.processName,
6283 cpr.appInfo, false, 0, "content provider",
6284 new ComponentName(cpi.applicationInfo.packageName,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006285 cpi.name), false, false);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006286 if (proc == null) {
6287 Slog.w(TAG, "Unable to launch app "
6288 + cpi.applicationInfo.packageName + "/"
6289 + cpi.applicationInfo.uid + " for provider "
6290 + name + ": process is bad");
6291 return null;
6292 }
6293 cpr.launchingApp = proc;
6294 mLaunchingProviders.add(cpr);
6295 } finally {
6296 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006297 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006298 }
6299
6300 // Make sure the provider is published (the same provider class
6301 // may be published under multiple names).
6302 if (firstClass) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006303 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006304 }
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006305
Amith Yamasani742a6712011-05-04 14:49:28 -07006306 mProviderMap.putProviderByName(name, cpr);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006307 incProviderCount(r, cpr, token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006308 }
6309 }
6310
6311 // Wait for the provider to be published...
6312 synchronized (cpr) {
6313 while (cpr.provider == null) {
6314 if (cpr.launchingApp == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006315 Slog.w(TAG, "Unable to launch app "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006316 + cpi.applicationInfo.packageName + "/"
6317 + cpi.applicationInfo.uid + " for provider "
6318 + name + ": launching app became null");
Doug Zongker2bec3d42009-12-04 12:52:44 -08006319 EventLog.writeEvent(EventLogTags.AM_PROVIDER_LOST_PROCESS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006320 cpi.applicationInfo.packageName,
6321 cpi.applicationInfo.uid, name);
6322 return null;
6323 }
6324 try {
Amith Yamasani742a6712011-05-04 14:49:28 -07006325 if (DEBUG_MU) {
6326 Slog.v(TAG_MU, "Waiting to start provider " + cpr + " launchingApp="
6327 + cpr.launchingApp);
6328 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006329 cpr.wait();
6330 } catch (InterruptedException ex) {
6331 }
6332 }
6333 }
6334 return cpr;
6335 }
6336
6337 public final ContentProviderHolder getContentProvider(
6338 IApplicationThread caller, String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006339 enforceNotIsolatedCaller("getContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006340 if (caller == null) {
6341 String msg = "null IApplicationThread when getting content provider "
6342 + name;
Joe Onorato8a9b2202010-02-26 18:56:32 -08006343 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006344 throw new SecurityException(msg);
6345 }
6346
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006347 return getContentProviderImpl(caller, name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006348 }
6349
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006350 public ContentProviderHolder getContentProviderExternal(String name, IBinder token) {
6351 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6352 "Do not have permission in call getContentProviderExternal()");
6353 return getContentProviderExternalUnchecked(name, token);
6354 }
6355
6356 private ContentProviderHolder getContentProviderExternalUnchecked(String name,IBinder token) {
6357 return getContentProviderImpl(null, name, token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006358 }
6359
6360 /**
6361 * Drop a content provider from a ProcessRecord's bookkeeping
6362 * @param cpr
6363 */
6364 public void removeContentProvider(IApplicationThread caller, String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006365 enforceNotIsolatedCaller("removeContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006366 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006367 int userId = UserId.getUserId(Binder.getCallingUid());
6368 ContentProviderRecord cpr = mProviderMap.getProviderByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006369 if(cpr == null) {
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006370 // remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006371 if (DEBUG_PROVIDER) Slog.v(TAG, name +
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006372 " provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006373 return;
6374 }
6375 final ProcessRecord r = getRecordForAppLocked(caller);
6376 if (r == null) {
6377 throw new SecurityException(
6378 "Unable to find app for caller " + caller +
6379 " when removing content provider " + name);
6380 }
6381 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006382 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006383 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp, userId);
6384 if (DEBUG_PROVIDER) Slog.v(TAG, "Removing provider requested by "
6385 + r.info.processName + " from process "
6386 + localCpr.appInfo.processName);
6387 if (localCpr.launchingApp == r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006388 //should not happen. taken care of as a local provider
Joe Onorato8a9b2202010-02-26 18:56:32 -08006389 Slog.w(TAG, "removeContentProvider called on local provider: "
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006390 + cpr.info.name + " in process " + r.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006391 return;
6392 } else {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006393 if (decProviderCount(r, localCpr, null)) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006394 updateOomAdjLocked();
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07006395 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006396 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006397 }
6398 }
6399
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006400 public void removeContentProviderExternal(String name, IBinder token) {
6401 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6402 "Do not have permission in call removeContentProviderExternal()");
6403 removeContentProviderExternalUnchecked(name, token);
6404 }
6405
6406 private void removeContentProviderExternalUnchecked(String name, IBinder token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006407 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006408 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
6409 Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006410 if(cpr == null) {
6411 //remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006412 if(localLOGV) Slog.v(TAG, name+" content provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006413 return;
6414 }
6415
6416 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006417 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006418 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp,
6419 Binder.getOrigCallingUser());
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006420 if (localCpr.hasExternalProcessHandles()) {
6421 if (localCpr.removeExternalProcessHandleLocked(token)) {
6422 updateOomAdjLocked();
6423 } else {
6424 Slog.e(TAG, "Attmpt to remove content provider " + localCpr
6425 + " with no external reference for token: "
6426 + token + ".");
6427 }
6428 } else {
6429 Slog.e(TAG, "Attmpt to remove content provider: " + localCpr
6430 + " with no external references.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006431 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006432 }
6433 }
6434
6435 public final void publishContentProviders(IApplicationThread caller,
6436 List<ContentProviderHolder> providers) {
6437 if (providers == null) {
6438 return;
6439 }
6440
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006441 enforceNotIsolatedCaller("publishContentProviders");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006442 synchronized(this) {
6443 final ProcessRecord r = getRecordForAppLocked(caller);
Amith Yamasani742a6712011-05-04 14:49:28 -07006444 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006445 Slog.v(TAG_MU, "ProcessRecord uid = " + r.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006446 if (r == null) {
6447 throw new SecurityException(
6448 "Unable to find app for caller " + caller
6449 + " (pid=" + Binder.getCallingPid()
6450 + ") when publishing content providers");
6451 }
6452
6453 final long origId = Binder.clearCallingIdentity();
6454
6455 final int N = providers.size();
6456 for (int i=0; i<N; i++) {
6457 ContentProviderHolder src = providers.get(i);
6458 if (src == null || src.info == null || src.provider == null) {
6459 continue;
6460 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07006461 ContentProviderRecord dst = r.pubProviders.get(src.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006462 if (DEBUG_MU)
6463 Slog.v(TAG_MU, "ContentProviderRecord uid = " + dst.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006464 if (dst != null) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006465 ComponentName comp = new ComponentName(dst.info.packageName, dst.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006466 mProviderMap.putProviderByClass(comp, dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006467 String names[] = dst.info.authority.split(";");
6468 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006469 mProviderMap.putProviderByName(names[j], dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006470 }
6471
6472 int NL = mLaunchingProviders.size();
6473 int j;
6474 for (j=0; j<NL; j++) {
6475 if (mLaunchingProviders.get(j) == dst) {
6476 mLaunchingProviders.remove(j);
6477 j--;
6478 NL--;
6479 }
6480 }
6481 synchronized (dst) {
6482 dst.provider = src.provider;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006483 dst.proc = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006484 dst.notifyAll();
6485 }
6486 updateOomAdjLocked(r);
6487 }
6488 }
6489
6490 Binder.restoreCallingIdentity(origId);
6491 }
6492 }
6493
6494 public static final void installSystemProviders() {
Jeff Brown10e89712011-07-08 18:52:57 -07006495 List<ProviderInfo> providers;
Josh Bartel2ecce342010-02-25 10:55:48 -06006496 synchronized (mSelf) {
6497 ProcessRecord app = mSelf.mProcessNames.get("system", Process.SYSTEM_UID);
6498 providers = mSelf.generateApplicationProvidersLocked(app);
Dianne Hackborn5c83a5f2010-03-12 16:46:46 -08006499 if (providers != null) {
6500 for (int i=providers.size()-1; i>=0; i--) {
6501 ProviderInfo pi = (ProviderInfo)providers.get(i);
6502 if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6503 Slog.w(TAG, "Not installing system proc provider " + pi.name
6504 + ": not system .apk");
6505 providers.remove(i);
6506 }
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006507 }
6508 }
6509 }
Josh Bartel2ecce342010-02-25 10:55:48 -06006510 if (providers != null) {
6511 mSystemThread.installSystemProviders(providers);
6512 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08006513
6514 mSelf.mCoreSettingsObserver = new CoreSettingsObserver(mSelf);
Mark Brophyc6350272011-08-05 16:16:39 +01006515
6516 mSelf.mUsageStatsService.monitorPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006517 }
6518
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006519 /**
6520 * Allows app to retrieve the MIME type of a URI without having permission
6521 * to access its content provider.
6522 *
6523 * CTS tests for this functionality can be run with "runtest cts-appsecurity".
6524 *
6525 * Test cases are at cts/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/
6526 * src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java
6527 */
6528 public String getProviderMimeType(Uri uri) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006529 enforceNotIsolatedCaller("getProviderMimeType");
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006530 final String name = uri.getAuthority();
6531 final long ident = Binder.clearCallingIdentity();
6532 ContentProviderHolder holder = null;
6533
6534 try {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006535 holder = getContentProviderExternalUnchecked(name, null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006536 if (holder != null) {
6537 return holder.provider.getType(uri);
6538 }
6539 } catch (RemoteException e) {
6540 Log.w(TAG, "Content provider dead retrieving " + uri, e);
6541 return null;
6542 } finally {
6543 if (holder != null) {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006544 removeContentProviderExternalUnchecked(name, null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006545 }
6546 Binder.restoreCallingIdentity(ident);
6547 }
6548
6549 return null;
6550 }
6551
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006552 // =========================================================
6553 // GLOBAL MANAGEMENT
6554 // =========================================================
6555
6556 final ProcessRecord newProcessRecordLocked(IApplicationThread thread,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006557 ApplicationInfo info, String customProcess, boolean isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006558 String proc = customProcess != null ? customProcess : info.processName;
6559 BatteryStatsImpl.Uid.Proc ps = null;
6560 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006561 int uid = info.uid;
6562 if (isolated) {
6563 int userId = UserId.getUserId(uid);
6564 int stepsLeft = Process.LAST_ISOLATED_UID - Process.FIRST_ISOLATED_UID + 1;
6565 uid = 0;
6566 while (true) {
6567 if (mNextIsolatedProcessUid < Process.FIRST_ISOLATED_UID
6568 || mNextIsolatedProcessUid > Process.LAST_ISOLATED_UID) {
6569 mNextIsolatedProcessUid = Process.FIRST_ISOLATED_UID;
6570 }
6571 uid = UserId.getUid(userId, mNextIsolatedProcessUid);
6572 mNextIsolatedProcessUid++;
6573 if (mIsolatedProcesses.indexOfKey(uid) < 0) {
6574 // No process for this uid, use it.
6575 break;
6576 }
6577 stepsLeft--;
6578 if (stepsLeft <= 0) {
6579 return null;
6580 }
6581 }
6582 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006583 synchronized (stats) {
6584 ps = stats.getProcessStatsLocked(info.uid, proc);
6585 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006586 return new ProcessRecord(ps, thread, info, proc, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006587 }
6588
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006589 final ProcessRecord addAppLocked(ApplicationInfo info, boolean isolated) {
6590 ProcessRecord app;
6591 if (!isolated) {
6592 app = getProcessRecordLocked(info.processName, info.uid);
6593 } else {
6594 app = null;
6595 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006596
6597 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006598 app = newProcessRecordLocked(null, info, null, isolated);
6599 mProcessNames.put(info.processName, app.uid, app);
6600 if (isolated) {
6601 mIsolatedProcesses.put(app.uid, app);
6602 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08006603 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006604 }
6605
Dianne Hackborne7f97212011-02-24 14:40:20 -08006606 // This package really, really can not be stopped.
6607 try {
6608 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07006609 info.packageName, false, UserId.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -08006610 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006611 } catch (IllegalArgumentException e) {
6612 Slog.w(TAG, "Failed trying to unstop package "
6613 + info.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006614 }
6615
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006616 if ((info.flags&(ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT))
6617 == (ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT)) {
6618 app.persistent = true;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07006619 app.maxAdj = ProcessList.PERSISTENT_PROC_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006620 }
6621 if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) {
6622 mPersistentStartingProcesses.add(app);
6623 startProcessLocked(app, "added application", app.processName);
6624 }
6625
6626 return app;
6627 }
6628
6629 public void unhandledBack() {
6630 enforceCallingPermission(android.Manifest.permission.FORCE_BACK,
6631 "unhandledBack()");
6632
6633 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006634 int count = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08006635 if (DEBUG_SWITCH) Slog.d(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006636 TAG, "Performing unhandledBack(): stack size = " + count);
6637 if (count > 1) {
6638 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006639 mMainStack.finishActivityLocked((ActivityRecord)mMainStack.mHistory.get(count-1),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006640 count-1, Activity.RESULT_CANCELED, null, "unhandled-back");
6641 Binder.restoreCallingIdentity(origId);
6642 }
6643 }
6644 }
6645
6646 public ParcelFileDescriptor openContentUri(Uri uri) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006647 enforceNotIsolatedCaller("openContentUri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006648 String name = uri.getAuthority();
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006649 ContentProviderHolder cph = getContentProviderExternalUnchecked(name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006650 ParcelFileDescriptor pfd = null;
6651 if (cph != null) {
6652 // We record the binder invoker's uid in thread-local storage before
6653 // going to the content provider to open the file. Later, in the code
6654 // that handles all permissions checks, we look for this uid and use
6655 // that rather than the Activity Manager's own uid. The effect is that
6656 // we do the check against the caller's permissions even though it looks
6657 // to the content provider like the Activity Manager itself is making
6658 // the request.
6659 sCallerIdentity.set(new Identity(
6660 Binder.getCallingPid(), Binder.getCallingUid()));
6661 try {
6662 pfd = cph.provider.openFile(uri, "r");
6663 } catch (FileNotFoundException e) {
6664 // do nothing; pfd will be returned null
6665 } finally {
6666 // Ensure that whatever happens, we clean up the identity state
6667 sCallerIdentity.remove();
6668 }
6669
6670 // We've got the fd now, so we're done with the provider.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006671 removeContentProviderExternalUnchecked(name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006672 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006673 Slog.d(TAG, "Failed to get provider for authority '" + name + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006674 }
6675 return pfd;
6676 }
6677
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006678 // Actually is sleeping or shutting down or whatever else in the future
6679 // is an inactive state.
6680 public boolean isSleeping() {
6681 return mSleeping || mShuttingDown;
6682 }
6683
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006684 public void goingToSleep() {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006685 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
6686 != PackageManager.PERMISSION_GRANTED) {
6687 throw new SecurityException("Requires permission "
6688 + android.Manifest.permission.DEVICE_POWER);
6689 }
6690
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006691 synchronized(this) {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006692 mWentToSleep = true;
Jeff Brownc042ee22012-05-08 13:03:42 -07006693 updateEventDispatchingLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006694
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006695 if (!mSleeping) {
6696 mSleeping = true;
6697 mMainStack.stopIfSleepingLocked();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006698
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006699 // Initialize the wake times of all processes.
6700 checkExcessivePowerUsageLocked(false);
6701 mHandler.removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
6702 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
6703 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
6704 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006705 }
6706 }
6707
Dianne Hackborn55280a92009-05-07 15:53:46 -07006708 public boolean shutdown(int timeout) {
6709 if (checkCallingPermission(android.Manifest.permission.SHUTDOWN)
6710 != PackageManager.PERMISSION_GRANTED) {
6711 throw new SecurityException("Requires permission "
6712 + android.Manifest.permission.SHUTDOWN);
6713 }
6714
6715 boolean timedout = false;
6716
6717 synchronized(this) {
6718 mShuttingDown = true;
Jeff Brownc042ee22012-05-08 13:03:42 -07006719 updateEventDispatchingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07006720
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006721 if (mMainStack.mResumedActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006722 mMainStack.stopIfSleepingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07006723 final long endTime = System.currentTimeMillis() + timeout;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006724 while (mMainStack.mResumedActivity != null
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08006725 || mMainStack.mPausingActivity != null) {
Dianne Hackborn55280a92009-05-07 15:53:46 -07006726 long delay = endTime - System.currentTimeMillis();
6727 if (delay <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006728 Slog.w(TAG, "Activity manager shutdown timed out");
Dianne Hackborn55280a92009-05-07 15:53:46 -07006729 timedout = true;
6730 break;
6731 }
6732 try {
6733 this.wait();
6734 } catch (InterruptedException e) {
6735 }
6736 }
6737 }
6738 }
6739
6740 mUsageStatsService.shutdown();
6741 mBatteryStatsService.shutdown();
6742
6743 return timedout;
6744 }
6745
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006746 public final void activitySlept(IBinder token) {
6747 if (localLOGV) Slog.v(
6748 TAG, "Activity slept: token=" + token);
6749
6750 ActivityRecord r = null;
6751
6752 final long origId = Binder.clearCallingIdentity();
6753
6754 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006755 r = mMainStack.isInStackLocked(token);
6756 if (r != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006757 mMainStack.activitySleptLocked(r);
6758 }
6759 }
6760
6761 Binder.restoreCallingIdentity(origId);
6762 }
6763
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006764 private void comeOutOfSleepIfNeededLocked() {
6765 if (!mWentToSleep && !mLockScreenShown) {
6766 if (mSleeping) {
6767 mSleeping = false;
6768 mMainStack.awakeFromSleepingLocked();
6769 mMainStack.resumeTopActivityLocked(null);
6770 }
6771 }
6772 }
6773
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006774 public void wakingUp() {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006775 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
6776 != PackageManager.PERMISSION_GRANTED) {
6777 throw new SecurityException("Requires permission "
6778 + android.Manifest.permission.DEVICE_POWER);
6779 }
6780
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006781 synchronized(this) {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006782 mWentToSleep = false;
Jeff Brownc042ee22012-05-08 13:03:42 -07006783 updateEventDispatchingLocked();
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006784 comeOutOfSleepIfNeededLocked();
6785 }
6786 }
6787
Jeff Brownc042ee22012-05-08 13:03:42 -07006788 private void updateEventDispatchingLocked() {
6789 mWindowManager.setEventDispatching(mBooted && !mWentToSleep && !mShuttingDown);
6790 }
6791
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006792 public void setLockScreenShown(boolean shown) {
6793 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
6794 != PackageManager.PERMISSION_GRANTED) {
6795 throw new SecurityException("Requires permission "
6796 + android.Manifest.permission.DEVICE_POWER);
6797 }
6798
6799 synchronized(this) {
6800 mLockScreenShown = shown;
6801 comeOutOfSleepIfNeededLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006802 }
6803 }
6804
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006805 public void stopAppSwitches() {
6806 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
6807 != PackageManager.PERMISSION_GRANTED) {
6808 throw new SecurityException("Requires permission "
6809 + android.Manifest.permission.STOP_APP_SWITCHES);
6810 }
6811
6812 synchronized(this) {
6813 mAppSwitchesAllowedTime = SystemClock.uptimeMillis()
6814 + APP_SWITCH_DELAY_TIME;
6815 mDidAppSwitch = false;
6816 mHandler.removeMessages(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
6817 Message msg = mHandler.obtainMessage(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
6818 mHandler.sendMessageDelayed(msg, APP_SWITCH_DELAY_TIME);
6819 }
6820 }
6821
6822 public void resumeAppSwitches() {
6823 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
6824 != PackageManager.PERMISSION_GRANTED) {
6825 throw new SecurityException("Requires permission "
6826 + android.Manifest.permission.STOP_APP_SWITCHES);
6827 }
6828
6829 synchronized(this) {
6830 // Note that we don't execute any pending app switches... we will
6831 // let those wait until either the timeout, or the next start
6832 // activity request.
6833 mAppSwitchesAllowedTime = 0;
6834 }
6835 }
6836
6837 boolean checkAppSwitchAllowedLocked(int callingPid, int callingUid,
6838 String name) {
6839 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
6840 return true;
6841 }
6842
6843 final int perm = checkComponentPermission(
6844 android.Manifest.permission.STOP_APP_SWITCHES, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006845 callingUid, -1, true);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006846 if (perm == PackageManager.PERMISSION_GRANTED) {
6847 return true;
6848 }
6849
Joe Onorato8a9b2202010-02-26 18:56:32 -08006850 Slog.w(TAG, name + " request from " + callingUid + " stopped");
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006851 return false;
6852 }
6853
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006854 public void setDebugApp(String packageName, boolean waitForDebugger,
6855 boolean persistent) {
6856 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
6857 "setDebugApp()");
6858
6859 // Note that this is not really thread safe if there are multiple
6860 // callers into it at the same time, but that's not a situation we
6861 // care about.
6862 if (persistent) {
6863 final ContentResolver resolver = mContext.getContentResolver();
6864 Settings.System.putString(
6865 resolver, Settings.System.DEBUG_APP,
6866 packageName);
6867 Settings.System.putInt(
6868 resolver, Settings.System.WAIT_FOR_DEBUGGER,
6869 waitForDebugger ? 1 : 0);
6870 }
6871
6872 synchronized (this) {
6873 if (!persistent) {
6874 mOrigDebugApp = mDebugApp;
6875 mOrigWaitForDebugger = mWaitForDebugger;
6876 }
6877 mDebugApp = packageName;
6878 mWaitForDebugger = waitForDebugger;
6879 mDebugTransient = !persistent;
6880 if (packageName != null) {
6881 final long origId = Binder.clearCallingIdentity();
Amith Yamasani483f3b02012-03-13 16:08:00 -07006882 forceStopPackageLocked(packageName, -1, false, false, true, true, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006883 Binder.restoreCallingIdentity(origId);
6884 }
6885 }
6886 }
6887
Siva Velusamy92a8b222012-03-09 16:24:04 -08006888 void setOpenGlTraceApp(ApplicationInfo app, String processName) {
6889 synchronized (this) {
6890 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
6891 if (!isDebuggable) {
6892 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
6893 throw new SecurityException("Process not debuggable: " + app.packageName);
6894 }
6895 }
6896
6897 mOpenGlTraceApp = processName;
6898 }
6899 }
6900
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07006901 void setProfileApp(ApplicationInfo app, String processName, String profileFile,
6902 ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
6903 synchronized (this) {
6904 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
6905 if (!isDebuggable) {
6906 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
6907 throw new SecurityException("Process not debuggable: " + app.packageName);
6908 }
6909 }
6910 mProfileApp = processName;
6911 mProfileFile = profileFile;
6912 if (mProfileFd != null) {
6913 try {
6914 mProfileFd.close();
6915 } catch (IOException e) {
6916 }
6917 mProfileFd = null;
6918 }
6919 mProfileFd = profileFd;
6920 mProfileType = 0;
6921 mAutoStopProfiler = autoStopProfiler;
6922 }
6923 }
6924
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006925 public void setAlwaysFinish(boolean enabled) {
6926 enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH,
6927 "setAlwaysFinish()");
6928
6929 Settings.System.putInt(
6930 mContext.getContentResolver(),
6931 Settings.System.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0);
6932
6933 synchronized (this) {
6934 mAlwaysFinishActivities = enabled;
6935 }
6936 }
6937
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006938 public void setActivityController(IActivityController controller) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006939 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006940 "setActivityController()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006941 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006942 mController = controller;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006943 }
6944 }
6945
Dianne Hackborn9327f4f2010-01-29 10:38:29 -08006946 public boolean isUserAMonkey() {
6947 // For now the fact that there is a controller implies
6948 // we have a monkey.
6949 synchronized (this) {
6950 return mController != null;
6951 }
6952 }
6953
Jeff Sharkeya4620792011-05-20 15:29:23 -07006954 public void registerProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08006955 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
6956 "registerProcessObserver()");
6957 synchronized (this) {
6958 mProcessObservers.register(observer);
6959 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07006960 }
6961
6962 public void unregisterProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08006963 synchronized (this) {
6964 mProcessObservers.unregister(observer);
6965 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07006966 }
6967
Daniel Sandler69a48172010-06-23 16:29:36 -04006968 public void setImmersive(IBinder token, boolean immersive) {
6969 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006970 ActivityRecord r = mMainStack.isInStackLocked(token);
6971 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04006972 throw new IllegalArgumentException();
6973 }
Daniel Sandler69a48172010-06-23 16:29:36 -04006974 r.immersive = immersive;
6975 }
6976 }
6977
6978 public boolean isImmersive(IBinder token) {
6979 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006980 ActivityRecord r = mMainStack.isInStackLocked(token);
6981 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04006982 throw new IllegalArgumentException();
6983 }
Daniel Sandler69a48172010-06-23 16:29:36 -04006984 return r.immersive;
6985 }
6986 }
6987
6988 public boolean isTopActivityImmersive() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006989 enforceNotIsolatedCaller("startActivity");
Daniel Sandler69a48172010-06-23 16:29:36 -04006990 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006991 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Daniel Sandler69a48172010-06-23 16:29:36 -04006992 return (r != null) ? r.immersive : false;
6993 }
6994 }
6995
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006996 public final void enterSafeMode() {
6997 synchronized(this) {
6998 // It only makes sense to do this before the system is ready
6999 // and started launching other packages.
7000 if (!mSystemReady) {
7001 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007002 AppGlobals.getPackageManager().enterSafeMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007003 } catch (RemoteException e) {
7004 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007005 }
7006 }
7007 }
7008
Jeff Brownb09abc12011-01-13 21:08:27 -08007009 public final void showSafeModeOverlay() {
7010 View v = LayoutInflater.from(mContext).inflate(
7011 com.android.internal.R.layout.safe_mode, null);
7012 WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
7013 lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
7014 lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
7015 lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
7016 lp.gravity = Gravity.BOTTOM | Gravity.LEFT;
7017 lp.format = v.getBackground().getOpacity();
7018 lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
7019 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
7020 ((WindowManager)mContext.getSystemService(
7021 Context.WINDOW_SERVICE)).addView(v, lp);
7022 }
7023
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007024 public void noteWakeupAlarm(IIntentSender sender) {
7025 if (!(sender instanceof PendingIntentRecord)) {
7026 return;
7027 }
7028 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
7029 synchronized (stats) {
7030 if (mBatteryStatsService.isOnBattery()) {
7031 mBatteryStatsService.enforceCallingPermission();
7032 PendingIntentRecord rec = (PendingIntentRecord)sender;
7033 int MY_UID = Binder.getCallingUid();
7034 int uid = rec.uid == MY_UID ? Process.SYSTEM_UID : rec.uid;
7035 BatteryStatsImpl.Uid.Pkg pkg =
7036 stats.getPackageStatsLocked(uid, rec.key.packageName);
7037 pkg.incWakeupsLocked();
7038 }
7039 }
7040 }
7041
Dianne Hackborn64825172011-03-02 21:32:58 -08007042 public boolean killPids(int[] pids, String pReason, boolean secure) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007043 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007044 throw new SecurityException("killPids only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007045 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007046 String reason = (pReason == null) ? "Unknown" : pReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007047 // XXX Note: don't acquire main activity lock here, because the window
7048 // manager calls in with its locks held.
7049
7050 boolean killed = false;
7051 synchronized (mPidsSelfLocked) {
7052 int[] types = new int[pids.length];
7053 int worstType = 0;
7054 for (int i=0; i<pids.length; i++) {
7055 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7056 if (proc != null) {
7057 int type = proc.setAdj;
7058 types[i] = type;
7059 if (type > worstType) {
7060 worstType = type;
7061 }
7062 }
7063 }
7064
Dianne Hackborn64825172011-03-02 21:32:58 -08007065 // If the worst oom_adj is somewhere in the hidden proc LRU range,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007066 // then constrain it so we will kill all hidden procs.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007067 if (worstType < ProcessList.HIDDEN_APP_MAX_ADJ
7068 && worstType > ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07007069 worstType = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007070 }
Dianne Hackborn64825172011-03-02 21:32:58 -08007071
7072 // If this is not a secure call, don't let it kill processes that
7073 // are important.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007074 if (!secure && worstType < ProcessList.SERVICE_ADJ) {
7075 worstType = ProcessList.SERVICE_ADJ;
Dianne Hackborn64825172011-03-02 21:32:58 -08007076 }
7077
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007078 Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007079 for (int i=0; i<pids.length; i++) {
7080 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7081 if (proc == null) {
7082 continue;
7083 }
7084 int adj = proc.setAdj;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007085 if (adj >= worstType && !proc.killedBackground) {
Dianne Hackborn8633e682010-04-22 16:03:41 -07007086 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007087 EventLog.writeEvent(EventLogTags.AM_KILL, proc.pid,
7088 proc.processName, adj, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007089 killed = true;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007090 proc.killedBackground = true;
7091 Process.killProcessQuiet(pids[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007092 }
7093 }
7094 }
7095 return killed;
7096 }
Jeff Sharkeyb9a07012012-03-22 17:00:04 -07007097
7098 @Override
7099 public boolean killProcessesBelowForeground(String reason) {
7100 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7101 throw new SecurityException("killProcessesBelowForeground() only available to system");
7102 }
7103
7104 return killProcessesBelowAdj(ProcessList.FOREGROUND_APP_ADJ, reason);
7105 }
7106
7107 private boolean killProcessesBelowAdj(int belowAdj, String reason) {
7108 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7109 throw new SecurityException("killProcessesBelowAdj() only available to system");
7110 }
7111
7112 boolean killed = false;
7113 synchronized (mPidsSelfLocked) {
7114 final int size = mPidsSelfLocked.size();
7115 for (int i = 0; i < size; i++) {
7116 final int pid = mPidsSelfLocked.keyAt(i);
7117 final ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7118 if (proc == null) continue;
7119
7120 final int adj = proc.setAdj;
7121 if (adj > belowAdj && !proc.killedBackground) {
7122 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
7123 EventLog.writeEvent(
7124 EventLogTags.AM_KILL, proc.pid, proc.processName, adj, reason);
7125 killed = true;
7126 proc.killedBackground = true;
7127 Process.killProcessQuiet(pid);
7128 }
7129 }
7130 }
7131 return killed;
7132 }
7133
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007134 public final void startRunning(String pkg, String cls, String action,
7135 String data) {
7136 synchronized(this) {
7137 if (mStartRunning) {
7138 return;
7139 }
7140 mStartRunning = true;
7141 mTopComponent = pkg != null && cls != null
7142 ? new ComponentName(pkg, cls) : null;
7143 mTopAction = action != null ? action : Intent.ACTION_MAIN;
7144 mTopData = data;
7145 if (!mSystemReady) {
7146 return;
7147 }
7148 }
7149
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007150 systemReady(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007151 }
7152
7153 private void retrieveSettings() {
7154 final ContentResolver resolver = mContext.getContentResolver();
7155 String debugApp = Settings.System.getString(
7156 resolver, Settings.System.DEBUG_APP);
7157 boolean waitForDebugger = Settings.System.getInt(
7158 resolver, Settings.System.WAIT_FOR_DEBUGGER, 0) != 0;
7159 boolean alwaysFinishActivities = Settings.System.getInt(
7160 resolver, Settings.System.ALWAYS_FINISH_ACTIVITIES, 0) != 0;
7161
7162 Configuration configuration = new Configuration();
7163 Settings.System.getConfiguration(resolver, configuration);
7164
7165 synchronized (this) {
7166 mDebugApp = mOrigDebugApp = debugApp;
7167 mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger;
7168 mAlwaysFinishActivities = alwaysFinishActivities;
7169 // This happens before any activities are started, so we can
7170 // change mConfiguration in-place.
Dianne Hackborn813075a62011-11-14 17:45:19 -08007171 updateConfigurationLocked(configuration, null, false, true);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007172 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Initial config: " + mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007173 }
7174 }
7175
7176 public boolean testIsSystemReady() {
7177 // no need to synchronize(this) just to read & return the value
7178 return mSystemReady;
7179 }
7180
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007181 private static File getCalledPreBootReceiversFile() {
7182 File dataDir = Environment.getDataDirectory();
7183 File systemDir = new File(dataDir, "system");
7184 File fname = new File(systemDir, "called_pre_boots.dat");
7185 return fname;
7186 }
Dianne Hackborn661cd522011-08-22 00:26:20 -07007187
7188 static final int LAST_DONE_VERSION = 10000;
7189
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007190 private static ArrayList<ComponentName> readLastDonePreBootReceivers() {
7191 ArrayList<ComponentName> lastDoneReceivers = new ArrayList<ComponentName>();
7192 File file = getCalledPreBootReceiversFile();
7193 FileInputStream fis = null;
7194 try {
7195 fis = new FileInputStream(file);
7196 DataInputStream dis = new DataInputStream(new BufferedInputStream(fis, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007197 int fvers = dis.readInt();
7198 if (fvers == LAST_DONE_VERSION) {
7199 String vers = dis.readUTF();
7200 String codename = dis.readUTF();
7201 String build = dis.readUTF();
7202 if (android.os.Build.VERSION.RELEASE.equals(vers)
7203 && android.os.Build.VERSION.CODENAME.equals(codename)
7204 && android.os.Build.VERSION.INCREMENTAL.equals(build)) {
7205 int num = dis.readInt();
7206 while (num > 0) {
7207 num--;
7208 String pkg = dis.readUTF();
7209 String cls = dis.readUTF();
7210 lastDoneReceivers.add(new ComponentName(pkg, cls));
7211 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007212 }
7213 }
7214 } catch (FileNotFoundException e) {
7215 } catch (IOException e) {
7216 Slog.w(TAG, "Failure reading last done pre-boot receivers", e);
7217 } finally {
7218 if (fis != null) {
7219 try {
7220 fis.close();
7221 } catch (IOException e) {
7222 }
7223 }
7224 }
7225 return lastDoneReceivers;
7226 }
7227
7228 private static void writeLastDonePreBootReceivers(ArrayList<ComponentName> list) {
7229 File file = getCalledPreBootReceiversFile();
7230 FileOutputStream fos = null;
7231 DataOutputStream dos = null;
7232 try {
7233 Slog.i(TAG, "Writing new set of last done pre-boot receivers...");
7234 fos = new FileOutputStream(file);
7235 dos = new DataOutputStream(new BufferedOutputStream(fos, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007236 dos.writeInt(LAST_DONE_VERSION);
7237 dos.writeUTF(android.os.Build.VERSION.RELEASE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007238 dos.writeUTF(android.os.Build.VERSION.CODENAME);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007239 dos.writeUTF(android.os.Build.VERSION.INCREMENTAL);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007240 dos.writeInt(list.size());
7241 for (int i=0; i<list.size(); i++) {
7242 dos.writeUTF(list.get(i).getPackageName());
7243 dos.writeUTF(list.get(i).getClassName());
7244 }
7245 } catch (IOException e) {
7246 Slog.w(TAG, "Failure writing last done pre-boot receivers", e);
7247 file.delete();
7248 } finally {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07007249 FileUtils.sync(fos);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007250 if (dos != null) {
7251 try {
7252 dos.close();
7253 } catch (IOException e) {
7254 // TODO Auto-generated catch block
7255 e.printStackTrace();
7256 }
7257 }
7258 }
7259 }
7260
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007261 public void systemReady(final Runnable goingCallback) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007262 synchronized(this) {
7263 if (mSystemReady) {
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007264 if (goingCallback != null) goingCallback.run();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007265 return;
7266 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007267
7268 // Check to see if there are any update receivers to run.
7269 if (!mDidUpdate) {
7270 if (mWaitingUpdate) {
7271 return;
7272 }
7273 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
7274 List<ResolveInfo> ris = null;
7275 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007276 ris = AppGlobals.getPackageManager().queryIntentReceivers(
Amith Yamasani483f3b02012-03-13 16:08:00 -07007277 intent, null, 0, 0);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007278 } catch (RemoteException e) {
7279 }
7280 if (ris != null) {
7281 for (int i=ris.size()-1; i>=0; i--) {
7282 if ((ris.get(i).activityInfo.applicationInfo.flags
7283 &ApplicationInfo.FLAG_SYSTEM) == 0) {
7284 ris.remove(i);
7285 }
7286 }
7287 intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007288
7289 ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers();
7290
7291 final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007292 for (int i=0; i<ris.size(); i++) {
7293 ActivityInfo ai = ris.get(i).activityInfo;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007294 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7295 if (lastDoneReceivers.contains(comp)) {
7296 ris.remove(i);
7297 i--;
7298 }
7299 }
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07007300
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007301 for (int i=0; i<ris.size(); i++) {
7302 ActivityInfo ai = ris.get(i).activityInfo;
7303 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7304 doneReceivers.add(comp);
7305 intent.setComponent(comp);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007306 IIntentReceiver finisher = null;
Dianne Hackbornd6847842010-01-12 18:14:19 -08007307 if (i == ris.size()-1) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007308 finisher = new IIntentReceiver.Stub() {
7309 public void performReceive(Intent intent, int resultCode,
Dianne Hackborn68d881c2009-10-05 13:58:17 -07007310 String data, Bundle extras, boolean ordered,
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007311 boolean sticky) {
7312 // The raw IIntentReceiver interface is called
7313 // with the AM lock held, so redispatch to
7314 // execute our code without the lock.
7315 mHandler.post(new Runnable() {
7316 public void run() {
7317 synchronized (ActivityManagerService.this) {
7318 mDidUpdate = true;
7319 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007320 writeLastDonePreBootReceivers(doneReceivers);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007321 showBootMessage(mContext.getText(
7322 R.string.android_upgrading_complete),
7323 false);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007324 systemReady(goingCallback);
7325 }
7326 });
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007327 }
7328 };
7329 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08007330 Slog.i(TAG, "Sending system update to: " + intent.getComponent());
Amith Yamasani742a6712011-05-04 14:49:28 -07007331 /* TODO: Send this to all users */
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007332 broadcastIntentLocked(null, null, intent, null, finisher,
Amith Yamasani742a6712011-05-04 14:49:28 -07007333 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID,
Amith Yamasanic600e21f2012-02-14 16:08:07 -08007334 0 /* UserId zero */);
Dianne Hackbornd6847842010-01-12 18:14:19 -08007335 if (finisher != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007336 mWaitingUpdate = true;
7337 }
7338 }
7339 }
7340 if (mWaitingUpdate) {
7341 return;
7342 }
7343 mDidUpdate = true;
7344 }
7345
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007346 mSystemReady = true;
7347 if (!mStartRunning) {
7348 return;
7349 }
7350 }
7351
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007352 ArrayList<ProcessRecord> procsToKill = null;
7353 synchronized(mPidsSelfLocked) {
7354 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
7355 ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7356 if (!isAllowedWhileBooting(proc.info)){
7357 if (procsToKill == null) {
7358 procsToKill = new ArrayList<ProcessRecord>();
7359 }
7360 procsToKill.add(proc);
7361 }
7362 }
7363 }
7364
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007365 synchronized(this) {
7366 if (procsToKill != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007367 for (int i=procsToKill.size()-1; i>=0; i--) {
7368 ProcessRecord proc = procsToKill.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007369 Slog.i(TAG, "Removing system update proc: " + proc);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007370 removeProcessLocked(proc, true, false, "system update done");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007371 }
7372 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007373
7374 // Now that we have cleaned up any update processes, we
7375 // are ready to start launching real processes and know that
7376 // we won't trample on them any more.
7377 mProcessesReady = true;
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007378 }
7379
Joe Onorato8a9b2202010-02-26 18:56:32 -08007380 Slog.i(TAG, "System now ready");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007381 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007382 SystemClock.uptimeMillis());
7383
7384 synchronized(this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007385 // Make sure we have no pre-ready processes sitting around.
7386
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007387 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
7388 ResolveInfo ri = mContext.getPackageManager()
7389 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST),
Dianne Hackborn1655be42009-05-08 14:29:01 -07007390 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007391 CharSequence errorMsg = null;
7392 if (ri != null) {
7393 ActivityInfo ai = ri.activityInfo;
7394 ApplicationInfo app = ai.applicationInfo;
7395 if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7396 mTopAction = Intent.ACTION_FACTORY_TEST;
7397 mTopData = null;
7398 mTopComponent = new ComponentName(app.packageName,
7399 ai.name);
7400 } else {
7401 errorMsg = mContext.getResources().getText(
7402 com.android.internal.R.string.factorytest_not_system);
7403 }
7404 } else {
7405 errorMsg = mContext.getResources().getText(
7406 com.android.internal.R.string.factorytest_no_action);
7407 }
7408 if (errorMsg != null) {
7409 mTopAction = null;
7410 mTopData = null;
7411 mTopComponent = null;
7412 Message msg = Message.obtain();
7413 msg.what = SHOW_FACTORY_ERROR_MSG;
7414 msg.getData().putCharSequence("msg", errorMsg);
7415 mHandler.sendMessage(msg);
7416 }
7417 }
7418 }
7419
7420 retrieveSettings();
7421
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007422 if (goingCallback != null) goingCallback.run();
7423
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007424 synchronized (this) {
7425 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
7426 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007427 List apps = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07007428 getPersistentApplications(STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007429 if (apps != null) {
7430 int N = apps.size();
7431 int i;
7432 for (i=0; i<N; i++) {
7433 ApplicationInfo info
7434 = (ApplicationInfo)apps.get(i);
7435 if (info != null &&
7436 !info.packageName.equals("android")) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007437 addAppLocked(info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007438 }
7439 }
7440 }
7441 } catch (RemoteException ex) {
7442 // pm is in same process, this will never happen.
7443 }
7444 }
7445
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007446 // Start up initial activity.
7447 mBooting = true;
7448
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007449 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007450 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007451 Message msg = Message.obtain();
7452 msg.what = SHOW_UID_ERROR_MSG;
7453 mHandler.sendMessage(msg);
7454 }
7455 } catch (RemoteException e) {
7456 }
7457
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007458 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007459 }
7460 }
7461
Dan Egnorb7f03672009-12-09 16:22:32 -08007462 private boolean makeAppCrashingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007463 String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007464 app.crashing = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007465 app.crashingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007466 ActivityManager.ProcessErrorStateInfo.CRASHED, null, shortMsg, longMsg, stackTrace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007467 startAppProblemLocked(app);
7468 app.stopFreezingAllLocked();
7469 return handleAppCrashLocked(app);
7470 }
7471
Dan Egnorb7f03672009-12-09 16:22:32 -08007472 private void makeAppNotRespondingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007473 String activity, String shortMsg, String longMsg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007474 app.notResponding = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007475 app.notRespondingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007476 ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING,
7477 activity, shortMsg, longMsg, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007478 startAppProblemLocked(app);
7479 app.stopFreezingAllLocked();
7480 }
7481
7482 /**
7483 * Generate a process error record, suitable for attachment to a ProcessRecord.
7484 *
7485 * @param app The ProcessRecord in which the error occurred.
7486 * @param condition Crashing, Application Not Responding, etc. Values are defined in
7487 * ActivityManager.AppErrorStateInfo
Dan Egnor60d87622009-12-16 16:32:58 -08007488 * @param activity The activity associated with the crash, if known.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007489 * @param shortMsg Short message describing the crash.
7490 * @param longMsg Long message describing the crash.
Dan Egnorb7f03672009-12-09 16:22:32 -08007491 * @param stackTrace Full crash stack trace, may be null.
7492 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007493 * @return Returns a fully-formed AppErrorStateInfo record.
7494 */
7495 private ActivityManager.ProcessErrorStateInfo generateProcessError(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007496 int condition, String activity, String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007497 ActivityManager.ProcessErrorStateInfo report = new ActivityManager.ProcessErrorStateInfo();
Dan Egnorb7f03672009-12-09 16:22:32 -08007498
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007499 report.condition = condition;
7500 report.processName = app.processName;
7501 report.pid = app.pid;
7502 report.uid = app.info.uid;
Dan Egnor60d87622009-12-16 16:32:58 -08007503 report.tag = activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007504 report.shortMsg = shortMsg;
7505 report.longMsg = longMsg;
Dan Egnorb7f03672009-12-09 16:22:32 -08007506 report.stackTrace = stackTrace;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007507
7508 return report;
7509 }
7510
Dan Egnor42471dd2010-01-07 17:25:22 -08007511 void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007512 synchronized (this) {
7513 app.crashing = false;
7514 app.crashingReport = null;
7515 app.notResponding = false;
7516 app.notRespondingReport = null;
7517 if (app.anrDialog == fromDialog) {
7518 app.anrDialog = null;
7519 }
7520 if (app.waitDialog == fromDialog) {
7521 app.waitDialog = null;
7522 }
7523 if (app.pid > 0 && app.pid != MY_PID) {
Dan Egnor42471dd2010-01-07 17:25:22 -08007524 handleAppCrashLocked(app);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007525 Slog.i(ActivityManagerService.TAG, "Killing " + app + ": user's request");
Dianne Hackborn8633e682010-04-22 16:03:41 -07007526 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
7527 app.processName, app.setAdj, "user's request after error");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007528 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007529 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007530 }
7531 }
Dan Egnor42471dd2010-01-07 17:25:22 -08007532
Dan Egnorb7f03672009-12-09 16:22:32 -08007533 private boolean handleAppCrashLocked(ProcessRecord app) {
Mike Lockwood86548c42011-09-13 17:21:46 -04007534 if (mHeadless) {
7535 Log.e(TAG, "handleAppCrashLocked: " + app.processName);
7536 return false;
7537 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007538 long now = SystemClock.uptimeMillis();
7539
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007540 Long crashTime;
7541 if (!app.isolated) {
7542 crashTime = mProcessCrashTimes.get(app.info.processName, app.uid);
7543 } else {
7544 crashTime = null;
7545 }
Dianne Hackborn7d608422011-08-07 16:24:18 -07007546 if (crashTime != null && now < crashTime+ProcessList.MIN_CRASH_INTERVAL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007547 // This process loses!
Joe Onorato8a9b2202010-02-26 18:56:32 -08007548 Slog.w(TAG, "Process " + app.info.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007549 + " has crashed too many times: killing!");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007550 EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007551 app.info.processName, app.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007552 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
7553 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007554 if (r.app == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007555 Slog.w(TAG, " Force finishing activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007556 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007557 r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED, null, "crashed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007558 }
7559 }
7560 if (!app.persistent) {
7561 // We don't want to start this process again until the user
7562 // explicitly does so... but for persistent process, we really
7563 // need to keep it running. If a persistent process is actually
7564 // repeatedly crashing, then badness for everyone.
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007565 EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007566 app.info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007567 if (!app.isolated) {
7568 // XXX We don't have a way to mark isolated processes
7569 // as bad, since they don't have a peristent identity.
7570 mBadProcesses.put(app.info.processName, app.uid, now);
7571 mProcessCrashTimes.remove(app.info.processName, app.uid);
7572 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007573 app.bad = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007574 app.removed = true;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07007575 // Don't let services in this process be restarted and potentially
7576 // annoy the user repeatedly. Unless it is persistent, since those
7577 // processes run critical code.
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007578 removeProcessLocked(app, false, false, "crash");
Dianne Hackborncb44d962011-03-10 17:02:27 -08007579 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007580 return false;
7581 }
Dianne Hackborncb44d962011-03-10 17:02:27 -08007582 mMainStack.resumeTopActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007583 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007584 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Kevin Hester-Chowd87a9be2012-03-05 08:01:00 -08007585 if (r != null && r.app == app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007586 // If the top running activity is from this crashing
7587 // process, then terminate it to avoid getting in a loop.
7588 Slog.w(TAG, " Force finishing activity "
7589 + r.intent.getComponent().flattenToShortString());
Dianne Hackbornbe707852011-11-11 14:32:10 -08007590 int index = mMainStack.indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007591 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007592 Activity.RESULT_CANCELED, null, "crashed");
Dianne Hackborn070783f2010-12-29 16:46:28 -08007593 // Also terminate any activities below it that aren't yet
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007594 // stopped, to avoid a situation where one will get
7595 // re-start our crashing activity once it gets resumed again.
7596 index--;
7597 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007598 r = (ActivityRecord)mMainStack.mHistory.get(index);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007599 if (r.state == ActivityState.RESUMED
7600 || r.state == ActivityState.PAUSING
7601 || r.state == ActivityState.PAUSED) {
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08007602 if (!r.isHomeActivity || mHomeProcess != r.app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007603 Slog.w(TAG, " Force finishing activity "
7604 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007605 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007606 Activity.RESULT_CANCELED, null, "crashed");
7607 }
7608 }
7609 }
7610 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007611 }
7612
7613 // Bump up the crash count of any services currently running in the proc.
7614 if (app.services.size() != 0) {
7615 // Any services running in the application need to be placed
7616 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -07007617 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007618 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07007619 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007620 sr.crashCount++;
7621 }
7622 }
Mattias Larssona4fd0072010-06-22 22:37:03 +02007623
7624 // If the crashing process is what we consider to be the "home process" and it has been
7625 // replaced by a third-party app, clear the package preferred activities from packages
7626 // with a home activity running in the process to prevent a repeatedly crashing app
7627 // from blocking the user to manually clear the list.
7628 if (app == mHomeProcess && mHomeProcess.activities.size() > 0
7629 && (mHomeProcess.info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
7630 Iterator it = mHomeProcess.activities.iterator();
7631 while (it.hasNext()) {
Jean-Baptiste Queru5ea89f72010-07-30 09:30:31 -07007632 ActivityRecord r = (ActivityRecord)it.next();
Mattias Larssona4fd0072010-06-22 22:37:03 +02007633 if (r.isHomeActivity) {
7634 Log.i(TAG, "Clearing package preferred activities from " + r.packageName);
7635 try {
7636 ActivityThread.getPackageManager()
7637 .clearPackagePreferredActivities(r.packageName);
7638 } catch (RemoteException c) {
7639 // pm is in same process, this will never happen.
7640 }
7641 }
7642 }
7643 }
7644
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007645 if (!app.isolated) {
7646 // XXX Can't keep track of crash times for isolated processes,
7647 // because they don't have a perisistent identity.
7648 mProcessCrashTimes.put(app.info.processName, app.uid, now);
7649 }
7650
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007651 return true;
7652 }
7653
7654 void startAppProblemLocked(ProcessRecord app) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08007655 app.errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver(
7656 mContext, app.info.packageName, app.info.flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007657 skipCurrentReceiverLocked(app);
7658 }
7659
7660 void skipCurrentReceiverLocked(ProcessRecord app) {
Christopher Tatef46723b2012-01-26 14:19:24 -08007661 for (BroadcastQueue queue : mBroadcastQueues) {
7662 queue.skipCurrentReceiverLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007663 }
7664 }
7665
Dan Egnor60d87622009-12-16 16:32:58 -08007666 /**
7667 * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes.
7668 * The application process will exit immediately after this call returns.
7669 * @param app object of the crashing app, null for the system server
7670 * @param crashInfo describing the exception
7671 */
7672 public void handleApplicationCrash(IBinder app, ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007673 ProcessRecord r = findAppProcess(app, "Crash");
Jeff Sharkeya353d262011-10-28 11:12:06 -07007674 final String processName = app == null ? "system_server"
7675 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08007676
7677 EventLog.writeEvent(EventLogTags.AM_CRASH, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07007678 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08007679 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08007680 crashInfo.exceptionClassName,
7681 crashInfo.exceptionMessage,
7682 crashInfo.throwFileName,
7683 crashInfo.throwLineNumber);
7684
Jeff Sharkeya353d262011-10-28 11:12:06 -07007685 addErrorToDropBox("crash", r, processName, null, null, null, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08007686
7687 crashApplication(r, crashInfo);
7688 }
7689
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007690 public void handleApplicationStrictModeViolation(
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007691 IBinder app,
7692 int violationMask,
7693 StrictMode.ViolationInfo info) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007694 ProcessRecord r = findAppProcess(app, "StrictMode");
7695 if (r == null) {
7696 return;
7697 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007698
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007699 if ((violationMask & StrictMode.PENALTY_DROPBOX) != 0) {
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08007700 Integer stackFingerprint = info.hashCode();
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007701 boolean logIt = true;
7702 synchronized (mAlreadyLoggedViolatedStacks) {
7703 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) {
7704 logIt = false;
7705 // TODO: sub-sample into EventLog for these, with
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007706 // the info.durationMillis? Then we'd get
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007707 // the relative pain numbers, without logging all
7708 // the stack traces repeatedly. We'd want to do
7709 // likewise in the client code, which also does
7710 // dup suppression, before the Binder call.
7711 } else {
7712 if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) {
7713 mAlreadyLoggedViolatedStacks.clear();
7714 }
7715 mAlreadyLoggedViolatedStacks.add(stackFingerprint);
7716 }
7717 }
7718 if (logIt) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007719 logStrictModeViolationToDropBox(r, info);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007720 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007721 }
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007722
7723 if ((violationMask & StrictMode.PENALTY_DIALOG) != 0) {
7724 AppErrorResult result = new AppErrorResult();
7725 synchronized (this) {
7726 final long origId = Binder.clearCallingIdentity();
7727
7728 Message msg = Message.obtain();
7729 msg.what = SHOW_STRICT_MODE_VIOLATION_MSG;
7730 HashMap<String, Object> data = new HashMap<String, Object>();
7731 data.put("result", result);
7732 data.put("app", r);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007733 data.put("violationMask", violationMask);
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007734 data.put("info", info);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007735 msg.obj = data;
7736 mHandler.sendMessage(msg);
7737
7738 Binder.restoreCallingIdentity(origId);
7739 }
7740 int res = result.get();
Dianne Hackbornb424b632010-08-18 15:59:05 -07007741 Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007742 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007743 }
7744
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007745 // Depending on the policy in effect, there could be a bunch of
7746 // these in quick succession so we try to batch these together to
7747 // minimize disk writes, number of dropbox entries, and maximize
7748 // compression, by having more fewer, larger records.
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007749 private void logStrictModeViolationToDropBox(
7750 ProcessRecord process,
7751 StrictMode.ViolationInfo info) {
7752 if (info == null) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007753 return;
7754 }
7755 final boolean isSystemApp = process == null ||
7756 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM |
7757 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07007758 final String processName = process == null ? "unknown" : process.processName;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007759 final String dropboxTag = isSystemApp ? "system_app_strictmode" : "data_app_strictmode";
7760 final DropBoxManager dbox = (DropBoxManager)
7761 mContext.getSystemService(Context.DROPBOX_SERVICE);
7762
7763 // Exit early if the dropbox isn't configured to accept this report type.
7764 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
7765
7766 boolean bufferWasEmpty;
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007767 boolean needsFlush;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007768 final StringBuilder sb = isSystemApp ? mStrictModeBuffer : new StringBuilder(1024);
7769 synchronized (sb) {
7770 bufferWasEmpty = sb.length() == 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07007771 appendDropBoxProcessHeaders(process, processName, sb);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007772 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
7773 sb.append("System-App: ").append(isSystemApp).append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007774 sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n");
7775 if (info.violationNumThisLoop != 0) {
7776 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n");
7777 }
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07007778 if (info.numAnimationsRunning != 0) {
7779 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n");
7780 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07007781 if (info.broadcastIntentAction != null) {
7782 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n");
7783 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08007784 if (info.durationMillis != -1) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007785 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n");
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007786 }
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08007787 if (info.numInstances != -1) {
7788 sb.append("Instance-Count: ").append(info.numInstances).append("\n");
7789 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08007790 if (info.tags != null) {
7791 for (String tag : info.tags) {
7792 sb.append("Span-Tag: ").append(tag).append("\n");
7793 }
7794 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007795 sb.append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007796 if (info.crashInfo != null && info.crashInfo.stackTrace != null) {
7797 sb.append(info.crashInfo.stackTrace);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007798 }
7799 sb.append("\n");
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007800
7801 // Only buffer up to ~64k. Various logging bits truncate
7802 // things at 128k.
7803 needsFlush = (sb.length() > 64 * 1024);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007804 }
7805
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007806 // Flush immediately if the buffer's grown too large, or this
7807 // is a non-system app. Non-system apps are isolated with a
7808 // different tag & policy and not batched.
7809 //
7810 // Batching is useful during internal testing with
7811 // StrictMode settings turned up high. Without batching,
7812 // thousands of separate files could be created on boot.
7813 if (!isSystemApp || needsFlush) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007814 new Thread("Error dump: " + dropboxTag) {
7815 @Override
7816 public void run() {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007817 String report;
7818 synchronized (sb) {
7819 report = sb.toString();
7820 sb.delete(0, sb.length());
7821 sb.trimToSize();
7822 }
7823 if (report.length() != 0) {
7824 dbox.addText(dropboxTag, report);
7825 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007826 }
7827 }.start();
7828 return;
7829 }
7830
7831 // System app batching:
7832 if (!bufferWasEmpty) {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007833 // An existing dropbox-writing thread is outstanding, so
7834 // we don't need to start it up. The existing thread will
7835 // catch the buffer appends we just did.
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007836 return;
7837 }
7838
7839 // Worker thread to both batch writes and to avoid blocking the caller on I/O.
7840 // (After this point, we shouldn't access AMS internal data structures.)
7841 new Thread("Error dump: " + dropboxTag) {
7842 @Override
7843 public void run() {
7844 // 5 second sleep to let stacks arrive and be batched together
7845 try {
7846 Thread.sleep(5000); // 5 seconds
7847 } catch (InterruptedException e) {}
7848
7849 String errorReport;
7850 synchronized (mStrictModeBuffer) {
7851 errorReport = mStrictModeBuffer.toString();
7852 if (errorReport.length() == 0) {
7853 return;
7854 }
7855 mStrictModeBuffer.delete(0, mStrictModeBuffer.length());
7856 mStrictModeBuffer.trimToSize();
7857 }
7858 dbox.addText(dropboxTag, errorReport);
7859 }
7860 }.start();
7861 }
7862
Dan Egnor60d87622009-12-16 16:32:58 -08007863 /**
7864 * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors.
7865 * @param app object of the crashing app, null for the system server
7866 * @param tag reported by the caller
7867 * @param crashInfo describing the context of the error
7868 * @return true if the process should exit immediately (WTF is fatal)
7869 */
7870 public boolean handleApplicationWtf(IBinder app, String tag,
Dan Egnorb7f03672009-12-09 16:22:32 -08007871 ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007872 ProcessRecord r = findAppProcess(app, "WTF");
Jeff Sharkeya353d262011-10-28 11:12:06 -07007873 final String processName = app == null ? "system_server"
7874 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08007875
7876 EventLog.writeEvent(EventLogTags.AM_WTF, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07007877 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08007878 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08007879 tag, crashInfo.exceptionMessage);
7880
Jeff Sharkeya353d262011-10-28 11:12:06 -07007881 addErrorToDropBox("wtf", r, processName, null, null, tag, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08007882
Dianne Hackborn1ab43772011-03-15 14:38:02 -07007883 if (r != null && r.pid != Process.myPid() &&
7884 Settings.Secure.getInt(mContext.getContentResolver(),
7885 Settings.Secure.WTF_IS_FATAL, 0) != 0) {
Dan Egnor60d87622009-12-16 16:32:58 -08007886 crashApplication(r, crashInfo);
7887 return true;
7888 } else {
7889 return false;
7890 }
7891 }
7892
7893 /**
7894 * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit})
7895 * @return the corresponding {@link ProcessRecord} object, or null if none could be found
7896 */
Dianne Hackborncb44d962011-03-10 17:02:27 -08007897 private ProcessRecord findAppProcess(IBinder app, String reason) {
Dan Egnor60d87622009-12-16 16:32:58 -08007898 if (app == null) {
7899 return null;
7900 }
7901
7902 synchronized (this) {
7903 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
7904 final int NA = apps.size();
7905 for (int ia=0; ia<NA; ia++) {
7906 ProcessRecord p = apps.valueAt(ia);
7907 if (p.thread != null && p.thread.asBinder() == app) {
7908 return p;
7909 }
7910 }
7911 }
7912
Dianne Hackborncb44d962011-03-10 17:02:27 -08007913 Slog.w(TAG, "Can't find mystery application for " + reason
7914 + " from pid=" + Binder.getCallingPid()
7915 + " uid=" + Binder.getCallingUid() + ": " + app);
Dan Egnor60d87622009-12-16 16:32:58 -08007916 return null;
7917 }
7918 }
7919
7920 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007921 * Utility function for addErrorToDropBox and handleStrictModeViolation's logging
7922 * to append various headers to the dropbox log text.
Dan Egnor60d87622009-12-16 16:32:58 -08007923 */
Jeff Sharkeya353d262011-10-28 11:12:06 -07007924 private void appendDropBoxProcessHeaders(ProcessRecord process, String processName,
7925 StringBuilder sb) {
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08007926 // Watchdog thread ends up invoking this function (with
7927 // a null ProcessRecord) to add the stack file to dropbox.
7928 // Do not acquire a lock on this (am) in such cases, as it
7929 // could cause a potential deadlock, if and when watchdog
7930 // is invoked due to unavailability of lock on am and it
7931 // would prevent watchdog from killing system_server.
7932 if (process == null) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07007933 sb.append("Process: ").append(processName).append("\n");
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08007934 return;
7935 }
Brad Fitzpatrick1e02d362010-09-10 09:19:50 -07007936 // Note: ProcessRecord 'process' is guarded by the service
7937 // instance. (notably process.pkgList, which could otherwise change
7938 // concurrently during execution of this method)
7939 synchronized (this) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07007940 sb.append("Process: ").append(processName).append("\n");
Dan Egnora455d192010-03-12 08:52:28 -08007941 int flags = process.info.flags;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007942 IPackageManager pm = AppGlobals.getPackageManager();
Dan Egnora455d192010-03-12 08:52:28 -08007943 sb.append("Flags: 0x").append(Integer.toString(flags, 16)).append("\n");
7944 for (String pkg : process.pkgList) {
7945 sb.append("Package: ").append(pkg);
Dan Egnor42471dd2010-01-07 17:25:22 -08007946 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07007947 PackageInfo pi = pm.getPackageInfo(pkg, 0, 0);
Dan Egnora455d192010-03-12 08:52:28 -08007948 if (pi != null) {
7949 sb.append(" v").append(pi.versionCode);
7950 if (pi.versionName != null) {
7951 sb.append(" (").append(pi.versionName).append(")");
7952 }
7953 }
7954 } catch (RemoteException e) {
7955 Slog.e(TAG, "Error getting package info: " + pkg, e);
Dan Egnor60d87622009-12-16 16:32:58 -08007956 }
Dan Egnora455d192010-03-12 08:52:28 -08007957 sb.append("\n");
Dan Egnor60d87622009-12-16 16:32:58 -08007958 }
Dan Egnora455d192010-03-12 08:52:28 -08007959 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007960 }
7961
7962 private static String processClass(ProcessRecord process) {
7963 if (process == null || process.pid == MY_PID) {
7964 return "system_server";
7965 } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
7966 return "system_app";
7967 } else {
7968 return "data_app";
7969 }
7970 }
7971
7972 /**
7973 * Write a description of an error (crash, WTF, ANR) to the drop box.
7974 * @param eventType to include in the drop box tag ("crash", "wtf", etc.)
7975 * @param process which caused the error, null means the system server
7976 * @param activity which triggered the error, null if unknown
7977 * @param parent activity related to the error, null if unknown
7978 * @param subject line related to the error, null if absent
7979 * @param report in long form describing the error, null if absent
7980 * @param logFile to include in the report, null if none
7981 * @param crashInfo giving an application stack trace, null if absent
7982 */
7983 public void addErrorToDropBox(String eventType,
Jeff Sharkeya353d262011-10-28 11:12:06 -07007984 ProcessRecord process, String processName, ActivityRecord activity,
7985 ActivityRecord parent, String subject,
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007986 final String report, final File logFile,
7987 final ApplicationErrorReport.CrashInfo crashInfo) {
7988 // NOTE -- this must never acquire the ActivityManagerService lock,
7989 // otherwise the watchdog may be prevented from resetting the system.
7990
7991 final String dropboxTag = processClass(process) + "_" + eventType;
7992 final DropBoxManager dbox = (DropBoxManager)
7993 mContext.getSystemService(Context.DROPBOX_SERVICE);
7994
7995 // Exit early if the dropbox isn't configured to accept this report type.
7996 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
7997
7998 final StringBuilder sb = new StringBuilder(1024);
Jeff Sharkeya353d262011-10-28 11:12:06 -07007999 appendDropBoxProcessHeaders(process, processName, sb);
Dan Egnora455d192010-03-12 08:52:28 -08008000 if (activity != null) {
8001 sb.append("Activity: ").append(activity.shortComponentName).append("\n");
8002 }
8003 if (parent != null && parent.app != null && parent.app.pid != process.pid) {
8004 sb.append("Parent-Process: ").append(parent.app.processName).append("\n");
8005 }
8006 if (parent != null && parent != activity) {
8007 sb.append("Parent-Activity: ").append(parent.shortComponentName).append("\n");
8008 }
8009 if (subject != null) {
8010 sb.append("Subject: ").append(subject).append("\n");
8011 }
8012 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
Christian Lindeberg03d2ca62010-09-28 14:52:20 +02008013 if (Debug.isDebuggerConnected()) {
8014 sb.append("Debugger: Connected\n");
8015 }
Dan Egnora455d192010-03-12 08:52:28 -08008016 sb.append("\n");
8017
8018 // Do the rest in a worker thread to avoid blocking the caller on I/O
8019 // (After this point, we shouldn't access AMS internal data structures.)
8020 Thread worker = new Thread("Error dump: " + dropboxTag) {
8021 @Override
8022 public void run() {
8023 if (report != null) {
8024 sb.append(report);
8025 }
8026 if (logFile != null) {
8027 try {
8028 sb.append(FileUtils.readTextFile(logFile, 128 * 1024, "\n\n[[TRUNCATED]]"));
8029 } catch (IOException e) {
8030 Slog.e(TAG, "Error reading " + logFile, e);
8031 }
8032 }
8033 if (crashInfo != null && crashInfo.stackTrace != null) {
8034 sb.append(crashInfo.stackTrace);
8035 }
8036
8037 String setting = Settings.Secure.ERROR_LOGCAT_PREFIX + dropboxTag;
8038 int lines = Settings.Secure.getInt(mContext.getContentResolver(), setting, 0);
8039 if (lines > 0) {
8040 sb.append("\n");
8041
8042 // Merge several logcat streams, and take the last N lines
8043 InputStreamReader input = null;
8044 try {
8045 java.lang.Process logcat = new ProcessBuilder("/system/bin/logcat",
8046 "-v", "time", "-b", "events", "-b", "system", "-b", "main",
8047 "-t", String.valueOf(lines)).redirectErrorStream(true).start();
8048
8049 try { logcat.getOutputStream().close(); } catch (IOException e) {}
8050 try { logcat.getErrorStream().close(); } catch (IOException e) {}
8051 input = new InputStreamReader(logcat.getInputStream());
8052
8053 int num;
8054 char[] buf = new char[8192];
8055 while ((num = input.read(buf)) > 0) sb.append(buf, 0, num);
8056 } catch (IOException e) {
8057 Slog.e(TAG, "Error running logcat", e);
8058 } finally {
8059 if (input != null) try { input.close(); } catch (IOException e) {}
8060 }
8061 }
8062
8063 dbox.addText(dropboxTag, sb.toString());
Dan Egnor60d87622009-12-16 16:32:58 -08008064 }
Dan Egnora455d192010-03-12 08:52:28 -08008065 };
8066
Dianne Hackborn56385cc2012-04-30 15:07:47 -07008067 if (process == null) {
8068 // If process is null, we are being called from some internal code
8069 // and may be about to die -- run this synchronously.
8070 worker.run();
Dan Egnora455d192010-03-12 08:52:28 -08008071 } else {
8072 worker.start();
Dan Egnor60d87622009-12-16 16:32:58 -08008073 }
8074 }
8075
8076 /**
8077 * Bring up the "unexpected error" dialog box for a crashing app.
8078 * Deal with edge cases (intercepts from instrumented applications,
8079 * ActivityController, error intent receivers, that sort of thing).
8080 * @param r the application crashing
8081 * @param crashInfo describing the failure
8082 */
8083 private void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008084 long timeMillis = System.currentTimeMillis();
8085 String shortMsg = crashInfo.exceptionClassName;
8086 String longMsg = crashInfo.exceptionMessage;
8087 String stackTrace = crashInfo.stackTrace;
8088 if (shortMsg != null && longMsg != null) {
8089 longMsg = shortMsg + ": " + longMsg;
8090 } else if (shortMsg != null) {
8091 longMsg = shortMsg;
8092 }
8093
Dan Egnor60d87622009-12-16 16:32:58 -08008094 AppErrorResult result = new AppErrorResult();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008095 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008096 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008097 try {
8098 String name = r != null ? r.processName : null;
8099 int pid = r != null ? r.pid : Binder.getCallingPid();
Dan Egnor60d87622009-12-16 16:32:58 -08008100 if (!mController.appCrashed(name, pid,
Dan Egnorb7f03672009-12-09 16:22:32 -08008101 shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008102 Slog.w(TAG, "Force-killing crashed app " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008103 + " at watcher's request");
8104 Process.killProcess(pid);
Dan Egnorb7f03672009-12-09 16:22:32 -08008105 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008106 }
8107 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008108 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008109 }
8110 }
8111
8112 final long origId = Binder.clearCallingIdentity();
8113
8114 // If this process is running instrumentation, finish it.
8115 if (r != null && r.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008116 Slog.w(TAG, "Error in app " + r.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008117 + " running instrumentation " + r.instrumentationClass + ":");
Joe Onorato8a9b2202010-02-26 18:56:32 -08008118 if (shortMsg != null) Slog.w(TAG, " " + shortMsg);
8119 if (longMsg != null) Slog.w(TAG, " " + longMsg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008120 Bundle info = new Bundle();
8121 info.putString("shortMsg", shortMsg);
8122 info.putString("longMsg", longMsg);
8123 finishInstrumentationLocked(r, Activity.RESULT_CANCELED, info);
8124 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008125 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008126 }
8127
Dan Egnor60d87622009-12-16 16:32:58 -08008128 // If we can't identify the process or it's already exceeded its crash quota,
8129 // quit right away without showing a crash dialog.
8130 if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008131 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008132 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008133 }
8134
8135 Message msg = Message.obtain();
8136 msg.what = SHOW_ERROR_MSG;
8137 HashMap data = new HashMap();
8138 data.put("result", result);
8139 data.put("app", r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008140 msg.obj = data;
8141 mHandler.sendMessage(msg);
8142
8143 Binder.restoreCallingIdentity(origId);
8144 }
8145
8146 int res = result.get();
8147
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008148 Intent appErrorIntent = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008149 synchronized (this) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008150 if (r != null && !r.isolated) {
8151 // XXX Can't keep track of crash time for isolated processes,
8152 // since they don't have a persistent identity.
8153 mProcessCrashTimes.put(r.info.processName, r.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008154 SystemClock.uptimeMillis());
8155 }
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008156 if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008157 appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008158 }
8159 }
8160
8161 if (appErrorIntent != null) {
8162 try {
8163 mContext.startActivity(appErrorIntent);
8164 } catch (ActivityNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008165 Slog.w(TAG, "bug report receiver dissappeared", e);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008166 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008167 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008168 }
Dan Egnorb7f03672009-12-09 16:22:32 -08008169
8170 Intent createAppErrorIntentLocked(ProcessRecord r,
8171 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
8172 ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008173 if (report == null) {
8174 return null;
8175 }
8176 Intent result = new Intent(Intent.ACTION_APP_ERROR);
8177 result.setComponent(r.errorReportReceiver);
8178 result.putExtra(Intent.EXTRA_BUG_REPORT, report);
8179 result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
8180 return result;
8181 }
8182
Dan Egnorb7f03672009-12-09 16:22:32 -08008183 private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r,
8184 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008185 if (r.errorReportReceiver == null) {
8186 return null;
8187 }
8188
8189 if (!r.crashing && !r.notResponding) {
8190 return null;
8191 }
8192
Dan Egnorb7f03672009-12-09 16:22:32 -08008193 ApplicationErrorReport report = new ApplicationErrorReport();
8194 report.packageName = r.info.packageName;
8195 report.installerPackageName = r.errorReportReceiver.getPackageName();
8196 report.processName = r.processName;
8197 report.time = timeMillis;
Jacek Surazskie0ee6ef2010-01-07 16:23:03 +01008198 report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008199
Dan Egnorb7f03672009-12-09 16:22:32 -08008200 if (r.crashing) {
8201 report.type = ApplicationErrorReport.TYPE_CRASH;
8202 report.crashInfo = crashInfo;
8203 } else if (r.notResponding) {
8204 report.type = ApplicationErrorReport.TYPE_ANR;
8205 report.anrInfo = new ApplicationErrorReport.AnrInfo();
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008206
Dan Egnorb7f03672009-12-09 16:22:32 -08008207 report.anrInfo.activity = r.notRespondingReport.tag;
8208 report.anrInfo.cause = r.notRespondingReport.shortMsg;
8209 report.anrInfo.info = r.notRespondingReport.longMsg;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008210 }
8211
Dan Egnorb7f03672009-12-09 16:22:32 -08008212 return report;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008213 }
8214
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008215 public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008216 enforceNotIsolatedCaller("getProcessesInErrorState");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008217 // assume our apps are happy - lazy create the list
8218 List<ActivityManager.ProcessErrorStateInfo> errList = null;
8219
8220 synchronized (this) {
8221
8222 // iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008223 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8224 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008225 if ((app.thread != null) && (app.crashing || app.notResponding)) {
8226 // This one's in trouble, so we'll generate a report for it
8227 // crashes are higher priority (in case there's a crash *and* an anr)
8228 ActivityManager.ProcessErrorStateInfo report = null;
8229 if (app.crashing) {
8230 report = app.crashingReport;
8231 } else if (app.notResponding) {
8232 report = app.notRespondingReport;
8233 }
8234
8235 if (report != null) {
8236 if (errList == null) {
8237 errList = new ArrayList<ActivityManager.ProcessErrorStateInfo>(1);
8238 }
8239 errList.add(report);
8240 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008241 Slog.w(TAG, "Missing app error report, app = " + app.processName +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008242 " crashing = " + app.crashing +
8243 " notResponding = " + app.notResponding);
8244 }
8245 }
8246 }
8247 }
8248
8249 return errList;
8250 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07008251
8252 static int oomAdjToImportance(int adj, ActivityManager.RunningAppProcessInfo currApp) {
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008253 if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008254 if (currApp != null) {
8255 currApp.lru = adj - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
8256 }
8257 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008258 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
8259 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008260 } else if (adj >= ProcessList.HOME_APP_ADJ) {
8261 if (currApp != null) {
8262 currApp.lru = 0;
8263 }
8264 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008265 } else if (adj >= ProcessList.SERVICE_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008266 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
8267 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
8268 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
8269 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
8270 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
8271 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
8272 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
8273 } else {
8274 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
8275 }
8276 }
8277
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008278 private void fillInProcMemInfo(ProcessRecord app,
8279 ActivityManager.RunningAppProcessInfo outInfo) {
8280 outInfo.pid = app.pid;
8281 outInfo.uid = app.info.uid;
8282 if (mHeavyWeightProcess == app) {
8283 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_CANT_SAVE_STATE;
8284 }
8285 if (app.persistent) {
8286 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_PERSISTENT;
8287 }
8288 outInfo.lastTrimLevel = app.trimMemoryLevel;
8289 int adj = app.curAdj;
8290 outInfo.importance = oomAdjToImportance(adj, outInfo);
8291 outInfo.importanceReasonCode = app.adjTypeCode;
8292 }
8293
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008294 public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008295 enforceNotIsolatedCaller("getRunningAppProcesses");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008296 // Lazy instantiation of list
8297 List<ActivityManager.RunningAppProcessInfo> runList = null;
8298 synchronized (this) {
8299 // Iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008300 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8301 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008302 if ((app.thread != null) && (!app.crashing && !app.notResponding)) {
8303 // Generate process state info for running application
8304 ActivityManager.RunningAppProcessInfo currApp =
8305 new ActivityManager.RunningAppProcessInfo(app.processName,
8306 app.pid, app.getPackageList());
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008307 fillInProcMemInfo(app, currApp);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008308 if (app.adjSource instanceof ProcessRecord) {
8309 currApp.importanceReasonPid = ((ProcessRecord)app.adjSource).pid;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008310 currApp.importanceReasonImportance = oomAdjToImportance(
8311 app.adjSourceOom, null);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008312 } else if (app.adjSource instanceof ActivityRecord) {
8313 ActivityRecord r = (ActivityRecord)app.adjSource;
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008314 if (r.app != null) currApp.importanceReasonPid = r.app.pid;
8315 }
8316 if (app.adjTarget instanceof ComponentName) {
8317 currApp.importanceReasonComponent = (ComponentName)app.adjTarget;
8318 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08008319 //Slog.v(TAG, "Proc " + app.processName + ": imp=" + currApp.importance
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008320 // + " lru=" + currApp.lru);
8321 if (runList == null) {
8322 runList = new ArrayList<ActivityManager.RunningAppProcessInfo>();
8323 }
8324 runList.add(currApp);
8325 }
8326 }
8327 }
8328 return runList;
8329 }
8330
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008331 public List<ApplicationInfo> getRunningExternalApplications() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008332 enforceNotIsolatedCaller("getRunningExternalApplications");
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008333 List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses();
8334 List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>();
8335 if (runningApps != null && runningApps.size() > 0) {
8336 Set<String> extList = new HashSet<String>();
8337 for (ActivityManager.RunningAppProcessInfo app : runningApps) {
8338 if (app.pkgList != null) {
8339 for (String pkg : app.pkgList) {
8340 extList.add(pkg);
8341 }
8342 }
8343 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008344 IPackageManager pm = AppGlobals.getPackageManager();
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008345 for (String pkg : extList) {
8346 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07008347 ApplicationInfo info = pm.getApplicationInfo(pkg, 0, UserId.getCallingUserId());
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008348 if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
8349 retList.add(info);
8350 }
8351 } catch (RemoteException e) {
8352 }
8353 }
8354 }
8355 return retList;
8356 }
8357
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008358 @Override
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008359 public void getMyMemoryState(ActivityManager.RunningAppProcessInfo outInfo) {
8360 enforceNotIsolatedCaller("getMyMemoryState");
8361 synchronized (this) {
8362 ProcessRecord proc;
8363 synchronized (mPidsSelfLocked) {
8364 proc = mPidsSelfLocked.get(Binder.getCallingPid());
8365 }
8366 fillInProcMemInfo(proc, outInfo);
8367 }
8368 }
8369
8370 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008371 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008372 if (checkCallingPermission(android.Manifest.permission.DUMP)
8373 != PackageManager.PERMISSION_GRANTED) {
8374 pw.println("Permission Denial: can't dump ActivityManager from from pid="
8375 + Binder.getCallingPid()
8376 + ", uid=" + Binder.getCallingUid()
8377 + " without permission "
8378 + android.Manifest.permission.DUMP);
8379 return;
8380 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008381
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008382 boolean dumpAll = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008383 boolean dumpClient = false;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008384 String dumpPackage = null;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008385
8386 int opti = 0;
8387 while (opti < args.length) {
8388 String opt = args[opti];
8389 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
8390 break;
8391 }
8392 opti++;
8393 if ("-a".equals(opt)) {
8394 dumpAll = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008395 } else if ("-c".equals(opt)) {
8396 dumpClient = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008397 } else if ("-h".equals(opt)) {
8398 pw.println("Activity manager dump options:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008399 pw.println(" [-a] [-c] [-h] [cmd] ...");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008400 pw.println(" cmd may be one of:");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008401 pw.println(" a[ctivities]: activity stack state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008402 pw.println(" b[roadcasts] [PACKAGE_NAME]: broadcast state");
8403 pw.println(" i[ntents] [PACKAGE_NAME]: pending intent state");
8404 pw.println(" p[rocesses] [PACKAGE_NAME]: process state");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008405 pw.println(" o[om]: out of memory management");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008406 pw.println(" prov[iders] [COMP_SPEC ...]: content provider state");
Marco Nelissen18cb2872011-11-15 11:19:53 -08008407 pw.println(" provider [COMP_SPEC]: provider client-side state");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008408 pw.println(" s[ervices] [COMP_SPEC ...]: service state");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008409 pw.println(" service [COMP_SPEC]: service client-side state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008410 pw.println(" package [PACKAGE_NAME]: all state related to given package");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008411 pw.println(" all: dump all activities");
8412 pw.println(" top: dump the top activity");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008413 pw.println(" cmd may also be a COMP_SPEC to dump activities.");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008414 pw.println(" COMP_SPEC may be a component name (com.foo/.myApp),");
8415 pw.println(" a partial substring in a component name, a");
8416 pw.println(" hex object identifier.");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008417 pw.println(" -a: include all available server state.");
8418 pw.println(" -c: include client state.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008419 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008420 } else {
8421 pw.println("Unknown argument: " + opt + "; use -h for help");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008422 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008423 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008424
8425 long origId = Binder.clearCallingIdentity();
8426 boolean more = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008427 // Is the caller requesting to dump a particular piece of data?
8428 if (opti < args.length) {
8429 String cmd = args[opti];
8430 opti++;
8431 if ("activities".equals(cmd) || "a".equals(cmd)) {
8432 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008433 dumpActivitiesLocked(fd, pw, args, opti, true, dumpClient, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008434 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008435 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008436 String[] newArgs;
8437 String name;
8438 if (opti >= args.length) {
8439 name = null;
8440 newArgs = EMPTY_STRING_ARRAY;
8441 } else {
8442 name = args[opti];
8443 opti++;
8444 newArgs = new String[args.length - opti];
8445 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8446 args.length - opti);
8447 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008448 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008449 dumpBroadcastsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008450 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008451 } else if ("intents".equals(cmd) || "i".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008452 String[] newArgs;
8453 String name;
8454 if (opti >= args.length) {
8455 name = null;
8456 newArgs = EMPTY_STRING_ARRAY;
8457 } else {
8458 name = args[opti];
8459 opti++;
8460 newArgs = new String[args.length - opti];
8461 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8462 args.length - opti);
8463 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008464 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008465 dumpPendingIntentsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008466 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008467 } else if ("processes".equals(cmd) || "p".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008468 String[] newArgs;
8469 String name;
8470 if (opti >= args.length) {
8471 name = null;
8472 newArgs = EMPTY_STRING_ARRAY;
8473 } else {
8474 name = args[opti];
8475 opti++;
8476 newArgs = new String[args.length - opti];
8477 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8478 args.length - opti);
8479 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008480 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008481 dumpProcessesLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008482 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008483 } else if ("oom".equals(cmd) || "o".equals(cmd)) {
8484 synchronized (this) {
8485 dumpOomLocked(fd, pw, args, opti, true);
8486 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08008487 } else if ("provider".equals(cmd)) {
8488 String[] newArgs;
8489 String name;
8490 if (opti >= args.length) {
8491 name = null;
8492 newArgs = EMPTY_STRING_ARRAY;
8493 } else {
8494 name = args[opti];
8495 opti++;
8496 newArgs = new String[args.length - opti];
8497 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
8498 }
8499 if (!dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) {
8500 pw.println("No providers match: " + name);
8501 pw.println("Use -h for help.");
8502 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008503 } else if ("providers".equals(cmd) || "prov".equals(cmd)) {
8504 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008505 dumpProvidersLocked(fd, pw, args, opti, true, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008506 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008507 } else if ("service".equals(cmd)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008508 String[] newArgs;
8509 String name;
8510 if (opti >= args.length) {
8511 name = null;
8512 newArgs = EMPTY_STRING_ARRAY;
8513 } else {
8514 name = args[opti];
8515 opti++;
8516 newArgs = new String[args.length - opti];
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008517 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8518 args.length - opti);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008519 }
8520 if (!dumpService(fd, pw, name, newArgs, 0, dumpAll)) {
8521 pw.println("No services match: " + name);
8522 pw.println("Use -h for help.");
8523 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008524 } else if ("package".equals(cmd)) {
8525 String[] newArgs;
8526 if (opti >= args.length) {
8527 pw.println("package: no package name specified");
8528 pw.println("Use -h for help.");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008529 } else {
8530 dumpPackage = args[opti];
8531 opti++;
8532 newArgs = new String[args.length - opti];
8533 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8534 args.length - opti);
8535 args = newArgs;
8536 opti = 0;
Amith Yamasani7463ada2012-04-11 15:02:39 -07008537 more = true;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008538 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008539 } else if ("services".equals(cmd) || "s".equals(cmd)) {
8540 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008541 dumpServicesLocked(fd, pw, args, opti, true, dumpClient, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008542 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07008543 } else {
8544 // Dumping a single activity?
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008545 if (!dumpActivity(fd, pw, cmd, args, opti, dumpAll)) {
8546 pw.println("Bad activity command, or no activities match: " + cmd);
8547 pw.println("Use -h for help.");
Dianne Hackborn625ac272010-09-17 18:29:22 -07008548 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008549 }
8550 if (!more) {
8551 Binder.restoreCallingIdentity(origId);
Dianne Hackborn30d71892010-12-11 10:37:55 -08008552 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008553 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008554 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008555
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008556 // No piece of data specified, dump everything.
8557 synchronized (this) {
8558 boolean needSep;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008559 needSep = dumpPendingIntentsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008560 if (needSep) {
8561 pw.println(" ");
8562 }
8563 if (dumpAll) {
8564 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008565 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008566 needSep = dumpBroadcastsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008567 if (needSep) {
8568 pw.println(" ");
8569 }
8570 if (dumpAll) {
8571 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008572 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008573 needSep = dumpProvidersLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008574 if (needSep) {
8575 pw.println(" ");
8576 }
8577 if (dumpAll) {
8578 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008579 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008580 needSep = dumpServicesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008581 if (needSep) {
8582 pw.println(" ");
8583 }
8584 if (dumpAll) {
8585 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008586 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008587 needSep = dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008588 if (needSep) {
8589 pw.println(" ");
8590 }
8591 if (dumpAll) {
8592 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008593 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008594 dumpProcessesLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008595 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008596 Binder.restoreCallingIdentity(origId);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008597 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008598
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008599 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008600 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008601 pw.println("ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
8602 pw.println(" Main stack:");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008603 dumpHistoryList(fd, pw, mMainStack.mHistory, " ", "Hist", true, !dumpAll, dumpClient,
8604 dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008605 pw.println(" ");
8606 pw.println(" Running activities (most recent first):");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008607 dumpHistoryList(fd, pw, mMainStack.mLRUActivities, " ", "Run", false, !dumpAll, false,
8608 dumpPackage);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008609 if (mMainStack.mWaitingVisibleActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008610 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008611 pw.println(" Activities waiting for another to become visible:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008612 dumpHistoryList(fd, pw, mMainStack.mWaitingVisibleActivities, " ", "Wait", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008613 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008614 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008615 if (mMainStack.mStoppingActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008616 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008617 pw.println(" Activities waiting to stop:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008618 dumpHistoryList(fd, pw, mMainStack.mStoppingActivities, " ", "Stop", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008619 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008620 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008621 if (mMainStack.mGoingToSleepActivities.size() > 0) {
8622 pw.println(" ");
8623 pw.println(" Activities waiting to sleep:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008624 dumpHistoryList(fd, pw, mMainStack.mGoingToSleepActivities, " ", "Sleep", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008625 !dumpAll, false, dumpPackage);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008626 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008627 if (mMainStack.mFinishingActivities.size() > 0) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008628 pw.println(" ");
8629 pw.println(" Activities waiting to finish:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008630 dumpHistoryList(fd, pw, mMainStack.mFinishingActivities, " ", "Fin", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008631 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008632 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008633
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008634 pw.println(" ");
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08008635 if (mMainStack.mPausingActivity != null) {
8636 pw.println(" mPausingActivity: " + mMainStack.mPausingActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008637 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008638 pw.println(" mResumedActivity: " + mMainStack.mResumedActivity);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008639 pw.println(" mFocusedActivity: " + mFocusedActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008640 if (dumpAll) {
8641 pw.println(" mLastPausedActivity: " + mMainStack.mLastPausedActivity);
8642 pw.println(" mSleepTimeout: " + mMainStack.mSleepTimeout);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07008643 pw.println(" mDismissKeyguardOnNextActivity: "
8644 + mMainStack.mDismissKeyguardOnNextActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008645 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008646
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008647 if (mRecentTasks.size() > 0) {
8648 pw.println();
8649 pw.println(" Recent tasks:");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008650
8651 final int N = mRecentTasks.size();
8652 for (int i=0; i<N; i++) {
8653 TaskRecord tr = mRecentTasks.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008654 if (dumpPackage != null) {
8655 if (tr.realActivity == null ||
8656 !dumpPackage.equals(tr.realActivity)) {
8657 continue;
8658 }
8659 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008660 pw.print(" * Recent #"); pw.print(i); pw.print(": ");
8661 pw.println(tr);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008662 if (dumpAll) {
8663 mRecentTasks.get(i).dump(pw, " ");
8664 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008665 }
8666 }
8667
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008668 if (dumpAll) {
8669 pw.println(" ");
8670 pw.println(" mCurTask: " + mCurTask);
8671 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008672
8673 return true;
8674 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008675
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008676 boolean dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008677 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008678 boolean needSep = false;
8679 int numPers = 0;
8680
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008681 pw.println("ACTIVITY MANAGER RUNNING PROCESSES (dumpsys activity processes)");
8682
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008683 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008684 for (SparseArray<ProcessRecord> procs : mProcessNames.getMap().values()) {
8685 final int NA = procs.size();
8686 for (int ia=0; ia<NA; ia++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008687 ProcessRecord r = procs.valueAt(ia);
8688 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8689 continue;
8690 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008691 if (!needSep) {
8692 pw.println(" All known processes:");
8693 needSep = true;
8694 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008695 pw.print(r.persistent ? " *PERS*" : " *APP*");
8696 pw.print(" UID "); pw.print(procs.keyAt(ia));
8697 pw.print(" "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008698 r.dump(pw, " ");
8699 if (r.persistent) {
8700 numPers++;
8701 }
8702 }
8703 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008704 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008705
8706 if (mIsolatedProcesses.size() > 0) {
8707 if (needSep) pw.println(" ");
8708 needSep = true;
8709 pw.println(" Isolated process list (sorted by uid):");
8710 for (int i=0; i<mIsolatedProcesses.size(); i++) {
8711 ProcessRecord r = mIsolatedProcesses.valueAt(i);
8712 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8713 continue;
8714 }
8715 pw.println(String.format("%sIsolated #%2d: %s",
8716 " ", i, r.toString()));
8717 }
8718 }
8719
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008720 if (mLruProcesses.size() > 0) {
8721 if (needSep) pw.println(" ");
8722 needSep = true;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008723 pw.println(" Process LRU list (sorted by oom_adj):");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008724 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008725 "Proc", "PERS", false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008726 needSep = true;
8727 }
8728
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008729 if (dumpAll) {
8730 synchronized (mPidsSelfLocked) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008731 boolean printed = false;
8732 for (int i=0; i<mPidsSelfLocked.size(); i++) {
8733 ProcessRecord r = mPidsSelfLocked.valueAt(i);
8734 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8735 continue;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008736 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008737 if (!printed) {
8738 if (needSep) pw.println(" ");
8739 needSep = true;
8740 pw.println(" PID mappings:");
8741 printed = true;
8742 }
8743 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i));
8744 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008745 }
8746 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008747 }
8748
8749 if (mForegroundProcesses.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008750 synchronized (mPidsSelfLocked) {
8751 boolean printed = false;
8752 for (int i=0; i<mForegroundProcesses.size(); i++) {
8753 ProcessRecord r = mPidsSelfLocked.get(
8754 mForegroundProcesses.valueAt(i).pid);
8755 if (dumpPackage != null && (r == null
8756 || !dumpPackage.equals(r.info.packageName))) {
8757 continue;
8758 }
8759 if (!printed) {
8760 if (needSep) pw.println(" ");
8761 needSep = true;
8762 pw.println(" Foreground Processes:");
8763 printed = true;
8764 }
8765 pw.print(" PID #"); pw.print(mForegroundProcesses.keyAt(i));
8766 pw.print(": "); pw.println(mForegroundProcesses.valueAt(i));
8767 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008768 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008769 }
8770
8771 if (mPersistentStartingProcesses.size() > 0) {
8772 if (needSep) pw.println(" ");
8773 needSep = true;
8774 pw.println(" Persisent processes that are starting:");
8775 dumpProcessList(pw, this, mPersistentStartingProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008776 "Starting Norm", "Restarting PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008777 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008778
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008779 if (mRemovedProcesses.size() > 0) {
8780 if (needSep) pw.println(" ");
8781 needSep = true;
8782 pw.println(" Processes that are being removed:");
8783 dumpProcessList(pw, this, mRemovedProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008784 "Removed Norm", "Removed PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008785 }
8786
8787 if (mProcessesOnHold.size() > 0) {
8788 if (needSep) pw.println(" ");
8789 needSep = true;
8790 pw.println(" Processes that are on old until the system is ready:");
8791 dumpProcessList(pw, this, mProcessesOnHold, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008792 "OnHold Norm", "OnHold PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008793 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008794
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008795 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008796
8797 if (mProcessCrashTimes.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008798 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008799 long now = SystemClock.uptimeMillis();
8800 for (Map.Entry<String, SparseArray<Long>> procs
8801 : mProcessCrashTimes.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008802 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008803 SparseArray<Long> uids = procs.getValue();
8804 final int N = uids.size();
8805 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008806 int puid = uids.keyAt(i);
8807 ProcessRecord r = mProcessNames.get(pname, puid);
8808 if (dumpPackage != null && (r == null
8809 || !dumpPackage.equals(r.info.packageName))) {
8810 continue;
8811 }
8812 if (!printed) {
8813 if (needSep) pw.println(" ");
8814 needSep = true;
8815 pw.println(" Time since processes crashed:");
8816 printed = true;
8817 }
8818 pw.print(" Process "); pw.print(pname);
8819 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008820 pw.print(": last crashed ");
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008821 TimeUtils.formatDuration(now-uids.valueAt(i), pw);
8822 pw.println(" ago");
Dianne Hackbornfd12af42009-08-27 00:44:33 -07008823 }
8824 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008825 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008826
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008827 if (mBadProcesses.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008828 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008829 for (Map.Entry<String, SparseArray<Long>> procs
8830 : mBadProcesses.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008831 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008832 SparseArray<Long> uids = procs.getValue();
8833 final int N = uids.size();
8834 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008835 int puid = uids.keyAt(i);
8836 ProcessRecord r = mProcessNames.get(pname, puid);
8837 if (dumpPackage != null && (r == null
8838 || !dumpPackage.equals(r.info.packageName))) {
8839 continue;
8840 }
8841 if (!printed) {
8842 if (needSep) pw.println(" ");
8843 needSep = true;
8844 pw.println(" Bad processes:");
8845 }
8846 pw.print(" Bad process "); pw.print(pname);
8847 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008848 pw.print(": crashed at time ");
8849 pw.println(uids.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008850 }
8851 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008852 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008853
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008854 pw.println();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008855 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07008856 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn50685602011-12-01 12:23:37 -08008857 if (dumpAll) {
8858 StringBuilder sb = new StringBuilder(128);
8859 sb.append(" mPreviousProcessVisibleTime: ");
8860 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
8861 pw.println(sb);
8862 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07008863 if (mHeavyWeightProcess != null) {
8864 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
8865 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008866 pw.println(" mConfiguration: " + mConfiguration);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008867 if (dumpAll) {
8868 pw.println(" mConfigWillChange: " + mMainStack.mConfigWillChange);
Dianne Hackborn3d0724d2011-05-12 15:39:41 -07008869 if (mCompatModePackages.getPackages().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008870 boolean printed = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07008871 for (Map.Entry<String, Integer> entry
8872 : mCompatModePackages.getPackages().entrySet()) {
8873 String pkg = entry.getKey();
8874 int mode = entry.getValue();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008875 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
8876 continue;
8877 }
8878 if (!printed) {
8879 pw.println(" mScreenCompatPackages:");
8880 printed = true;
8881 }
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07008882 pw.print(" "); pw.print(pkg); pw.print(": ");
8883 pw.print(mode); pw.println();
8884 }
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07008885 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008886 }
Dianne Hackbornff5b1582012-04-12 17:24:07 -07008887 if (mSleeping || mWentToSleep || mLockScreenShown) {
8888 pw.println(" mSleeping=" + mSleeping + " mWentToSleep=" + mWentToSleep
8889 + " mLockScreenShown " + mLockScreenShown);
8890 }
8891 if (mShuttingDown) {
8892 pw.println(" mShuttingDown=" + mShuttingDown);
8893 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008894 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
8895 || mOrigWaitForDebugger) {
8896 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp
8897 + " mDebugTransient=" + mDebugTransient
8898 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger);
8899 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08008900 if (mOpenGlTraceApp != null) {
8901 pw.println(" mOpenGlTraceApp=" + mOpenGlTraceApp);
8902 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07008903 if (mProfileApp != null || mProfileProc != null || mProfileFile != null
8904 || mProfileFd != null) {
8905 pw.println(" mProfileApp=" + mProfileApp + " mProfileProc=" + mProfileProc);
8906 pw.println(" mProfileFile=" + mProfileFile + " mProfileFd=" + mProfileFd);
8907 pw.println(" mProfileType=" + mProfileType + " mAutoStopProfiler="
8908 + mAutoStopProfiler);
8909 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008910 if (mAlwaysFinishActivities || mController != null) {
8911 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities
8912 + " mController=" + mController);
8913 }
8914 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008915 pw.println(" Total persistent processes: " + numPers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008916 pw.println(" mStartRunning=" + mStartRunning
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07008917 + " mProcessesReady=" + mProcessesReady
8918 + " mSystemReady=" + mSystemReady);
8919 pw.println(" mBooting=" + mBooting
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008920 + " mBooted=" + mBooted
8921 + " mFactoryTest=" + mFactoryTest);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008922 pw.print(" mLastPowerCheckRealtime=");
8923 TimeUtils.formatDuration(mLastPowerCheckRealtime, pw);
8924 pw.println("");
8925 pw.print(" mLastPowerCheckUptime=");
8926 TimeUtils.formatDuration(mLastPowerCheckUptime, pw);
8927 pw.println("");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008928 pw.println(" mGoingToSleep=" + mMainStack.mGoingToSleep);
8929 pw.println(" mLaunchingActivity=" + mMainStack.mLaunchingActivity);
Dianne Hackborn906497c2010-05-10 15:57:38 -07008930 pw.println(" mAdjSeq=" + mAdjSeq + " mLruSeq=" + mLruSeq);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008931 pw.println(" mNumServiceProcs=" + mNumServiceProcs
8932 + " mNewNumServiceProcs=" + mNewNumServiceProcs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008933 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008934
8935 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008936 }
8937
Dianne Hackborn287952c2010-09-22 22:34:31 -07008938 boolean dumpProcessesToGc(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008939 int opti, boolean needSep, boolean dumpAll, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07008940 if (mProcessesToGc.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008941 boolean printed = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -07008942 long now = SystemClock.uptimeMillis();
8943 for (int i=0; i<mProcessesToGc.size(); i++) {
8944 ProcessRecord proc = mProcessesToGc.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008945 if (dumpPackage != null && !dumpPackage.equals(proc.info.packageName)) {
8946 continue;
8947 }
8948 if (!printed) {
8949 if (needSep) pw.println(" ");
8950 needSep = true;
8951 pw.println(" Processes that are waiting to GC:");
8952 printed = true;
8953 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008954 pw.print(" Process "); pw.println(proc);
8955 pw.print(" lowMem="); pw.print(proc.reportLowMemory);
8956 pw.print(", last gced=");
8957 pw.print(now-proc.lastRequestedGc);
8958 pw.print(" ms ago, last lowMem=");
8959 pw.print(now-proc.lastLowMemory);
8960 pw.println(" ms ago");
8961
8962 }
8963 }
8964 return needSep;
8965 }
8966
8967 boolean dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args,
8968 int opti, boolean dumpAll) {
8969 boolean needSep = false;
8970
8971 if (mLruProcesses.size() > 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07008972 if (needSep) pw.println(" ");
8973 needSep = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -07008974 pw.println(" OOM levels:");
Dianne Hackborn7d608422011-08-07 16:24:18 -07008975 pw.print(" SYSTEM_ADJ: "); pw.println(ProcessList.SYSTEM_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008976 pw.print(" PERSISTENT_PROC_ADJ: "); pw.println(ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07008977 pw.print(" FOREGROUND_APP_ADJ: "); pw.println(ProcessList.FOREGROUND_APP_ADJ);
8978 pw.print(" VISIBLE_APP_ADJ: "); pw.println(ProcessList.VISIBLE_APP_ADJ);
8979 pw.print(" PERCEPTIBLE_APP_ADJ: "); pw.println(ProcessList.PERCEPTIBLE_APP_ADJ);
8980 pw.print(" HEAVY_WEIGHT_APP_ADJ: "); pw.println(ProcessList.HEAVY_WEIGHT_APP_ADJ);
8981 pw.print(" BACKUP_APP_ADJ: "); pw.println(ProcessList.BACKUP_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008982 pw.print(" SERVICE_ADJ: "); pw.println(ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07008983 pw.print(" HOME_APP_ADJ: "); pw.println(ProcessList.HOME_APP_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07008984 pw.print(" PREVIOUS_APP_ADJ: "); pw.println(ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008985 pw.print(" SERVICE_B_ADJ: "); pw.println(ProcessList.SERVICE_B_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07008986 pw.print(" HIDDEN_APP_MIN_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008987 pw.print(" HIDDEN_APP_MAX_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MAX_ADJ);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07008988
8989 if (needSep) pw.println(" ");
8990 needSep = true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07008991 pw.println(" Process OOM control:");
Dianne Hackborn905577f2011-09-07 18:31:28 -07008992 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008993 "Proc", "PERS", true, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008994 needSep = true;
8995 }
8996
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008997 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008998
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008999 pw.println();
Dianne Hackborn287952c2010-09-22 22:34:31 -07009000 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009001 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009002 if (mHeavyWeightProcess != null) {
9003 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
9004 }
9005
9006 return true;
9007 }
9008
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009009 /**
9010 * There are three ways to call this:
9011 * - no service specified: dump all the services
9012 * - a flattened component name that matched an existing service was specified as the
9013 * first arg: dump that one service
9014 * - the first arg isn't the flattened component name of an existing service:
9015 * dump all services whose component contains the first arg as a substring
9016 */
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009017 protected boolean dumpService(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9018 int opti, boolean dumpAll) {
9019 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009020
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009021 if ("all".equals(name)) {
Dianne Hackborn14bfa392010-07-24 19:58:06 -07009022 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07009023 try {
9024 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
9025 for (UserInfo user : users) {
9026 for (ServiceRecord r1 : mServiceMap.getAllServices(user.id)) {
9027 services.add(r1);
9028 }
9029 }
9030 } catch (RemoteException re) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009031 }
9032 }
9033 } else {
9034 ComponentName componentName = name != null
9035 ? ComponentName.unflattenFromString(name) : null;
9036 int objectId = 0;
9037 if (componentName == null) {
9038 // Not a '/' separated full component name; maybe an object ID?
9039 try {
9040 objectId = Integer.parseInt(name, 16);
9041 name = null;
9042 componentName = null;
9043 } catch (RuntimeException e) {
9044 }
9045 }
9046
9047 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07009048 try {
9049 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
9050 for (UserInfo user : users) {
9051 for (ServiceRecord r1 : mServiceMap.getAllServices(user.id)) {
9052 if (componentName != null) {
9053 if (r1.name.equals(componentName)) {
9054 services.add(r1);
9055 }
9056 } else if (name != null) {
9057 if (r1.name.flattenToString().contains(name)) {
9058 services.add(r1);
9059 }
9060 } else if (System.identityHashCode(r1) == objectId) {
9061 services.add(r1);
9062 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009063 }
Dianne Hackborn14bfa392010-07-24 19:58:06 -07009064 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009065 } catch (RemoteException re) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009066 }
9067 }
9068 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009069
9070 if (services.size() <= 0) {
9071 return false;
9072 }
9073
9074 boolean needSep = false;
9075 for (int i=0; i<services.size(); i++) {
9076 if (needSep) {
9077 pw.println();
9078 }
9079 needSep = true;
9080 dumpService("", fd, pw, services.get(i), args, dumpAll);
9081 }
9082 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009083 }
9084
9085 /**
9086 * Invokes IApplicationThread.dumpService() on the thread of the specified service if
9087 * there is a thread associated with the service.
9088 */
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009089 private void dumpService(String prefix, FileDescriptor fd, PrintWriter pw,
9090 final ServiceRecord r, String[] args, boolean dumpAll) {
9091 String innerPrefix = prefix + " ";
9092 synchronized (this) {
9093 pw.print(prefix); pw.print("SERVICE ");
9094 pw.print(r.shortName); pw.print(" ");
9095 pw.print(Integer.toHexString(System.identityHashCode(r)));
9096 pw.print(" pid=");
9097 if (r.app != null) pw.println(r.app.pid);
9098 else pw.println("(not running)");
9099 if (dumpAll) {
9100 r.dump(pw, innerPrefix);
9101 }
9102 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009103 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009104 pw.print(prefix); pw.println(" Client:");
9105 pw.flush();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009106 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009107 TransferPipe tp = new TransferPipe();
9108 try {
9109 r.app.thread.dumpService(tp.getWriteFd().getFileDescriptor(), r, args);
9110 tp.setBufferPrefix(prefix + " ");
9111 tp.go(fd);
9112 } finally {
9113 tp.kill();
9114 }
9115 } catch (IOException e) {
9116 pw.println(prefix + " Failure while dumping the service: " + e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009117 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009118 pw.println(prefix + " Got a RemoteException while dumping the service");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009119 }
9120 }
9121 }
9122
Marco Nelissen18cb2872011-11-15 11:19:53 -08009123 /**
9124 * There are three ways to call this:
9125 * - no provider specified: dump all the providers
9126 * - a flattened component name that matched an existing provider was specified as the
9127 * first arg: dump that one provider
9128 * - the first arg isn't the flattened component name of an existing provider:
9129 * dump all providers whose component contains the first arg as a substring
9130 */
9131 protected boolean dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9132 int opti, boolean dumpAll) {
Marco Nelissende7408c2012-02-08 14:57:38 -08009133 return mProviderMap.dumpProvider(fd, pw, name, args, opti, dumpAll);
Marco Nelissen18cb2872011-11-15 11:19:53 -08009134 }
9135
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009136 static class ItemMatcher {
9137 ArrayList<ComponentName> components;
9138 ArrayList<String> strings;
9139 ArrayList<Integer> objects;
9140 boolean all;
9141
9142 ItemMatcher() {
9143 all = true;
9144 }
9145
9146 void build(String name) {
9147 ComponentName componentName = ComponentName.unflattenFromString(name);
9148 if (componentName != null) {
9149 if (components == null) {
9150 components = new ArrayList<ComponentName>();
9151 }
9152 components.add(componentName);
9153 all = false;
9154 } else {
9155 int objectId = 0;
9156 // Not a '/' separated full component name; maybe an object ID?
9157 try {
9158 objectId = Integer.parseInt(name, 16);
9159 if (objects == null) {
9160 objects = new ArrayList<Integer>();
9161 }
9162 objects.add(objectId);
9163 all = false;
9164 } catch (RuntimeException e) {
9165 // Not an integer; just do string match.
9166 if (strings == null) {
9167 strings = new ArrayList<String>();
9168 }
9169 strings.add(name);
9170 all = false;
9171 }
9172 }
9173 }
9174
9175 int build(String[] args, int opti) {
9176 for (; opti<args.length; opti++) {
9177 String name = args[opti];
9178 if ("--".equals(name)) {
9179 return opti+1;
9180 }
9181 build(name);
9182 }
9183 return opti;
9184 }
9185
9186 boolean match(Object object, ComponentName comp) {
9187 if (all) {
9188 return true;
9189 }
9190 if (components != null) {
9191 for (int i=0; i<components.size(); i++) {
9192 if (components.get(i).equals(comp)) {
9193 return true;
9194 }
9195 }
9196 }
9197 if (objects != null) {
9198 for (int i=0; i<objects.size(); i++) {
9199 if (System.identityHashCode(object) == objects.get(i)) {
9200 return true;
9201 }
9202 }
9203 }
9204 if (strings != null) {
9205 String flat = comp.flattenToString();
9206 for (int i=0; i<strings.size(); i++) {
9207 if (flat.contains(strings.get(i))) {
9208 return true;
9209 }
9210 }
9211 }
9212 return false;
9213 }
9214 }
9215
Dianne Hackborn625ac272010-09-17 18:29:22 -07009216 /**
9217 * There are three things that cmd can be:
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009218 * - a flattened component name that matches an existing activity
Dianne Hackborn625ac272010-09-17 18:29:22 -07009219 * - the cmd arg isn't the flattened component name of an existing activity:
9220 * dump all activity whose component contains the cmd as a substring
9221 * - A hex number of the ActivityRecord object instance.
9222 */
9223 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9224 int opti, boolean dumpAll) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009225 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009226
9227 if ("all".equals(name)) {
9228 synchronized (this) {
9229 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009230 activities.add(r1);
9231 }
9232 }
Dianne Hackbornf9302322011-06-14 18:36:14 -07009233 } else if ("top".equals(name)) {
9234 synchronized (this) {
9235 final int N = mMainStack.mHistory.size();
9236 if (N > 0) {
9237 activities.add((ActivityRecord)mMainStack.mHistory.get(N-1));
9238 }
9239 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009240 } else {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009241 ItemMatcher matcher = new ItemMatcher();
9242 matcher.build(name);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009243
9244 synchronized (this) {
9245 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009246 if (matcher.match(r1, r1.intent.getComponent())) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009247 activities.add(r1);
9248 }
9249 }
9250 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009251 }
9252
9253 if (activities.size() <= 0) {
9254 return false;
9255 }
9256
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009257 String[] newArgs = new String[args.length - opti];
9258 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
9259
Dianne Hackborn30d71892010-12-11 10:37:55 -08009260 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009261 boolean needSep = false;
Dianne Hackborn30d71892010-12-11 10:37:55 -08009262 for (int i=activities.size()-1; i>=0; i--) {
9263 ActivityRecord r = (ActivityRecord)activities.get(i);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009264 if (needSep) {
9265 pw.println();
9266 }
9267 needSep = true;
9268 synchronized (this) {
9269 if (lastTask != r.task) {
9270 lastTask = r.task;
9271 pw.print("TASK "); pw.print(lastTask.affinity);
9272 pw.print(" id="); pw.println(lastTask.taskId);
9273 if (dumpAll) {
9274 lastTask.dump(pw, " ");
9275 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08009276 }
9277 }
9278 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009279 }
9280 return true;
9281 }
9282
9283 /**
9284 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
9285 * there is a thread associated with the activity.
9286 */
Dianne Hackborn30d71892010-12-11 10:37:55 -08009287 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009288 final ActivityRecord r, String[] args, boolean dumpAll) {
9289 String innerPrefix = prefix + " ";
Dianne Hackborn30d71892010-12-11 10:37:55 -08009290 synchronized (this) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009291 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
9292 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
9293 pw.print(" pid=");
Dianne Hackborn30d71892010-12-11 10:37:55 -08009294 if (r.app != null) pw.println(r.app.pid);
9295 else pw.println("(not running)");
9296 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009297 r.dump(pw, innerPrefix);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009298 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009299 }
9300 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009301 // flush anything that is already in the PrintWriter since the thread is going
9302 // to write to the file descriptor directly
9303 pw.flush();
Dianne Hackborn625ac272010-09-17 18:29:22 -07009304 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009305 TransferPipe tp = new TransferPipe();
9306 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009307 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9308 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009309 tp.go(fd);
9310 } finally {
9311 tp.kill();
9312 }
9313 } catch (IOException e) {
9314 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009315 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009316 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
Dianne Hackborn625ac272010-09-17 18:29:22 -07009317 }
9318 }
9319 }
9320
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009321 boolean dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009322 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009323 boolean needSep = false;
9324
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009325 pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009326 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009327 if (mRegisteredReceivers.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009328 boolean printed = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009329 Iterator it = mRegisteredReceivers.values().iterator();
9330 while (it.hasNext()) {
9331 ReceiverList r = (ReceiverList)it.next();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009332 if (dumpPackage != null && (r.app == null ||
9333 !dumpPackage.equals(r.app.info.packageName))) {
9334 continue;
9335 }
9336 if (!printed) {
9337 pw.println(" Registered Receivers:");
9338 needSep = true;
9339 printed = true;
9340 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009341 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009342 r.dump(pw, " ");
9343 }
9344 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009345
9346 if (mReceiverResolver.dump(pw, needSep ?
9347 "\n Receiver Resolver Table:" : " Receiver Resolver Table:",
9348 " ", dumpPackage, false)) {
9349 needSep = true;
9350 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009351 }
Christopher Tatef46723b2012-01-26 14:19:24 -08009352
9353 for (BroadcastQueue q : mBroadcastQueues) {
9354 needSep = q.dumpLocked(fd, pw, args, opti, dumpAll, dumpPackage, needSep);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009355 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009356
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009357 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009358
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009359 if (mStickyBroadcasts != null && dumpPackage == null) {
9360 if (needSep) {
9361 pw.println();
9362 }
9363 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009364 pw.println(" Sticky broadcasts:");
9365 StringBuilder sb = new StringBuilder(128);
9366 for (Map.Entry<String, ArrayList<Intent>> ent
9367 : mStickyBroadcasts.entrySet()) {
9368 pw.print(" * Sticky action "); pw.print(ent.getKey());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009369 if (dumpAll) {
9370 pw.println(":");
9371 ArrayList<Intent> intents = ent.getValue();
9372 final int N = intents.size();
9373 for (int i=0; i<N; i++) {
9374 sb.setLength(0);
9375 sb.append(" Intent: ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009376 intents.get(i).toShortString(sb, false, true, false, false);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009377 pw.println(sb.toString());
9378 Bundle bundle = intents.get(i).getExtras();
9379 if (bundle != null) {
9380 pw.print(" ");
9381 pw.println(bundle.toString());
9382 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009383 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009384 } else {
9385 pw.println("");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009386 }
9387 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009388 needSep = true;
9389 }
9390
9391 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009392 pw.println();
Christopher Tatef46723b2012-01-26 14:19:24 -08009393 for (BroadcastQueue queue : mBroadcastQueues) {
9394 pw.println(" mBroadcastsScheduled [" + queue.mQueueName + "]="
9395 + queue.mBroadcastsScheduled);
9396 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009397 pw.println(" mHandler:");
9398 mHandler.dump(new PrintWriterPrinter(pw), " ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009399 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009400 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009401
9402 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009403 }
9404
Marco Nelissen18cb2872011-11-15 11:19:53 -08009405 /**
9406 * Prints a list of ServiceRecords (dumpsys activity services)
9407 */
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009408 boolean dumpServicesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009409 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009410 boolean needSep = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009411
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009412 ItemMatcher matcher = new ItemMatcher();
9413 matcher.build(args, opti);
9414
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009415 pw.println("ACTIVITY MANAGER SERVICES (dumpsys activity services)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009416 try {
9417 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
9418 for (UserInfo user : users) {
9419 if (mServiceMap.getAllServices(user.id).size() > 0) {
9420 boolean printed = false;
9421 long nowReal = SystemClock.elapsedRealtime();
9422 Iterator<ServiceRecord> it = mServiceMap.getAllServices(
9423 user.id).iterator();
9424 needSep = false;
9425 while (it.hasNext()) {
9426 ServiceRecord r = it.next();
9427 if (!matcher.match(r, r.name)) {
9428 continue;
9429 }
9430 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9431 continue;
9432 }
9433 if (!printed) {
9434 pw.println(" Active services:");
9435 printed = true;
9436 }
9437 if (needSep) {
9438 pw.println();
9439 }
9440 pw.print(" * ");
9441 pw.println(r);
9442 if (dumpAll) {
9443 r.dump(pw, " ");
9444 needSep = true;
9445 } else {
9446 pw.print(" app=");
9447 pw.println(r.app);
9448 pw.print(" created=");
9449 TimeUtils.formatDuration(r.createTime, nowReal, pw);
9450 pw.print(" started=");
9451 pw.print(r.startRequested);
9452 pw.print(" connections=");
9453 pw.println(r.connections.size());
9454 if (r.connections.size() > 0) {
9455 pw.println(" Connections:");
9456 for (ArrayList<ConnectionRecord> clist : r.connections.values()) {
9457 for (int i = 0; i < clist.size(); i++) {
9458 ConnectionRecord conn = clist.get(i);
9459 pw.print(" ");
9460 pw.print(conn.binding.intent.intent.getIntent()
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009461 .toShortString(false, false, false, false));
Amith Yamasani742a6712011-05-04 14:49:28 -07009462 pw.print(" -> ");
9463 ProcessRecord proc = conn.binding.client;
9464 pw.println(proc != null ? proc.toShortString() : "null");
9465 }
9466 }
Dianne Hackborn8ec8d412011-11-14 18:27:24 -08009467 }
9468 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009469 if (dumpClient && r.app != null && r.app.thread != null) {
9470 pw.println(" Client:");
9471 pw.flush();
9472 try {
9473 TransferPipe tp = new TransferPipe();
9474 try {
9475 r.app.thread.dumpService(tp.getWriteFd().getFileDescriptor(),
9476 r, args);
9477 tp.setBufferPrefix(" ");
9478 // Short timeout, since blocking here can
9479 // deadlock with the application.
9480 tp.go(fd, 2000);
9481 } finally {
9482 tp.kill();
9483 }
9484 } catch (IOException e) {
9485 pw.println(" Failure while dumping the service: " + e);
9486 } catch (RemoteException e) {
9487 pw.println(" Got a RemoteException while dumping the service");
9488 }
9489 needSep = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009490 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009491 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009492 needSep = printed;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009493 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009494 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009495 } catch (RemoteException re) {
9496
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009497 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009498
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009499 if (mPendingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009500 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009501 for (int i=0; i<mPendingServices.size(); i++) {
9502 ServiceRecord r = mPendingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009503 if (!matcher.match(r, r.name)) {
9504 continue;
9505 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009506 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9507 continue;
9508 }
9509 if (!printed) {
9510 if (needSep) pw.println(" ");
9511 needSep = true;
9512 pw.println(" Pending services:");
9513 printed = true;
9514 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009515 pw.print(" * Pending "); pw.println(r);
9516 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009517 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009518 needSep = true;
9519 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009520
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009521 if (mRestartingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009522 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009523 for (int i=0; i<mRestartingServices.size(); i++) {
9524 ServiceRecord r = mRestartingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009525 if (!matcher.match(r, r.name)) {
9526 continue;
9527 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009528 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9529 continue;
9530 }
9531 if (!printed) {
9532 if (needSep) pw.println(" ");
9533 needSep = true;
9534 pw.println(" Restarting services:");
9535 printed = true;
9536 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009537 pw.print(" * Restarting "); pw.println(r);
9538 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009539 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009540 needSep = true;
9541 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009542
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009543 if (mStoppingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009544 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009545 for (int i=0; i<mStoppingServices.size(); i++) {
9546 ServiceRecord r = mStoppingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009547 if (!matcher.match(r, r.name)) {
9548 continue;
9549 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009550 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9551 continue;
9552 }
9553 if (!printed) {
9554 if (needSep) pw.println(" ");
9555 needSep = true;
9556 pw.println(" Stopping services:");
9557 printed = true;
9558 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009559 pw.print(" * Stopping "); pw.println(r);
9560 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009561 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009562 needSep = true;
9563 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009564
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009565 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009566 if (mServiceConnections.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009567 boolean printed = false;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009568 Iterator<ArrayList<ConnectionRecord>> it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009569 = mServiceConnections.values().iterator();
9570 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009571 ArrayList<ConnectionRecord> r = it.next();
9572 for (int i=0; i<r.size(); i++) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009573 ConnectionRecord cr = r.get(i);
9574 if (!matcher.match(cr.binding.service, cr.binding.service.name)) {
9575 continue;
9576 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009577 if (dumpPackage != null && (cr.binding.client == null
9578 || !dumpPackage.equals(cr.binding.client.info.packageName))) {
9579 continue;
9580 }
9581 if (!printed) {
9582 if (needSep) pw.println(" ");
9583 needSep = true;
9584 pw.println(" Connection bindings to services:");
9585 printed = true;
9586 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009587 pw.print(" * "); pw.println(cr);
9588 cr.dump(pw, " ");
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009589 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009590 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009591 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009592 }
9593 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009594
9595 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009596 }
9597
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009598 boolean dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009599 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07009600 boolean needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009601
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009602 ItemMatcher matcher = new ItemMatcher();
9603 matcher.build(args, opti);
9604
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009605 pw.println("ACTIVITY MANAGER CONTENT PROVIDERS (dumpsys activity providers)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009606
9607 mProviderMap.dumpProvidersLocked(pw, dumpAll);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009608
9609 if (mLaunchingProviders.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009610 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009611 for (int i=mLaunchingProviders.size()-1; i>=0; i--) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009612 ContentProviderRecord r = mLaunchingProviders.get(i);
9613 if (dumpPackage != null && !dumpPackage.equals(r.name.getPackageName())) {
9614 continue;
9615 }
9616 if (!printed) {
9617 if (needSep) pw.println(" ");
9618 needSep = true;
9619 pw.println(" Launching content providers:");
9620 printed = true;
9621 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009622 pw.print(" Launching #"); pw.print(i); pw.print(": ");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009623 pw.println(r);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009624 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009625 }
9626
9627 if (mGrantedUriPermissions.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009628 if (needSep) pw.println();
9629 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009630 pw.println("Granted Uri Permissions:");
9631 for (int i=0; i<mGrantedUriPermissions.size(); i++) {
9632 int uid = mGrantedUriPermissions.keyAt(i);
9633 HashMap<Uri, UriPermission> perms
9634 = mGrantedUriPermissions.valueAt(i);
9635 pw.print(" * UID "); pw.print(uid);
9636 pw.println(" holds:");
9637 for (UriPermission perm : perms.values()) {
9638 pw.print(" "); pw.println(perm);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009639 if (dumpAll) {
9640 perm.dump(pw, " ");
9641 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009642 }
9643 }
9644 needSep = true;
9645 }
9646
9647 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009648 }
9649
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009650 boolean dumpPendingIntentsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009651 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009652 boolean needSep = false;
9653
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009654 if (mIntentSenderRecords.size() > 0) {
9655 boolean printed = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009656 Iterator<WeakReference<PendingIntentRecord>> it
9657 = mIntentSenderRecords.values().iterator();
9658 while (it.hasNext()) {
9659 WeakReference<PendingIntentRecord> ref = it.next();
9660 PendingIntentRecord rec = ref != null ? ref.get(): null;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009661 if (dumpPackage != null && (rec == null
9662 || !dumpPackage.equals(rec.key.packageName))) {
9663 continue;
9664 }
9665 if (!printed) {
9666 pw.println("ACTIVITY MANAGER PENDING INTENTS (dumpsys activity intents)");
9667 printed = true;
9668 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009669 needSep = true;
9670 if (rec != null) {
9671 pw.print(" * "); pw.println(rec);
9672 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009673 rec.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009674 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009675 } else {
9676 pw.print(" * "); pw.println(ref);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009677 }
9678 }
9679 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009680
9681 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009682 }
9683
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009684 private static final void dumpHistoryList(FileDescriptor fd, PrintWriter pw, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009685 String prefix, String label, boolean complete, boolean brief, boolean client,
9686 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009687 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009688 boolean needNL = false;
9689 final String innerPrefix = prefix + " ";
9690 final String[] args = new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009691 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009692 final ActivityRecord r = (ActivityRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009693 if (dumpPackage != null && !dumpPackage.equals(r.packageName)) {
9694 continue;
9695 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07009696 final boolean full = !brief && (complete || !r.isInHistory());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009697 if (needNL) {
9698 pw.println(" ");
9699 needNL = false;
9700 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009701 if (lastTask != r.task) {
9702 lastTask = r.task;
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009703 pw.print(prefix);
9704 pw.print(full ? "* " : " ");
9705 pw.println(lastTask);
9706 if (full) {
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009707 lastTask.dump(pw, prefix + " ");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009708 } else if (complete) {
9709 // Complete + brief == give a summary. Isn't that obvious?!?
9710 if (lastTask.intent != null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009711 pw.print(prefix); pw.print(" ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009712 pw.println(lastTask.intent.toInsecureStringWithClip());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009713 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009714 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009715 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009716 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label);
9717 pw.print(" #"); pw.print(i); pw.print(": ");
9718 pw.println(r);
9719 if (full) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009720 r.dump(pw, innerPrefix);
9721 } else if (complete) {
9722 // Complete + brief == give a summary. Isn't that obvious?!?
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009723 pw.print(innerPrefix); pw.println(r.intent.toInsecureString());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009724 if (r.app != null) {
9725 pw.print(innerPrefix); pw.println(r.app);
9726 }
9727 }
9728 if (client && r.app != null && r.app.thread != null) {
9729 // flush anything that is already in the PrintWriter since the thread is going
9730 // to write to the file descriptor directly
9731 pw.flush();
9732 try {
9733 TransferPipe tp = new TransferPipe();
9734 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009735 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9736 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009737 // Short timeout, since blocking here can
9738 // deadlock with the application.
9739 tp.go(fd, 2000);
9740 } finally {
9741 tp.kill();
9742 }
9743 } catch (IOException e) {
9744 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
9745 } catch (RemoteException e) {
9746 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
9747 }
9748 needNL = true;
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009749 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009750 }
9751 }
9752
Dianne Hackborn09c916b2009-12-08 14:50:51 -08009753 private static String buildOomTag(String prefix, String space, int val, int base) {
9754 if (val == base) {
9755 if (space == null) return prefix;
9756 return prefix + " ";
9757 }
9758 return prefix + "+" + Integer.toString(val-base);
9759 }
9760
9761 private static final int dumpProcessList(PrintWriter pw,
9762 ActivityManagerService service, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009763 String prefix, String normalLabel, String persistentLabel,
9764 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009765 int numPers = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07009766 final int N = list.size()-1;
9767 for (int i=N; i>=0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009768 ProcessRecord r = (ProcessRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009769 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9770 continue;
9771 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009772 pw.println(String.format("%s%s #%2d: %s",
9773 prefix, (r.persistent ? persistentLabel : normalLabel),
9774 i, r.toString()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009775 if (r.persistent) {
9776 numPers++;
9777 }
9778 }
9779 return numPers;
9780 }
9781
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009782 private static final boolean dumpProcessOomList(PrintWriter pw,
Dianne Hackborn905577f2011-09-07 18:31:28 -07009783 ActivityManagerService service, List<ProcessRecord> origList,
Dianne Hackborn287952c2010-09-22 22:34:31 -07009784 String prefix, String normalLabel, String persistentLabel,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009785 boolean inclDetails, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009786
Dianne Hackborn905577f2011-09-07 18:31:28 -07009787 ArrayList<Pair<ProcessRecord, Integer>> list
9788 = new ArrayList<Pair<ProcessRecord, Integer>>(origList.size());
9789 for (int i=0; i<origList.size(); i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009790 ProcessRecord r = origList.get(i);
9791 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9792 continue;
9793 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07009794 list.add(new Pair<ProcessRecord, Integer>(origList.get(i), i));
9795 }
9796
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009797 if (list.size() <= 0) {
9798 return false;
9799 }
9800
Dianne Hackborn905577f2011-09-07 18:31:28 -07009801 Comparator<Pair<ProcessRecord, Integer>> comparator
9802 = new Comparator<Pair<ProcessRecord, Integer>>() {
9803 @Override
9804 public int compare(Pair<ProcessRecord, Integer> object1,
9805 Pair<ProcessRecord, Integer> object2) {
9806 if (object1.first.setAdj != object2.first.setAdj) {
9807 return object1.first.setAdj > object2.first.setAdj ? -1 : 1;
9808 }
9809 if (object1.second.intValue() != object2.second.intValue()) {
9810 return object1.second.intValue() > object2.second.intValue() ? -1 : 1;
9811 }
9812 return 0;
9813 }
9814 };
9815
9816 Collections.sort(list, comparator);
9817
Dianne Hackborn287952c2010-09-22 22:34:31 -07009818 final long curRealtime = SystemClock.elapsedRealtime();
9819 final long realtimeSince = curRealtime - service.mLastPowerCheckRealtime;
9820 final long curUptime = SystemClock.uptimeMillis();
9821 final long uptimeSince = curUptime - service.mLastPowerCheckUptime;
9822
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009823 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07009824 ProcessRecord r = list.get(i).first;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009825 String oomAdj;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009826 if (r.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07009827 oomAdj = buildOomTag("bak", " ", r.setAdj, ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009828 } else if (r.setAdj >= ProcessList.SERVICE_B_ADJ) {
9829 oomAdj = buildOomTag("svcb ", null, r.setAdj, ProcessList.SERVICE_B_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009830 } else if (r.setAdj >= ProcessList.PREVIOUS_APP_ADJ) {
9831 oomAdj = buildOomTag("prev ", null, r.setAdj, ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009832 } else if (r.setAdj >= ProcessList.HOME_APP_ADJ) {
9833 oomAdj = buildOomTag("home ", null, r.setAdj, ProcessList.HOME_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009834 } else if (r.setAdj >= ProcessList.SERVICE_ADJ) {
9835 oomAdj = buildOomTag("svc ", null, r.setAdj, ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009836 } else if (r.setAdj >= ProcessList.BACKUP_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08009837 oomAdj = buildOomTag("bkup ", null, r.setAdj, ProcessList.BACKUP_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009838 } else if (r.setAdj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
9839 oomAdj = buildOomTag("hvy ", null, r.setAdj, ProcessList.HEAVY_WEIGHT_APP_ADJ);
9840 } else if (r.setAdj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
9841 oomAdj = buildOomTag("prcp ", null, r.setAdj, ProcessList.PERCEPTIBLE_APP_ADJ);
9842 } else if (r.setAdj >= ProcessList.VISIBLE_APP_ADJ) {
9843 oomAdj = buildOomTag("vis ", null, r.setAdj, ProcessList.VISIBLE_APP_ADJ);
9844 } else if (r.setAdj >= ProcessList.FOREGROUND_APP_ADJ) {
9845 oomAdj = buildOomTag("fore ", null, r.setAdj, ProcessList.FOREGROUND_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009846 } else if (r.setAdj >= ProcessList.PERSISTENT_PROC_ADJ) {
9847 oomAdj = buildOomTag("pers ", null, r.setAdj, ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009848 } else if (r.setAdj >= ProcessList.SYSTEM_ADJ) {
9849 oomAdj = buildOomTag("sys ", null, r.setAdj, ProcessList.SYSTEM_ADJ);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009850 } else {
9851 oomAdj = Integer.toString(r.setAdj);
9852 }
9853 String schedGroup;
9854 switch (r.setSchedGroup) {
9855 case Process.THREAD_GROUP_BG_NONINTERACTIVE:
9856 schedGroup = "B";
9857 break;
9858 case Process.THREAD_GROUP_DEFAULT:
9859 schedGroup = "F";
9860 break;
9861 default:
9862 schedGroup = Integer.toString(r.setSchedGroup);
9863 break;
9864 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07009865 String foreground;
9866 if (r.foregroundActivities) {
9867 foreground = "A";
9868 } else if (r.foregroundServices) {
9869 foreground = "S";
9870 } else {
9871 foreground = " ";
9872 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07009873 pw.println(String.format("%s%s #%2d: adj=%s/%s%s trm=%2d %s (%s)",
Dianne Hackborn287952c2010-09-22 22:34:31 -07009874 prefix, (r.persistent ? persistentLabel : normalLabel),
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009875 (origList.size()-1)-list.get(i).second, oomAdj, schedGroup,
9876 foreground, r.trimMemoryLevel, r.toShortString(), r.adjType));
Dianne Hackborn287952c2010-09-22 22:34:31 -07009877 if (r.adjSource != null || r.adjTarget != null) {
9878 pw.print(prefix);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009879 pw.print(" ");
Dianne Hackborn287952c2010-09-22 22:34:31 -07009880 if (r.adjTarget instanceof ComponentName) {
9881 pw.print(((ComponentName)r.adjTarget).flattenToShortString());
9882 } else if (r.adjTarget != null) {
9883 pw.print(r.adjTarget.toString());
9884 } else {
9885 pw.print("{null}");
9886 }
9887 pw.print("<=");
9888 if (r.adjSource instanceof ProcessRecord) {
9889 pw.print("Proc{");
9890 pw.print(((ProcessRecord)r.adjSource).toShortString());
9891 pw.println("}");
9892 } else if (r.adjSource != null) {
9893 pw.println(r.adjSource.toString());
9894 } else {
9895 pw.println("{null}");
9896 }
9897 }
9898 if (inclDetails) {
9899 pw.print(prefix);
9900 pw.print(" ");
9901 pw.print("oom: max="); pw.print(r.maxAdj);
9902 pw.print(" hidden="); pw.print(r.hiddenAdj);
9903 pw.print(" curRaw="); pw.print(r.curRawAdj);
9904 pw.print(" setRaw="); pw.print(r.setRawAdj);
9905 pw.print(" cur="); pw.print(r.curAdj);
9906 pw.print(" set="); pw.println(r.setAdj);
9907 pw.print(prefix);
9908 pw.print(" ");
9909 pw.print("keeping="); pw.print(r.keeping);
9910 pw.print(" hidden="); pw.print(r.hidden);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009911 pw.print(" empty="); pw.print(r.empty);
9912 pw.print(" hasAboveClient="); pw.println(r.hasAboveClient);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009913
9914 if (!r.keeping) {
9915 if (r.lastWakeTime != 0) {
9916 long wtime;
9917 BatteryStatsImpl stats = service.mBatteryStatsService.getActiveStatistics();
9918 synchronized (stats) {
9919 wtime = stats.getProcessWakeTime(r.info.uid,
9920 r.pid, curRealtime);
9921 }
9922 long timeUsed = wtime - r.lastWakeTime;
9923 pw.print(prefix);
9924 pw.print(" ");
9925 pw.print("keep awake over ");
9926 TimeUtils.formatDuration(realtimeSince, pw);
9927 pw.print(" used ");
9928 TimeUtils.formatDuration(timeUsed, pw);
9929 pw.print(" (");
9930 pw.print((timeUsed*100)/realtimeSince);
9931 pw.println("%)");
9932 }
9933 if (r.lastCpuTime != 0) {
9934 long timeUsed = r.curCpuTime - r.lastCpuTime;
9935 pw.print(prefix);
9936 pw.print(" ");
9937 pw.print("run cpu over ");
9938 TimeUtils.formatDuration(uptimeSince, pw);
9939 pw.print(" used ");
9940 TimeUtils.formatDuration(timeUsed, pw);
9941 pw.print(" (");
9942 pw.print((timeUsed*100)/uptimeSince);
9943 pw.println("%)");
9944 }
9945 }
9946 }
9947 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009948 return true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009949 }
9950
Dianne Hackbornb437e092011-08-05 17:50:29 -07009951 ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, String[] args) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009952 ArrayList<ProcessRecord> procs;
9953 synchronized (this) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009954 if (args != null && args.length > start
9955 && args[start].charAt(0) != '-') {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009956 procs = new ArrayList<ProcessRecord>();
9957 int pid = -1;
9958 try {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009959 pid = Integer.parseInt(args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009960 } catch (NumberFormatException e) {
9961
9962 }
9963 for (int i=mLruProcesses.size()-1; i>=0; i--) {
9964 ProcessRecord proc = mLruProcesses.get(i);
9965 if (proc.pid == pid) {
9966 procs.add(proc);
Dianne Hackbornb437e092011-08-05 17:50:29 -07009967 } else if (proc.processName.equals(args[start])) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009968 procs.add(proc);
9969 }
9970 }
9971 if (procs.size() <= 0) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009972 pw.println("No process found for: " + args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009973 return null;
9974 }
9975 } else {
9976 procs = new ArrayList<ProcessRecord>(mLruProcesses);
9977 }
9978 }
9979 return procs;
9980 }
9981
9982 final void dumpGraphicsHardwareUsage(FileDescriptor fd,
9983 PrintWriter pw, String[] args) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009984 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009985 if (procs == null) {
9986 return;
9987 }
9988
9989 long uptime = SystemClock.uptimeMillis();
9990 long realtime = SystemClock.elapsedRealtime();
9991 pw.println("Applications Graphics Acceleration Info:");
9992 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
9993
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009994 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
9995 ProcessRecord r = procs.get(i);
Chet Haase9c1e23b2011-03-24 10:51:31 -07009996 if (r.thread != null) {
9997 pw.println("\n** Graphics info for pid " + r.pid + " [" + r.processName + "] **");
9998 pw.flush();
9999 try {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010000 TransferPipe tp = new TransferPipe();
10001 try {
10002 r.thread.dumpGfxInfo(tp.getWriteFd().getFileDescriptor(), args);
10003 tp.go(fd);
10004 } finally {
10005 tp.kill();
10006 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010007 } catch (IOException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010008 pw.println("Failure while dumping the app: " + r);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010009 pw.flush();
Chet Haase9c1e23b2011-03-24 10:51:31 -070010010 } catch (RemoteException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010011 pw.println("Got a RemoteException while dumping the app " + r);
Chet Haase9c1e23b2011-03-24 10:51:31 -070010012 pw.flush();
10013 }
10014 }
10015 }
Chet Haase9c1e23b2011-03-24 10:51:31 -070010016 }
10017
Jeff Brown6754ba22011-12-14 20:20:01 -080010018 final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) {
10019 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
10020 if (procs == null) {
10021 return;
10022 }
10023
10024 pw.println("Applications Database Info:");
10025
10026 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10027 ProcessRecord r = procs.get(i);
10028 if (r.thread != null) {
10029 pw.println("\n** Database info for pid " + r.pid + " [" + r.processName + "] **");
10030 pw.flush();
10031 try {
10032 TransferPipe tp = new TransferPipe();
10033 try {
10034 r.thread.dumpDbInfo(tp.getWriteFd().getFileDescriptor(), args);
10035 tp.go(fd);
10036 } finally {
10037 tp.kill();
10038 }
10039 } catch (IOException e) {
10040 pw.println("Failure while dumping the app: " + r);
10041 pw.flush();
10042 } catch (RemoteException e) {
10043 pw.println("Got a RemoteException while dumping the app " + r);
10044 pw.flush();
10045 }
10046 }
10047 }
10048 }
10049
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010050 final static class MemItem {
10051 final String label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010052 final String shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010053 final long pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010054 final int id;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010055 ArrayList<MemItem> subitems;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010056
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010057 public MemItem(String _label, String _shortLabel, long _pss, int _id) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010058 label = _label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010059 shortLabel = _shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010060 pss = _pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010061 id = _id;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010062 }
10063 }
10064
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010065 static final void dumpMemItems(PrintWriter pw, String prefix, ArrayList<MemItem> items,
Dianne Hackbornb437e092011-08-05 17:50:29 -070010066 boolean sort) {
10067 if (sort) {
10068 Collections.sort(items, new Comparator<MemItem>() {
10069 @Override
10070 public int compare(MemItem lhs, MemItem rhs) {
10071 if (lhs.pss < rhs.pss) {
10072 return 1;
10073 } else if (lhs.pss > rhs.pss) {
10074 return -1;
10075 }
10076 return 0;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010077 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010078 });
10079 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010080
10081 for (int i=0; i<items.size(); i++) {
10082 MemItem mi = items.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010083 pw.print(prefix); pw.printf("%7d kB: ", mi.pss); pw.println(mi.label);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010084 if (mi.subitems != null) {
10085 dumpMemItems(pw, prefix + " ", mi.subitems, true);
10086 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010087 }
10088 }
10089
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010090 // These are in KB.
10091 static final long[] DUMP_MEM_BUCKETS = new long[] {
10092 5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024,
10093 120*1024, 160*1024, 200*1024,
10094 250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024,
10095 1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024
10096 };
10097
Dianne Hackborn672342c2011-11-29 11:29:02 -080010098 static final void appendMemBucket(StringBuilder out, long memKB, String label,
10099 boolean stackLike) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010100 int start = label.lastIndexOf('.');
10101 if (start >= 0) start++;
10102 else start = 0;
10103 int end = label.length();
10104 for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) {
10105 if (DUMP_MEM_BUCKETS[i] >= memKB) {
10106 long bucket = DUMP_MEM_BUCKETS[i]/1024;
10107 out.append(bucket);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010108 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010109 out.append(label, start, end);
10110 return;
10111 }
10112 }
10113 out.append(memKB/1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010114 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010115 out.append(label, start, end);
10116 }
10117
10118 static final int[] DUMP_MEM_OOM_ADJ = new int[] {
10119 ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ, ProcessList.FOREGROUND_APP_ADJ,
10120 ProcessList.VISIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ,
10121 ProcessList.BACKUP_APP_ADJ, ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ,
10122 ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.HIDDEN_APP_MAX_ADJ
10123 };
10124 static final String[] DUMP_MEM_OOM_LABEL = new String[] {
10125 "System", "Persistent", "Foreground",
10126 "Visible", "Perceptible", "Heavy Weight",
10127 "Backup", "A Services", "Home", "Previous",
10128 "B Services", "Background"
10129 };
10130
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010131 final void dumpApplicationMemoryUsage(FileDescriptor fd,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010132 PrintWriter pw, String prefix, String[] args, boolean brief,
Dianne Hackborn672342c2011-11-29 11:29:02 -080010133 PrintWriter categoryPw, StringBuilder outTag, StringBuilder outStack) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010134 boolean dumpAll = false;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010135 boolean oomOnly = false;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010136
10137 int opti = 0;
10138 while (opti < args.length) {
10139 String opt = args[opti];
10140 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
10141 break;
10142 }
10143 opti++;
10144 if ("-a".equals(opt)) {
10145 dumpAll = true;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010146 } else if ("--oom".equals(opt)) {
10147 oomOnly = true;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010148 } else if ("-h".equals(opt)) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010149 pw.println("meminfo dump options: [-a] [--oom] [process]");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010150 pw.println(" -a: include all available information for each process.");
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010151 pw.println(" --oom: only show processes organized by oom adj.");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010152 pw.println("If [process] is specified it can be the name or ");
10153 pw.println("pid of a specific process to dump.");
10154 return;
10155 } else {
10156 pw.println("Unknown argument: " + opt + "; use -h for help");
10157 }
10158 }
10159
10160 ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010161 if (procs == null) {
10162 return;
10163 }
10164
Dianne Hackborn6447ca32009-04-07 19:50:08 -070010165 final boolean isCheckinRequest = scanArgs(args, "--checkin");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010166 long uptime = SystemClock.uptimeMillis();
10167 long realtime = SystemClock.elapsedRealtime();
Dianne Hackbornb437e092011-08-05 17:50:29 -070010168
10169 if (procs.size() == 1 || isCheckinRequest) {
10170 dumpAll = true;
10171 }
10172
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010173 if (isCheckinRequest) {
10174 // short checkin version
10175 pw.println(uptime + "," + realtime);
10176 pw.flush();
10177 } else {
10178 pw.println("Applications Memory Usage (kB):");
10179 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10180 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010181
Dianne Hackbornb437e092011-08-05 17:50:29 -070010182 String[] innerArgs = new String[args.length-opti];
10183 System.arraycopy(args, opti, innerArgs, 0, args.length-opti);
10184
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010185 ArrayList<MemItem> procMems = new ArrayList<MemItem>();
10186 long nativePss=0, dalvikPss=0, otherPss=0;
10187 long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
10188
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010189 long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length];
10190 ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[])
10191 new ArrayList[DUMP_MEM_OOM_LABEL.length];
Dianne Hackbornb437e092011-08-05 17:50:29 -070010192
10193 long totalPss = 0;
10194
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010195 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10196 ProcessRecord r = procs.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010197 if (r.thread != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010198 if (!isCheckinRequest && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010199 pw.println("\n** MEMINFO in pid " + r.pid + " [" + r.processName + "] **");
10200 pw.flush();
10201 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010202 Debug.MemoryInfo mi = null;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010203 if (dumpAll) {
10204 try {
10205 mi = r.thread.dumpMemInfo(fd, isCheckinRequest, dumpAll, innerArgs);
10206 } catch (RemoteException e) {
10207 if (!isCheckinRequest) {
10208 pw.println("Got RemoteException!");
10209 pw.flush();
10210 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010211 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010212 } else {
10213 mi = new Debug.MemoryInfo();
10214 Debug.getMemoryInfo(r.pid, mi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010215 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010216
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010217 if (!isCheckinRequest && mi != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010218 long myTotalPss = mi.getTotalPss();
10219 totalPss += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010220 MemItem pssItem = new MemItem(r.processName + " (pid " + r.pid + ")",
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010221 r.processName, myTotalPss, 0);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010222 procMems.add(pssItem);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010223
10224 nativePss += mi.nativePss;
10225 dalvikPss += mi.dalvikPss;
10226 otherPss += mi.otherPss;
10227 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
10228 long mem = mi.getOtherPss(j);
10229 miscPss[j] += mem;
10230 otherPss -= mem;
10231 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010232
10233 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010234 if (r.setAdj <= DUMP_MEM_OOM_ADJ[oomIndex]
10235 || oomIndex == (oomPss.length-1)) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010236 oomPss[oomIndex] += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010237 if (oomProcs[oomIndex] == null) {
10238 oomProcs[oomIndex] = new ArrayList<MemItem>();
10239 }
10240 oomProcs[oomIndex].add(pssItem);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010241 break;
10242 }
10243 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010244 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010245 }
10246 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010247
10248 if (!isCheckinRequest && procs.size() > 1) {
10249 ArrayList<MemItem> catMems = new ArrayList<MemItem>();
10250
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010251 catMems.add(new MemItem("Native", "Native", nativePss, -1));
10252 catMems.add(new MemItem("Dalvik", "Dalvik", dalvikPss, -2));
10253 catMems.add(new MemItem("Unknown", "Unknown", otherPss, -3));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010254 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010255 String label = Debug.MemoryInfo.getOtherLabel(j);
10256 catMems.add(new MemItem(label, label, miscPss[j], j));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010257 }
10258
Dianne Hackbornb437e092011-08-05 17:50:29 -070010259 ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
10260 for (int j=0; j<oomPss.length; j++) {
10261 if (oomPss[j] != 0) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010262 String label = DUMP_MEM_OOM_LABEL[j];
10263 MemItem item = new MemItem(label, label, oomPss[j],
10264 DUMP_MEM_OOM_ADJ[j]);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010265 item.subitems = oomProcs[j];
10266 oomMems.add(item);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010267 }
10268 }
10269
Dianne Hackborn672342c2011-11-29 11:29:02 -080010270 if (outTag != null || outStack != null) {
10271 if (outTag != null) {
10272 appendMemBucket(outTag, totalPss, "total", false);
10273 }
10274 if (outStack != null) {
10275 appendMemBucket(outStack, totalPss, "total", true);
10276 }
10277 boolean firstLine = true;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010278 for (int i=0; i<oomMems.size(); i++) {
10279 MemItem miCat = oomMems.get(i);
10280 if (miCat.subitems == null || miCat.subitems.size() < 1) {
10281 continue;
10282 }
10283 if (miCat.id < ProcessList.SERVICE_ADJ
10284 || miCat.id == ProcessList.HOME_APP_ADJ
10285 || miCat.id == ProcessList.PREVIOUS_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010286 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10287 outTag.append(" / ");
10288 }
10289 if (outStack != null) {
10290 if (miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10291 if (firstLine) {
10292 outStack.append(":");
10293 firstLine = false;
10294 }
10295 outStack.append("\n\t at ");
10296 } else {
10297 outStack.append("$");
10298 }
10299 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010300 for (int j=0; j<miCat.subitems.size(); j++) {
10301 MemItem mi = miCat.subitems.get(j);
10302 if (j > 0) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010303 if (outTag != null) {
10304 outTag.append(" ");
10305 }
10306 if (outStack != null) {
10307 outStack.append("$");
10308 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010309 }
Dianne Hackborn672342c2011-11-29 11:29:02 -080010310 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10311 appendMemBucket(outTag, mi.pss, mi.shortLabel, false);
10312 }
10313 if (outStack != null) {
10314 appendMemBucket(outStack, mi.pss, mi.shortLabel, true);
10315 }
10316 }
10317 if (outStack != null && miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10318 outStack.append("(");
10319 for (int k=0; k<DUMP_MEM_OOM_ADJ.length; k++) {
10320 if (DUMP_MEM_OOM_ADJ[k] == miCat.id) {
10321 outStack.append(DUMP_MEM_OOM_LABEL[k]);
10322 outStack.append(":");
10323 outStack.append(DUMP_MEM_OOM_ADJ[k]);
10324 }
10325 }
10326 outStack.append(")");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010327 }
10328 }
10329 }
10330 }
10331
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010332 if (!brief && !oomOnly) {
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010333 pw.println();
10334 pw.println("Total PSS by process:");
10335 dumpMemItems(pw, " ", procMems, true);
10336 pw.println();
10337 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010338 pw.println("Total PSS by OOM adjustment:");
10339 dumpMemItems(pw, " ", oomMems, false);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010340 if (!oomOnly) {
10341 PrintWriter out = categoryPw != null ? categoryPw : pw;
10342 out.println();
10343 out.println("Total PSS by category:");
10344 dumpMemItems(out, " ", catMems, true);
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010345 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010346 pw.println();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010347 pw.print("Total PSS: "); pw.print(totalPss); pw.println(" kB");
Dianne Hackbornd3e677b2012-04-05 14:58:18 -070010348 final int[] SINGLE_LONG_FORMAT = new int[] {
10349 Process.PROC_SPACE_TERM|Process.PROC_OUT_LONG
10350 };
10351 long[] longOut = new long[1];
10352 Process.readProcFile("/sys/kernel/mm/ksm/pages_shared",
10353 SINGLE_LONG_FORMAT, null, longOut, null);
10354 long shared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10355 longOut[0] = 0;
10356 Process.readProcFile("/sys/kernel/mm/ksm/pages_sharing",
10357 SINGLE_LONG_FORMAT, null, longOut, null);
10358 long sharing = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10359 longOut[0] = 0;
10360 Process.readProcFile("/sys/kernel/mm/ksm/pages_unshared",
10361 SINGLE_LONG_FORMAT, null, longOut, null);
10362 long unshared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10363 longOut[0] = 0;
10364 Process.readProcFile("/sys/kernel/mm/ksm/pages_volatile",
10365 SINGLE_LONG_FORMAT, null, longOut, null);
10366 long voltile = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10367 pw.print(" KSM: "); pw.print(sharing); pw.print(" kB saved from shared ");
10368 pw.print(shared); pw.println(" kB");
10369 pw.print(" "); pw.print(unshared); pw.print(" kB unshared; ");
10370 pw.print(voltile); pw.println(" kB volatile");
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010371 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010372 }
10373
10374 /**
10375 * Searches array of arguments for the specified string
10376 * @param args array of argument strings
10377 * @param value value to search for
10378 * @return true if the value is contained in the array
10379 */
10380 private static boolean scanArgs(String[] args, String value) {
10381 if (args != null) {
10382 for (String arg : args) {
10383 if (value.equals(arg)) {
10384 return true;
10385 }
10386 }
10387 }
10388 return false;
10389 }
10390
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010391 private final void killServicesLocked(ProcessRecord app,
10392 boolean allowRestart) {
10393 // Report disconnected services.
10394 if (false) {
10395 // XXX we are letting the client link to the service for
10396 // death notifications.
10397 if (app.services.size() > 0) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010398 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010399 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010400 ServiceRecord r = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010401 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010402 Iterator<ArrayList<ConnectionRecord>> jt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010403 = r.connections.values().iterator();
10404 while (jt.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010405 ArrayList<ConnectionRecord> cl = jt.next();
10406 for (int i=0; i<cl.size(); i++) {
10407 ConnectionRecord c = cl.get(i);
10408 if (c.binding.client != app) {
10409 try {
10410 //c.conn.connected(r.className, null);
10411 } catch (Exception e) {
10412 // todo: this should be asynchronous!
10413 Slog.w(TAG, "Exception thrown disconnected servce "
10414 + r.shortName
10415 + " from app " + app.processName, e);
10416 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010417 }
10418 }
10419 }
10420 }
10421 }
10422 }
10423 }
10424
10425 // Clean up any connections this application has to other services.
10426 if (app.connections.size() > 0) {
10427 Iterator<ConnectionRecord> it = app.connections.iterator();
10428 while (it.hasNext()) {
10429 ConnectionRecord r = it.next();
10430 removeConnectionLocked(r, app, null);
10431 }
10432 }
10433 app.connections.clear();
10434
10435 if (app.services.size() != 0) {
10436 // Any services running in the application need to be placed
10437 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -070010438 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010439 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010440 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010441 synchronized (sr.stats.getBatteryStats()) {
10442 sr.stats.stopLaunchedLocked();
10443 }
10444 sr.app = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010445 sr.isolatedProc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010446 sr.executeNesting = 0;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010447 if (mStoppingServices.remove(sr)) {
10448 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
10449 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010450
10451 boolean hasClients = sr.bindings.size() > 0;
10452 if (hasClients) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010453 Iterator<IntentBindRecord> bindings
10454 = sr.bindings.values().iterator();
10455 while (bindings.hasNext()) {
10456 IntentBindRecord b = bindings.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -080010457 if (DEBUG_SERVICE) Slog.v(TAG, "Killing binding " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010458 + ": shouldUnbind=" + b.hasBound);
10459 b.binder = null;
10460 b.requested = b.received = b.hasBound = false;
10461 }
10462 }
10463
Dianne Hackborn070783f2010-12-29 16:46:28 -080010464 if (sr.crashCount >= 2 && (sr.serviceInfo.applicationInfo.flags
10465 &ApplicationInfo.FLAG_PERSISTENT) == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010466 Slog.w(TAG, "Service crashed " + sr.crashCount
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010467 + " times, stopping: " + sr);
Doug Zongker2bec3d42009-12-04 12:52:44 -080010468 EventLog.writeEvent(EventLogTags.AM_SERVICE_CRASHED_TOO_MUCH,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010469 sr.crashCount, sr.shortName, app.pid);
10470 bringDownServiceLocked(sr, true);
10471 } else if (!allowRestart) {
10472 bringDownServiceLocked(sr, true);
10473 } else {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010474 boolean canceled = scheduleServiceRestartLocked(sr, true);
10475
10476 // Should the service remain running? Note that in the
10477 // extreme case of so many attempts to deliver a command
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010478 // that it failed we also will stop it here.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010479 if (sr.startRequested && (sr.stopIfKilled || canceled)) {
10480 if (sr.pendingStarts.size() == 0) {
10481 sr.startRequested = false;
10482 if (!hasClients) {
10483 // Whoops, no reason to restart!
10484 bringDownServiceLocked(sr, true);
10485 }
10486 }
10487 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010488 }
10489 }
10490
10491 if (!allowRestart) {
10492 app.services.clear();
10493 }
10494 }
10495
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010496 // Make sure we have no more records on the stopping list.
10497 int i = mStoppingServices.size();
10498 while (i > 0) {
10499 i--;
10500 ServiceRecord sr = mStoppingServices.get(i);
10501 if (sr.app == app) {
10502 mStoppingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010503 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010504 }
10505 }
10506
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010507 app.executingServices.clear();
10508 }
10509
10510 private final void removeDyingProviderLocked(ProcessRecord proc,
10511 ContentProviderRecord cpr) {
10512 synchronized (cpr) {
10513 cpr.launchingApp = null;
10514 cpr.notifyAll();
10515 }
10516
Amith Yamasani742a6712011-05-04 14:49:28 -070010517 mProviderMap.removeProviderByClass(cpr.name, UserId.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010518 String names[] = cpr.info.authority.split(";");
10519 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010520 mProviderMap.removeProviderByName(names[j], UserId.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010521 }
10522
10523 Iterator<ProcessRecord> cit = cpr.clients.iterator();
10524 while (cit.hasNext()) {
10525 ProcessRecord capp = cit.next();
10526 if (!capp.persistent && capp.thread != null
10527 && capp.pid != 0
10528 && capp.pid != MY_PID) {
Dianne Hackborn8633e682010-04-22 16:03:41 -070010529 Slog.i(TAG, "Kill " + capp.processName
10530 + " (pid " + capp.pid + "): provider " + cpr.info.name
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010531 + " in dying process " + (proc != null ? proc.processName : "??"));
Dianne Hackborn8633e682010-04-22 16:03:41 -070010532 EventLog.writeEvent(EventLogTags.AM_KILL, capp.pid,
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010533 capp.processName, capp.setAdj, "dying provider "
10534 + cpr.name.toShortString());
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070010535 Process.killProcessQuiet(capp.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010536 }
10537 }
10538
10539 mLaunchingProviders.remove(cpr);
10540 }
10541
10542 /**
10543 * Main code for cleaning up a process when it has gone away. This is
10544 * called both as a result of the process dying, or directly when stopping
10545 * a process when running in single process mode.
10546 */
10547 private final void cleanUpApplicationRecordLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010548 boolean restarting, boolean allowRestart, int index) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010549 if (index >= 0) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010550 mLruProcesses.remove(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010551 }
10552
Dianne Hackborn36124872009-10-08 16:22:03 -070010553 mProcessesToGc.remove(app);
10554
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010555 // Dismiss any open dialogs.
10556 if (app.crashDialog != null) {
10557 app.crashDialog.dismiss();
10558 app.crashDialog = null;
10559 }
10560 if (app.anrDialog != null) {
10561 app.anrDialog.dismiss();
10562 app.anrDialog = null;
10563 }
10564 if (app.waitDialog != null) {
10565 app.waitDialog.dismiss();
10566 app.waitDialog = null;
10567 }
10568
10569 app.crashing = false;
10570 app.notResponding = false;
10571
10572 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -070010573 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010574 app.thread = null;
10575 app.forcingToForeground = null;
10576 app.foregroundServices = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010577 app.foregroundActivities = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070010578 app.hasShownUi = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010579 app.hasAboveClient = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010580
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010581 killServicesLocked(app, allowRestart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010582
10583 boolean restart = false;
10584
10585 int NL = mLaunchingProviders.size();
10586
10587 // Remove published content providers.
10588 if (!app.pubProviders.isEmpty()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010589 Iterator<ContentProviderRecord> it = app.pubProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010590 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010591 ContentProviderRecord cpr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010592 cpr.provider = null;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010593 cpr.proc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010594
10595 // See if someone is waiting for this provider... in which
10596 // case we don't remove it, but just let it restart.
10597 int i = 0;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010598 if (!app.bad && allowRestart) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010599 for (; i<NL; i++) {
10600 if (mLaunchingProviders.get(i) == cpr) {
10601 restart = true;
10602 break;
10603 }
10604 }
10605 } else {
10606 i = NL;
10607 }
10608
10609 if (i >= NL) {
10610 removeDyingProviderLocked(app, cpr);
10611 NL = mLaunchingProviders.size();
10612 }
10613 }
10614 app.pubProviders.clear();
10615 }
10616
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010617 // Take care of any launching providers waiting for this process.
10618 if (checkAppInLaunchingProvidersLocked(app, false)) {
10619 restart = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010620 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010621
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010622 // Unregister from connected content providers.
10623 if (!app.conProviders.isEmpty()) {
Dianne Hackborn0c3154d2009-10-06 17:18:05 -070010624 Iterator it = app.conProviders.keySet().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010625 while (it.hasNext()) {
10626 ContentProviderRecord cpr = (ContentProviderRecord)it.next();
10627 cpr.clients.remove(app);
10628 }
10629 app.conProviders.clear();
10630 }
10631
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010632 // At this point there may be remaining entries in mLaunchingProviders
10633 // where we were the only one waiting, so they are no longer of use.
10634 // Look for these and clean up if found.
10635 // XXX Commented out for now. Trying to figure out a way to reproduce
10636 // the actual situation to identify what is actually going on.
10637 if (false) {
10638 for (int i=0; i<NL; i++) {
10639 ContentProviderRecord cpr = (ContentProviderRecord)
10640 mLaunchingProviders.get(i);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080010641 if (cpr.clients.size() <= 0 && !cpr.hasExternalProcessHandles()) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010642 synchronized (cpr) {
10643 cpr.launchingApp = null;
10644 cpr.notifyAll();
10645 }
10646 }
10647 }
10648 }
10649
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010650 skipCurrentReceiverLocked(app);
10651
10652 // Unregister any receivers.
10653 if (app.receivers.size() > 0) {
10654 Iterator<ReceiverList> it = app.receivers.iterator();
10655 while (it.hasNext()) {
10656 removeReceiverLocked(it.next());
10657 }
10658 app.receivers.clear();
10659 }
10660
Christopher Tate181fafa2009-05-14 11:12:14 -070010661 // If the app is undergoing backup, tell the backup manager about it
10662 if (mBackupTarget != null && app.pid == mBackupTarget.app.pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010663 if (DEBUG_BACKUP) Slog.d(TAG, "App " + mBackupTarget.appInfo + " died during backup");
Christopher Tate181fafa2009-05-14 11:12:14 -070010664 try {
10665 IBackupManager bm = IBackupManager.Stub.asInterface(
10666 ServiceManager.getService(Context.BACKUP_SERVICE));
10667 bm.agentDisconnected(app.info.packageName);
10668 } catch (RemoteException e) {
10669 // can't happen; backup manager is local
10670 }
10671 }
10672
Jeff Sharkey287bd832011-05-28 19:36:26 -070010673 mHandler.obtainMessage(DISPATCH_PROCESS_DIED, app.pid, app.info.uid, null).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010674
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010675 // If the caller is restarting this app, then leave it in its
10676 // current lists and let the caller take care of it.
10677 if (restarting) {
10678 return;
10679 }
10680
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010681 if (!app.persistent || app.isolated) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010682 if (DEBUG_PROCESSES) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010683 "Removing non-persistent process during cleanup: " + app);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010684 mProcessNames.remove(app.processName, app.uid);
10685 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -070010686 if (mHeavyWeightProcess == app) {
10687 mHeavyWeightProcess = null;
10688 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
10689 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010690 } else if (!app.removed) {
10691 // This app is persistent, so we need to keep its record around.
10692 // If it is not already on the pending app list, add it there
10693 // and start a new process for it.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010694 if (mPersistentStartingProcesses.indexOf(app) < 0) {
10695 mPersistentStartingProcesses.add(app);
10696 restart = true;
10697 }
10698 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070010699 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
10700 "Clean-up removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010701 mProcessesOnHold.remove(app);
10702
The Android Open Source Project4df24232009-03-05 14:34:35 -080010703 if (app == mHomeProcess) {
10704 mHomeProcess = null;
10705 }
Dianne Hackbornf35fe232011-11-01 19:25:20 -070010706 if (app == mPreviousProcess) {
10707 mPreviousProcess = null;
10708 }
10709
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010710 if (restart && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010711 // We have components that still need to be running in the
10712 // process, so re-launch it.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010713 mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010714 startProcessLocked(app, "restart", app.processName);
10715 } else if (app.pid > 0 && app.pid != MY_PID) {
10716 // Goodbye!
10717 synchronized (mPidsSelfLocked) {
10718 mPidsSelfLocked.remove(app.pid);
10719 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
10720 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010721 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010722 }
10723 }
10724
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010725 boolean checkAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) {
10726 // Look through the content providers we are waiting to have launched,
10727 // and if any run in this process then either schedule a restart of
10728 // the process or kill the client waiting for it if this process has
10729 // gone bad.
10730 int NL = mLaunchingProviders.size();
10731 boolean restart = false;
10732 for (int i=0; i<NL; i++) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010733 ContentProviderRecord cpr = mLaunchingProviders.get(i);
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010734 if (cpr.launchingApp == app) {
10735 if (!alwaysBad && !app.bad) {
10736 restart = true;
10737 } else {
10738 removeDyingProviderLocked(app, cpr);
10739 NL = mLaunchingProviders.size();
10740 }
10741 }
10742 }
10743 return restart;
10744 }
10745
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010746 // =========================================================
10747 // SERVICES
10748 // =========================================================
10749
10750 ActivityManager.RunningServiceInfo makeRunningServiceInfoLocked(ServiceRecord r) {
10751 ActivityManager.RunningServiceInfo info =
10752 new ActivityManager.RunningServiceInfo();
10753 info.service = r.name;
10754 if (r.app != null) {
10755 info.pid = r.app.pid;
10756 }
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010757 info.uid = r.appInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010758 info.process = r.processName;
10759 info.foreground = r.isForeground;
10760 info.activeSince = r.createTime;
10761 info.started = r.startRequested;
10762 info.clientCount = r.connections.size();
10763 info.crashCount = r.crashCount;
10764 info.lastActivityTime = r.lastActivity;
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010765 if (r.isForeground) {
10766 info.flags |= ActivityManager.RunningServiceInfo.FLAG_FOREGROUND;
10767 }
10768 if (r.startRequested) {
10769 info.flags |= ActivityManager.RunningServiceInfo.FLAG_STARTED;
10770 }
Dan Egnor42471dd2010-01-07 17:25:22 -080010771 if (r.app != null && r.app.pid == MY_PID) {
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010772 info.flags |= ActivityManager.RunningServiceInfo.FLAG_SYSTEM_PROCESS;
10773 }
10774 if (r.app != null && r.app.persistent) {
10775 info.flags |= ActivityManager.RunningServiceInfo.FLAG_PERSISTENT_PROCESS;
10776 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010777
10778 for (ArrayList<ConnectionRecord> connl : r.connections.values()) {
10779 for (int i=0; i<connl.size(); i++) {
10780 ConnectionRecord conn = connl.get(i);
10781 if (conn.clientLabel != 0) {
10782 info.clientPackage = conn.binding.client.info.packageName;
10783 info.clientLabel = conn.clientLabel;
10784 return info;
10785 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010786 }
10787 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010788 return info;
10789 }
10790
10791 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum,
10792 int flags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010793 enforceNotIsolatedCaller("getServices");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010794 synchronized (this) {
10795 ArrayList<ActivityManager.RunningServiceInfo> res
10796 = new ArrayList<ActivityManager.RunningServiceInfo>();
10797
Amith Yamasani742a6712011-05-04 14:49:28 -070010798 int userId = UserId.getUserId(Binder.getCallingUid());
10799 if (mServiceMap.getAllServices(userId).size() > 0) {
10800 Iterator<ServiceRecord> it
10801 = mServiceMap.getAllServices(userId).iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010802 while (it.hasNext() && res.size() < maxNum) {
10803 res.add(makeRunningServiceInfoLocked(it.next()));
10804 }
10805 }
10806
10807 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
10808 ServiceRecord r = mRestartingServices.get(i);
10809 ActivityManager.RunningServiceInfo info =
10810 makeRunningServiceInfoLocked(r);
10811 info.restarting = r.nextRestartTime;
10812 res.add(info);
10813 }
10814
10815 return res;
10816 }
10817 }
10818
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010819 public PendingIntent getRunningServiceControlPanel(ComponentName name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010820 enforceNotIsolatedCaller("getRunningServiceControlPanel");
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010821 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010822 int userId = UserId.getUserId(Binder.getCallingUid());
10823 ServiceRecord r = mServiceMap.getServiceByName(name, userId);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010824 if (r != null) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010825 for (ArrayList<ConnectionRecord> conn : r.connections.values()) {
10826 for (int i=0; i<conn.size(); i++) {
10827 if (conn.get(i).clientIntent != null) {
10828 return conn.get(i).clientIntent;
10829 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010830 }
10831 }
10832 }
10833 }
10834 return null;
10835 }
10836
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010837 private final ServiceRecord findServiceLocked(ComponentName name,
10838 IBinder token) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010839 ServiceRecord r = mServiceMap.getServiceByName(name, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010840 return r == token ? r : null;
10841 }
10842
10843 private final class ServiceLookupResult {
10844 final ServiceRecord record;
10845 final String permission;
10846
10847 ServiceLookupResult(ServiceRecord _record, String _permission) {
10848 record = _record;
10849 permission = _permission;
10850 }
10851 };
10852
10853 private ServiceLookupResult findServiceLocked(Intent service,
Amith Yamasani483f3b02012-03-13 16:08:00 -070010854 String resolvedType, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010855 ServiceRecord r = null;
10856 if (service.getComponent() != null) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070010857 r = mServiceMap.getServiceByName(service.getComponent(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010858 }
10859 if (r == null) {
10860 Intent.FilterComparison filter = new Intent.FilterComparison(service);
Amith Yamasani483f3b02012-03-13 16:08:00 -070010861 r = mServiceMap.getServiceByIntent(filter, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010862 }
10863
10864 if (r == null) {
10865 try {
10866 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070010867 AppGlobals.getPackageManager().resolveService(
Amith Yamasani483f3b02012-03-13 16:08:00 -070010868 service, resolvedType, 0, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010869 ServiceInfo sInfo =
10870 rInfo != null ? rInfo.serviceInfo : null;
10871 if (sInfo == null) {
10872 return null;
10873 }
10874
10875 ComponentName name = new ComponentName(
10876 sInfo.applicationInfo.packageName, sInfo.name);
Amith Yamasani742a6712011-05-04 14:49:28 -070010877 r = mServiceMap.getServiceByName(name, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010878 } catch (RemoteException ex) {
10879 // pm is in same process, this will never happen.
10880 }
10881 }
10882 if (r != null) {
10883 int callingPid = Binder.getCallingPid();
10884 int callingUid = Binder.getCallingUid();
10885 if (checkComponentPermission(r.permission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010886 callingPid, callingUid, r.appInfo.uid, r.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010887 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010888 if (!r.exported) {
10889 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
10890 + " from pid=" + callingPid
10891 + ", uid=" + callingUid
10892 + " that is not exported from uid " + r.appInfo.uid);
10893 return new ServiceLookupResult(null, "not exported from uid "
10894 + r.appInfo.uid);
10895 }
Joe Onorato8a9b2202010-02-26 18:56:32 -080010896 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010897 + " from pid=" + callingPid
10898 + ", uid=" + callingUid
10899 + " requires " + r.permission);
10900 return new ServiceLookupResult(null, r.permission);
10901 }
10902 return new ServiceLookupResult(r, null);
10903 }
10904 return null;
10905 }
10906
10907 private class ServiceRestarter implements Runnable {
10908 private ServiceRecord mService;
10909
10910 void setService(ServiceRecord service) {
10911 mService = service;
10912 }
10913
10914 public void run() {
10915 synchronized(ActivityManagerService.this) {
10916 performServiceRestartLocked(mService);
10917 }
10918 }
10919 }
10920
10921 private ServiceLookupResult retrieveServiceLocked(Intent service,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010922 String resolvedType, int callingPid, int callingUid, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010923 ServiceRecord r = null;
Amith Yamasani742a6712011-05-04 14:49:28 -070010924 if (DEBUG_SERVICE)
10925 Slog.v(TAG, "retrieveServiceLocked: " + service + " type=" + resolvedType
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010926 + " callingUid=" + callingUid);
Amith Yamasani742a6712011-05-04 14:49:28 -070010927
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010928 if (service.getComponent() != null) {
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010929 r = mServiceMap.getServiceByName(service.getComponent(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010930 }
Amith Yamasani742a6712011-05-04 14:49:28 -070010931 if (r == null) {
10932 Intent.FilterComparison filter = new Intent.FilterComparison(service);
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010933 r = mServiceMap.getServiceByIntent(filter, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -070010934 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010935 if (r == null) {
10936 try {
10937 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070010938 AppGlobals.getPackageManager().resolveService(
Amith Yamasani483f3b02012-03-13 16:08:00 -070010939 service, resolvedType, STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010940 ServiceInfo sInfo =
10941 rInfo != null ? rInfo.serviceInfo : null;
10942 if (sInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010943 Slog.w(TAG, "Unable to start service " + service +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010944 ": not found");
10945 return null;
10946 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010947 if (userId > 0) {
Amith Yamasania4a54e22012-04-16 15:44:19 -070010948 if (isSingleton(sInfo.processName, sInfo.applicationInfo)) {
10949 userId = 0;
10950 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010951 sInfo.applicationInfo = getAppInfoForUser(sInfo.applicationInfo, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -070010952 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010953 ComponentName name = new ComponentName(
10954 sInfo.applicationInfo.packageName, sInfo.name);
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010955 r = mServiceMap.getServiceByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010956 if (r == null) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010957 Intent.FilterComparison filter = new Intent.FilterComparison(
10958 service.cloneFilter());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010959 ServiceRestarter res = new ServiceRestarter();
10960 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
10961 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
10962 synchronized (stats) {
10963 ss = stats.getServiceStatsLocked(
10964 sInfo.applicationInfo.uid, sInfo.packageName,
10965 sInfo.name);
10966 }
Dianne Hackbornb1c4a2a2010-01-19 15:36:42 -080010967 r = new ServiceRecord(this, ss, name, filter, sInfo, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010968 res.setService(r);
Amith Yamasani742a6712011-05-04 14:49:28 -070010969 mServiceMap.putServiceByName(name, UserId.getUserId(r.appInfo.uid), r);
10970 mServiceMap.putServiceByIntent(filter, UserId.getUserId(r.appInfo.uid), r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010971
10972 // Make sure this component isn't in the pending list.
10973 int N = mPendingServices.size();
10974 for (int i=0; i<N; i++) {
10975 ServiceRecord pr = mPendingServices.get(i);
10976 if (pr.name.equals(name)) {
10977 mPendingServices.remove(i);
10978 i--;
10979 N--;
10980 }
10981 }
10982 }
10983 } catch (RemoteException ex) {
10984 // pm is in same process, this will never happen.
10985 }
10986 }
10987 if (r != null) {
10988 if (checkComponentPermission(r.permission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010989 callingPid, callingUid, r.appInfo.uid, r.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010990 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010991 if (!r.exported) {
10992 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
10993 + " from pid=" + callingPid
10994 + ", uid=" + callingUid
10995 + " that is not exported from uid " + r.appInfo.uid);
10996 return new ServiceLookupResult(null, "not exported from uid "
10997 + r.appInfo.uid);
10998 }
Joe Onorato8a9b2202010-02-26 18:56:32 -080010999 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011000 + " from pid=" + callingPid
11001 + ", uid=" + callingUid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011002 + " requires " + r.permission);
11003 return new ServiceLookupResult(null, r.permission);
11004 }
11005 return new ServiceLookupResult(r, null);
11006 }
11007 return null;
11008 }
11009
Dianne Hackborn287952c2010-09-22 22:34:31 -070011010 private final void bumpServiceExecutingLocked(ServiceRecord r, String why) {
11011 if (DEBUG_SERVICE) Log.v(TAG, ">>> EXECUTING "
11012 + why + " of " + r + " in app " + r.app);
11013 else if (DEBUG_SERVICE_EXECUTING) Log.v(TAG, ">>> EXECUTING "
11014 + why + " of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011015 long now = SystemClock.uptimeMillis();
11016 if (r.executeNesting == 0 && r.app != null) {
11017 if (r.app.executingServices.size() == 0) {
11018 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
11019 msg.obj = r.app;
11020 mHandler.sendMessageAtTime(msg, now+SERVICE_TIMEOUT);
11021 }
11022 r.app.executingServices.add(r);
11023 }
11024 r.executeNesting++;
11025 r.executingStart = now;
11026 }
11027
11028 private final void sendServiceArgsLocked(ServiceRecord r,
11029 boolean oomAdjusted) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011030 final int N = r.pendingStarts.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011031 if (N == 0) {
11032 return;
11033 }
11034
Dianne Hackborn39792d22010-08-19 18:01:52 -070011035 while (r.pendingStarts.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011036 try {
Dianne Hackborn39792d22010-08-19 18:01:52 -070011037 ServiceRecord.StartItem si = r.pendingStarts.remove(0);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011038 if (DEBUG_SERVICE) Slog.v(TAG, "Sending arguments to: "
11039 + r + " " + r.intent + " args=" + si.intent);
Dianne Hackborn3a28f222011-03-01 12:25:54 -080011040 if (si.intent == null && N > 1) {
11041 // If somehow we got a dummy null intent in the middle,
11042 // then skip it. DO NOT skip a null intent when it is
11043 // the only one in the list -- this is to support the
11044 // onStartCommand(null) case.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011045 continue;
11046 }
Dianne Hackborn39792d22010-08-19 18:01:52 -070011047 si.deliveredTime = SystemClock.uptimeMillis();
11048 r.deliveredStarts.add(si);
11049 si.deliveryCount++;
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011050 if (si.neededGrants != null) {
11051 grantUriPermissionUncheckedFromIntentLocked(si.neededGrants,
11052 si.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -070011053 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070011054 bumpServiceExecutingLocked(r, "start");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011055 if (!oomAdjusted) {
11056 oomAdjusted = true;
11057 updateOomAdjLocked(r.app);
11058 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011059 int flags = 0;
11060 if (si.deliveryCount > 0) {
11061 flags |= Service.START_FLAG_RETRY;
11062 }
11063 if (si.doneExecutingCount > 0) {
11064 flags |= Service.START_FLAG_REDELIVERY;
11065 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011066 r.app.thread.scheduleServiceArgs(r, si.taskRemoved, si.id, flags, si.intent);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011067 } catch (RemoteException e) {
11068 // Remote process gone... we'll let the normal cleanup take
11069 // care of this.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011070 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while scheduling start: " + r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011071 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011072 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011073 Slog.w(TAG, "Unexpected exception", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011074 break;
11075 }
11076 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011077 }
11078
11079 private final boolean requestServiceBindingLocked(ServiceRecord r,
11080 IntentBindRecord i, boolean rebind) {
11081 if (r.app == null || r.app.thread == null) {
11082 // If service is not currently running, can't yet bind.
11083 return false;
11084 }
11085 if ((!i.requested || rebind) && i.apps.size() > 0) {
11086 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011087 bumpServiceExecutingLocked(r, "bind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011088 r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind);
11089 if (!rebind) {
11090 i.requested = true;
11091 }
11092 i.hasBound = true;
11093 i.doRebind = false;
11094 } catch (RemoteException e) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011095 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while binding " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011096 return false;
11097 }
11098 }
11099 return true;
11100 }
11101
11102 private final void requestServiceBindingsLocked(ServiceRecord r) {
11103 Iterator<IntentBindRecord> bindings = r.bindings.values().iterator();
11104 while (bindings.hasNext()) {
11105 IntentBindRecord i = bindings.next();
11106 if (!requestServiceBindingLocked(r, i, false)) {
11107 break;
11108 }
11109 }
11110 }
11111
11112 private final void realStartServiceLocked(ServiceRecord r,
11113 ProcessRecord app) throws RemoteException {
11114 if (app.thread == null) {
11115 throw new RemoteException();
11116 }
Amith Yamasani742a6712011-05-04 14:49:28 -070011117 if (DEBUG_MU)
11118 Slog.v(TAG_MU, "realStartServiceLocked, ServiceRecord.uid = " + r.appInfo.uid
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011119 + ", ProcessRecord.uid = " + app.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011120 r.app = app;
The Android Open Source Project10592532009-03-18 17:39:46 -070011121 r.restartTime = r.lastActivity = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011122
11123 app.services.add(r);
Dianne Hackborn287952c2010-09-22 22:34:31 -070011124 bumpServiceExecutingLocked(r, "create");
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011125 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011126
11127 boolean created = false;
11128 try {
Dianne Hackborna33e3f72009-09-29 17:28:24 -070011129 mStringBuilder.setLength(0);
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011130 r.intent.getIntent().toShortString(mStringBuilder, true, false, true, false);
Doug Zongker2bec3d42009-12-04 12:52:44 -080011131 EventLog.writeEvent(EventLogTags.AM_CREATE_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011132 System.identityHashCode(r), r.shortName,
Dianne Hackborna33e3f72009-09-29 17:28:24 -070011133 mStringBuilder.toString(), r.app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011134 synchronized (r.stats.getBatteryStats()) {
11135 r.stats.startLaunchedLocked();
11136 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -070011137 ensurePackageDexOpt(r.serviceInfo.packageName);
Dianne Hackborne2515ee2011-04-27 18:52:56 -040011138 app.thread.scheduleCreateService(r, r.serviceInfo,
11139 compatibilityInfoForPackageLocked(r.serviceInfo.applicationInfo));
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011140 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011141 created = true;
11142 } finally {
11143 if (!created) {
11144 app.services.remove(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011145 scheduleServiceRestartLocked(r, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011146 }
11147 }
11148
11149 requestServiceBindingsLocked(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011150
11151 // If the service is in the started state, and there are no
11152 // pending arguments, then fake up one so its onStartCommand() will
11153 // be called.
11154 if (r.startRequested && r.callStart && r.pendingStarts.size() == 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011155 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011156 null, null));
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011157 }
11158
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011159 sendServiceArgsLocked(r, true);
11160 }
11161
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011162 private final boolean scheduleServiceRestartLocked(ServiceRecord r,
11163 boolean allowCancel) {
11164 boolean canceled = false;
11165
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011166 final long now = SystemClock.uptimeMillis();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011167 long minDuration = SERVICE_RESTART_DURATION;
Dianne Hackborn6ccd2af2009-08-27 12:26:44 -070011168 long resetTime = SERVICE_RESET_RUN_DURATION;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011169
Dianne Hackborn070783f2010-12-29 16:46:28 -080011170 if ((r.serviceInfo.applicationInfo.flags
11171 &ApplicationInfo.FLAG_PERSISTENT) != 0) {
11172 minDuration /= 4;
11173 }
11174
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011175 // Any delivered but not yet finished starts should be put back
11176 // on the pending list.
11177 final int N = r.deliveredStarts.size();
11178 if (N > 0) {
11179 for (int i=N-1; i>=0; i--) {
11180 ServiceRecord.StartItem si = r.deliveredStarts.get(i);
Dianne Hackborn39792d22010-08-19 18:01:52 -070011181 si.removeUriPermissionsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011182 if (si.intent == null) {
11183 // We'll generate this again if needed.
11184 } else if (!allowCancel || (si.deliveryCount < ServiceRecord.MAX_DELIVERY_COUNT
11185 && si.doneExecutingCount < ServiceRecord.MAX_DONE_EXECUTING_COUNT)) {
11186 r.pendingStarts.add(0, si);
11187 long dur = SystemClock.uptimeMillis() - si.deliveredTime;
11188 dur *= 2;
11189 if (minDuration < dur) minDuration = dur;
11190 if (resetTime < dur) resetTime = dur;
11191 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011192 Slog.w(TAG, "Canceling start item " + si.intent + " in service "
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011193 + r.name);
11194 canceled = true;
11195 }
11196 }
11197 r.deliveredStarts.clear();
11198 }
11199
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011200 r.totalRestartCount++;
11201 if (r.restartDelay == 0) {
11202 r.restartCount++;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011203 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011204 } else {
11205 // If it has been a "reasonably long time" since the service
11206 // was started, then reset our restart duration back to
11207 // the beginning, so we don't infinitely increase the duration
11208 // on a service that just occasionally gets killed (which is
11209 // a normal case, due to process being killed to reclaim memory).
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011210 if (now > (r.restartTime+resetTime)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011211 r.restartCount = 1;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011212 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011213 } else {
Dianne Hackborn070783f2010-12-29 16:46:28 -080011214 if ((r.serviceInfo.applicationInfo.flags
11215 &ApplicationInfo.FLAG_PERSISTENT) != 0) {
11216 // Services in peristent processes will restart much more
11217 // quickly, since they are pretty important. (Think SystemUI).
11218 r.restartDelay += minDuration/2;
11219 } else {
11220 r.restartDelay *= SERVICE_RESTART_DURATION_FACTOR;
11221 if (r.restartDelay < minDuration) {
11222 r.restartDelay = minDuration;
11223 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011224 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011225 }
11226 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011227
11228 r.nextRestartTime = now + r.restartDelay;
11229
11230 // Make sure that we don't end up restarting a bunch of services
11231 // all at the same time.
11232 boolean repeat;
11233 do {
11234 repeat = false;
11235 for (int i=mRestartingServices.size()-1; i>=0; i--) {
11236 ServiceRecord r2 = mRestartingServices.get(i);
11237 if (r2 != r && r.nextRestartTime
11238 >= (r2.nextRestartTime-SERVICE_MIN_RESTART_TIME_BETWEEN)
11239 && r.nextRestartTime
11240 < (r2.nextRestartTime+SERVICE_MIN_RESTART_TIME_BETWEEN)) {
11241 r.nextRestartTime = r2.nextRestartTime + SERVICE_MIN_RESTART_TIME_BETWEEN;
11242 r.restartDelay = r.nextRestartTime - now;
11243 repeat = true;
11244 break;
11245 }
11246 }
11247 } while (repeat);
11248
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011249 if (!mRestartingServices.contains(r)) {
11250 mRestartingServices.add(r);
11251 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011252
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011253 r.cancelNotification();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011254
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011255 mHandler.removeCallbacks(r.restarter);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011256 mHandler.postAtTime(r.restarter, r.nextRestartTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011257 r.nextRestartTime = SystemClock.uptimeMillis() + r.restartDelay;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011258 Slog.w(TAG, "Scheduling restart of crashed service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011259 + r.shortName + " in " + r.restartDelay + "ms");
Doug Zongker2bec3d42009-12-04 12:52:44 -080011260 EventLog.writeEvent(EventLogTags.AM_SCHEDULE_SERVICE_RESTART,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011261 r.shortName, r.restartDelay);
11262
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011263 return canceled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011264 }
11265
11266 final void performServiceRestartLocked(ServiceRecord r) {
11267 if (!mRestartingServices.contains(r)) {
11268 return;
11269 }
11270 bringUpServiceLocked(r, r.intent.getIntent().getFlags(), true);
11271 }
11272
11273 private final boolean unscheduleServiceRestartLocked(ServiceRecord r) {
11274 if (r.restartDelay == 0) {
11275 return false;
11276 }
11277 r.resetRestartCounter();
11278 mRestartingServices.remove(r);
11279 mHandler.removeCallbacks(r.restarter);
11280 return true;
11281 }
11282
11283 private final boolean bringUpServiceLocked(ServiceRecord r,
11284 int intentFlags, boolean whileRestarting) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011285 //Slog.i(TAG, "Bring up service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011286 //r.dump(" ");
11287
Dianne Hackborn36124872009-10-08 16:22:03 -070011288 if (r.app != null && r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011289 sendServiceArgsLocked(r, false);
11290 return true;
11291 }
11292
11293 if (!whileRestarting && r.restartDelay > 0) {
11294 // If waiting for a restart, then do nothing.
11295 return true;
11296 }
11297
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011298 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing up " + r + " " + r.intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011299
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011300 // We are now bringing the service up, so no longer in the
11301 // restarting state.
11302 mRestartingServices.remove(r);
11303
Dianne Hackborne7f97212011-02-24 14:40:20 -080011304 // Service is now being launched, its package can't be stopped.
11305 try {
11306 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -070011307 r.packageName, false, r.userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -080011308 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080011309 } catch (IllegalArgumentException e) {
11310 Slog.w(TAG, "Failed trying to unstop package "
11311 + r.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080011312 }
11313
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011314 final boolean isolated = (r.serviceInfo.flags&ServiceInfo.FLAG_ISOLATED_PROCESS) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011315 final String appName = r.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011316 ProcessRecord app;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011317
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011318 if (!isolated) {
11319 app = getProcessRecordLocked(appName, r.appInfo.uid);
11320 if (DEBUG_MU)
11321 Slog.v(TAG_MU, "bringUpServiceLocked: appInfo.uid=" + r.appInfo.uid + " app=" + app);
11322 if (app != null && app.thread != null) {
11323 try {
11324 app.addPackage(r.appInfo.packageName);
11325 realStartServiceLocked(r, app);
11326 return true;
11327 } catch (RemoteException e) {
11328 Slog.w(TAG, "Exception when starting service " + r.shortName, e);
11329 }
11330
11331 // If a dead object exception was thrown -- fall through to
11332 // restart the application.
11333 }
11334 } else {
11335 // If this service runs in an isolated process, then each time
11336 // we call startProcessLocked() we will get a new isolated
11337 // process, starting another process if we are currently waiting
11338 // for a previous process to come up. To deal with this, we store
11339 // in the service any current isolated process it is running in or
11340 // waiting to have come up.
11341 app = r.isolatedProc;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011342 }
11343
Dianne Hackborn36124872009-10-08 16:22:03 -070011344 // Not running -- get it started, and enqueue this service record
11345 // to be executed when the app comes up.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011346 if (app == null) {
11347 if ((app=startProcessLocked(appName, r.appInfo, true, intentFlags,
11348 "service", r.name, false, isolated)) == null) {
11349 Slog.w(TAG, "Unable to launch app "
11350 + r.appInfo.packageName + "/"
11351 + r.appInfo.uid + " for service "
11352 + r.intent.getIntent() + ": process is bad");
11353 bringDownServiceLocked(r, true);
11354 return false;
11355 }
11356 if (isolated) {
11357 r.isolatedProc = app;
11358 }
Dianne Hackborn36124872009-10-08 16:22:03 -070011359 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011360
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011361 if (!mPendingServices.contains(r)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011362 mPendingServices.add(r);
11363 }
Dianne Hackborn36124872009-10-08 16:22:03 -070011364
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011365 return true;
11366 }
11367
11368 private final void bringDownServiceLocked(ServiceRecord r, boolean force) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011369 //Slog.i(TAG, "Bring down service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011370 //r.dump(" ");
11371
11372 // Does it still need to run?
11373 if (!force && r.startRequested) {
11374 return;
11375 }
11376 if (r.connections.size() > 0) {
11377 if (!force) {
11378 // XXX should probably keep a count of the number of auto-create
11379 // connections directly in the service.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011380 Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011381 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011382 ArrayList<ConnectionRecord> cr = it.next();
11383 for (int i=0; i<cr.size(); i++) {
11384 if ((cr.get(i).flags&Context.BIND_AUTO_CREATE) != 0) {
11385 return;
11386 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011387 }
11388 }
11389 }
11390
11391 // Report to all of the connections that the service is no longer
11392 // available.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011393 Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011394 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011395 ArrayList<ConnectionRecord> c = it.next();
11396 for (int i=0; i<c.size(); i++) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011397 ConnectionRecord cr = c.get(i);
11398 // There is still a connection to the service that is
11399 // being brought down. Mark it as dead.
11400 cr.serviceDead = true;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011401 try {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011402 cr.conn.connected(r.name, null);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011403 } catch (Exception e) {
11404 Slog.w(TAG, "Failure disconnecting service " + r.name +
11405 " to connection " + c.get(i).conn.asBinder() +
11406 " (in " + c.get(i).binding.client.processName + ")", e);
11407 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011408 }
11409 }
11410 }
11411
11412 // Tell the service that it has been unbound.
11413 if (r.bindings.size() > 0 && r.app != null && r.app.thread != null) {
11414 Iterator<IntentBindRecord> it = r.bindings.values().iterator();
11415 while (it.hasNext()) {
11416 IntentBindRecord ibr = it.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -080011417 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down binding " + ibr
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011418 + ": hasBound=" + ibr.hasBound);
11419 if (r.app != null && r.app.thread != null && ibr.hasBound) {
11420 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011421 bumpServiceExecutingLocked(r, "bring down unbind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011422 updateOomAdjLocked(r.app);
11423 ibr.hasBound = false;
11424 r.app.thread.scheduleUnbindService(r,
11425 ibr.intent.getIntent());
11426 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011427 Slog.w(TAG, "Exception when unbinding service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011428 + r.shortName, e);
11429 serviceDoneExecutingLocked(r, true);
11430 }
11431 }
11432 }
11433 }
11434
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011435 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down " + r + " " + r.intent);
Doug Zongker2bec3d42009-12-04 12:52:44 -080011436 EventLog.writeEvent(EventLogTags.AM_DESTROY_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011437 System.identityHashCode(r), r.shortName,
11438 (r.app != null) ? r.app.pid : -1);
11439
Amith Yamasani742a6712011-05-04 14:49:28 -070011440 mServiceMap.removeServiceByName(r.name, r.userId);
11441 mServiceMap.removeServiceByIntent(r.intent, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011442 r.totalRestartCount = 0;
11443 unscheduleServiceRestartLocked(r);
11444
11445 // Also make sure it is not on the pending list.
11446 int N = mPendingServices.size();
11447 for (int i=0; i<N; i++) {
11448 if (mPendingServices.get(i) == r) {
11449 mPendingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011450 if (DEBUG_SERVICE) Slog.v(TAG, "Removed pending: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011451 i--;
11452 N--;
11453 }
11454 }
11455
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011456 r.cancelNotification();
11457 r.isForeground = false;
11458 r.foregroundId = 0;
11459 r.foregroundNoti = null;
11460
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011461 // Clear start entries.
Dianne Hackborn39792d22010-08-19 18:01:52 -070011462 r.clearDeliveredStartsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011463 r.pendingStarts.clear();
11464
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011465 if (r.app != null) {
11466 synchronized (r.stats.getBatteryStats()) {
11467 r.stats.stopLaunchedLocked();
11468 }
11469 r.app.services.remove(r);
11470 if (r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011471 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011472 bumpServiceExecutingLocked(r, "stop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011473 mStoppingServices.add(r);
11474 updateOomAdjLocked(r.app);
11475 r.app.thread.scheduleStopService(r);
11476 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011477 Slog.w(TAG, "Exception when stopping service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011478 + r.shortName, e);
11479 serviceDoneExecutingLocked(r, true);
11480 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011481 updateServiceForegroundLocked(r.app, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011482 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011483 if (DEBUG_SERVICE) Slog.v(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011484 TAG, "Removed service that has no process: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011485 }
11486 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011487 if (DEBUG_SERVICE) Slog.v(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011488 TAG, "Removed service that is not running: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011489 }
Vairavan Srinivasana207ce22010-12-23 13:51:48 -080011490
11491 if (r.bindings.size() > 0) {
11492 r.bindings.clear();
11493 }
11494
11495 if (r.restarter instanceof ServiceRestarter) {
11496 ((ServiceRestarter)r.restarter).setService(null);
11497 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011498 }
11499
11500 ComponentName startServiceLocked(IApplicationThread caller,
11501 Intent service, String resolvedType,
11502 int callingPid, int callingUid) {
11503 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011504 if (DEBUG_SERVICE) Slog.v(TAG, "startService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011505 + " type=" + resolvedType + " args=" + service.getExtras());
11506
11507 if (caller != null) {
11508 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11509 if (callerApp == null) {
11510 throw new SecurityException(
11511 "Unable to find app for caller " + caller
11512 + " (pid=" + Binder.getCallingPid()
11513 + ") when starting service " + service);
11514 }
11515 }
11516
11517 ServiceLookupResult res =
11518 retrieveServiceLocked(service, resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011519 callingPid, callingUid, UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011520 if (res == null) {
11521 return null;
11522 }
11523 if (res.record == null) {
11524 return new ComponentName("!", res.permission != null
11525 ? res.permission : "private to package");
11526 }
11527 ServiceRecord r = res.record;
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011528 NeededUriGrants neededGrants = checkGrantUriPermissionFromIntentLocked(
11529 callingUid, r.packageName, service, service.getFlags(), null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011530 if (unscheduleServiceRestartLocked(r)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011531 if (DEBUG_SERVICE) Slog.v(TAG, "START SERVICE WHILE RESTART PENDING: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011532 }
11533 r.startRequested = true;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011534 r.callStart = false;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011535 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011536 service, neededGrants));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011537 r.lastActivity = SystemClock.uptimeMillis();
11538 synchronized (r.stats.getBatteryStats()) {
11539 r.stats.startRunningLocked();
11540 }
11541 if (!bringUpServiceLocked(r, service.getFlags(), false)) {
11542 return new ComponentName("!", "Service process is bad");
11543 }
11544 return r.name;
11545 }
11546 }
11547
11548 public ComponentName startService(IApplicationThread caller, Intent service,
11549 String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011550 enforceNotIsolatedCaller("startService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011551 // Refuse possible leaked file descriptors
11552 if (service != null && service.hasFileDescriptors() == true) {
11553 throw new IllegalArgumentException("File descriptors passed in Intent");
11554 }
11555
Amith Yamasani742a6712011-05-04 14:49:28 -070011556 if (DEBUG_SERVICE)
11557 Slog.v(TAG, "startService: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011558 synchronized(this) {
11559 final int callingPid = Binder.getCallingPid();
11560 final int callingUid = Binder.getCallingUid();
11561 final long origId = Binder.clearCallingIdentity();
11562 ComponentName res = startServiceLocked(caller, service,
11563 resolvedType, callingPid, callingUid);
11564 Binder.restoreCallingIdentity(origId);
11565 return res;
11566 }
11567 }
11568
11569 ComponentName startServiceInPackage(int uid,
11570 Intent service, String resolvedType) {
11571 synchronized(this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070011572 if (DEBUG_SERVICE)
11573 Slog.v(TAG, "startServiceInPackage: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011574 final long origId = Binder.clearCallingIdentity();
11575 ComponentName res = startServiceLocked(null, service,
11576 resolvedType, -1, uid);
11577 Binder.restoreCallingIdentity(origId);
11578 return res;
11579 }
11580 }
11581
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011582 private void stopServiceLocked(ServiceRecord service) {
11583 synchronized (service.stats.getBatteryStats()) {
11584 service.stats.stopRunningLocked();
11585 }
11586 service.startRequested = false;
11587 service.callStart = false;
11588 bringDownServiceLocked(service, false);
11589 }
11590
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011591 public int stopService(IApplicationThread caller, Intent service,
11592 String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011593 enforceNotIsolatedCaller("stopService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011594 // Refuse possible leaked file descriptors
11595 if (service != null && service.hasFileDescriptors() == true) {
11596 throw new IllegalArgumentException("File descriptors passed in Intent");
11597 }
11598
11599 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011600 if (DEBUG_SERVICE) Slog.v(TAG, "stopService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011601 + " type=" + resolvedType);
11602
11603 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11604 if (caller != null && callerApp == null) {
11605 throw new SecurityException(
11606 "Unable to find app for caller " + caller
11607 + " (pid=" + Binder.getCallingPid()
11608 + ") when stopping service " + service);
11609 }
11610
11611 // If this service is active, make sure it is stopped.
Amith Yamasani483f3b02012-03-13 16:08:00 -070011612 ServiceLookupResult r = findServiceLocked(service, resolvedType,
11613 callerApp == null ? UserId.getCallingUserId() : callerApp.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011614 if (r != null) {
11615 if (r.record != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011616 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011617 try {
11618 stopServiceLocked(r.record);
11619 } finally {
11620 Binder.restoreCallingIdentity(origId);
11621 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011622 return 1;
11623 }
11624 return -1;
11625 }
11626 }
11627
11628 return 0;
11629 }
11630
11631 public IBinder peekService(Intent service, String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011632 enforceNotIsolatedCaller("peekService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011633 // Refuse possible leaked file descriptors
11634 if (service != null && service.hasFileDescriptors() == true) {
11635 throw new IllegalArgumentException("File descriptors passed in Intent");
11636 }
11637
11638 IBinder ret = null;
11639
11640 synchronized(this) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070011641 ServiceLookupResult r = findServiceLocked(service, resolvedType,
11642 UserId.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011643
11644 if (r != null) {
11645 // r.record is null if findServiceLocked() failed the caller permission check
11646 if (r.record == null) {
11647 throw new SecurityException(
11648 "Permission Denial: Accessing service " + r.record.name
11649 + " from pid=" + Binder.getCallingPid()
11650 + ", uid=" + Binder.getCallingUid()
11651 + " requires " + r.permission);
11652 }
11653 IntentBindRecord ib = r.record.bindings.get(r.record.intent);
11654 if (ib != null) {
11655 ret = ib.binder;
11656 }
11657 }
11658 }
11659
11660 return ret;
11661 }
11662
11663 public boolean stopServiceToken(ComponentName className, IBinder token,
11664 int startId) {
11665 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011666 if (DEBUG_SERVICE) Slog.v(TAG, "stopServiceToken: " + className
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011667 + " " + token + " startId=" + startId);
11668 ServiceRecord r = findServiceLocked(className, token);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011669 if (r != null) {
11670 if (startId >= 0) {
11671 // Asked to only stop if done with all work. Note that
11672 // to avoid leaks, we will take this as dropping all
11673 // start items up to and including this one.
11674 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
11675 if (si != null) {
11676 while (r.deliveredStarts.size() > 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -070011677 ServiceRecord.StartItem cur = r.deliveredStarts.remove(0);
11678 cur.removeUriPermissionsLocked();
11679 if (cur == si) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011680 break;
11681 }
11682 }
11683 }
11684
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011685 if (r.getLastStartId() != startId) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011686 return false;
11687 }
11688
11689 if (r.deliveredStarts.size() > 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011690 Slog.w(TAG, "stopServiceToken startId " + startId
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011691 + " is last, but have " + r.deliveredStarts.size()
11692 + " remaining args");
11693 }
11694 }
11695
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011696 synchronized (r.stats.getBatteryStats()) {
11697 r.stats.stopRunningLocked();
11698 r.startRequested = false;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011699 r.callStart = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011700 }
11701 final long origId = Binder.clearCallingIdentity();
11702 bringDownServiceLocked(r, false);
11703 Binder.restoreCallingIdentity(origId);
11704 return true;
11705 }
11706 }
11707 return false;
11708 }
11709
11710 public void setServiceForeground(ComponentName className, IBinder token,
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011711 int id, Notification notification, boolean removeNotification) {
11712 final long origId = Binder.clearCallingIdentity();
11713 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011714 synchronized(this) {
11715 ServiceRecord r = findServiceLocked(className, token);
11716 if (r != null) {
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011717 if (id != 0) {
11718 if (notification == null) {
11719 throw new IllegalArgumentException("null notification");
11720 }
11721 if (r.foregroundId != id) {
11722 r.cancelNotification();
11723 r.foregroundId = id;
11724 }
11725 notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
11726 r.foregroundNoti = notification;
11727 r.isForeground = true;
11728 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011729 if (r.app != null) {
11730 updateServiceForegroundLocked(r.app, true);
11731 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011732 } else {
11733 if (r.isForeground) {
11734 r.isForeground = false;
11735 if (r.app != null) {
Dianne Hackborn8633e682010-04-22 16:03:41 -070011736 updateLruProcessLocked(r.app, false, true);
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011737 updateServiceForegroundLocked(r.app, true);
11738 }
11739 }
11740 if (removeNotification) {
11741 r.cancelNotification();
11742 r.foregroundId = 0;
11743 r.foregroundNoti = null;
11744 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011745 }
11746 }
11747 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011748 } finally {
11749 Binder.restoreCallingIdentity(origId);
11750 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011751 }
11752
11753 public void updateServiceForegroundLocked(ProcessRecord proc, boolean oomAdj) {
11754 boolean anyForeground = false;
Dianne Hackborn860755f2010-06-03 18:47:52 -070011755 for (ServiceRecord sr : proc.services) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011756 if (sr.isForeground) {
11757 anyForeground = true;
11758 break;
11759 }
11760 }
11761 if (anyForeground != proc.foregroundServices) {
11762 proc.foregroundServices = anyForeground;
11763 if (oomAdj) {
11764 updateOomAdjLocked();
11765 }
11766 }
11767 }
Amith Yamasania4a54e22012-04-16 15:44:19 -070011768
11769 boolean isSingleton(String componentProcessName, ApplicationInfo aInfo) {
11770 boolean result = false;
11771 if (UserId.getAppId(aInfo.uid) >= Process.FIRST_APPLICATION_UID) {
11772 result = false;
11773 } else if (componentProcessName == aInfo.packageName) {
11774 result = (aInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0;
11775 } else if ("system".equals(componentProcessName)) {
11776 result = true;
11777 }
11778 if (DEBUG_MU) {
11779 Slog.v(TAG, "isSingleton(" + componentProcessName + ", " + aInfo + ") = " + result);
11780 }
11781 return result;
11782 }
11783
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011784 public int bindService(IApplicationThread caller, IBinder token,
11785 Intent service, String resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011786 IServiceConnection connection, int flags, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011787 enforceNotIsolatedCaller("bindService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011788 // Refuse possible leaked file descriptors
11789 if (service != null && service.hasFileDescriptors() == true) {
11790 throw new IllegalArgumentException("File descriptors passed in Intent");
11791 }
11792
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011793 checkValidCaller(Binder.getCallingUid(), userId);
11794
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011795 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011796 if (DEBUG_SERVICE) Slog.v(TAG, "bindService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011797 + " type=" + resolvedType + " conn=" + connection.asBinder()
11798 + " flags=0x" + Integer.toHexString(flags));
Amith Yamasani742a6712011-05-04 14:49:28 -070011799 if (DEBUG_MU)
11800 Slog.i(TAG_MU, "bindService uid=" + Binder.getCallingUid() + " origUid="
11801 + Binder.getOrigCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011802 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11803 if (callerApp == null) {
11804 throw new SecurityException(
11805 "Unable to find app for caller " + caller
11806 + " (pid=" + Binder.getCallingPid()
11807 + ") when binding service " + service);
11808 }
11809
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011810 ActivityRecord activity = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011811 if (token != null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070011812 activity = mMainStack.isInStackLocked(token);
11813 if (activity == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011814 Slog.w(TAG, "Binding with unknown activity: " + token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011815 return 0;
11816 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011817 }
11818
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011819 int clientLabel = 0;
11820 PendingIntent clientIntent = null;
11821
11822 if (callerApp.info.uid == Process.SYSTEM_UID) {
11823 // Hacky kind of thing -- allow system stuff to tell us
11824 // what they are, so we can report this elsewhere for
11825 // others to know why certain services are running.
11826 try {
11827 clientIntent = (PendingIntent)service.getParcelableExtra(
11828 Intent.EXTRA_CLIENT_INTENT);
11829 } catch (RuntimeException e) {
11830 }
11831 if (clientIntent != null) {
11832 clientLabel = service.getIntExtra(Intent.EXTRA_CLIENT_LABEL, 0);
11833 if (clientLabel != 0) {
11834 // There are no useful extras in the intent, trash them.
11835 // System code calling with this stuff just needs to know
11836 // this will happen.
11837 service = service.cloneFilter();
11838 }
11839 }
11840 }
11841
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011842 ServiceLookupResult res =
11843 retrieveServiceLocked(service, resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011844 Binder.getCallingPid(), Binder.getCallingUid(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011845 if (res == null) {
11846 return 0;
11847 }
11848 if (res.record == null) {
11849 return -1;
11850 }
Amith Yamasania4a54e22012-04-16 15:44:19 -070011851 if (isSingleton(res.record.processName, res.record.appInfo)) {
11852 userId = 0;
11853 res = retrieveServiceLocked(service, resolvedType, Binder.getCallingPid(),
11854 Binder.getCallingUid(), 0);
11855 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011856 ServiceRecord s = res.record;
11857
11858 final long origId = Binder.clearCallingIdentity();
11859
11860 if (unscheduleServiceRestartLocked(s)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011861 if (DEBUG_SERVICE) Slog.v(TAG, "BIND SERVICE WHILE RESTART PENDING: "
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011862 + s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011863 }
11864
11865 AppBindRecord b = s.retrieveAppBindingLocked(service, callerApp);
11866 ConnectionRecord c = new ConnectionRecord(b, activity,
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011867 connection, flags, clientLabel, clientIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011868
11869 IBinder binder = connection.asBinder();
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011870 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
11871 if (clist == null) {
11872 clist = new ArrayList<ConnectionRecord>();
11873 s.connections.put(binder, clist);
11874 }
11875 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011876 b.connections.add(c);
11877 if (activity != null) {
11878 if (activity.connections == null) {
11879 activity.connections = new HashSet<ConnectionRecord>();
11880 }
11881 activity.connections.add(c);
11882 }
11883 b.client.connections.add(c);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070011884 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
11885 b.client.hasAboveClient = true;
11886 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011887 clist = mServiceConnections.get(binder);
11888 if (clist == null) {
11889 clist = new ArrayList<ConnectionRecord>();
11890 mServiceConnections.put(binder, clist);
11891 }
11892 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011893
11894 if ((flags&Context.BIND_AUTO_CREATE) != 0) {
11895 s.lastActivity = SystemClock.uptimeMillis();
11896 if (!bringUpServiceLocked(s, service.getFlags(), false)) {
11897 return 0;
11898 }
11899 }
11900
11901 if (s.app != null) {
11902 // This could have made the service more important.
11903 updateOomAdjLocked(s.app);
11904 }
11905
Joe Onorato8a9b2202010-02-26 18:56:32 -080011906 if (DEBUG_SERVICE) Slog.v(TAG, "Bind " + s + " with " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011907 + ": received=" + b.intent.received
11908 + " apps=" + b.intent.apps.size()
11909 + " doRebind=" + b.intent.doRebind);
11910
11911 if (s.app != null && b.intent.received) {
11912 // Service is already running, so we can immediately
11913 // publish the connection.
11914 try {
11915 c.conn.connected(s.name, b.intent.binder);
11916 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011917 Slog.w(TAG, "Failure sending service " + s.shortName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011918 + " to connection " + c.conn.asBinder()
11919 + " (in " + c.binding.client.processName + ")", e);
11920 }
11921
11922 // If this is the first app connected back to this binding,
11923 // and the service had previously asked to be told when
11924 // rebound, then do so.
11925 if (b.intent.apps.size() == 1 && b.intent.doRebind) {
11926 requestServiceBindingLocked(s, b.intent, true);
11927 }
11928 } else if (!b.intent.requested) {
11929 requestServiceBindingLocked(s, b.intent, false);
11930 }
11931
11932 Binder.restoreCallingIdentity(origId);
11933 }
11934
11935 return 1;
11936 }
11937
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070011938 void removeConnectionLocked(
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011939 ConnectionRecord c, ProcessRecord skipApp, ActivityRecord skipAct) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011940 IBinder binder = c.conn.asBinder();
11941 AppBindRecord b = c.binding;
11942 ServiceRecord s = b.service;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011943 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
11944 if (clist != null) {
11945 clist.remove(c);
11946 if (clist.size() == 0) {
11947 s.connections.remove(binder);
11948 }
11949 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011950 b.connections.remove(c);
11951 if (c.activity != null && c.activity != skipAct) {
11952 if (c.activity.connections != null) {
11953 c.activity.connections.remove(c);
11954 }
11955 }
11956 if (b.client != skipApp) {
11957 b.client.connections.remove(c);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070011958 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
11959 b.client.updateHasAboveClientLocked();
11960 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011961 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011962 clist = mServiceConnections.get(binder);
11963 if (clist != null) {
11964 clist.remove(c);
11965 if (clist.size() == 0) {
11966 mServiceConnections.remove(binder);
11967 }
11968 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011969
11970 if (b.connections.size() == 0) {
11971 b.intent.apps.remove(b.client);
11972 }
11973
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011974 if (!c.serviceDead) {
11975 if (DEBUG_SERVICE) Slog.v(TAG, "Disconnecting binding " + b.intent
11976 + ": shouldUnbind=" + b.intent.hasBound);
11977 if (s.app != null && s.app.thread != null && b.intent.apps.size() == 0
11978 && b.intent.hasBound) {
11979 try {
11980 bumpServiceExecutingLocked(s, "unbind");
11981 updateOomAdjLocked(s.app);
11982 b.intent.hasBound = false;
11983 // Assume the client doesn't want to know about a rebind;
11984 // we will deal with that later if it asks for one.
11985 b.intent.doRebind = false;
11986 s.app.thread.scheduleUnbindService(s, b.intent.intent.getIntent());
11987 } catch (Exception e) {
11988 Slog.w(TAG, "Exception when unbinding service " + s.shortName, e);
11989 serviceDoneExecutingLocked(s, true);
11990 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011991 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011992
11993 if ((c.flags&Context.BIND_AUTO_CREATE) != 0) {
11994 bringDownServiceLocked(s, false);
11995 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011996 }
11997 }
11998
11999 public boolean unbindService(IServiceConnection connection) {
12000 synchronized (this) {
12001 IBinder binder = connection.asBinder();
Joe Onorato8a9b2202010-02-26 18:56:32 -080012002 if (DEBUG_SERVICE) Slog.v(TAG, "unbindService: conn=" + binder);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012003 ArrayList<ConnectionRecord> clist = mServiceConnections.get(binder);
12004 if (clist == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012005 Slog.w(TAG, "Unbind failed: could not find connection for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012006 + connection.asBinder());
12007 return false;
12008 }
12009
12010 final long origId = Binder.clearCallingIdentity();
12011
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012012 while (clist.size() > 0) {
12013 ConnectionRecord r = clist.get(0);
12014 removeConnectionLocked(r, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012015
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012016 if (r.binding.service.app != null) {
12017 // This could have made the service less important.
12018 updateOomAdjLocked(r.binding.service.app);
12019 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012020 }
12021
12022 Binder.restoreCallingIdentity(origId);
12023 }
12024
12025 return true;
12026 }
12027
12028 public void publishService(IBinder token, Intent intent, IBinder service) {
12029 // Refuse possible leaked file descriptors
12030 if (intent != null && intent.hasFileDescriptors() == true) {
12031 throw new IllegalArgumentException("File descriptors passed in Intent");
12032 }
12033
12034 synchronized(this) {
12035 if (!(token instanceof ServiceRecord)) {
12036 throw new IllegalArgumentException("Invalid service token");
12037 }
12038 ServiceRecord r = (ServiceRecord)token;
12039
12040 final long origId = Binder.clearCallingIdentity();
12041
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012042 if (DEBUG_SERVICE) Slog.v(TAG, "PUBLISHING " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012043 + " " + intent + ": " + service);
12044 if (r != null) {
12045 Intent.FilterComparison filter
12046 = new Intent.FilterComparison(intent);
12047 IntentBindRecord b = r.bindings.get(filter);
12048 if (b != null && !b.received) {
12049 b.binder = service;
12050 b.requested = true;
12051 b.received = true;
12052 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012053 Iterator<ArrayList<ConnectionRecord>> it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012054 = r.connections.values().iterator();
12055 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012056 ArrayList<ConnectionRecord> clist = it.next();
12057 for (int i=0; i<clist.size(); i++) {
12058 ConnectionRecord c = clist.get(i);
12059 if (!filter.equals(c.binding.intent.intent)) {
12060 if (DEBUG_SERVICE) Slog.v(
12061 TAG, "Not publishing to: " + c);
12062 if (DEBUG_SERVICE) Slog.v(
12063 TAG, "Bound intent: " + c.binding.intent.intent);
12064 if (DEBUG_SERVICE) Slog.v(
12065 TAG, "Published intent: " + intent);
12066 continue;
12067 }
12068 if (DEBUG_SERVICE) Slog.v(TAG, "Publishing to: " + c);
12069 try {
12070 c.conn.connected(r.name, service);
12071 } catch (Exception e) {
12072 Slog.w(TAG, "Failure sending service " + r.name +
12073 " to connection " + c.conn.asBinder() +
12074 " (in " + c.binding.client.processName + ")", e);
12075 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012076 }
12077 }
12078 }
12079 }
12080
12081 serviceDoneExecutingLocked(r, mStoppingServices.contains(r));
12082
12083 Binder.restoreCallingIdentity(origId);
12084 }
12085 }
12086 }
12087
12088 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
12089 // Refuse possible leaked file descriptors
12090 if (intent != null && intent.hasFileDescriptors() == true) {
12091 throw new IllegalArgumentException("File descriptors passed in Intent");
12092 }
12093
12094 synchronized(this) {
12095 if (!(token instanceof ServiceRecord)) {
12096 throw new IllegalArgumentException("Invalid service token");
12097 }
12098 ServiceRecord r = (ServiceRecord)token;
12099
12100 final long origId = Binder.clearCallingIdentity();
12101
12102 if (r != null) {
12103 Intent.FilterComparison filter
12104 = new Intent.FilterComparison(intent);
12105 IntentBindRecord b = r.bindings.get(filter);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012106 if (DEBUG_SERVICE) Slog.v(TAG, "unbindFinished in " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012107 + " at " + b + ": apps="
12108 + (b != null ? b.apps.size() : 0));
Per Edelberg78f9fff2010-08-30 20:01:35 +020012109
12110 boolean inStopping = mStoppingServices.contains(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012111 if (b != null) {
Per Edelberg78f9fff2010-08-30 20:01:35 +020012112 if (b.apps.size() > 0 && !inStopping) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012113 // Applications have already bound since the last
12114 // unbind, so just rebind right here.
12115 requestServiceBindingLocked(r, b, true);
12116 } else {
12117 // Note to tell the service the next time there is
12118 // a new client.
12119 b.doRebind = true;
12120 }
12121 }
12122
Per Edelberg78f9fff2010-08-30 20:01:35 +020012123 serviceDoneExecutingLocked(r, inStopping);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012124
12125 Binder.restoreCallingIdentity(origId);
12126 }
12127 }
12128 }
12129
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012130 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012131 synchronized(this) {
12132 if (!(token instanceof ServiceRecord)) {
12133 throw new IllegalArgumentException("Invalid service token");
12134 }
12135 ServiceRecord r = (ServiceRecord)token;
12136 boolean inStopping = mStoppingServices.contains(token);
12137 if (r != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012138 if (r != token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012139 Slog.w(TAG, "Done executing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012140 + " with incorrect token: given " + token
12141 + ", expected " + r);
12142 return;
12143 }
12144
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012145 if (type == 1) {
12146 // This is a call from a service start... take care of
12147 // book-keeping.
12148 r.callStart = true;
12149 switch (res) {
12150 case Service.START_STICKY_COMPATIBILITY:
12151 case Service.START_STICKY: {
12152 // We are done with the associated start arguments.
12153 r.findDeliveredStart(startId, true);
12154 // Don't stop if killed.
12155 r.stopIfKilled = false;
12156 break;
12157 }
12158 case Service.START_NOT_STICKY: {
12159 // We are done with the associated start arguments.
12160 r.findDeliveredStart(startId, true);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070012161 if (r.getLastStartId() == startId) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012162 // There is no more work, and this service
12163 // doesn't want to hang around if killed.
12164 r.stopIfKilled = true;
12165 }
12166 break;
12167 }
12168 case Service.START_REDELIVER_INTENT: {
12169 // We'll keep this item until they explicitly
12170 // call stop for it, but keep track of the fact
12171 // that it was delivered.
12172 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
12173 if (si != null) {
12174 si.deliveryCount = 0;
12175 si.doneExecutingCount++;
12176 // Don't stop if killed.
12177 r.stopIfKilled = true;
12178 }
12179 break;
12180 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070012181 case Service.START_TASK_REMOVED_COMPLETE: {
12182 // Special processing for onTaskRemoved(). Don't
12183 // impact normal onStartCommand() processing.
12184 r.findDeliveredStart(startId, true);
12185 break;
12186 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012187 default:
12188 throw new IllegalArgumentException(
12189 "Unknown service start result: " + res);
12190 }
12191 if (res == Service.START_STICKY_COMPATIBILITY) {
12192 r.callStart = false;
12193 }
12194 }
Amith Yamasani742a6712011-05-04 14:49:28 -070012195 if (DEBUG_MU)
12196 Slog.v(TAG_MU, "before serviceDontExecutingLocked, uid="
12197 + Binder.getOrigCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012198 final long origId = Binder.clearCallingIdentity();
12199 serviceDoneExecutingLocked(r, inStopping);
12200 Binder.restoreCallingIdentity(origId);
12201 } else {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012202 Slog.w(TAG, "Done executing unknown service from pid "
12203 + Binder.getCallingPid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012204 }
12205 }
12206 }
12207
12208 public void serviceDoneExecutingLocked(ServiceRecord r, boolean inStopping) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012209 if (DEBUG_SERVICE) Slog.v(TAG, "<<< DONE EXECUTING " + r
12210 + ": nesting=" + r.executeNesting
12211 + ", inStopping=" + inStopping + ", app=" + r.app);
Dianne Hackborn287952c2010-09-22 22:34:31 -070012212 else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG, "<<< DONE EXECUTING " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012213 r.executeNesting--;
12214 if (r.executeNesting <= 0 && r.app != null) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012215 if (DEBUG_SERVICE) Slog.v(TAG,
12216 "Nesting at 0 of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012217 r.app.executingServices.remove(r);
12218 if (r.app.executingServices.size() == 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012219 if (DEBUG_SERVICE || DEBUG_SERVICE_EXECUTING) Slog.v(TAG,
12220 "No more executingServices of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012221 mHandler.removeMessages(SERVICE_TIMEOUT_MSG, r.app);
12222 }
12223 if (inStopping) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012224 if (DEBUG_SERVICE) Slog.v(TAG,
12225 "doneExecuting remove stopping " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012226 mStoppingServices.remove(r);
Mattias Petersson3996b412010-10-27 09:32:51 +020012227 r.bindings.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012228 }
12229 updateOomAdjLocked(r.app);
12230 }
12231 }
12232
12233 void serviceTimeout(ProcessRecord proc) {
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012234 String anrMessage = null;
12235
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012236 synchronized(this) {
12237 if (proc.executingServices.size() == 0 || proc.thread == null) {
12238 return;
12239 }
12240 long maxTime = SystemClock.uptimeMillis() - SERVICE_TIMEOUT;
12241 Iterator<ServiceRecord> it = proc.executingServices.iterator();
12242 ServiceRecord timeout = null;
12243 long nextTime = 0;
12244 while (it.hasNext()) {
12245 ServiceRecord sr = it.next();
12246 if (sr.executingStart < maxTime) {
12247 timeout = sr;
12248 break;
12249 }
12250 if (sr.executingStart > nextTime) {
12251 nextTime = sr.executingStart;
12252 }
12253 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012254 if (timeout != null && mLruProcesses.contains(proc)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012255 Slog.w(TAG, "Timeout executing service: " + timeout);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012256 anrMessage = "Executing service " + timeout.shortName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012257 } else {
12258 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
12259 msg.obj = proc;
12260 mHandler.sendMessageAtTime(msg, nextTime+SERVICE_TIMEOUT);
12261 }
12262 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012263
12264 if (anrMessage != null) {
12265 appNotResponding(proc, null, null, anrMessage);
12266 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012267 }
12268
12269 // =========================================================
Christopher Tate181fafa2009-05-14 11:12:14 -070012270 // BACKUP AND RESTORE
12271 // =========================================================
12272
12273 // Cause the target app to be launched if necessary and its backup agent
12274 // instantiated. The backup agent will invoke backupAgentCreated() on the
12275 // activity manager to announce its creation.
12276 public boolean bindBackupAgent(ApplicationInfo app, int backupMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012277 if (DEBUG_BACKUP) Slog.v(TAG, "startBackupAgent: app=" + app + " mode=" + backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070012278 enforceCallingPermission("android.permission.BACKUP", "startBackupAgent");
12279
12280 synchronized(this) {
12281 // !!! TODO: currently no check here that we're already bound
12282 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
12283 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
12284 synchronized (stats) {
12285 ss = stats.getServiceStatsLocked(app.uid, app.packageName, app.name);
12286 }
12287
Dianne Hackborne7f97212011-02-24 14:40:20 -080012288 // Backup agent is now in use, its package can't be stopped.
12289 try {
12290 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -070012291 app.packageName, false, UserId.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -080012292 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080012293 } catch (IllegalArgumentException e) {
12294 Slog.w(TAG, "Failed trying to unstop package "
12295 + app.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080012296 }
12297
Christopher Tate181fafa2009-05-14 11:12:14 -070012298 BackupRecord r = new BackupRecord(ss, app, backupMode);
Christopher Tate4a627c72011-04-01 14:43:32 -070012299 ComponentName hostingName = (backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL)
12300 ? new ComponentName(app.packageName, app.backupAgentName)
12301 : new ComponentName("android", "FullBackupAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -070012302 // startProcessLocked() returns existing proc's record if it's already running
12303 ProcessRecord proc = startProcessLocked(app.processName, app,
Dianne Hackborna0c283e2012-02-09 10:47:01 -080012304 false, 0, "backup", hostingName, false, false);
Christopher Tate181fafa2009-05-14 11:12:14 -070012305 if (proc == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012306 Slog.e(TAG, "Unable to start backup agent process " + r);
Christopher Tate181fafa2009-05-14 11:12:14 -070012307 return false;
12308 }
12309
12310 r.app = proc;
12311 mBackupTarget = r;
12312 mBackupAppName = app.packageName;
12313
Christopher Tate6fa95972009-06-05 18:43:55 -070012314 // Try not to kill the process during backup
12315 updateOomAdjLocked(proc);
12316
Christopher Tate181fafa2009-05-14 11:12:14 -070012317 // If the process is already attached, schedule the creation of the backup agent now.
12318 // If it is not yet live, this will be done when it attaches to the framework.
12319 if (proc.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012320 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc already running: " + proc);
Christopher Tate181fafa2009-05-14 11:12:14 -070012321 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040012322 proc.thread.scheduleCreateBackupAgent(app,
12323 compatibilityInfoForPackageLocked(app), backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070012324 } catch (RemoteException e) {
Christopher Tate436344a2009-09-30 16:17:37 -070012325 // Will time out on the backup manager side
Christopher Tate181fafa2009-05-14 11:12:14 -070012326 }
12327 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012328 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc not running, waiting for attach");
Christopher Tate181fafa2009-05-14 11:12:14 -070012329 }
12330 // Invariants: at this point, the target app process exists and the application
12331 // is either already running or in the process of coming up. mBackupTarget and
12332 // mBackupAppName describe the app, so that when it binds back to the AM we
12333 // know that it's scheduled for a backup-agent operation.
12334 }
12335
12336 return true;
12337 }
12338
12339 // A backup agent has just come up
12340 public void backupAgentCreated(String agentPackageName, IBinder agent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012341 if (DEBUG_BACKUP) Slog.v(TAG, "backupAgentCreated: " + agentPackageName
Christopher Tate181fafa2009-05-14 11:12:14 -070012342 + " = " + agent);
12343
12344 synchronized(this) {
12345 if (!agentPackageName.equals(mBackupAppName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012346 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
Christopher Tate181fafa2009-05-14 11:12:14 -070012347 return;
12348 }
Dianne Hackborn06740692010-09-22 22:46:21 -070012349 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012350
Dianne Hackborn06740692010-09-22 22:46:21 -070012351 long oldIdent = Binder.clearCallingIdentity();
12352 try {
12353 IBackupManager bm = IBackupManager.Stub.asInterface(
12354 ServiceManager.getService(Context.BACKUP_SERVICE));
12355 bm.agentConnected(agentPackageName, agent);
12356 } catch (RemoteException e) {
12357 // can't happen; the backup manager service is local
12358 } catch (Exception e) {
12359 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: ");
12360 e.printStackTrace();
12361 } finally {
12362 Binder.restoreCallingIdentity(oldIdent);
Christopher Tate181fafa2009-05-14 11:12:14 -070012363 }
12364 }
12365
12366 // done with this agent
12367 public void unbindBackupAgent(ApplicationInfo appInfo) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012368 if (DEBUG_BACKUP) Slog.v(TAG, "unbindBackupAgent: " + appInfo);
Christopher Tate8a27f922009-06-26 11:49:18 -070012369 if (appInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012370 Slog.w(TAG, "unbind backup agent for null app");
Christopher Tate8a27f922009-06-26 11:49:18 -070012371 return;
12372 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012373
12374 synchronized(this) {
Christopher Tate8a27f922009-06-26 11:49:18 -070012375 if (mBackupAppName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012376 Slog.w(TAG, "Unbinding backup agent with no active backup");
Christopher Tate8a27f922009-06-26 11:49:18 -070012377 return;
12378 }
12379
Christopher Tate181fafa2009-05-14 11:12:14 -070012380 if (!mBackupAppName.equals(appInfo.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012381 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
Christopher Tate181fafa2009-05-14 11:12:14 -070012382 return;
12383 }
12384
Christopher Tate6fa95972009-06-05 18:43:55 -070012385 ProcessRecord proc = mBackupTarget.app;
12386 mBackupTarget = null;
12387 mBackupAppName = null;
12388
12389 // Not backing this app up any more; reset its OOM adjustment
12390 updateOomAdjLocked(proc);
12391
Christopher Tatec7b31e32009-06-10 15:49:30 -070012392 // If the app crashed during backup, 'thread' will be null here
12393 if (proc.thread != null) {
12394 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040012395 proc.thread.scheduleDestroyBackupAgent(appInfo,
12396 compatibilityInfoForPackageLocked(appInfo));
Christopher Tatec7b31e32009-06-10 15:49:30 -070012397 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012398 Slog.e(TAG, "Exception when unbinding backup agent:");
Christopher Tatec7b31e32009-06-10 15:49:30 -070012399 e.printStackTrace();
12400 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012401 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012402 }
12403 }
12404 // =========================================================
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012405 // BROADCASTS
12406 // =========================================================
12407
Josh Bartel7f208742010-02-25 11:01:44 -060012408 private final List getStickiesLocked(String action, IntentFilter filter,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012409 List cur) {
12410 final ContentResolver resolver = mContext.getContentResolver();
12411 final ArrayList<Intent> list = mStickyBroadcasts.get(action);
12412 if (list == null) {
12413 return cur;
12414 }
12415 int N = list.size();
12416 for (int i=0; i<N; i++) {
12417 Intent intent = list.get(i);
12418 if (filter.match(resolver, intent, true, TAG) >= 0) {
12419 if (cur == null) {
12420 cur = new ArrayList<Intent>();
12421 }
12422 cur.add(intent);
12423 }
12424 }
12425 return cur;
12426 }
12427
Christopher Tatef46723b2012-01-26 14:19:24 -080012428 boolean isPendingBroadcastProcessLocked(int pid) {
12429 return mFgBroadcastQueue.isPendingBroadcastProcessLocked(pid)
12430 || mBgBroadcastQueue.isPendingBroadcastProcessLocked(pid);
12431 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012432
Christopher Tatef46723b2012-01-26 14:19:24 -080012433 void skipPendingBroadcastLocked(int pid) {
12434 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
12435 for (BroadcastQueue queue : mBroadcastQueues) {
12436 queue.skipPendingBroadcastLocked(pid);
12437 }
12438 }
12439
12440 // The app just attached; send any pending broadcasts that it should receive
12441 boolean sendPendingBroadcastsLocked(ProcessRecord app) {
12442 boolean didSomething = false;
12443 for (BroadcastQueue queue : mBroadcastQueues) {
12444 didSomething |= queue.sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012445 }
Christopher Tatef46723b2012-01-26 14:19:24 -080012446 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012447 }
12448
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012449 public Intent registerReceiver(IApplicationThread caller, String callerPackage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012450 IIntentReceiver receiver, IntentFilter filter, String permission) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012451 enforceNotIsolatedCaller("registerReceiver");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012452 synchronized(this) {
12453 ProcessRecord callerApp = null;
12454 if (caller != null) {
12455 callerApp = getRecordForAppLocked(caller);
12456 if (callerApp == null) {
12457 throw new SecurityException(
12458 "Unable to find app for caller " + caller
12459 + " (pid=" + Binder.getCallingPid()
12460 + ") when registering receiver " + receiver);
12461 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012462 if (callerApp.info.uid != Process.SYSTEM_UID &&
12463 !callerApp.pkgList.contains(callerPackage)) {
12464 throw new SecurityException("Given caller package " + callerPackage
12465 + " is not running in process " + callerApp);
12466 }
12467 } else {
12468 callerPackage = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012469 }
12470
12471 List allSticky = null;
12472
12473 // Look for any matching sticky broadcasts...
12474 Iterator actions = filter.actionsIterator();
12475 if (actions != null) {
12476 while (actions.hasNext()) {
12477 String action = (String)actions.next();
Josh Bartel7f208742010-02-25 11:01:44 -060012478 allSticky = getStickiesLocked(action, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012479 }
12480 } else {
Josh Bartel7f208742010-02-25 11:01:44 -060012481 allSticky = getStickiesLocked(null, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012482 }
12483
12484 // The first sticky in the list is returned directly back to
12485 // the client.
12486 Intent sticky = allSticky != null ? (Intent)allSticky.get(0) : null;
12487
Joe Onorato8a9b2202010-02-26 18:56:32 -080012488 if (DEBUG_BROADCAST) Slog.v(TAG, "Register receiver " + filter
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012489 + ": " + sticky);
12490
12491 if (receiver == null) {
12492 return sticky;
12493 }
12494
12495 ReceiverList rl
12496 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
12497 if (rl == null) {
12498 rl = new ReceiverList(this, callerApp,
12499 Binder.getCallingPid(),
12500 Binder.getCallingUid(), receiver);
12501 if (rl.app != null) {
12502 rl.app.receivers.add(rl);
12503 } else {
12504 try {
12505 receiver.asBinder().linkToDeath(rl, 0);
12506 } catch (RemoteException e) {
12507 return sticky;
12508 }
12509 rl.linkedToDeath = true;
12510 }
12511 mRegisteredReceivers.put(receiver.asBinder(), rl);
12512 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012513 BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage, permission);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012514 rl.add(bf);
12515 if (!bf.debugCheck()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012516 Slog.w(TAG, "==> For Dynamic broadast");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012517 }
12518 mReceiverResolver.addFilter(bf);
12519
12520 // Enqueue broadcasts for all existing stickies that match
12521 // this filter.
12522 if (allSticky != null) {
12523 ArrayList receivers = new ArrayList();
12524 receivers.add(bf);
12525
12526 int N = allSticky.size();
12527 for (int i=0; i<N; i++) {
12528 Intent intent = (Intent)allSticky.get(i);
Christopher Tatef46723b2012-01-26 14:19:24 -080012529 BroadcastQueue queue = broadcastQueueForIntent(intent);
12530 BroadcastRecord r = new BroadcastRecord(queue, intent, null,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012531 null, -1, -1, null, receivers, null, 0, null, null,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012532 false, true, true);
Christopher Tatef46723b2012-01-26 14:19:24 -080012533 queue.enqueueParallelBroadcastLocked(r);
12534 queue.scheduleBroadcastsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012535 }
12536 }
12537
12538 return sticky;
12539 }
12540 }
12541
12542 public void unregisterReceiver(IIntentReceiver receiver) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012543 if (DEBUG_BROADCAST) Slog.v(TAG, "Unregister receiver: " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012544
Christopher Tatef46723b2012-01-26 14:19:24 -080012545 final long origId = Binder.clearCallingIdentity();
12546 try {
12547 boolean doTrim = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012548
Christopher Tatef46723b2012-01-26 14:19:24 -080012549 synchronized(this) {
12550 ReceiverList rl
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012551 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
Christopher Tatef46723b2012-01-26 14:19:24 -080012552 if (rl != null) {
12553 if (rl.curBroadcast != null) {
12554 BroadcastRecord r = rl.curBroadcast;
12555 final boolean doNext = finishReceiverLocked(
12556 receiver.asBinder(), r.resultCode, r.resultData,
12557 r.resultExtras, r.resultAbort, true);
12558 if (doNext) {
12559 doTrim = true;
12560 r.queue.processNextBroadcast(false);
12561 }
12562 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012563
Christopher Tatef46723b2012-01-26 14:19:24 -080012564 if (rl.app != null) {
12565 rl.app.receivers.remove(rl);
12566 }
12567 removeReceiverLocked(rl);
12568 if (rl.linkedToDeath) {
12569 rl.linkedToDeath = false;
12570 rl.receiver.asBinder().unlinkToDeath(rl, 0);
12571 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012572 }
12573 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012574
Christopher Tatef46723b2012-01-26 14:19:24 -080012575 // If we actually concluded any broadcasts, we might now be able
12576 // to trim the recipients' apps from our working set
12577 if (doTrim) {
12578 trimApplications();
12579 return;
12580 }
12581
12582 } finally {
12583 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012584 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012585 }
12586
12587 void removeReceiverLocked(ReceiverList rl) {
12588 mRegisteredReceivers.remove(rl.receiver.asBinder());
12589 int N = rl.size();
12590 for (int i=0; i<N; i++) {
12591 mReceiverResolver.removeFilter(rl.get(i));
12592 }
12593 }
12594
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012595 private final void sendPackageBroadcastLocked(int cmd, String[] packages) {
12596 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
12597 ProcessRecord r = mLruProcesses.get(i);
12598 if (r.thread != null) {
12599 try {
12600 r.thread.dispatchPackageBroadcast(cmd, packages);
12601 } catch (RemoteException ex) {
12602 }
12603 }
12604 }
12605 }
12606
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012607 private final int broadcastIntentLocked(ProcessRecord callerApp,
12608 String callerPackage, Intent intent, String resolvedType,
12609 IIntentReceiver resultTo, int resultCode, String resultData,
12610 Bundle map, String requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070012611 boolean ordered, boolean sticky, int callingPid, int callingUid,
12612 int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012613 intent = new Intent(intent);
12614
Dianne Hackborne7f97212011-02-24 14:40:20 -080012615 // By default broadcasts do not go to stopped apps.
12616 intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
12617
Joe Onorato8a9b2202010-02-26 18:56:32 -080012618 if (DEBUG_BROADCAST_LIGHT) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012619 TAG, (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
Amith Yamasani13593602012-03-22 16:16:17 -070012620 + " ordered=" + ordered + " userid=" + userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012621 if ((resultTo != null) && !ordered) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012622 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012623 }
12624
12625 // Handle special intents: if this broadcast is from the package
12626 // manager about a package being removed, we need to remove all of
12627 // its activities from the history stack.
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012628 final boolean uidRemoved = Intent.ACTION_UID_REMOVED.equals(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012629 intent.getAction());
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012630 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())
12631 || Intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction())
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080012632 || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012633 || uidRemoved) {
12634 if (checkComponentPermission(
12635 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080012636 callingPid, callingUid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012637 == PackageManager.PERMISSION_GRANTED) {
12638 if (uidRemoved) {
12639 final Bundle intentExtras = intent.getExtras();
12640 final int uid = intentExtras != null
12641 ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
12642 if (uid >= 0) {
12643 BatteryStatsImpl bs = mBatteryStatsService.getActiveStatistics();
12644 synchronized (bs) {
12645 bs.removeUidStatsLocked(uid);
12646 }
12647 }
12648 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012649 // If resources are unvailble just force stop all
12650 // those packages and flush the attribute cache as well.
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080012651 if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012652 String list[] = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
12653 if (list != null && (list.length > 0)) {
12654 for (String pkg : list) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070012655 forceStopPackageLocked(pkg, -1, false, true, true, false, userId);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012656 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012657 sendPackageBroadcastLocked(
12658 IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE, list);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012659 }
12660 } else {
12661 Uri data = intent.getData();
12662 String ssp;
12663 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
12664 if (!intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false)) {
12665 forceStopPackageLocked(ssp,
Amith Yamasani483f3b02012-03-13 16:08:00 -070012666 intent.getIntExtra(Intent.EXTRA_UID, -1), false, true, true,
12667 false, userId);
Dianne Hackbornde7faf62009-06-30 13:27:30 -070012668 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012669 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012670 sendPackageBroadcastLocked(IApplicationThread.PACKAGE_REMOVED,
12671 new String[] {ssp});
12672 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012673 }
12674 }
12675 }
12676 } else {
12677 String msg = "Permission Denial: " + intent.getAction()
12678 + " broadcast from " + callerPackage + " (pid=" + callingPid
12679 + ", uid=" + callingUid + ")"
12680 + " requires "
12681 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012682 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012683 throw new SecurityException(msg);
12684 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012685
12686 // Special case for adding a package: by default turn on compatibility
12687 // mode.
12688 } else if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -070012689 Uri data = intent.getData();
12690 String ssp;
12691 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
12692 mCompatModePackages.handlePackageAddedLocked(ssp,
12693 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false));
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012694 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012695 }
12696
12697 /*
12698 * If this is the time zone changed action, queue up a message that will reset the timezone
12699 * of all currently running processes. This message will get queued up before the broadcast
12700 * happens.
12701 */
12702 if (intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) {
12703 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
12704 }
12705
Robert Greenwalt03595d02010-11-02 14:08:23 -070012706 if (intent.ACTION_CLEAR_DNS_CACHE.equals(intent.getAction())) {
12707 mHandler.sendEmptyMessage(CLEAR_DNS_CACHE);
12708 }
12709
Robert Greenwalt434203a2010-10-11 16:00:27 -070012710 if (Proxy.PROXY_CHANGE_ACTION.equals(intent.getAction())) {
12711 ProxyProperties proxy = intent.getParcelableExtra("proxy");
12712 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY, proxy));
12713 }
12714
Dianne Hackborn854060af2009-07-09 18:14:31 -070012715 /*
12716 * Prevent non-system code (defined here to be non-persistent
12717 * processes) from sending protected broadcasts.
12718 */
12719 if (callingUid == Process.SYSTEM_UID || callingUid == Process.PHONE_UID
12720 || callingUid == Process.SHELL_UID || callingUid == 0) {
12721 // Always okay.
12722 } else if (callerApp == null || !callerApp.persistent) {
12723 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012724 if (AppGlobals.getPackageManager().isProtectedBroadcast(
Dianne Hackborn854060af2009-07-09 18:14:31 -070012725 intent.getAction())) {
12726 String msg = "Permission Denial: not allowed to send broadcast "
12727 + intent.getAction() + " from pid="
12728 + callingPid + ", uid=" + callingUid;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012729 Slog.w(TAG, msg);
Dianne Hackborn854060af2009-07-09 18:14:31 -070012730 throw new SecurityException(msg);
12731 }
12732 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012733 Slog.w(TAG, "Remote exception", e);
Dianne Hackborna4972e92012-03-14 10:38:05 -070012734 return ActivityManager.BROADCAST_SUCCESS;
Dianne Hackborn854060af2009-07-09 18:14:31 -070012735 }
12736 }
12737
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012738 // Add to the sticky list if requested.
12739 if (sticky) {
12740 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
12741 callingPid, callingUid)
12742 != PackageManager.PERMISSION_GRANTED) {
12743 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
12744 + callingPid + ", uid=" + callingUid
12745 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012746 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012747 throw new SecurityException(msg);
12748 }
12749 if (requiredPermission != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012750 Slog.w(TAG, "Can't broadcast sticky intent " + intent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012751 + " and enforce permission " + requiredPermission);
Dianne Hackborna4972e92012-03-14 10:38:05 -070012752 return ActivityManager.BROADCAST_STICKY_CANT_HAVE_PERMISSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012753 }
12754 if (intent.getComponent() != null) {
12755 throw new SecurityException(
12756 "Sticky broadcasts can't target a specific component");
12757 }
12758 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
12759 if (list == null) {
12760 list = new ArrayList<Intent>();
12761 mStickyBroadcasts.put(intent.getAction(), list);
12762 }
12763 int N = list.size();
12764 int i;
12765 for (i=0; i<N; i++) {
12766 if (intent.filterEquals(list.get(i))) {
12767 // This sticky already exists, replace it.
12768 list.set(i, new Intent(intent));
12769 break;
12770 }
12771 }
12772 if (i >= N) {
12773 list.add(new Intent(intent));
12774 }
12775 }
12776
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012777 // Figure out who all will receive this broadcast.
12778 List receivers = null;
12779 List<BroadcastFilter> registeredReceivers = null;
12780 try {
12781 if (intent.getComponent() != null) {
12782 // Broadcast is going to one specific receiver class...
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012783 ActivityInfo ai = AppGlobals.getPackageManager().
Amith Yamasani483f3b02012-03-13 16:08:00 -070012784 getReceiverInfo(intent.getComponent(), STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012785 if (ai != null) {
12786 receivers = new ArrayList();
12787 ResolveInfo ri = new ResolveInfo();
Amith Yamasania4a54e22012-04-16 15:44:19 -070012788 if (isSingleton(ai.processName, ai.applicationInfo)) {
12789 ri.activityInfo = getActivityInfoForUser(ai, 0);
12790 } else {
12791 ri.activityInfo = getActivityInfoForUser(ai, userId);
12792 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012793 receivers.add(ri);
12794 }
12795 } else {
12796 // Need to resolve the intent to interested receivers...
12797 if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
12798 == 0) {
12799 receivers =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012800 AppGlobals.getPackageManager().queryIntentReceivers(
Amith Yamasani483f3b02012-03-13 16:08:00 -070012801 intent, resolvedType, STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012802 }
Amith Yamasani483f3b02012-03-13 16:08:00 -070012803 registeredReceivers = mReceiverResolver.queryIntent(intent, resolvedType, false,
12804 userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012805 }
12806 } catch (RemoteException ex) {
12807 // pm is in same process, this will never happen.
12808 }
12809
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012810 final boolean replacePending =
12811 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
12812
Joe Onorato8a9b2202010-02-26 18:56:32 -080012813 if (DEBUG_BROADCAST) Slog.v(TAG, "Enqueing broadcast: " + intent.getAction()
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012814 + " replacePending=" + replacePending);
12815
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012816 int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
12817 if (!ordered && NR > 0) {
12818 // If we are not serializing this broadcast, then send the
12819 // registered receivers separately so they don't wait for the
12820 // components to be launched.
Christopher Tatef46723b2012-01-26 14:19:24 -080012821 final BroadcastQueue queue = broadcastQueueForIntent(intent);
12822 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012823 callerPackage, callingPid, callingUid, requiredPermission,
12824 registeredReceivers, resultTo, resultCode, resultData, map,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012825 ordered, sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012826 if (DEBUG_BROADCAST) Slog.v(
Christopher Tatef46723b2012-01-26 14:19:24 -080012827 TAG, "Enqueueing parallel broadcast " + r);
12828 final boolean replaced = replacePending && queue.replaceParallelBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012829 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012830 queue.enqueueParallelBroadcastLocked(r);
12831 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012832 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012833 registeredReceivers = null;
12834 NR = 0;
12835 }
12836
12837 // Merge into one list.
12838 int ir = 0;
12839 if (receivers != null) {
12840 // A special case for PACKAGE_ADDED: do not allow the package
12841 // being added to see this broadcast. This prevents them from
12842 // using this as a back door to get run as soon as they are
12843 // installed. Maybe in the future we want to have a special install
12844 // broadcast or such for apps, but we'd like to deliberately make
12845 // this decision.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012846 String skipPackages[] = null;
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012847 if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
12848 || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
12849 || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012850 Uri data = intent.getData();
12851 if (data != null) {
12852 String pkgName = data.getSchemeSpecificPart();
12853 if (pkgName != null) {
12854 skipPackages = new String[] { pkgName };
12855 }
12856 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012857 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012858 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
The Android Open Source Project10592532009-03-18 17:39:46 -070012859 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012860 if (skipPackages != null && (skipPackages.length > 0)) {
12861 for (String skipPackage : skipPackages) {
12862 if (skipPackage != null) {
12863 int NT = receivers.size();
12864 for (int it=0; it<NT; it++) {
12865 ResolveInfo curt = (ResolveInfo)receivers.get(it);
12866 if (curt.activityInfo.packageName.equals(skipPackage)) {
12867 receivers.remove(it);
12868 it--;
12869 NT--;
12870 }
12871 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012872 }
12873 }
12874 }
12875
12876 int NT = receivers != null ? receivers.size() : 0;
12877 int it = 0;
12878 ResolveInfo curt = null;
12879 BroadcastFilter curr = null;
12880 while (it < NT && ir < NR) {
12881 if (curt == null) {
12882 curt = (ResolveInfo)receivers.get(it);
12883 }
12884 if (curr == null) {
12885 curr = registeredReceivers.get(ir);
12886 }
12887 if (curr.getPriority() >= curt.priority) {
12888 // Insert this broadcast record into the final list.
12889 receivers.add(it, curr);
12890 ir++;
12891 curr = null;
12892 it++;
12893 NT++;
12894 } else {
12895 // Skip to the next ResolveInfo in the final list.
12896 it++;
12897 curt = null;
12898 }
12899 }
12900 }
12901 while (ir < NR) {
12902 if (receivers == null) {
12903 receivers = new ArrayList();
12904 }
12905 receivers.add(registeredReceivers.get(ir));
12906 ir++;
12907 }
12908
12909 if ((receivers != null && receivers.size() > 0)
12910 || resultTo != null) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012911 BroadcastQueue queue = broadcastQueueForIntent(intent);
12912 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012913 callerPackage, callingPid, callingUid, requiredPermission,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012914 receivers, resultTo, resultCode, resultData, map, ordered,
12915 sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012916 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012917 TAG, "Enqueueing ordered broadcast " + r
Christopher Tatef46723b2012-01-26 14:19:24 -080012918 + ": prev had " + queue.mOrderedBroadcasts.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012919 if (DEBUG_BROADCAST) {
12920 int seq = r.intent.getIntExtra("seq", -1);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012921 Slog.i(TAG, "Enqueueing broadcast " + r.intent.getAction() + " seq=" + seq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012922 }
Christopher Tatef46723b2012-01-26 14:19:24 -080012923 boolean replaced = replacePending && queue.replaceOrderedBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012924 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012925 queue.enqueueOrderedBroadcastLocked(r);
12926 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012927 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012928 }
12929
Dianne Hackborna4972e92012-03-14 10:38:05 -070012930 return ActivityManager.BROADCAST_SUCCESS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012931 }
12932
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012933 final Intent verifyBroadcastLocked(Intent intent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012934 // Refuse possible leaked file descriptors
12935 if (intent != null && intent.hasFileDescriptors() == true) {
12936 throw new IllegalArgumentException("File descriptors passed in Intent");
12937 }
12938
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012939 int flags = intent.getFlags();
12940
12941 if (!mProcessesReady) {
12942 // if the caller really truly claims to know what they're doing, go
12943 // ahead and allow the broadcast without launching any receivers
12944 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
12945 intent = new Intent(intent);
12946 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
12947 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
12948 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
12949 + " before boot completion");
12950 throw new IllegalStateException("Cannot broadcast before boot completed");
12951 }
12952 }
12953
12954 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
12955 throw new IllegalArgumentException(
12956 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
12957 }
12958
12959 return intent;
12960 }
12961
12962 public final int broadcastIntent(IApplicationThread caller,
12963 Intent intent, String resolvedType, IIntentReceiver resultTo,
12964 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070012965 String requiredPermission, boolean serialized, boolean sticky, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012966 enforceNotIsolatedCaller("broadcastIntent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012967 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012968 intent = verifyBroadcastLocked(intent);
Dianne Hackborn9acc0302009-08-25 00:27:12 -070012969
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012970 final ProcessRecord callerApp = getRecordForAppLocked(caller);
12971 final int callingPid = Binder.getCallingPid();
12972 final int callingUid = Binder.getCallingUid();
12973 final long origId = Binder.clearCallingIdentity();
12974 int res = broadcastIntentLocked(callerApp,
12975 callerApp != null ? callerApp.info.packageName : null,
12976 intent, resolvedType, resultTo,
Amith Yamasani742a6712011-05-04 14:49:28 -070012977 resultCode, resultData, map, requiredPermission, serialized, sticky,
12978 callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012979 Binder.restoreCallingIdentity(origId);
12980 return res;
12981 }
12982 }
12983
12984 int broadcastIntentInPackage(String packageName, int uid,
12985 Intent intent, String resolvedType, IIntentReceiver resultTo,
12986 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070012987 String requiredPermission, boolean serialized, boolean sticky, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012988 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012989 intent = verifyBroadcastLocked(intent);
12990
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012991 final long origId = Binder.clearCallingIdentity();
12992 int res = broadcastIntentLocked(null, packageName, intent, resolvedType,
12993 resultTo, resultCode, resultData, map, requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070012994 serialized, sticky, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012995 Binder.restoreCallingIdentity(origId);
12996 return res;
12997 }
12998 }
12999
Amith Yamasani742a6712011-05-04 14:49:28 -070013000 // TODO: Use the userId; maybe mStickyBroadcasts need to be tied to the user.
13001 public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013002 // Refuse possible leaked file descriptors
13003 if (intent != null && intent.hasFileDescriptors() == true) {
13004 throw new IllegalArgumentException("File descriptors passed in Intent");
13005 }
13006
13007 synchronized(this) {
13008 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
13009 != PackageManager.PERMISSION_GRANTED) {
13010 String msg = "Permission Denial: unbroadcastIntent() from pid="
13011 + Binder.getCallingPid()
13012 + ", uid=" + Binder.getCallingUid()
13013 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080013014 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013015 throw new SecurityException(msg);
13016 }
13017 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
13018 if (list != null) {
13019 int N = list.size();
13020 int i;
13021 for (i=0; i<N; i++) {
13022 if (intent.filterEquals(list.get(i))) {
13023 list.remove(i);
13024 break;
13025 }
13026 }
13027 }
13028 }
13029 }
13030
13031 private final boolean finishReceiverLocked(IBinder receiver, int resultCode,
13032 String resultData, Bundle resultExtras, boolean resultAbort,
13033 boolean explicit) {
Christopher Tatef46723b2012-01-26 14:19:24 -080013034 final BroadcastRecord r = broadcastRecordForReceiverLocked(receiver);
13035 if (r == null) {
13036 Slog.w(TAG, "finishReceiver called but not found on queue");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013037 return false;
13038 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013039
Christopher Tatef46723b2012-01-26 14:19:24 -080013040 return r.queue.finishReceiverLocked(r, resultCode, resultData, resultExtras, resultAbort,
13041 explicit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013042 }
13043
13044 public void finishReceiver(IBinder who, int resultCode, String resultData,
13045 Bundle resultExtras, boolean resultAbort) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013046 if (DEBUG_BROADCAST) Slog.v(TAG, "Finish receiver: " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013047
13048 // Refuse possible leaked file descriptors
13049 if (resultExtras != null && resultExtras.hasFileDescriptors()) {
13050 throw new IllegalArgumentException("File descriptors passed in Bundle");
13051 }
13052
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013053 final long origId = Binder.clearCallingIdentity();
Christopher Tatef46723b2012-01-26 14:19:24 -080013054 try {
13055 boolean doNext = false;
13056 BroadcastRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013057
Christopher Tatef46723b2012-01-26 14:19:24 -080013058 synchronized(this) {
13059 r = broadcastRecordForReceiverLocked(who);
13060 if (r != null) {
13061 doNext = r.queue.finishReceiverLocked(r, resultCode,
13062 resultData, resultExtras, resultAbort, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013063 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013064 }
Jeff Brown4d94a762010-09-23 11:33:28 -070013065
Christopher Tatef46723b2012-01-26 14:19:24 -080013066 if (doNext) {
13067 r.queue.processNextBroadcast(false);
13068 }
13069 trimApplications();
13070 } finally {
13071 Binder.restoreCallingIdentity(origId);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070013072 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013073 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013074
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013075 // =========================================================
13076 // INSTRUMENTATION
13077 // =========================================================
13078
13079 public boolean startInstrumentation(ComponentName className,
13080 String profileFile, int flags, Bundle arguments,
13081 IInstrumentationWatcher watcher) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080013082 enforceNotIsolatedCaller("startInstrumentation");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013083 // Refuse possible leaked file descriptors
13084 if (arguments != null && arguments.hasFileDescriptors()) {
13085 throw new IllegalArgumentException("File descriptors passed in Bundle");
13086 }
13087
13088 synchronized(this) {
13089 InstrumentationInfo ii = null;
13090 ApplicationInfo ai = null;
13091 try {
13092 ii = mContext.getPackageManager().getInstrumentationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070013093 className, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013094 ai = mContext.getPackageManager().getApplicationInfo(
Amith Yamasani483f3b02012-03-13 16:08:00 -070013095 ii.targetPackage, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013096 } catch (PackageManager.NameNotFoundException e) {
13097 }
13098 if (ii == null) {
13099 reportStartInstrumentationFailure(watcher, className,
13100 "Unable to find instrumentation info for: " + className);
13101 return false;
13102 }
13103 if (ai == null) {
13104 reportStartInstrumentationFailure(watcher, className,
13105 "Unable to find instrumentation target package: " + ii.targetPackage);
13106 return false;
13107 }
13108
13109 int match = mContext.getPackageManager().checkSignatures(
13110 ii.targetPackage, ii.packageName);
13111 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
13112 String msg = "Permission Denial: starting instrumentation "
13113 + className + " from pid="
13114 + Binder.getCallingPid()
13115 + ", uid=" + Binder.getCallingPid()
13116 + " not allowed because package " + ii.packageName
13117 + " does not have a signature matching the target "
13118 + ii.targetPackage;
13119 reportStartInstrumentationFailure(watcher, className, msg);
13120 throw new SecurityException(msg);
13121 }
13122
Amith Yamasani483f3b02012-03-13 16:08:00 -070013123 int userId = UserId.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013124 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -070013125 // Instrumentation can kill and relaunch even persistent processes
Amith Yamasani483f3b02012-03-13 16:08:00 -070013126 forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true, userId);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013127 ProcessRecord app = addAppLocked(ai, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013128 app.instrumentationClass = className;
Dianne Hackborn1655be42009-05-08 14:29:01 -070013129 app.instrumentationInfo = ai;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013130 app.instrumentationProfileFile = profileFile;
13131 app.instrumentationArguments = arguments;
13132 app.instrumentationWatcher = watcher;
13133 app.instrumentationResultClass = className;
13134 Binder.restoreCallingIdentity(origId);
13135 }
13136
13137 return true;
13138 }
13139
13140 /**
13141 * Report errors that occur while attempting to start Instrumentation. Always writes the
13142 * error to the logs, but if somebody is watching, send the report there too. This enables
13143 * the "am" command to report errors with more information.
13144 *
13145 * @param watcher The IInstrumentationWatcher. Null if there isn't one.
13146 * @param cn The component name of the instrumentation.
13147 * @param report The error report.
13148 */
13149 private void reportStartInstrumentationFailure(IInstrumentationWatcher watcher,
13150 ComponentName cn, String report) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013151 Slog.w(TAG, report);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013152 try {
13153 if (watcher != null) {
13154 Bundle results = new Bundle();
13155 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
13156 results.putString("Error", report);
13157 watcher.instrumentationStatus(cn, -1, results);
13158 }
13159 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013160 Slog.w(TAG, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013161 }
13162 }
13163
13164 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
13165 if (app.instrumentationWatcher != null) {
13166 try {
13167 // NOTE: IInstrumentationWatcher *must* be oneway here
13168 app.instrumentationWatcher.instrumentationFinished(
13169 app.instrumentationClass,
13170 resultCode,
13171 results);
13172 } catch (RemoteException e) {
13173 }
13174 }
13175 app.instrumentationWatcher = null;
13176 app.instrumentationClass = null;
Dianne Hackborn1655be42009-05-08 14:29:01 -070013177 app.instrumentationInfo = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013178 app.instrumentationProfileFile = null;
13179 app.instrumentationArguments = null;
13180
Amith Yamasani483f3b02012-03-13 16:08:00 -070013181 forceStopPackageLocked(app.processName, -1, false, false, true, true, app.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013182 }
13183
13184 public void finishInstrumentation(IApplicationThread target,
13185 int resultCode, Bundle results) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070013186 int userId = UserId.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013187 // Refuse possible leaked file descriptors
13188 if (results != null && results.hasFileDescriptors()) {
13189 throw new IllegalArgumentException("File descriptors passed in Intent");
13190 }
13191
13192 synchronized(this) {
13193 ProcessRecord app = getRecordForAppLocked(target);
13194 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013195 Slog.w(TAG, "finishInstrumentation: no app for " + target);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013196 return;
13197 }
13198 final long origId = Binder.clearCallingIdentity();
13199 finishInstrumentationLocked(app, resultCode, results);
13200 Binder.restoreCallingIdentity(origId);
13201 }
13202 }
13203
13204 // =========================================================
13205 // CONFIGURATION
13206 // =========================================================
13207
13208 public ConfigurationInfo getDeviceConfigurationInfo() {
13209 ConfigurationInfo config = new ConfigurationInfo();
13210 synchronized (this) {
13211 config.reqTouchScreen = mConfiguration.touchscreen;
13212 config.reqKeyboardType = mConfiguration.keyboard;
13213 config.reqNavigation = mConfiguration.navigation;
Dianne Hackbornfae76f52009-07-16 13:41:23 -070013214 if (mConfiguration.navigation == Configuration.NAVIGATION_DPAD
13215 || mConfiguration.navigation == Configuration.NAVIGATION_TRACKBALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013216 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
13217 }
Dianne Hackbornfae76f52009-07-16 13:41:23 -070013218 if (mConfiguration.keyboard != Configuration.KEYBOARD_UNDEFINED
13219 && mConfiguration.keyboard != Configuration.KEYBOARD_NOKEYS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013220 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
13221 }
Jack Palevichb90d28c2009-07-22 15:35:24 -070013222 config.reqGlEsVersion = GL_ES_VERSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013223 }
13224 return config;
13225 }
13226
13227 public Configuration getConfiguration() {
13228 Configuration ci;
13229 synchronized(this) {
13230 ci = new Configuration(mConfiguration);
13231 }
13232 return ci;
13233 }
13234
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013235 public void updatePersistentConfiguration(Configuration values) {
13236 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
13237 "updateConfiguration()");
13238 enforceCallingPermission(android.Manifest.permission.WRITE_SETTINGS,
13239 "updateConfiguration()");
13240 if (values == null) {
13241 throw new NullPointerException("Configuration must not be null");
13242 }
13243
13244 synchronized(this) {
13245 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn813075a62011-11-14 17:45:19 -080013246 updateConfigurationLocked(values, null, true, false);
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013247 Binder.restoreCallingIdentity(origId);
13248 }
13249 }
13250
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013251 public void updateConfiguration(Configuration values) {
13252 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
13253 "updateConfiguration()");
13254
13255 synchronized(this) {
13256 if (values == null && mWindowManager != null) {
13257 // sentinel: fetch the current configuration from the window manager
13258 values = mWindowManager.computeNewConfiguration();
13259 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013260
13261 if (mWindowManager != null) {
13262 mProcessList.applyDisplaySize(mWindowManager);
13263 }
13264
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013265 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013266 if (values != null) {
13267 Settings.System.clearConfiguration(values);
13268 }
Dianne Hackborn813075a62011-11-14 17:45:19 -080013269 updateConfigurationLocked(values, null, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013270 Binder.restoreCallingIdentity(origId);
13271 }
13272 }
13273
13274 /**
13275 * Do either or both things: (1) change the current configuration, and (2)
13276 * make sure the given activity is running with the (now) current
13277 * configuration. Returns true if the activity has been left running, or
13278 * false if <var>starting</var> is being destroyed to match the new
13279 * configuration.
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013280 * @param persistent TODO
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013281 */
Dianne Hackborna573f6a2012-02-09 16:12:18 -080013282 boolean updateConfigurationLocked(Configuration values,
Dianne Hackborn813075a62011-11-14 17:45:19 -080013283 ActivityRecord starting, boolean persistent, boolean initLocale) {
Mike Lockwood3a74bd32011-08-12 13:55:22 -070013284 // do nothing if we are headless
13285 if (mHeadless) return true;
13286
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013287 int changes = 0;
13288
13289 boolean kept = true;
13290
13291 if (values != null) {
13292 Configuration newConfig = new Configuration(mConfiguration);
13293 changes = newConfig.updateFrom(values);
13294 if (changes != 0) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013295 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013296 Slog.i(TAG, "Updating configuration to: " + values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013297 }
13298
Doug Zongker2bec3d42009-12-04 12:52:44 -080013299 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013300
Dianne Hackborn813075a62011-11-14 17:45:19 -080013301 if (values.locale != null && !initLocale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013302 saveLocaleLocked(values.locale,
13303 !values.locale.equals(mConfiguration.locale),
13304 values.userSetLocale);
13305 }
13306
Dianne Hackborne36d6e22010-02-17 19:46:25 -080013307 mConfigurationSeq++;
13308 if (mConfigurationSeq <= 0) {
13309 mConfigurationSeq = 1;
13310 }
13311 newConfig.seq = mConfigurationSeq;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013312 mConfiguration = newConfig;
Joe Onorato8a9b2202010-02-26 18:56:32 -080013313 Slog.i(TAG, "Config changed: " + newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013314
13315 final Configuration configCopy = new Configuration(mConfiguration);
Joe Onorato54a4a412011-11-02 20:50:08 -070013316
13317 // TODO: If our config changes, should we auto dismiss any currently
13318 // showing dialogs?
13319 mShowDialogs = shouldShowDialogs(newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013320
Dianne Hackborn826d17c2009-11-12 12:55:51 -080013321 AttributeCache ac = AttributeCache.instance();
13322 if (ac != null) {
Dianne Hackborn813075a62011-11-14 17:45:19 -080013323 ac.updateConfiguration(configCopy);
Dianne Hackborn826d17c2009-11-12 12:55:51 -080013324 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013325
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070013326 // Make sure all resources in our process are updated
13327 // right now, so that anyone who is going to retrieve
13328 // resource values after we return will be sure to get
13329 // the new ones. This is especially important during
13330 // boot, where the first config change needs to guarantee
13331 // all resources have that config before following boot
13332 // code is executed.
Dianne Hackborn813075a62011-11-14 17:45:19 -080013333 mSystemThread.applyConfigurationToResources(configCopy);
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070013334
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013335 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080013336 Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013337 msg.obj = new Configuration(configCopy);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080013338 mHandler.sendMessage(msg);
13339 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013340
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013341 for (int i=mLruProcesses.size()-1; i>=0; i--) {
13342 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013343 try {
13344 if (app.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013345 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending to proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013346 + app.processName + " new config " + mConfiguration);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013347 app.thread.scheduleConfigurationChanged(configCopy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013348 }
13349 } catch (Exception e) {
13350 }
13351 }
13352 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080013353 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
13354 | Intent.FLAG_RECEIVER_REPLACE_PENDING);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013355 broadcastIntentLocked(null, null, intent, null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070013356 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080013357 if ((changes&ActivityInfo.CONFIG_LOCALE) != 0) {
13358 broadcastIntentLocked(null, null,
13359 new Intent(Intent.ACTION_LOCALE_CHANGED),
13360 null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070013361 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080013362 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013363 }
13364 }
13365
13366 if (changes != 0 && starting == null) {
13367 // If the configuration changed, and the caller is not already
13368 // in the process of starting an activity, then find the top
13369 // activity to check if its configuration needs to change.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013370 starting = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013371 }
13372
13373 if (starting != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013374 kept = mMainStack.ensureActivityConfigurationLocked(starting, changes);
Dianne Hackborn5f4d6432010-12-21 20:40:11 -080013375 // And we need to make sure at this point that all other activities
13376 // are made visible with the correct configuration.
13377 mMainStack.ensureActivitiesVisibleLocked(starting, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013378 }
13379
Dianne Hackborne36d6e22010-02-17 19:46:25 -080013380 if (values != null && mWindowManager != null) {
13381 mWindowManager.setNewConfiguration(mConfiguration);
13382 }
13383
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013384 return kept;
13385 }
Joe Onorato54a4a412011-11-02 20:50:08 -070013386
13387 /**
13388 * Decide based on the configuration whether we should shouw the ANR,
13389 * crash, etc dialogs. The idea is that if there is no affordnace to
13390 * press the on-screen buttons, we shouldn't show the dialog.
13391 *
13392 * A thought: SystemUI might also want to get told about this, the Power
13393 * dialog / global actions also might want different behaviors.
13394 */
13395 private static final boolean shouldShowDialogs(Configuration config) {
13396 return !(config.keyboard == Configuration.KEYBOARD_NOKEYS
13397 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH);
13398 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013399
13400 /**
13401 * Save the locale. You must be inside a synchronized (this) block.
13402 */
13403 private void saveLocaleLocked(Locale l, boolean isDiff, boolean isPersist) {
13404 if(isDiff) {
13405 SystemProperties.set("user.language", l.getLanguage());
13406 SystemProperties.set("user.region", l.getCountry());
13407 }
13408
13409 if(isPersist) {
13410 SystemProperties.set("persist.sys.language", l.getLanguage());
13411 SystemProperties.set("persist.sys.country", l.getCountry());
13412 SystemProperties.set("persist.sys.localevar", l.getVariant());
13413 }
13414 }
13415
Adam Powelldd8fab22012-03-22 17:47:27 -070013416 @Override
13417 public boolean targetTaskAffinityMatchesActivity(IBinder token, String destAffinity) {
13418 ActivityRecord srec = ActivityRecord.forToken(token);
Adam Powellb71a5bc2012-04-24 14:20:57 -070013419 return srec != null && srec.task.affinity != null &&
13420 srec.task.affinity.equals(destAffinity);
Adam Powelldd8fab22012-03-22 17:47:27 -070013421 }
13422
13423 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
13424 Intent resultData) {
13425 ComponentName dest = destIntent.getComponent();
13426
13427 synchronized (this) {
13428 ActivityRecord srec = ActivityRecord.forToken(token);
Adam Powellb71a5bc2012-04-24 14:20:57 -070013429 if (srec == null) {
13430 return false;
13431 }
Adam Powelldd8fab22012-03-22 17:47:27 -070013432 ArrayList<ActivityRecord> history = srec.stack.mHistory;
13433 final int start = history.indexOf(srec);
13434 if (start < 0) {
13435 // Current activity is not in history stack; do nothing.
13436 return false;
13437 }
13438 int finishTo = start - 1;
13439 ActivityRecord parent = null;
13440 boolean foundParentInTask = false;
13441 if (dest != null) {
13442 TaskRecord tr = srec.task;
13443 for (int i = start - 1; i >= 0; i--) {
13444 ActivityRecord r = history.get(i);
13445 if (tr != r.task) {
13446 // Couldn't find parent in the same task; stop at the one above this.
13447 // (Root of current task; in-app "home" behavior)
13448 // Always at least finish the current activity.
13449 finishTo = Math.min(start - 1, i + 1);
13450 parent = history.get(finishTo);
13451 break;
13452 } else if (r.info.packageName.equals(dest.getPackageName()) &&
13453 r.info.name.equals(dest.getClassName())) {
13454 finishTo = i;
13455 parent = r;
13456 foundParentInTask = true;
13457 break;
13458 }
13459 }
13460 }
13461
13462 if (mController != null) {
13463 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
13464 if (next != null) {
13465 // ask watcher if this is allowed
13466 boolean resumeOK = true;
13467 try {
13468 resumeOK = mController.activityResuming(next.packageName);
13469 } catch (RemoteException e) {
13470 mController = null;
13471 }
13472
13473 if (!resumeOK) {
13474 return false;
13475 }
13476 }
13477 }
13478 final long origId = Binder.clearCallingIdentity();
13479 for (int i = start; i > finishTo; i--) {
13480 ActivityRecord r = history.get(i);
13481 mMainStack.requestFinishActivityLocked(r.appToken, resultCode, resultData,
13482 "navigate-up");
13483 // Only return the supplied result for the first activity finished
13484 resultCode = Activity.RESULT_CANCELED;
13485 resultData = null;
13486 }
13487
13488 if (parent != null && foundParentInTask) {
13489 final int parentLaunchMode = parent.info.launchMode;
13490 final int destIntentFlags = destIntent.getFlags();
13491 if (parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE ||
13492 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TASK ||
13493 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TOP ||
13494 (destIntentFlags & Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
13495 parent.deliverNewIntentLocked(srec.app.uid, destIntent);
13496 } else {
13497 try {
13498 ActivityInfo aInfo = AppGlobals.getPackageManager().getActivityInfo(
13499 destIntent.getComponent(), 0, UserId.getCallingUserId());
13500 int res = mMainStack.startActivityLocked(srec.app.thread, destIntent,
13501 null, aInfo, parent.appToken, null,
13502 0, -1, parent.launchedFromUid, 0, null, true, null);
13503 foundParentInTask = res == ActivityManager.START_SUCCESS;
13504 } catch (RemoteException e) {
13505 foundParentInTask = false;
13506 }
13507 mMainStack.requestFinishActivityLocked(parent.appToken, resultCode,
13508 resultData, "navigate-up");
13509 }
13510 }
13511 Binder.restoreCallingIdentity(origId);
13512 return foundParentInTask;
13513 }
13514 }
13515
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013516 // =========================================================
13517 // LIFETIME MANAGEMENT
13518 // =========================================================
13519
Christopher Tatef46723b2012-01-26 14:19:24 -080013520 // Returns which broadcast queue the app is the current [or imminent] receiver
13521 // on, or 'null' if the app is not an active broadcast recipient.
13522 private BroadcastQueue isReceivingBroadcast(ProcessRecord app) {
13523 BroadcastRecord r = app.curReceiver;
13524 if (r != null) {
13525 return r.queue;
13526 }
13527
13528 // It's not the current receiver, but it might be starting up to become one
13529 synchronized (this) {
13530 for (BroadcastQueue queue : mBroadcastQueues) {
13531 r = queue.mPendingBroadcast;
13532 if (r != null && r.curApp == app) {
13533 // found it; report which queue it's in
13534 return queue;
13535 }
13536 }
13537 }
13538
13539 return null;
13540 }
13541
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013542 private final int computeOomAdjLocked(ProcessRecord app, int hiddenAdj,
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013543 ProcessRecord TOP_APP, boolean recursed, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013544 if (mAdjSeq == app.adjSeq) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013545 // This adjustment has already been computed. If we are calling
13546 // from the top, we may have already computed our adjustment with
13547 // an earlier hidden adjustment that isn't really for us... if
13548 // so, use the new hidden adjustment.
13549 if (!recursed && app.hidden) {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013550 app.curAdj = app.curRawAdj = app.nonStoppingAdj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013551 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013552 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013553 }
13554
13555 if (app.thread == null) {
13556 app.adjSeq = mAdjSeq;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013557 app.curSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013558 return (app.curAdj=ProcessList.HIDDEN_APP_MAX_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013559 }
13560
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013561 app.adjTypeCode = ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN;
13562 app.adjSource = null;
13563 app.adjTarget = null;
13564 app.empty = false;
13565 app.hidden = false;
13566
13567 final int activitiesSize = app.activities.size();
13568
Dianne Hackborn7d608422011-08-07 16:24:18 -070013569 if (app.maxAdj <= ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013570 // The max adjustment doesn't allow this app to be anything
13571 // below foreground, so it is not worth doing work for it.
13572 app.adjType = "fixed";
13573 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013574 app.curRawAdj = app.nonStoppingAdj = app.maxAdj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013575 app.foregroundActivities = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013576 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013577 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013578 // System process can do UI, and when they do we want to have
13579 // them trim their memory after the user leaves the UI. To
13580 // facilitate this, here we need to determine whether or not it
13581 // is currently showing UI.
13582 app.systemNoUi = true;
13583 if (app == TOP_APP) {
13584 app.systemNoUi = false;
13585 } else if (activitiesSize > 0) {
13586 for (int j = 0; j < activitiesSize; j++) {
13587 final ActivityRecord r = app.activities.get(j);
13588 if (r.visible) {
13589 app.systemNoUi = false;
13590 break;
13591 }
13592 }
13593 }
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013594 return (app.curAdj=app.maxAdj);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013595 }
13596
13597 final boolean hadForegroundActivities = app.foregroundActivities;
13598
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013599 app.foregroundActivities = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013600 app.keeping = false;
13601 app.systemNoUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013602
The Android Open Source Project4df24232009-03-05 14:34:35 -080013603 // Determine the importance of the process, starting with most
13604 // important to least, and assign an appropriate OOM adjustment.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013605 int adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013606 int schedGroup;
Christopher Tatef46723b2012-01-26 14:19:24 -080013607 BroadcastQueue queue;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013608 if (app == TOP_APP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013609 // The last app on the list is the foreground app.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013610 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013611 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013612 app.adjType = "top-activity";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013613 app.foregroundActivities = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013614 } else if (app.instrumentationClass != null) {
13615 // Don't want to kill running instrumentation.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013616 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013617 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013618 app.adjType = "instrumentation";
Christopher Tatef46723b2012-01-26 14:19:24 -080013619 } else if ((queue = isReceivingBroadcast(app)) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013620 // An app that is currently receiving a broadcast also
Christopher Tatef46723b2012-01-26 14:19:24 -080013621 // counts as being in the foreground for OOM killer purposes.
13622 // It's placed in a sched group based on the nature of the
13623 // broadcast as reflected by which queue it's active in.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013624 adj = ProcessList.FOREGROUND_APP_ADJ;
Christopher Tatef46723b2012-01-26 14:19:24 -080013625 schedGroup = (queue == mFgBroadcastQueue)
13626 ? Process.THREAD_GROUP_DEFAULT : Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013627 app.adjType = "broadcast";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013628 } else if (app.executingServices.size() > 0) {
13629 // An app that is currently executing a service callback also
13630 // counts as being in the foreground.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013631 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013632 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013633 app.adjType = "exec-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013634 } else if (activitiesSize > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013635 // This app is in the background with paused activities.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013636 // We inspect activities to potentially upgrade adjustment further below.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013637 adj = hiddenAdj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013638 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013639 app.hidden = true;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013640 app.adjType = "bg-activities";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013641 } else {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013642 // A very not-needed process. If this is lower in the lru list,
13643 // we will push it in to the empty bucket.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013644 adj = hiddenAdj;
13645 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013646 app.hidden = true;
13647 app.empty = true;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013648 app.adjType = "bg-empty";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013649 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013650
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013651 boolean hasStoppingActivities = false;
13652
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013653 // Examine all activities if not already foreground.
13654 if (!app.foregroundActivities && activitiesSize > 0) {
13655 for (int j = 0; j < activitiesSize; j++) {
13656 final ActivityRecord r = app.activities.get(j);
13657 if (r.visible) {
13658 // App has a visible activity; only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013659 if (adj > ProcessList.VISIBLE_APP_ADJ) {
13660 adj = ProcessList.VISIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013661 app.adjType = "visible";
13662 }
13663 schedGroup = Process.THREAD_GROUP_DEFAULT;
13664 app.hidden = false;
13665 app.foregroundActivities = true;
13666 break;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013667 } else if (r.state == ActivityState.PAUSING || r.state == ActivityState.PAUSED) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013668 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13669 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013670 app.adjType = "pausing";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013671 }
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -080013672 app.hidden = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013673 app.foregroundActivities = true;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013674 } else if (r.state == ActivityState.STOPPING) {
13675 // We will apply the actual adjustment later, because
13676 // we want to allow this process to immediately go through
13677 // any memory trimming that is in effect.
13678 app.hidden = false;
13679 app.foregroundActivities = true;
13680 hasStoppingActivities = true;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013681 }
13682 }
13683 }
13684
Dianne Hackborn7d608422011-08-07 16:24:18 -070013685 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013686 if (app.foregroundServices) {
13687 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013688 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013689 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013690 app.adjType = "foreground-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013691 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013692 } else if (app.forcingToForeground != null) {
13693 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013694 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013695 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013696 app.adjType = "force-foreground";
13697 app.adjSource = app.forcingToForeground;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013698 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013699 }
13700 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013701
Dianne Hackborn7d608422011-08-07 16:24:18 -070013702 if (adj > ProcessList.HEAVY_WEIGHT_APP_ADJ && app == mHeavyWeightProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013703 // We don't want to kill the current heavy-weight process.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013704 adj = ProcessList.HEAVY_WEIGHT_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013705 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013706 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013707 app.adjType = "heavy";
13708 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013709
Dianne Hackborn7d608422011-08-07 16:24:18 -070013710 if (adj > ProcessList.HOME_APP_ADJ && app == mHomeProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013711 // This process is hosting what we currently consider to be the
13712 // home app, so we don't want to let it go into the background.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013713 adj = ProcessList.HOME_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013714 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013715 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013716 app.adjType = "home";
13717 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013718
Dianne Hackbornf35fe232011-11-01 19:25:20 -070013719 if (adj > ProcessList.PREVIOUS_APP_ADJ && app == mPreviousProcess
13720 && app.activities.size() > 0) {
13721 // This was the previous process that showed UI to the user.
13722 // We want to try to keep it around more aggressively, to give
13723 // a good experience around switching between two apps.
13724 adj = ProcessList.PREVIOUS_APP_ADJ;
13725 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
13726 app.hidden = false;
13727 app.adjType = "previous";
13728 }
13729
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013730 if (false) Slog.i(TAG, "OOM " + app + ": initial adj=" + adj
13731 + " reason=" + app.adjType);
13732
The Android Open Source Project4df24232009-03-05 14:34:35 -080013733 // By default, we use the computed adjustment. It may be changed if
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013734 // there are applications dependent on our services or providers, but
13735 // this gives us a baseline and makes sure we don't get into an
13736 // infinite recursion.
13737 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013738 app.curRawAdj = app.nonStoppingAdj = adj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013739
Christopher Tate6fa95972009-06-05 18:43:55 -070013740 if (mBackupTarget != null && app == mBackupTarget.app) {
13741 // If possible we want to avoid killing apps while they're being backed up
Dianne Hackborn7d608422011-08-07 16:24:18 -070013742 if (adj > ProcessList.BACKUP_APP_ADJ) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013743 if (DEBUG_BACKUP) Slog.v(TAG, "oom BACKUP_APP_ADJ for " + app);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013744 adj = ProcessList.BACKUP_APP_ADJ;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013745 app.adjType = "backup";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013746 app.hidden = false;
Christopher Tate6fa95972009-06-05 18:43:55 -070013747 }
13748 }
13749
Dianne Hackborn7d608422011-08-07 16:24:18 -070013750 if (app.services.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013751 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013752 final long now = SystemClock.uptimeMillis();
13753 // This process is more important if the top activity is
13754 // bound to the service.
Dianne Hackborn860755f2010-06-03 18:47:52 -070013755 Iterator<ServiceRecord> jt = app.services.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013756 while (jt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013757 ServiceRecord s = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013758 if (s.startRequested) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013759 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013760 // If this process has shown some UI, let it immediately
13761 // go to the LRU list because it may be pretty heavy with
13762 // UI stuff. We'll tag it with a label just to help
13763 // debug and understand what is going on.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013764 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013765 app.adjType = "started-bg-ui-services";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013766 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013767 } else {
13768 if (now < (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
13769 // This service has seen some activity within
13770 // recent memory, so we will keep its process ahead
13771 // of the background processes.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013772 if (adj > ProcessList.SERVICE_ADJ) {
13773 adj = ProcessList.SERVICE_ADJ;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013774 app.adjType = "started-services";
13775 app.hidden = false;
13776 }
13777 }
13778 // If we have let the service slide into the background
13779 // state, still have some text describing what it is doing
13780 // even though the service no longer has an impact.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013781 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013782 app.adjType = "started-bg-services";
13783 }
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080013784 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013785 // Don't kill this process because it is doing work; it
13786 // has said it is doing work.
13787 app.keeping = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013788 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013789 if (s.connections.size() > 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013790 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013791 Iterator<ArrayList<ConnectionRecord>> kt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013792 = s.connections.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013793 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013794 ArrayList<ConnectionRecord> clist = kt.next();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013795 for (int i=0; i<clist.size() && adj > ProcessList.FOREGROUND_APP_ADJ; i++) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013796 // XXX should compute this based on the max of
13797 // all connected clients.
13798 ConnectionRecord cr = clist.get(i);
13799 if (cr.binding.client == app) {
13800 // Binding to ourself is not interesting.
13801 continue;
13802 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013803 if ((cr.flags&Context.BIND_WAIVE_PRIORITY) == 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013804 ProcessRecord client = cr.binding.client;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013805 int clientAdj = adj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013806 int myHiddenAdj = hiddenAdj;
13807 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013808 if (client.hiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013809 myHiddenAdj = client.hiddenAdj;
13810 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013811 myHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013812 }
13813 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013814 clientAdj = computeOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013815 client, myHiddenAdj, TOP_APP, true, doingAll);
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013816 String adjType = null;
13817 if ((cr.flags&Context.BIND_ALLOW_OOM_MANAGEMENT) != 0) {
13818 // Not doing bind OOM management, so treat
13819 // this guy more like a started service.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013820 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013821 // If this process has shown some UI, let it immediately
13822 // go to the LRU list because it may be pretty heavy with
13823 // UI stuff. We'll tag it with a label just to help
13824 // debug and understand what is going on.
13825 if (adj > clientAdj) {
13826 adjType = "bound-bg-ui-services";
13827 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013828 app.hidden = false;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013829 clientAdj = adj;
13830 } else {
13831 if (now >= (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
13832 // This service has not seen activity within
13833 // recent memory, so allow it to drop to the
13834 // LRU list if there is no other reason to keep
13835 // it around. We'll also tag it with a label just
13836 // to help debug and undertand what is going on.
13837 if (adj > clientAdj) {
13838 adjType = "bound-bg-services";
13839 }
13840 clientAdj = adj;
13841 }
13842 }
13843 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013844 if (adj > clientAdj) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013845 // If this process has recently shown UI, and
13846 // the process that is binding to it is less
13847 // important than being visible, then we don't
13848 // care about the binding as much as we care
13849 // about letting this process get into the LRU
13850 // list to be killed and restarted if needed for
13851 // memory.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013852 if (app.hasShownUi && app != mHomeProcess
13853 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013854 adjType = "bound-bg-ui-services";
13855 } else {
13856 if ((cr.flags&(Context.BIND_ABOVE_CLIENT
13857 |Context.BIND_IMPORTANT)) != 0) {
13858 adj = clientAdj;
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070013859 } else if ((cr.flags&Context.BIND_NOT_VISIBLE) != 0
13860 && clientAdj < ProcessList.PERCEPTIBLE_APP_ADJ
13861 && adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13862 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13863 } else if (clientAdj > ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013864 adj = clientAdj;
13865 } else {
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070013866 app.pendingUiClean = true;
13867 if (adj > ProcessList.VISIBLE_APP_ADJ) {
13868 adj = ProcessList.VISIBLE_APP_ADJ;
13869 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013870 }
13871 if (!client.hidden) {
13872 app.hidden = false;
13873 }
13874 if (client.keeping) {
13875 app.keeping = true;
13876 }
13877 adjType = "service";
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013878 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013879 }
13880 if (adjType != null) {
13881 app.adjType = adjType;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013882 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13883 .REASON_SERVICE_IN_USE;
13884 app.adjSource = cr.binding.client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013885 app.adjSourceOom = clientAdj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013886 app.adjTarget = s.name;
13887 }
13888 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
13889 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
13890 schedGroup = Process.THREAD_GROUP_DEFAULT;
13891 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013892 }
13893 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013894 if ((cr.flags&Context.BIND_ADJUST_WITH_ACTIVITY) != 0) {
13895 ActivityRecord a = cr.activity;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013896 if (a != null && adj > ProcessList.FOREGROUND_APP_ADJ &&
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013897 (a.visible || a.state == ActivityState.RESUMED
13898 || a.state == ActivityState.PAUSING)) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013899 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013900 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
13901 schedGroup = Process.THREAD_GROUP_DEFAULT;
13902 }
13903 app.hidden = false;
13904 app.adjType = "service";
13905 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13906 .REASON_SERVICE_IN_USE;
13907 app.adjSource = a;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013908 app.adjSourceOom = adj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013909 app.adjTarget = s.name;
13910 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013911 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013912 }
13913 }
13914 }
13915 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013916
Dianne Hackborn287952c2010-09-22 22:34:31 -070013917 // Finally, if this process has active services running in it, we
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013918 // would like to avoid killing it unless it would prevent the current
13919 // application from running. By default we put the process in
13920 // with the rest of the background processes; as we scan through
13921 // its services we may bump it up from there.
13922 if (adj > hiddenAdj) {
13923 adj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013924 app.hidden = false;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013925 app.adjType = "bg-services";
13926 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013927 }
13928
Dianne Hackborn7d608422011-08-07 16:24:18 -070013929 if (app.pubProviders.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013930 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013931 Iterator<ContentProviderRecord> jt = app.pubProviders.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013932 while (jt.hasNext() && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013933 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013934 ContentProviderRecord cpr = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013935 if (cpr.clients.size() != 0) {
13936 Iterator<ProcessRecord> kt = cpr.clients.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013937 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013938 ProcessRecord client = kt.next();
The Android Open Source Project10592532009-03-18 17:39:46 -070013939 if (client == app) {
13940 // Being our own client is not interesting.
13941 continue;
13942 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013943 int myHiddenAdj = hiddenAdj;
13944 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013945 if (client.hiddenAdj > ProcessList.FOREGROUND_APP_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013946 myHiddenAdj = client.hiddenAdj;
13947 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013948 myHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013949 }
13950 }
13951 int clientAdj = computeOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013952 client, myHiddenAdj, TOP_APP, true, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013953 if (adj > clientAdj) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013954 if (app.hasShownUi && app != mHomeProcess
13955 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013956 app.adjType = "bg-ui-provider";
13957 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013958 adj = clientAdj > ProcessList.FOREGROUND_APP_ADJ
13959 ? clientAdj : ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013960 app.adjType = "provider";
13961 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013962 if (!client.hidden) {
13963 app.hidden = false;
13964 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013965 if (client.keeping) {
13966 app.keeping = true;
13967 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070013968 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13969 .REASON_PROVIDER_IN_USE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013970 app.adjSource = client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013971 app.adjSourceOom = clientAdj;
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070013972 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013973 }
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013974 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
13975 schedGroup = Process.THREAD_GROUP_DEFAULT;
13976 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013977 }
13978 }
13979 // If the provider has external (non-framework) process
13980 // dependencies, ensure that its adjustment is at least
13981 // FOREGROUND_APP_ADJ.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080013982 if (cpr.hasExternalProcessHandles()) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013983 if (adj > ProcessList.FOREGROUND_APP_ADJ) {
13984 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013985 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013986 app.hidden = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013987 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013988 app.adjType = "provider";
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070013989 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013990 }
13991 }
13992 }
13993 }
13994
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013995 if (adj == ProcessList.SERVICE_ADJ) {
13996 if (doingAll) {
13997 app.serviceb = mNewNumServiceProcs > (mNumServiceProcs/3);
13998 mNewNumServiceProcs++;
13999 }
14000 if (app.serviceb) {
14001 adj = ProcessList.SERVICE_B_ADJ;
14002 }
14003 } else {
14004 app.serviceb = false;
14005 }
14006
14007 app.nonStoppingAdj = adj;
14008
14009 if (hasStoppingActivities) {
14010 // Only upgrade adjustment.
14011 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
14012 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
14013 app.adjType = "stopping";
14014 }
14015 }
14016
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014017 app.curRawAdj = adj;
14018
Joe Onorato8a9b2202010-02-26 18:56:32 -080014019 //Slog.i(TAG, "OOM ADJ " + app + ": pid=" + app.pid +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014020 // " adj=" + adj + " curAdj=" + app.curAdj + " maxAdj=" + app.maxAdj);
14021 if (adj > app.maxAdj) {
14022 adj = app.maxAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070014023 if (app.maxAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014024 schedGroup = Process.THREAD_GROUP_DEFAULT;
14025 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014026 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070014027 if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070014028 app.keeping = true;
14029 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014030
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014031 if (app.hasAboveClient) {
14032 // If this process has bound to any services with BIND_ABOVE_CLIENT,
14033 // then we need to drop its adjustment to be lower than the service's
14034 // in order to honor the request. We want to drop it by one adjustment
14035 // level... but there is special meaning applied to various levels so
14036 // we will skip some of them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014037 if (adj < ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014038 // System process will not get dropped, ever
Dianne Hackborn7d608422011-08-07 16:24:18 -070014039 } else if (adj < ProcessList.VISIBLE_APP_ADJ) {
14040 adj = ProcessList.VISIBLE_APP_ADJ;
14041 } else if (adj < ProcessList.PERCEPTIBLE_APP_ADJ) {
14042 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
14043 } else if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
14044 adj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014045 } else if (adj < ProcessList.HIDDEN_APP_MAX_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014046 adj++;
14047 }
14048 }
14049
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014050 app.curAdj = adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014051 app.curSchedGroup = schedGroup;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070014052
14053 if (hadForegroundActivities != app.foregroundActivities) {
Jeff Sharkey287bd832011-05-28 19:36:26 -070014054 mHandler.obtainMessage(DISPATCH_FOREGROUND_ACTIVITIES_CHANGED, app.pid, app.info.uid,
14055 app.foregroundActivities).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070014056 }
14057
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014058 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014059 }
14060
14061 /**
14062 * Ask a given process to GC right now.
14063 */
14064 final void performAppGcLocked(ProcessRecord app) {
14065 try {
14066 app.lastRequestedGc = SystemClock.uptimeMillis();
14067 if (app.thread != null) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014068 if (app.reportLowMemory) {
14069 app.reportLowMemory = false;
14070 app.thread.scheduleLowMemory();
14071 } else {
14072 app.thread.processInBackground();
14073 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014074 }
14075 } catch (Exception e) {
14076 // whatever.
14077 }
14078 }
14079
14080 /**
14081 * Returns true if things are idle enough to perform GCs.
14082 */
Josh Bartel7f208742010-02-25 11:01:44 -060014083 private final boolean canGcNowLocked() {
Christopher Tatef46723b2012-01-26 14:19:24 -080014084 boolean processingBroadcasts = false;
14085 for (BroadcastQueue q : mBroadcastQueues) {
14086 if (q.mParallelBroadcasts.size() != 0 || q.mOrderedBroadcasts.size() != 0) {
14087 processingBroadcasts = true;
14088 }
14089 }
14090 return !processingBroadcasts
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014091 && (mSleeping || (mMainStack.mResumedActivity != null &&
14092 mMainStack.mResumedActivity.idle));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014093 }
14094
14095 /**
14096 * Perform GCs on all processes that are waiting for it, but only
14097 * if things are idle.
14098 */
14099 final void performAppGcsLocked() {
14100 final int N = mProcessesToGc.size();
14101 if (N <= 0) {
14102 return;
14103 }
Josh Bartel7f208742010-02-25 11:01:44 -060014104 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014105 while (mProcessesToGc.size() > 0) {
14106 ProcessRecord proc = mProcessesToGc.remove(0);
Dianne Hackborn7d608422011-08-07 16:24:18 -070014107 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014108 if ((proc.lastRequestedGc+GC_MIN_INTERVAL)
14109 <= SystemClock.uptimeMillis()) {
14110 // To avoid spamming the system, we will GC processes one
14111 // at a time, waiting a few seconds between each.
14112 performAppGcLocked(proc);
14113 scheduleAppGcsLocked();
14114 return;
14115 } else {
14116 // It hasn't been long enough since we last GCed this
14117 // process... put it in the list to wait for its time.
14118 addProcessToGcListLocked(proc);
14119 break;
14120 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014121 }
14122 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014123
14124 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014125 }
14126 }
14127
14128 /**
14129 * If all looks good, perform GCs on all processes waiting for them.
14130 */
14131 final void performAppGcsIfAppropriateLocked() {
Josh Bartel7f208742010-02-25 11:01:44 -060014132 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014133 performAppGcsLocked();
14134 return;
14135 }
14136 // Still not idle, wait some more.
14137 scheduleAppGcsLocked();
14138 }
14139
14140 /**
14141 * Schedule the execution of all pending app GCs.
14142 */
14143 final void scheduleAppGcsLocked() {
14144 mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014145
14146 if (mProcessesToGc.size() > 0) {
14147 // Schedule a GC for the time to the next process.
14148 ProcessRecord proc = mProcessesToGc.get(0);
14149 Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG);
14150
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014151 long when = proc.lastRequestedGc + GC_MIN_INTERVAL;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014152 long now = SystemClock.uptimeMillis();
14153 if (when < (now+GC_TIMEOUT)) {
14154 when = now + GC_TIMEOUT;
14155 }
14156 mHandler.sendMessageAtTime(msg, when);
14157 }
14158 }
14159
14160 /**
14161 * Add a process to the array of processes waiting to be GCed. Keeps the
14162 * list in sorted order by the last GC time. The process can't already be
14163 * on the list.
14164 */
14165 final void addProcessToGcListLocked(ProcessRecord proc) {
14166 boolean added = false;
14167 for (int i=mProcessesToGc.size()-1; i>=0; i--) {
14168 if (mProcessesToGc.get(i).lastRequestedGc <
14169 proc.lastRequestedGc) {
14170 added = true;
14171 mProcessesToGc.add(i+1, proc);
14172 break;
14173 }
14174 }
14175 if (!added) {
14176 mProcessesToGc.add(0, proc);
14177 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014178 }
14179
14180 /**
14181 * Set up to ask a process to GC itself. This will either do it
14182 * immediately, or put it on the list of processes to gc the next
14183 * time things are idle.
14184 */
14185 final void scheduleAppGcLocked(ProcessRecord app) {
14186 long now = SystemClock.uptimeMillis();
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014187 if ((app.lastRequestedGc+GC_MIN_INTERVAL) > now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014188 return;
14189 }
14190 if (!mProcessesToGc.contains(app)) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014191 addProcessToGcListLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014192 scheduleAppGcsLocked();
14193 }
14194 }
14195
Dianne Hackborn287952c2010-09-22 22:34:31 -070014196 final void checkExcessivePowerUsageLocked(boolean doKills) {
14197 updateCpuStatsNow();
14198
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014199 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborn287952c2010-09-22 22:34:31 -070014200 boolean doWakeKills = doKills;
14201 boolean doCpuKills = doKills;
14202 if (mLastPowerCheckRealtime == 0) {
14203 doWakeKills = false;
14204 }
14205 if (mLastPowerCheckUptime == 0) {
14206 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014207 }
14208 if (stats.isScreenOn()) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070014209 doWakeKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014210 }
14211 final long curRealtime = SystemClock.elapsedRealtime();
Dianne Hackborn287952c2010-09-22 22:34:31 -070014212 final long realtimeSince = curRealtime - mLastPowerCheckRealtime;
14213 final long curUptime = SystemClock.uptimeMillis();
14214 final long uptimeSince = curUptime - mLastPowerCheckUptime;
14215 mLastPowerCheckRealtime = curRealtime;
14216 mLastPowerCheckUptime = curUptime;
14217 if (realtimeSince < WAKE_LOCK_MIN_CHECK_DURATION) {
14218 doWakeKills = false;
14219 }
14220 if (uptimeSince < CPU_MIN_CHECK_DURATION) {
14221 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014222 }
14223 int i = mLruProcesses.size();
14224 while (i > 0) {
14225 i--;
14226 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn287952c2010-09-22 22:34:31 -070014227 if (!app.keeping) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014228 long wtime;
14229 synchronized (stats) {
14230 wtime = stats.getProcessWakeTime(app.info.uid,
14231 app.pid, curRealtime);
14232 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070014233 long wtimeUsed = wtime - app.lastWakeTime;
14234 long cputimeUsed = app.curCpuTime - app.lastCpuTime;
14235 if (DEBUG_POWER) {
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014236 StringBuilder sb = new StringBuilder(128);
14237 sb.append("Wake for ");
14238 app.toShortString(sb);
14239 sb.append(": over ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070014240 TimeUtils.formatDuration(realtimeSince, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014241 sb.append(" used ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070014242 TimeUtils.formatDuration(wtimeUsed, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014243 sb.append(" (");
Dianne Hackborn287952c2010-09-22 22:34:31 -070014244 sb.append((wtimeUsed*100)/realtimeSince);
14245 sb.append("%)");
14246 Slog.i(TAG, sb.toString());
14247 sb.setLength(0);
14248 sb.append("CPU for ");
14249 app.toShortString(sb);
14250 sb.append(": over ");
14251 TimeUtils.formatDuration(uptimeSince, sb);
14252 sb.append(" used ");
14253 TimeUtils.formatDuration(cputimeUsed, sb);
14254 sb.append(" (");
14255 sb.append((cputimeUsed*100)/uptimeSince);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014256 sb.append("%)");
14257 Slog.i(TAG, sb.toString());
14258 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014259 // If a process has held a wake lock for more
14260 // than 50% of the time during this period,
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014261 // that sounds bad. Kill!
Dianne Hackborn287952c2010-09-22 22:34:31 -070014262 if (doWakeKills && realtimeSince > 0
14263 && ((wtimeUsed*100)/realtimeSince) >= 50) {
14264 synchronized (stats) {
14265 stats.reportExcessiveWakeLocked(app.info.uid, app.processName,
14266 realtimeSince, wtimeUsed);
14267 }
14268 Slog.w(TAG, "Excessive wake lock in " + app.processName
14269 + " (pid " + app.pid + "): held " + wtimeUsed
14270 + " during " + realtimeSince);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014271 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14272 app.processName, app.setAdj, "excessive wake lock");
14273 Process.killProcessQuiet(app.pid);
Dianne Hackborn287952c2010-09-22 22:34:31 -070014274 } else if (doCpuKills && uptimeSince > 0
14275 && ((cputimeUsed*100)/uptimeSince) >= 50) {
14276 synchronized (stats) {
14277 stats.reportExcessiveCpuLocked(app.info.uid, app.processName,
14278 uptimeSince, cputimeUsed);
14279 }
14280 Slog.w(TAG, "Excessive CPU in " + app.processName
14281 + " (pid " + app.pid + "): used " + cputimeUsed
14282 + " during " + uptimeSince);
14283 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14284 app.processName, app.setAdj, "excessive cpu");
14285 Process.killProcessQuiet(app.pid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014286 } else {
14287 app.lastWakeTime = wtime;
Dianne Hackborn287952c2010-09-22 22:34:31 -070014288 app.lastCpuTime = app.curCpuTime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014289 }
14290 }
14291 }
14292 }
14293
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014294 private final boolean updateOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014295 ProcessRecord app, int hiddenAdj, ProcessRecord TOP_APP, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014296 app.hiddenAdj = hiddenAdj;
14297
14298 if (app.thread == null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014299 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014300 }
14301
Dianne Hackborn287952c2010-09-22 22:34:31 -070014302 final boolean wasKeeping = app.keeping;
14303
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014304 boolean success = true;
14305
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014306 computeOomAdjLocked(app, hiddenAdj, TOP_APP, false, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014307
Jeff Brown10e89712011-07-08 18:52:57 -070014308 if (app.curRawAdj != app.setRawAdj) {
Jeff Brown10e89712011-07-08 18:52:57 -070014309 if (wasKeeping && !app.keeping) {
14310 // This app is no longer something we want to keep. Note
14311 // its current wake lock time to later know to kill it if
14312 // it is not behaving well.
14313 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
14314 synchronized (stats) {
14315 app.lastWakeTime = stats.getProcessWakeTime(app.info.uid,
14316 app.pid, SystemClock.elapsedRealtime());
14317 }
14318 app.lastCpuTime = app.curCpuTime;
14319 }
14320
14321 app.setRawAdj = app.curRawAdj;
14322 }
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014323
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014324 if (app.curAdj != app.setAdj) {
14325 if (Process.setOomAdj(app.pid, app.curAdj)) {
Dianne Hackbornbbb09ac2011-11-30 11:31:29 -080014326 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014327 TAG, "Set " + app.pid + " " + app.processName +
14328 " adj " + app.curAdj + ": " + app.adjType);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014329 app.setAdj = app.curAdj;
Jeff Brown10e89712011-07-08 18:52:57 -070014330 } else {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014331 success = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014332 Slog.w(TAG, "Failed setting oom adj of " + app + " to " + app.curAdj);
Jeff Brown10e89712011-07-08 18:52:57 -070014333 }
14334 }
14335 if (app.setSchedGroup != app.curSchedGroup) {
14336 app.setSchedGroup = app.curSchedGroup;
14337 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
14338 "Setting process group of " + app.processName
14339 + " to " + app.curSchedGroup);
14340 if (app.waitingToKill != null &&
14341 app.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
14342 Slog.i(TAG, "Killing " + app.toShortString() + ": " + app.waitingToKill);
14343 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14344 app.processName, app.setAdj, app.waitingToKill);
14345 Process.killProcessQuiet(app.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014346 success = false;
Jeff Brown10e89712011-07-08 18:52:57 -070014347 } else {
14348 if (true) {
14349 long oldId = Binder.clearCallingIdentity();
14350 try {
14351 Process.setProcessGroup(app.pid, app.curSchedGroup);
14352 } catch (Exception e) {
14353 Slog.w(TAG, "Failed setting process group of " + app.pid
14354 + " to " + app.curSchedGroup);
14355 e.printStackTrace();
14356 } finally {
14357 Binder.restoreCallingIdentity(oldId);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014358 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014359 } else {
Jeff Brown10e89712011-07-08 18:52:57 -070014360 if (app.thread != null) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070014361 try {
Jeff Brown10e89712011-07-08 18:52:57 -070014362 app.thread.setSchedulingGroup(app.curSchedGroup);
14363 } catch (RemoteException e) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070014364 }
14365 }
14366 }
14367 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014368 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014369 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014370 }
14371
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014372 private final ActivityRecord resumedAppLocked() {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014373 ActivityRecord resumedActivity = mMainStack.mResumedActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014374 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -080014375 resumedActivity = mMainStack.mPausingActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014376 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014377 resumedActivity = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014378 }
14379 }
14380 return resumedActivity;
14381 }
14382
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014383 private final boolean updateOomAdjLocked(ProcessRecord app) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014384 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014385 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
14386 int curAdj = app.curAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070014387 final boolean wasHidden = curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
14388 && curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014389
14390 mAdjSeq++;
14391
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014392 boolean success = updateOomAdjLocked(app, app.hiddenAdj, TOP_APP, false);
Dianne Hackborn7d608422011-08-07 16:24:18 -070014393 final boolean nowHidden = app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
14394 && app.curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014395 if (nowHidden != wasHidden) {
14396 // Changed to/from hidden state, so apps after it in the LRU
14397 // list may also be changed.
14398 updateOomAdjLocked();
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 Hackbornce86ba82011-07-13 19:33:41 -070014403 final void updateOomAdjLocked() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014404 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014405 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
14406
14407 if (false) {
14408 RuntimeException e = new RuntimeException();
14409 e.fillInStackTrace();
Joe Onorato8a9b2202010-02-26 18:56:32 -080014410 Slog.i(TAG, "updateOomAdj: top=" + TOP_ACT, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014411 }
14412
14413 mAdjSeq++;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014414 mNewNumServiceProcs = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014415
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014416 // Let's determine how many processes we have running vs.
14417 // how many slots we have for background processes; we may want
14418 // to put multiple processes in a slot of there are enough of
14419 // them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014420 int numSlots = ProcessList.HIDDEN_APP_MAX_ADJ - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014421 int factor = (mLruProcesses.size()-4)/numSlots;
14422 if (factor < 1) factor = 1;
14423 int step = 0;
Dianne Hackborn8633e682010-04-22 16:03:41 -070014424 int numHidden = 0;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014425 int numTrimming = 0;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014426
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014427 // First update the OOM adjustment for each of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014428 // application processes based on their current state.
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014429 int i = mLruProcesses.size();
Dianne Hackborn7d608422011-08-07 16:24:18 -070014430 int curHiddenAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014431 while (i > 0) {
14432 i--;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014433 ProcessRecord app = mLruProcesses.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080014434 //Slog.i(TAG, "OOM " + app + ": cur hidden=" + curHiddenAdj);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014435 updateOomAdjLocked(app, curHiddenAdj, TOP_APP, true);
14436 if (curHiddenAdj < ProcessList.HIDDEN_APP_MAX_ADJ
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014437 && app.curAdj == curHiddenAdj) {
14438 step++;
14439 if (step >= factor) {
14440 step = 0;
14441 curHiddenAdj++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014442 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014443 }
14444 if (!app.killedBackground) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070014445 if (app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014446 numHidden++;
14447 if (numHidden > mProcessLimit) {
14448 Slog.i(TAG, "No longer want " + app.processName
14449 + " (pid " + app.pid + "): hidden #" + numHidden);
14450 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14451 app.processName, app.setAdj, "too many background");
14452 app.killedBackground = true;
14453 Process.killProcessQuiet(app.pid);
Dianne Hackborn8633e682010-04-22 16:03:41 -070014454 }
14455 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -080014456 if (!app.killedBackground && app.isolated && app.services.size() <= 0) {
14457 // If this is an isolated process, and there are no
14458 // services running in it, then the process is no longer
14459 // needed. We agressively kill these because we can by
14460 // definition not re-use the same process again, and it is
14461 // good to avoid having whatever code was running in them
14462 // left sitting around after no longer needed.
14463 Slog.i(TAG, "Isolated process " + app.processName
14464 + " (pid " + app.pid + ") no longer needed");
14465 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14466 app.processName, app.setAdj, "isolated not needed");
14467 app.killedBackground = true;
14468 Process.killProcessQuiet(app.pid);
14469 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014470 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
14471 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
14472 && !app.killedBackground) {
14473 numTrimming++;
14474 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014475 }
14476 }
14477
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014478 mNumServiceProcs = mNewNumServiceProcs;
14479
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014480 // Now determine the memory trimming level of background processes.
14481 // Unfortunately we need to start at the back of the list to do this
14482 // properly. We only do this if the number of background apps we
14483 // are managing to keep around is less than half the maximum we desire;
14484 // if we are keeping a good number around, we'll let them use whatever
14485 // memory they want.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014486 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/2)) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014487 final int N = mLruProcesses.size();
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014488 factor = numTrimming/3;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080014489 int minFactor = 2;
14490 if (mHomeProcess != null) minFactor++;
14491 if (mPreviousProcess != null) minFactor++;
14492 if (factor < minFactor) factor = minFactor;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014493 step = 0;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014494 int fgTrimLevel;
14495 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/5)) {
14496 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL;
14497 } else if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/3)) {
14498 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW;
14499 } else {
14500 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE;
14501 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014502 int curLevel = ComponentCallbacks2.TRIM_MEMORY_COMPLETE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014503 for (i=0; i<N; i++) {
14504 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014505 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
14506 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080014507 && !app.killedBackground) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014508 if (app.trimMemoryLevel < curLevel && app.thread != null) {
14509 try {
14510 app.thread.scheduleTrimMemory(curLevel);
14511 } catch (RemoteException e) {
14512 }
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080014513 if (false) {
14514 // For now we won't do this; our memory trimming seems
14515 // to be good enough at this point that destroying
14516 // activities causes more harm than good.
14517 if (curLevel >= ComponentCallbacks2.TRIM_MEMORY_COMPLETE
14518 && app != mHomeProcess && app != mPreviousProcess) {
14519 // For these apps we will also finish their activities
14520 // to help them free memory.
14521 mMainStack.destroyActivitiesLocked(app, false, "trim");
14522 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014523 }
14524 }
14525 app.trimMemoryLevel = curLevel;
14526 step++;
14527 if (step >= factor) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014528 step = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014529 switch (curLevel) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014530 case ComponentCallbacks2.TRIM_MEMORY_COMPLETE:
14531 curLevel = ComponentCallbacks2.TRIM_MEMORY_MODERATE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014532 break;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014533 case ComponentCallbacks2.TRIM_MEMORY_MODERATE:
14534 curLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014535 break;
14536 }
14537 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014538 } else if (app.nonStoppingAdj == ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014539 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014540 && app.thread != null) {
14541 try {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014542 app.thread.scheduleTrimMemory(
14543 ComponentCallbacks2.TRIM_MEMORY_BACKGROUND);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014544 } catch (RemoteException e) {
14545 }
14546 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014547 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014548 } else {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014549 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014550 && app.pendingUiClean) {
14551 // If this application is now in the background and it
14552 // had done UI, then give it the special trim level to
14553 // have it free UI resources.
14554 final int level = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
14555 if (app.trimMemoryLevel < level && app.thread != null) {
14556 try {
14557 app.thread.scheduleTrimMemory(level);
14558 } catch (RemoteException e) {
14559 }
14560 }
14561 app.pendingUiClean = false;
14562 }
14563 if (app.trimMemoryLevel < fgTrimLevel && app.thread != null) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014564 try {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014565 app.thread.scheduleTrimMemory(fgTrimLevel);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014566 } catch (RemoteException e) {
14567 }
14568 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014569 app.trimMemoryLevel = fgTrimLevel;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014570 }
14571 }
14572 } else {
14573 final int N = mLruProcesses.size();
14574 for (i=0; i<N; i++) {
14575 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014576 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014577 && app.pendingUiClean) {
14578 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
14579 && app.thread != null) {
14580 try {
14581 app.thread.scheduleTrimMemory(
14582 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
14583 } catch (RemoteException e) {
14584 }
14585 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014586 app.pendingUiClean = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014587 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014588 app.trimMemoryLevel = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014589 }
14590 }
14591
14592 if (mAlwaysFinishActivities) {
Dianne Hackborn28695e02011-11-02 21:59:51 -070014593 mMainStack.destroyActivitiesLocked(null, false, "always-finish");
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014594 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014595 }
14596
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014597 final void trimApplications() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014598 synchronized (this) {
14599 int i;
14600
14601 // First remove any unused application processes whose package
14602 // has been removed.
14603 for (i=mRemovedProcesses.size()-1; i>=0; i--) {
14604 final ProcessRecord app = mRemovedProcesses.get(i);
14605 if (app.activities.size() == 0
14606 && app.curReceiver == null && app.services.size() == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080014607 Slog.i(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014608 TAG, "Exiting empty application process "
14609 + app.processName + " ("
14610 + (app.thread != null ? app.thread.asBinder() : null)
14611 + ")\n");
14612 if (app.pid > 0 && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070014613 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14614 app.processName, app.setAdj, "empty");
14615 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014616 } else {
14617 try {
14618 app.thread.scheduleExit();
14619 } catch (Exception e) {
14620 // Ignore exceptions.
14621 }
14622 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070014623 cleanUpApplicationRecordLocked(app, false, true, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014624 mRemovedProcesses.remove(i);
14625
14626 if (app.persistent) {
14627 if (app.persistent) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080014628 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014629 }
14630 }
14631 }
14632 }
14633
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014634 // Now update the oom adj for all processes.
14635 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014636 }
14637 }
14638
14639 /** This method sends the specified signal to each of the persistent apps */
14640 public void signalPersistentProcesses(int sig) throws RemoteException {
14641 if (sig != Process.SIGNAL_USR1) {
14642 throw new SecurityException("Only SIGNAL_USR1 is allowed");
14643 }
14644
14645 synchronized (this) {
14646 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
14647 != PackageManager.PERMISSION_GRANTED) {
14648 throw new SecurityException("Requires permission "
14649 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
14650 }
14651
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014652 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
14653 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014654 if (r.thread != null && r.persistent) {
14655 Process.sendSignal(r.pid, sig);
14656 }
14657 }
14658 }
14659 }
14660
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014661 private void stopProfilerLocked(ProcessRecord proc, String path, int profileType) {
14662 if (proc == null || proc == mProfileProc) {
14663 proc = mProfileProc;
14664 path = mProfileFile;
14665 profileType = mProfileType;
14666 clearProfilerLocked();
14667 }
14668 if (proc == null) {
14669 return;
14670 }
14671 try {
14672 proc.thread.profilerControl(false, path, null, profileType);
14673 } catch (RemoteException e) {
14674 throw new IllegalStateException("Process disappeared");
14675 }
14676 }
14677
14678 private void clearProfilerLocked() {
14679 if (mProfileFd != null) {
14680 try {
14681 mProfileFd.close();
14682 } catch (IOException e) {
14683 }
14684 }
14685 mProfileApp = null;
14686 mProfileProc = null;
14687 mProfileFile = null;
14688 mProfileType = 0;
14689 mAutoStopProfiler = false;
14690 }
14691
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014692 public boolean profileControl(String process, boolean start,
Romain Guy7eabe552011-07-21 14:56:34 -070014693 String path, ParcelFileDescriptor fd, int profileType) throws RemoteException {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014694
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014695 try {
14696 synchronized (this) {
14697 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14698 // its own permission.
14699 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14700 != PackageManager.PERMISSION_GRANTED) {
14701 throw new SecurityException("Requires permission "
14702 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014703 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014704
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014705 if (start && fd == null) {
14706 throw new IllegalArgumentException("null fd");
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014707 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014708
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014709 ProcessRecord proc = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014710 if (process != null) {
14711 try {
14712 int pid = Integer.parseInt(process);
14713 synchronized (mPidsSelfLocked) {
14714 proc = mPidsSelfLocked.get(pid);
14715 }
14716 } catch (NumberFormatException e) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014717 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014718
14719 if (proc == null) {
14720 HashMap<String, SparseArray<ProcessRecord>> all
14721 = mProcessNames.getMap();
14722 SparseArray<ProcessRecord> procs = all.get(process);
14723 if (procs != null && procs.size() > 0) {
14724 proc = procs.valueAt(0);
14725 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014726 }
14727 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014728
14729 if (start && (proc == null || proc.thread == null)) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014730 throw new IllegalArgumentException("Unknown process: " + process);
14731 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014732
14733 if (start) {
14734 stopProfilerLocked(null, null, 0);
14735 setProfileApp(proc.info, proc.processName, path, fd, false);
14736 mProfileProc = proc;
14737 mProfileType = profileType;
14738 try {
14739 fd = fd.dup();
14740 } catch (IOException e) {
14741 fd = null;
14742 }
14743 proc.thread.profilerControl(start, path, fd, profileType);
14744 fd = null;
14745 mProfileFd = null;
14746 } else {
14747 stopProfilerLocked(proc, path, profileType);
14748 if (fd != null) {
14749 try {
14750 fd.close();
14751 } catch (IOException e) {
14752 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014753 }
14754 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014755
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014756 return true;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014757 }
14758 } catch (RemoteException e) {
14759 throw new IllegalStateException("Process disappeared");
14760 } finally {
14761 if (fd != null) {
14762 try {
14763 fd.close();
14764 } catch (IOException e) {
14765 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014766 }
14767 }
14768 }
Andy McFadden824c5102010-07-09 16:26:57 -070014769
14770 public boolean dumpHeap(String process, boolean managed,
14771 String path, ParcelFileDescriptor fd) throws RemoteException {
14772
14773 try {
14774 synchronized (this) {
14775 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14776 // its own permission (same as profileControl).
14777 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14778 != PackageManager.PERMISSION_GRANTED) {
14779 throw new SecurityException("Requires permission "
14780 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
14781 }
14782
14783 if (fd == null) {
14784 throw new IllegalArgumentException("null fd");
14785 }
14786
14787 ProcessRecord proc = null;
14788 try {
14789 int pid = Integer.parseInt(process);
14790 synchronized (mPidsSelfLocked) {
14791 proc = mPidsSelfLocked.get(pid);
14792 }
14793 } catch (NumberFormatException e) {
14794 }
14795
14796 if (proc == null) {
14797 HashMap<String, SparseArray<ProcessRecord>> all
14798 = mProcessNames.getMap();
14799 SparseArray<ProcessRecord> procs = all.get(process);
14800 if (procs != null && procs.size() > 0) {
14801 proc = procs.valueAt(0);
14802 }
14803 }
14804
14805 if (proc == null || proc.thread == null) {
14806 throw new IllegalArgumentException("Unknown process: " + process);
14807 }
14808
Dianne Hackbornf02e57b2011-03-01 22:21:04 -080014809 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
14810 if (!isDebuggable) {
Andy McFadden824c5102010-07-09 16:26:57 -070014811 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
14812 throw new SecurityException("Process not debuggable: " + proc);
14813 }
14814 }
14815
14816 proc.thread.dumpHeap(managed, path, fd);
14817 fd = null;
14818 return true;
14819 }
14820 } catch (RemoteException e) {
14821 throw new IllegalStateException("Process disappeared");
14822 } finally {
14823 if (fd != null) {
14824 try {
14825 fd.close();
14826 } catch (IOException e) {
14827 }
14828 }
14829 }
14830 }
14831
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014832 /** In this method we try to acquire our lock to make sure that we have not deadlocked */
14833 public void monitor() {
14834 synchronized (this) { }
14835 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014836
Dianne Hackborna573f6a2012-02-09 16:12:18 -080014837 void onCoreSettingsChange(Bundle settings) {
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014838 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
14839 ProcessRecord processRecord = mLruProcesses.get(i);
14840 try {
14841 if (processRecord.thread != null) {
14842 processRecord.thread.setCoreSettings(settings);
14843 }
14844 } catch (RemoteException re) {
14845 /* ignore */
14846 }
14847 }
14848 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014849
14850 // Multi-user methods
14851
Amith Yamasani742a6712011-05-04 14:49:28 -070014852 private int mCurrentUserId;
14853 private SparseIntArray mLoggedInUsers = new SparseIntArray(5);
14854
14855 public boolean switchUser(int userId) {
14856 final int callingUid = Binder.getCallingUid();
14857 if (callingUid != 0 && callingUid != Process.myUid()) {
14858 Slog.e(TAG, "Trying to switch user from unauthorized app");
14859 return false;
14860 }
14861 if (mCurrentUserId == userId)
14862 return true;
14863
14864 synchronized (this) {
14865 // Check if user is already logged in, otherwise check if user exists first before
14866 // adding to the list of logged in users.
14867 if (mLoggedInUsers.indexOfKey(userId) < 0) {
14868 if (!userExists(userId)) {
14869 return false;
14870 }
14871 mLoggedInUsers.append(userId, userId);
14872 }
14873
14874 mCurrentUserId = userId;
14875 boolean haveActivities = mMainStack.switchUser(userId);
14876 if (!haveActivities) {
14877 startHomeActivityLocked(userId);
14878 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014879
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014880 }
Amith Yamasani13593602012-03-22 16:16:17 -070014881
14882 // Inform of user switch
14883 Intent addedIntent = new Intent(Intent.ACTION_USER_SWITCHED);
14884 addedIntent.putExtra(Intent.EXTRA_USERID, userId);
14885 mContext.sendBroadcast(addedIntent, android.Manifest.permission.MANAGE_ACCOUNTS);
14886
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014887 return true;
14888 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014889
Amith Yamasani52f1d752012-03-28 18:19:29 -070014890 @Override
14891 public UserInfo getCurrentUser() throws RemoteException {
14892 final int callingUid = Binder.getCallingUid();
14893 if (callingUid != 0 && callingUid != Process.myUid()) {
14894 Slog.e(TAG, "Trying to get user from unauthorized app");
14895 return null;
14896 }
14897 return AppGlobals.getPackageManager().getUser(mCurrentUserId);
14898 }
14899
Amith Yamasani13593602012-03-22 16:16:17 -070014900 private void onUserRemoved(Intent intent) {
14901 int extraUserId = intent.getIntExtra(Intent.EXTRA_USERID, -1);
14902 if (extraUserId < 1) return;
14903
14904 // Kill all the processes for the user
14905 ArrayList<Pair<String, Integer>> pkgAndUids = new ArrayList<Pair<String,Integer>>();
14906 synchronized (this) {
14907 HashMap<String,SparseArray<ProcessRecord>> map = mProcessNames.getMap();
14908 for (Entry<String, SparseArray<ProcessRecord>> uidMap : map.entrySet()) {
14909 SparseArray<ProcessRecord> uids = uidMap.getValue();
14910 for (int i = 0; i < uids.size(); i++) {
14911 if (UserId.getUserId(uids.keyAt(i)) == extraUserId) {
14912 pkgAndUids.add(new Pair<String,Integer>(uidMap.getKey(), uids.keyAt(i)));
14913 }
14914 }
14915 }
14916
14917 for (Pair<String,Integer> pkgAndUid : pkgAndUids) {
14918 forceStopPackageLocked(pkgAndUid.first, pkgAndUid.second,
14919 false, false, true, true, extraUserId);
14920 }
14921 }
14922 }
14923
Amith Yamasani742a6712011-05-04 14:49:28 -070014924 private boolean userExists(int userId) {
14925 try {
Amith Yamasani13593602012-03-22 16:16:17 -070014926 UserInfo user = AppGlobals.getPackageManager().getUser(userId);
14927 return user != null;
Amith Yamasani742a6712011-05-04 14:49:28 -070014928 } catch (RemoteException re) {
14929 // Won't happen, in same process
14930 }
14931
14932 return false;
14933 }
14934
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014935 private void checkValidCaller(int uid, int userId) {
14936 if (UserId.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) return;
14937
14938 throw new SecurityException("Caller uid=" + uid
14939 + " is not privileged to communicate with user=" + userId);
14940 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014941
14942 private int applyUserId(int uid, int userId) {
14943 return UserId.getUid(userId, uid);
14944 }
14945
14946 private ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080014947 if (info == null) return null;
Amith Yamasani742a6712011-05-04 14:49:28 -070014948 ApplicationInfo newInfo = new ApplicationInfo(info);
14949 newInfo.uid = applyUserId(info.uid, userId);
Amith Yamasania4a54e22012-04-16 15:44:19 -070014950 newInfo.dataDir = USER_DATA_DIR + userId + "/"
14951 + info.packageName;
Amith Yamasani742a6712011-05-04 14:49:28 -070014952 return newInfo;
14953 }
14954
14955 ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) {
Amith Yamasania4a54e22012-04-16 15:44:19 -070014956 if (aInfo == null
14957 || (userId < 1 && aInfo.applicationInfo.uid < UserId.PER_USER_RANGE)) {
Amith Yamasani742a6712011-05-04 14:49:28 -070014958 return aInfo;
14959 }
14960
14961 ActivityInfo info = new ActivityInfo(aInfo);
14962 info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId);
14963 return info;
14964 }
14965
14966 static class ServiceMap {
14967
14968 private final SparseArray<HashMap<ComponentName, ServiceRecord>> mServicesByNamePerUser
14969 = new SparseArray<HashMap<ComponentName, ServiceRecord>>();
14970 private final SparseArray<HashMap<Intent.FilterComparison, ServiceRecord>>
14971 mServicesByIntentPerUser = new SparseArray<
14972 HashMap<Intent.FilterComparison, ServiceRecord>>();
14973
14974 ServiceRecord getServiceByName(ComponentName name, int callingUser) {
14975 // TODO: Deal with global services
14976 if (DEBUG_MU)
14977 Slog.v(TAG_MU, "getServiceByName(" + name + "), callingUser = " + callingUser);
14978 return getServices(callingUser).get(name);
14979 }
14980
14981 ServiceRecord getServiceByName(ComponentName name) {
14982 return getServiceByName(name, -1);
14983 }
14984
14985 ServiceRecord getServiceByIntent(Intent.FilterComparison filter, int callingUser) {
14986 // TODO: Deal with global services
14987 if (DEBUG_MU)
14988 Slog.v(TAG_MU, "getServiceByIntent(" + filter + "), callingUser = " + callingUser);
14989 return getServicesByIntent(callingUser).get(filter);
14990 }
14991
14992 ServiceRecord getServiceByIntent(Intent.FilterComparison filter) {
14993 return getServiceByIntent(filter, -1);
14994 }
14995
14996 void putServiceByName(ComponentName name, int callingUser, ServiceRecord value) {
14997 // TODO: Deal with global services
14998 getServices(callingUser).put(name, value);
14999 }
15000
15001 void putServiceByIntent(Intent.FilterComparison filter, int callingUser,
15002 ServiceRecord value) {
15003 // TODO: Deal with global services
15004 getServicesByIntent(callingUser).put(filter, value);
15005 }
15006
15007 void removeServiceByName(ComponentName name, int callingUser) {
15008 // TODO: Deal with global services
15009 ServiceRecord removed = getServices(callingUser).remove(name);
15010 if (DEBUG_MU)
15011 Slog.v(TAG, "removeServiceByName user=" + callingUser + " name=" + name
15012 + " removed=" + removed);
15013 }
15014
15015 void removeServiceByIntent(Intent.FilterComparison filter, int callingUser) {
15016 // TODO: Deal with global services
15017 ServiceRecord removed = getServicesByIntent(callingUser).remove(filter);
15018 if (DEBUG_MU)
15019 Slog.v(TAG_MU, "removeServiceByIntent user=" + callingUser + " intent=" + filter
15020 + " removed=" + removed);
15021 }
15022
15023 Collection<ServiceRecord> getAllServices(int callingUser) {
15024 // TODO: Deal with global services
15025 return getServices(callingUser).values();
15026 }
15027
15028 private HashMap<ComponentName, ServiceRecord> getServices(int callingUser) {
15029 HashMap map = mServicesByNamePerUser.get(callingUser);
15030 if (map == null) {
15031 map = new HashMap<ComponentName, ServiceRecord>();
15032 mServicesByNamePerUser.put(callingUser, map);
15033 }
15034 return map;
15035 }
15036
15037 private HashMap<Intent.FilterComparison, ServiceRecord> getServicesByIntent(
15038 int callingUser) {
15039 HashMap map = mServicesByIntentPerUser.get(callingUser);
15040 if (map == null) {
15041 map = new HashMap<Intent.FilterComparison, ServiceRecord>();
15042 mServicesByIntentPerUser.put(callingUser, map);
15043 }
15044 return map;
15045 }
15046 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015047}