blob: 529537c1bd821ab149ffdcaa39e66d3e4a7daf0a [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006-2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.am;
18
Jeff Sharkey110a6b62012-03-12 11:12:41 -070019import static android.content.pm.PackageManager.PERMISSION_GRANTED;
20
Dianne Hackborn860755f2010-06-03 18:47:52 -070021import com.android.internal.R;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080022import com.android.internal.os.BatteryStatsImpl;
Dianne Hackborn45ce8642011-07-14 16:10:16 -070023import com.android.internal.os.ProcessStats;
Dianne Hackbornde7faf62009-06-30 13:27:30 -070024import com.android.server.AttributeCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025import com.android.server.IntentResolver;
26import com.android.server.ProcessMap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080027import com.android.server.SystemServer;
28import com.android.server.Watchdog;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070029import com.android.server.am.ActivityStack.ActivityState;
Dianne Hackborna924dc0d2011-02-17 14:22:17 -080030import com.android.server.wm.WindowManagerService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031
Dianne Hackborndd71fc82009-12-16 19:24:32 -080032import dalvik.system.Zygote;
33
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080034import android.app.Activity;
35import android.app.ActivityManager;
36import android.app.ActivityManagerNative;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -070037import android.app.ActivityOptions;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038import android.app.ActivityThread;
39import android.app.AlertDialog;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070040import android.app.AppGlobals;
Jacek Surazskif5b9c722009-05-18 12:09:59 +020041import android.app.ApplicationErrorReport;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import android.app.Dialog;
Dianne Hackbornb06ea702009-07-13 13:07:51 -070043import android.app.IActivityController;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044import android.app.IApplicationThread;
45import android.app.IInstrumentationWatcher;
Dianne Hackborn860755f2010-06-03 18:47:52 -070046import android.app.INotificationManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -070047import android.app.IProcessObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048import android.app.IServiceConnection;
49import android.app.IThumbnailReceiver;
50import android.app.Instrumentation;
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070051import android.app.Notification;
Dianne Hackborn860755f2010-06-03 18:47:52 -070052import android.app.NotificationManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080053import android.app.PendingIntent;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070054import android.app.Service;
Christopher Tate45281862010-03-05 15:46:30 -080055import android.app.backup.IBackupManager;
Jacek Surazskif5b9c722009-05-18 12:09:59 +020056import android.content.ActivityNotFoundException;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -080057import android.content.BroadcastReceiver;
Dianne Hackborn21c241e2012-03-08 13:57:23 -080058import android.content.ClipData;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070059import android.content.ComponentCallbacks2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060import android.content.ComponentName;
Jeff Sharkey110a6b62012-03-12 11:12:41 -070061import android.content.ContentProvider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062import android.content.ContentResolver;
63import android.content.Context;
Christian Mehlmauer7664e202010-07-20 08:46:17 +020064import android.content.DialogInterface;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070065import android.content.IIntentReceiver;
66import android.content.IIntentSender;
Adam Powelldd8fab22012-03-22 17:47:27 -070067import android.content.Intent;
68import android.content.IntentFilter;
Dianne Hackbornfa82f222009-09-17 15:14:12 -070069import android.content.IntentSender;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070import android.content.pm.ActivityInfo;
71import android.content.pm.ApplicationInfo;
72import android.content.pm.ConfigurationInfo;
73import android.content.pm.IPackageDataObserver;
74import android.content.pm.IPackageManager;
75import android.content.pm.InstrumentationInfo;
Dan Egnor66c40e72010-01-26 16:23:11 -080076import android.content.pm.PackageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077import android.content.pm.PackageManager;
Adam Powelldd8fab22012-03-22 17:47:27 -070078import android.content.pm.PackageManager.NameNotFoundException;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070079import android.content.pm.PathPermission;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080080import android.content.pm.ProviderInfo;
81import android.content.pm.ResolveInfo;
82import android.content.pm.ServiceInfo;
Amith Yamasani742a6712011-05-04 14:49:28 -070083import android.content.pm.UserInfo;
Dianne Hackborne2515ee2011-04-27 18:52:56 -040084import android.content.res.CompatibilityInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085import android.content.res.Configuration;
86import android.graphics.Bitmap;
Robert Greenwalt434203a2010-10-11 16:00:27 -070087import android.net.Proxy;
88import android.net.ProxyProperties;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080089import android.net.Uri;
90import android.os.Binder;
Dan Egnor60d87622009-12-16 16:32:58 -080091import android.os.Build;
Dan Egnor42471dd2010-01-07 17:25:22 -080092import android.os.Bundle;
Dianne Hackborn3025ef32009-08-31 21:31:47 -070093import android.os.Debug;
Dan Egnor60d87622009-12-16 16:32:58 -080094import android.os.DropBoxManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080095import android.os.Environment;
Dan Egnor42471dd2010-01-07 17:25:22 -080096import android.os.FileObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080097import android.os.FileUtils;
98import android.os.Handler;
99import android.os.IBinder;
100import android.os.IPermissionController;
101import android.os.Looper;
102import android.os.Message;
103import android.os.Parcel;
104import android.os.ParcelFileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800105import android.os.Process;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700106import android.os.RemoteCallbackList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107import android.os.RemoteException;
108import android.os.ServiceManager;
Brad Fitzpatrick46d42382010-06-11 13:57:58 -0700109import android.os.StrictMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110import android.os.SystemClock;
111import android.os.SystemProperties;
Amith Yamasani742a6712011-05-04 14:49:28 -0700112import android.os.UserId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113import android.provider.Settings;
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700114import android.text.format.Time;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800115import android.util.EventLog;
Joe Onorato5d3bea62010-03-01 13:44:29 -0800116import android.util.Log;
Adam Powelldd8fab22012-03-22 17:47:27 -0700117import android.util.Pair;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118import android.util.PrintWriterPrinter;
Adam Powelldd8fab22012-03-22 17:47:27 -0700119import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800120import android.util.SparseArray;
Amith Yamasani742a6712011-05-04 14:49:28 -0700121import android.util.SparseIntArray;
Dianne Hackborn1ebccf52010-08-15 13:04:34 -0700122import android.util.TimeUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800123import android.view.Gravity;
124import android.view.LayoutInflater;
125import android.view.View;
126import android.view.WindowManager;
127import android.view.WindowManagerPolicy;
128
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700129import java.io.BufferedInputStream;
130import java.io.BufferedOutputStream;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700131import java.io.BufferedReader;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700132import java.io.DataInputStream;
133import java.io.DataOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800134import java.io.File;
135import java.io.FileDescriptor;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700136import java.io.FileInputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800137import java.io.FileNotFoundException;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700138import java.io.FileOutputStream;
Jacek Surazskif5b9c722009-05-18 12:09:59 +0200139import java.io.IOException;
Dan Egnora455d192010-03-12 08:52:28 -0800140import java.io.InputStreamReader;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800141import java.io.PrintWriter;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700142import java.io.StringWriter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800143import java.lang.ref.WeakReference;
144import java.util.ArrayList;
Amith Yamasani742a6712011-05-04 14:49:28 -0700145import java.util.Collection;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700146import java.util.Collections;
147import java.util.Comparator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800148import java.util.HashMap;
149import java.util.HashSet;
150import java.util.Iterator;
151import java.util.List;
152import java.util.Locale;
153import java.util.Map;
Amith Yamasani13593602012-03-22 16:16:17 -0700154import java.util.Map.Entry;
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -0700155import java.util.Set;
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700156import java.util.concurrent.atomic.AtomicBoolean;
157import java.util.concurrent.atomic.AtomicLong;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800158
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700159public final class ActivityManagerService extends ActivityManagerNative
160 implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
Amith Yamasani742a6712011-05-04 14:49:28 -0700161 private static final String USER_DATA_DIR = "/data/user/";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800162 static final String TAG = "ActivityManager";
Amith Yamasani742a6712011-05-04 14:49:28 -0700163 static final String TAG_MU = "ActivityManagerServiceMU";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800164 static final boolean DEBUG = false;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400165 static final boolean localLOGV = DEBUG;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800166 static final boolean DEBUG_SWITCH = localLOGV || false;
167 static final boolean DEBUG_TASKS = localLOGV || false;
168 static final boolean DEBUG_PAUSE = localLOGV || false;
169 static final boolean DEBUG_OOM_ADJ = localLOGV || false;
170 static final boolean DEBUG_TRANSITION = localLOGV || false;
171 static final boolean DEBUG_BROADCAST = localLOGV || false;
Christopher Tatef46723b2012-01-26 14:19:24 -0800172 static final boolean DEBUG_BACKGROUND_BROADCAST = DEBUG_BROADCAST || false;
Dianne Hackborn82f3f002009-06-16 18:49:05 -0700173 static final boolean DEBUG_BROADCAST_LIGHT = DEBUG_BROADCAST || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800174 static final boolean DEBUG_SERVICE = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700175 static final boolean DEBUG_SERVICE_EXECUTING = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800176 static final boolean DEBUG_VISBILITY = localLOGV || false;
177 static final boolean DEBUG_PROCESSES = localLOGV || false;
Dianne Hackborna1e989b2009-09-01 19:54:29 -0700178 static final boolean DEBUG_PROVIDER = localLOGV || false;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800179 static final boolean DEBUG_URI_PERMISSION = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800180 static final boolean DEBUG_USER_LEAVING = localLOGV || false;
The Android Open Source Project10592532009-03-18 17:39:46 -0700181 static final boolean DEBUG_RESULTS = localLOGV || false;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -0700182 static final boolean DEBUG_BACKUP = localLOGV || false;
Dianne Hackborndc6b6352009-09-30 14:20:09 -0700183 static final boolean DEBUG_CONFIGURATION = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700184 static final boolean DEBUG_POWER = localLOGV || false;
185 static final boolean DEBUG_POWER_QUICK = DEBUG_POWER || false;
Amith Yamasani742a6712011-05-04 14:49:28 -0700186 static final boolean DEBUG_MU = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800187 static final boolean VALIDATE_TOKENS = false;
188 static final boolean SHOW_ACTIVITY_START_TIME = true;
189
190 // Control over CPU and battery monitoring.
191 static final long BATTERY_STATS_TIME = 30*60*1000; // write battery stats every 30 minutes.
192 static final boolean MONITOR_CPU_USAGE = true;
193 static final long MONITOR_CPU_MIN_TIME = 5*1000; // don't sample cpu less than every 5 seconds.
194 static final long MONITOR_CPU_MAX_TIME = 0x0fffffff; // wait possibly forever for next cpu sample.
195 static final boolean MONITOR_THREAD_CPU_USAGE = false;
196
Dianne Hackborn1655be42009-05-08 14:29:01 -0700197 // The flags that are set for all calls we make to the package manager.
Dianne Hackborn11b822d2009-07-21 20:03:02 -0700198 static final int STOCK_PM_FLAGS = PackageManager.GET_SHARED_LIBRARY_FILES;
Dianne Hackborn1655be42009-05-08 14:29:01 -0700199
Dianne Hackbornf02e57b2011-03-01 22:21:04 -0800200 private static final String SYSTEM_DEBUGGABLE = "ro.debuggable";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800201
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700202 static final boolean IS_USER_BUILD = "user".equals(Build.TYPE);
203
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800204 // Maximum number of recent tasks that we can remember.
205 static final int MAX_RECENT_TASKS = 20;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700206
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700207 // Amount of time after a call to stopAppSwitches() during which we will
208 // prevent further untrusted switches from happening.
209 static final long APP_SWITCH_DELAY_TIME = 5*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800210
211 // How long we wait for a launched process to attach to the activity manager
212 // before we decide it's never going to come up for real.
213 static final int PROC_START_TIMEOUT = 10*1000;
214
Jeff Brown3f9dd282011-07-08 20:02:19 -0700215 // How long we wait for a launched process to attach to the activity manager
216 // before we decide it's never going to come up for real, when the process was
217 // started with a wrapper for instrumentation (such as Valgrind) because it
218 // could take much longer than usual.
219 static final int PROC_START_TIMEOUT_WITH_WRAPPER = 300*1000;
220
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800221 // How long to wait after going idle before forcing apps to GC.
222 static final int GC_TIMEOUT = 5*1000;
223
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700224 // The minimum amount of time between successive GC requests for a process.
225 static final int GC_MIN_INTERVAL = 60*1000;
226
Dianne Hackborn287952c2010-09-22 22:34:31 -0700227 // The rate at which we check for apps using excessive power -- 15 mins.
228 static final int POWER_CHECK_DELAY = (DEBUG_POWER_QUICK ? 2 : 15) * 60*1000;
229
230 // The minimum sample duration we will allow before deciding we have
231 // enough data on wake locks to start killing things.
232 static final int WAKE_LOCK_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
233
234 // The minimum sample duration we will allow before deciding we have
235 // enough data on CPU usage to start killing things.
236 static final int CPU_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700237
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800238 // How long we allow a receiver to run before giving up on it.
Christopher Tatef46723b2012-01-26 14:19:24 -0800239 static final int BROADCAST_FG_TIMEOUT = 10*1000;
240 static final int BROADCAST_BG_TIMEOUT = 60*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800241
242 // How long we wait for a service to finish executing.
243 static final int SERVICE_TIMEOUT = 20*1000;
244
245 // How long a service needs to be running until restarting its process
246 // is no longer considered to be a relaunch of the service.
247 static final int SERVICE_RESTART_DURATION = 5*1000;
248
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700249 // How long a service needs to be running until it will start back at
250 // SERVICE_RESTART_DURATION after being killed.
251 static final int SERVICE_RESET_RUN_DURATION = 60*1000;
252
253 // Multiplying factor to increase restart duration time by, for each time
254 // a service is killed before it has run for SERVICE_RESET_RUN_DURATION.
255 static final int SERVICE_RESTART_DURATION_FACTOR = 4;
256
257 // The minimum amount of time between restarting services that we allow.
258 // That is, when multiple services are restarting, we won't allow each
259 // to restart less than this amount of time from the last one.
260 static final int SERVICE_MIN_RESTART_TIME_BETWEEN = 10*1000;
261
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800262 // Maximum amount of time for there to be no activity on a service before
263 // we consider it non-essential and allow its process to go on the
264 // LRU background list.
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700265 static final int MAX_SERVICE_INACTIVITY = 30*60*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800266
267 // How long we wait until we timeout on key dispatching.
268 static final int KEY_DISPATCHING_TIMEOUT = 5*1000;
269
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800270 // How long we wait until we timeout on key dispatching during instrumentation.
271 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT = 60*1000;
272
Dan Egnor42471dd2010-01-07 17:25:22 -0800273 static final int MY_PID = Process.myPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800274
275 static final String[] EMPTY_STRING_ARRAY = new String[0];
276
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700277 public ActivityStack mMainStack;
Mike Lockwood3a74bd32011-08-12 13:55:22 -0700278
279 private final boolean mHeadless;
280
Joe Onorato54a4a412011-11-02 20:50:08 -0700281 // Whether we should show our dialogs (ANR, crash, etc) or just perform their
282 // default actuion automatically. Important for devices without direct input
283 // devices.
284 private boolean mShowDialogs = true;
285
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800286 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700287 * Description of a request to start a new activity, which has been held
288 * due to app switches being disabled.
289 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700290 static class PendingActivityLaunch {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700291 ActivityRecord r;
292 ActivityRecord sourceRecord;
Dianne Hackborna4972e92012-03-14 10:38:05 -0700293 int startFlags;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700294 }
295
296 final ArrayList<PendingActivityLaunch> mPendingActivityLaunches
297 = new ArrayList<PendingActivityLaunch>();
298
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800299
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800300 BroadcastQueue mFgBroadcastQueue;
301 BroadcastQueue mBgBroadcastQueue;
Christopher Tatef46723b2012-01-26 14:19:24 -0800302 // Convenient for easy iteration over the queues. Foreground is first
303 // so that dispatch of foreground broadcasts gets precedence.
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800304 final BroadcastQueue[] mBroadcastQueues = new BroadcastQueue[2];
Christopher Tatef46723b2012-01-26 14:19:24 -0800305
306 BroadcastQueue broadcastQueueForIntent(Intent intent) {
307 final boolean isFg = (intent.getFlags() & Intent.FLAG_RECEIVER_FOREGROUND) != 0;
308 if (DEBUG_BACKGROUND_BROADCAST) {
309 Slog.i(TAG, "Broadcast intent " + intent + " on "
310 + (isFg ? "foreground" : "background")
311 + " queue");
312 }
313 return (isFg) ? mFgBroadcastQueue : mBgBroadcastQueue;
314 }
315
316 BroadcastRecord broadcastRecordForReceiverLocked(IBinder receiver) {
317 for (BroadcastQueue queue : mBroadcastQueues) {
318 BroadcastRecord r = queue.getMatchingOrderedReceiver(receiver);
319 if (r != null) {
320 return r;
321 }
322 }
323 return null;
324 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800325
326 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800327 * Activity we have told the window manager to have key focus.
328 */
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700329 ActivityRecord mFocusedActivity = null;
Dianne Hackbornbfe319e2009-09-21 00:34:05 -0700330 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800331 * List of intents that were used to start the most recent tasks.
332 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700333 final ArrayList<TaskRecord> mRecentTasks = new ArrayList<TaskRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800334
335 /**
Dianne Hackborn7d608422011-08-07 16:24:18 -0700336 * Process management.
337 */
338 final ProcessList mProcessList = new ProcessList();
339
340 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800341 * All of the applications we currently have running organized by name.
342 * The keys are strings of the application package name (as
343 * returned by the package manager), and the keys are ApplicationRecord
344 * objects.
345 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700346 final ProcessMap<ProcessRecord> mProcessNames = new ProcessMap<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800347
348 /**
Dianne Hackborna0c283e2012-02-09 10:47:01 -0800349 * The currently running isolated processes.
350 */
351 final SparseArray<ProcessRecord> mIsolatedProcesses = new SparseArray<ProcessRecord>();
352
353 /**
354 * Counter for assigning isolated process uids, to avoid frequently reusing the
355 * same ones.
356 */
357 int mNextIsolatedProcessUid = 0;
358
359 /**
Dianne Hackborn860755f2010-06-03 18:47:52 -0700360 * The currently running heavy-weight process, if any.
361 */
362 ProcessRecord mHeavyWeightProcess = null;
363
364 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800365 * The last time that various processes have crashed.
366 */
367 final ProcessMap<Long> mProcessCrashTimes = new ProcessMap<Long>();
368
369 /**
370 * Set of applications that we consider to be bad, and will reject
371 * incoming broadcasts from (which the user has no control over).
372 * Processes are added to this set when they have crashed twice within
373 * a minimum amount of time; they are removed from it when they are
374 * later restarted (hopefully due to some user action). The value is the
375 * time it was added to the list.
376 */
377 final ProcessMap<Long> mBadProcesses = new ProcessMap<Long>();
378
379 /**
380 * All of the processes we currently have running organized by pid.
381 * The keys are the pid running the application.
382 *
383 * <p>NOTE: This object is protected by its own lock, NOT the global
384 * activity manager lock!
385 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700386 final SparseArray<ProcessRecord> mPidsSelfLocked = new SparseArray<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800387
388 /**
389 * All of the processes that have been forced to be foreground. The key
390 * is the pid of the caller who requested it (we hold a death
391 * link on it).
392 */
393 abstract class ForegroundToken implements IBinder.DeathRecipient {
394 int pid;
395 IBinder token;
396 }
397 final SparseArray<ForegroundToken> mForegroundProcesses
398 = new SparseArray<ForegroundToken>();
399
400 /**
401 * List of records for processes that someone had tried to start before the
402 * system was ready. We don't start them at that point, but ensure they
403 * are started by the time booting is complete.
404 */
405 final ArrayList<ProcessRecord> mProcessesOnHold
406 = new ArrayList<ProcessRecord>();
407
408 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800409 * List of persistent applications that are in the process
410 * of being started.
411 */
412 final ArrayList<ProcessRecord> mPersistentStartingProcesses
413 = new ArrayList<ProcessRecord>();
414
415 /**
416 * Processes that are being forcibly torn down.
417 */
418 final ArrayList<ProcessRecord> mRemovedProcesses
419 = new ArrayList<ProcessRecord>();
420
421 /**
422 * List of running applications, sorted by recent usage.
423 * The first entry in the list is the least recently used.
424 * It contains ApplicationRecord objects. This list does NOT include
425 * any persistent application records (since we never want to exit them).
426 */
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800427 final ArrayList<ProcessRecord> mLruProcesses
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800428 = new ArrayList<ProcessRecord>();
429
430 /**
431 * List of processes that should gc as soon as things are idle.
432 */
433 final ArrayList<ProcessRecord> mProcessesToGc
434 = new ArrayList<ProcessRecord>();
435
436 /**
The Android Open Source Project4df24232009-03-05 14:34:35 -0800437 * This is the process holding what we currently consider to be
438 * the "home" activity.
439 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700440 ProcessRecord mHomeProcess;
The Android Open Source Project4df24232009-03-05 14:34:35 -0800441
442 /**
Dianne Hackbornf35fe232011-11-01 19:25:20 -0700443 * This is the process holding the activity the user last visited that
444 * is in a different process from the one they are currently in.
445 */
446 ProcessRecord mPreviousProcess;
Dianne Hackborn50685602011-12-01 12:23:37 -0800447
448 /**
449 * The time at which the previous process was last visible.
450 */
451 long mPreviousProcessVisibleTime;
452
Dianne Hackbornf35fe232011-11-01 19:25:20 -0700453 /**
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400454 * Packages that the user has asked to have run in screen size
455 * compatibility mode instead of filling the screen.
456 */
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -0700457 final CompatModePackages mCompatModePackages;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400458
459 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800460 * Set of PendingResultRecord objects that are currently active.
461 */
462 final HashSet mPendingResultRecords = new HashSet();
463
464 /**
465 * Set of IntentSenderRecord objects that are currently active.
466 */
467 final HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>> mIntentSenderRecords
468 = new HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>>();
469
470 /**
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -0800471 * Fingerprints (hashCode()) of stack traces that we've
Brad Fitzpatrick143666f2010-06-14 12:40:21 -0700472 * already logged DropBox entries for. Guarded by itself. If
473 * something (rogue user app) forces this over
474 * MAX_DUP_SUPPRESSED_STACKS entries, the contents are cleared.
475 */
476 private final HashSet<Integer> mAlreadyLoggedViolatedStacks = new HashSet<Integer>();
477 private static final int MAX_DUP_SUPPRESSED_STACKS = 5000;
478
479 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -0700480 * Strict Mode background batched logging state.
481 *
482 * The string buffer is guarded by itself, and its lock is also
483 * used to determine if another batched write is already
484 * in-flight.
485 */
486 private final StringBuilder mStrictModeBuffer = new StringBuilder();
487
488 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800489 * Keeps track of all IIntentReceivers that have been registered for
490 * broadcasts. Hash keys are the receiver IBinder, hash value is
491 * a ReceiverList.
492 */
493 final HashMap mRegisteredReceivers = new HashMap();
494
495 /**
496 * Resolver for broadcast intents to registered receivers.
497 * Holds BroadcastFilter (subclass of IntentFilter).
498 */
499 final IntentResolver<BroadcastFilter, BroadcastFilter> mReceiverResolver
500 = new IntentResolver<BroadcastFilter, BroadcastFilter>() {
501 @Override
502 protected boolean allowFilterResult(
503 BroadcastFilter filter, List<BroadcastFilter> dest) {
504 IBinder target = filter.receiverList.receiver.asBinder();
505 for (int i=dest.size()-1; i>=0; i--) {
506 if (dest.get(i).receiverList.receiver.asBinder() == target) {
507 return false;
508 }
509 }
510 return true;
511 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700512
513 @Override
514 protected String packageForFilter(BroadcastFilter filter) {
515 return filter.packageName;
516 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800517 };
518
519 /**
520 * State of all active sticky broadcasts. Keys are the action of the
521 * sticky Intent, values are an ArrayList of all broadcasted intents with
522 * that action (which should usually be one).
523 */
524 final HashMap<String, ArrayList<Intent>> mStickyBroadcasts =
525 new HashMap<String, ArrayList<Intent>>();
526
Amith Yamasani742a6712011-05-04 14:49:28 -0700527 final ServiceMap mServiceMap = new ServiceMap();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800528
529 /**
530 * All currently bound service connections. Keys are the IBinder of
531 * the client's IServiceConnection.
532 */
Dianne Hackborn43d9ac82010-08-25 15:06:25 -0700533 final HashMap<IBinder, ArrayList<ConnectionRecord>> mServiceConnections
534 = new HashMap<IBinder, ArrayList<ConnectionRecord>>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800535
536 /**
537 * List of services that we have been asked to start,
538 * but haven't yet been able to. It is used to hold start requests
539 * while waiting for their corresponding application thread to get
540 * going.
541 */
542 final ArrayList<ServiceRecord> mPendingServices
543 = new ArrayList<ServiceRecord>();
544
545 /**
546 * List of services that are scheduled to restart following a crash.
547 */
548 final ArrayList<ServiceRecord> mRestartingServices
549 = new ArrayList<ServiceRecord>();
550
551 /**
552 * List of services that are in the process of being stopped.
553 */
554 final ArrayList<ServiceRecord> mStoppingServices
555 = new ArrayList<ServiceRecord>();
556
557 /**
Christopher Tate181fafa2009-05-14 11:12:14 -0700558 * Backup/restore process management
559 */
560 String mBackupAppName = null;
561 BackupRecord mBackupTarget = null;
562
563 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800564 * List of PendingThumbnailsRecord objects of clients who are still
565 * waiting to receive all of the thumbnails for a task.
566 */
567 final ArrayList mPendingThumbnails = new ArrayList();
568
569 /**
570 * List of HistoryRecord objects that have been finished and must
571 * still report back to a pending thumbnail receiver.
572 */
573 final ArrayList mCancelledThumbnails = new ArrayList();
574
Amith Yamasani742a6712011-05-04 14:49:28 -0700575 final ProviderMap mProviderMap = new ProviderMap();
576
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800577 /**
578 * List of content providers who have clients waiting for them. The
579 * application is currently being launched and the provider will be
580 * removed from this list once it is published.
581 */
Dianne Hackborn860755f2010-06-03 18:47:52 -0700582 final ArrayList<ContentProviderRecord> mLaunchingProviders
583 = new ArrayList<ContentProviderRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800584
585 /**
586 * Global set of specific Uri permissions that have been granted.
587 */
588 final private SparseArray<HashMap<Uri, UriPermission>> mGrantedUriPermissions
589 = new SparseArray<HashMap<Uri, UriPermission>>();
590
Svetoslav Ganov54d068e2011-03-02 12:58:40 -0800591 CoreSettingsObserver mCoreSettingsObserver;
592
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800593 /**
594 * Thread-local storage used to carry caller permissions over through
595 * indirect content-provider access.
596 * @see #ActivityManagerService.openContentUri()
597 */
598 private class Identity {
599 public int pid;
600 public int uid;
601
602 Identity(int _pid, int _uid) {
603 pid = _pid;
604 uid = _uid;
605 }
606 }
Amith Yamasani742a6712011-05-04 14:49:28 -0700607
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800608 private static ThreadLocal<Identity> sCallerIdentity = new ThreadLocal<Identity>();
609
610 /**
611 * All information we have collected about the runtime performance of
612 * any user id that can impact battery performance.
613 */
614 final BatteryStatsService mBatteryStatsService;
615
616 /**
617 * information about component usage
618 */
619 final UsageStatsService mUsageStatsService;
620
621 /**
622 * Current configuration information. HistoryRecord objects are given
623 * a reference to this object to indicate which configuration they are
624 * currently running in, so this object must be kept immutable.
625 */
626 Configuration mConfiguration = new Configuration();
627
628 /**
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800629 * Current sequencing integer of the configuration, for skipping old
630 * configurations.
631 */
632 int mConfigurationSeq = 0;
633
634 /**
Jack Palevichb90d28c2009-07-22 15:35:24 -0700635 * Hardware-reported OpenGLES version.
636 */
637 final int GL_ES_VERSION;
638
639 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800640 * List of initialization arguments to pass to all processes when binding applications to them.
641 * For example, references to the commonly used services.
642 */
643 HashMap<String, IBinder> mAppBindArgs;
644
645 /**
Dianne Hackbornf210d6b2009-04-13 18:42:49 -0700646 * Temporary to avoid allocations. Protected by main lock.
647 */
648 final StringBuilder mStringBuilder = new StringBuilder(256);
649
650 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800651 * Used to control how we initialize the service.
652 */
653 boolean mStartRunning = false;
654 ComponentName mTopComponent;
655 String mTopAction;
656 String mTopData;
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700657 boolean mProcessesReady = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800658 boolean mSystemReady = false;
659 boolean mBooting = false;
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700660 boolean mWaitingUpdate = false;
661 boolean mDidUpdate = false;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700662 boolean mOnBattery = false;
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700663 boolean mLaunchWarningShown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800664
665 Context mContext;
666
667 int mFactoryTest;
668
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -0700669 boolean mCheckedForSetup;
670
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800671 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700672 * The time at which we will allow normal application switches again,
673 * after a call to {@link #stopAppSwitches()}.
674 */
675 long mAppSwitchesAllowedTime;
676
677 /**
678 * This is set to true after the first switch after mAppSwitchesAllowedTime
679 * is set; any switches after that will clear the time.
680 */
681 boolean mDidAppSwitch;
682
683 /**
Dianne Hackborn287952c2010-09-22 22:34:31 -0700684 * Last time (in realtime) at which we checked for power usage.
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700685 */
Dianne Hackborn287952c2010-09-22 22:34:31 -0700686 long mLastPowerCheckRealtime;
687
688 /**
689 * Last time (in uptime) at which we checked for power usage.
690 */
691 long mLastPowerCheckUptime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700692
693 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800694 * Set while we are wanting to sleep, to prevent any
695 * activities from being started/resumed.
696 */
697 boolean mSleeping = false;
698
699 /**
Dianne Hackbornff5b1582012-04-12 17:24:07 -0700700 * State of external calls telling us if the device is asleep.
701 */
702 boolean mWentToSleep = false;
703
704 /**
705 * State of external call telling us if the lock screen is shown.
706 */
707 boolean mLockScreenShown = false;
708
709 /**
Dianne Hackborn55280a92009-05-07 15:53:46 -0700710 * Set if we are shutting down the system, similar to sleeping.
711 */
712 boolean mShuttingDown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800713
714 /**
715 * Task identifier that activities are currently being started
716 * in. Incremented each time a new task is created.
717 * todo: Replace this with a TokenSpace class that generates non-repeating
718 * integers that won't wrap.
719 */
720 int mCurTask = 1;
721
722 /**
723 * Current sequence id for oom_adj computation traversal.
724 */
725 int mAdjSeq = 0;
726
727 /**
Dianne Hackborn906497c2010-05-10 15:57:38 -0700728 * Current sequence id for process LRU updating.
729 */
730 int mLruSeq = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800731
732 /**
Dianne Hackborne02c88a2011-10-28 13:58:15 -0700733 * Keep track of the number of service processes we last found, to
734 * determine on the next iteration which should be B services.
735 */
736 int mNumServiceProcs = 0;
737 int mNewNumServiceProcs = 0;
738
739 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800740 * System monitoring: number of processes that died since the last
741 * N procs were started.
742 */
743 int[] mProcDeaths = new int[20];
744
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700745 /**
746 * This is set if we had to do a delayed dexopt of an app before launching
747 * it, to increasing the ANR timeouts in that case.
748 */
749 boolean mDidDexOpt;
750
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800751 String mDebugApp = null;
752 boolean mWaitForDebugger = false;
753 boolean mDebugTransient = false;
754 String mOrigDebugApp = null;
755 boolean mOrigWaitForDebugger = false;
756 boolean mAlwaysFinishActivities = false;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700757 IActivityController mController = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700758 String mProfileApp = null;
759 ProcessRecord mProfileProc = null;
760 String mProfileFile;
761 ParcelFileDescriptor mProfileFd;
762 int mProfileType = 0;
763 boolean mAutoStopProfiler = false;
Siva Velusamy92a8b222012-03-09 16:24:04 -0800764 String mOpenGlTraceApp = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800765
Jeff Sharkeya4620792011-05-20 15:29:23 -0700766 final RemoteCallbackList<IProcessObserver> mProcessObservers
767 = new RemoteCallbackList<IProcessObserver>();
768
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800769 /**
770 * Callback of last caller to {@link #requestPss}.
771 */
772 Runnable mRequestPssCallback;
773
774 /**
775 * Remaining processes for which we are waiting results from the last
776 * call to {@link #requestPss}.
777 */
778 final ArrayList<ProcessRecord> mRequestPssList
779 = new ArrayList<ProcessRecord>();
780
781 /**
782 * Runtime statistics collection thread. This object's lock is used to
783 * protect all related state.
784 */
785 final Thread mProcessStatsThread;
786
787 /**
788 * Used to collect process stats when showing not responding dialog.
789 * Protected by mProcessStatsThread.
790 */
791 final ProcessStats mProcessStats = new ProcessStats(
792 MONITOR_THREAD_CPU_USAGE);
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700793 final AtomicLong mLastCpuTime = new AtomicLong(0);
794 final AtomicBoolean mProcessStatsMutexFree = new AtomicBoolean(true);
795
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800796 long mLastWriteTime = 0;
797
798 /**
799 * Set to true after the system has finished booting.
800 */
801 boolean mBooted = false;
802
Dianne Hackborn7d608422011-08-07 16:24:18 -0700803 int mProcessLimit = ProcessList.MAX_HIDDEN_APPS;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700804 int mProcessLimitOverride = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800805
806 WindowManagerService mWindowManager;
807
808 static ActivityManagerService mSelf;
809 static ActivityThread mSystemThread;
810
811 private final class AppDeathRecipient implements IBinder.DeathRecipient {
812 final ProcessRecord mApp;
813 final int mPid;
814 final IApplicationThread mAppThread;
815
816 AppDeathRecipient(ProcessRecord app, int pid,
817 IApplicationThread thread) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800818 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800819 TAG, "New death recipient " + this
820 + " for thread " + thread.asBinder());
821 mApp = app;
822 mPid = pid;
823 mAppThread = thread;
824 }
825
826 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800827 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800828 TAG, "Death received in " + this
829 + " for thread " + mAppThread.asBinder());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800830 synchronized(ActivityManagerService.this) {
831 appDiedLocked(mApp, mPid, mAppThread);
832 }
833 }
834 }
835
836 static final int SHOW_ERROR_MSG = 1;
837 static final int SHOW_NOT_RESPONDING_MSG = 2;
838 static final int SHOW_FACTORY_ERROR_MSG = 3;
839 static final int UPDATE_CONFIGURATION_MSG = 4;
840 static final int GC_BACKGROUND_PROCESSES_MSG = 5;
841 static final int WAIT_FOR_DEBUGGER_MSG = 6;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800842 static final int SERVICE_TIMEOUT_MSG = 12;
843 static final int UPDATE_TIME_ZONE = 13;
844 static final int SHOW_UID_ERROR_MSG = 14;
845 static final int IM_FEELING_LUCKY_MSG = 15;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800846 static final int PROC_START_TIMEOUT_MSG = 20;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700847 static final int DO_PENDING_ACTIVITY_LAUNCHES_MSG = 21;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -0700848 static final int KILL_APPLICATION_MSG = 22;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800849 static final int FINALIZE_PENDING_INTENT_MSG = 23;
Dianne Hackborn860755f2010-06-03 18:47:52 -0700850 static final int POST_HEAVY_NOTIFICATION_MSG = 24;
851 static final int CANCEL_HEAVY_NOTIFICATION_MSG = 25;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700852 static final int SHOW_STRICT_MODE_VIOLATION_MSG = 26;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700853 static final int CHECK_EXCESSIVE_WAKE_LOCKS_MSG = 27;
Robert Greenwalt03595d02010-11-02 14:08:23 -0700854 static final int CLEAR_DNS_CACHE = 28;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700855 static final int UPDATE_HTTP_PROXY = 29;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700856 static final int SHOW_COMPAT_MODE_DIALOG_MSG = 30;
Dianne Hackborn36f80f32011-05-31 18:26:45 -0700857 static final int DISPATCH_FOREGROUND_ACTIVITIES_CHANGED = 31;
858 static final int DISPATCH_PROCESS_DIED = 32;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700859 static final int REPORT_MEM_USAGE = 33;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800860
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800861 static final int FIRST_ACTIVITY_STACK_MSG = 100;
862 static final int FIRST_BROADCAST_QUEUE_MSG = 200;
863 static final int FIRST_COMPAT_MODE_MSG = 300;
864
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800865 AlertDialog mUidAlert;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700866 CompatModeDialog mCompatModeDialog;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700867 long mLastMemUsageReportTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800868
869 final Handler mHandler = new Handler() {
870 //public Handler() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800871 // if (localLOGV) Slog.v(TAG, "Handler started!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800872 //}
873
874 public void handleMessage(Message msg) {
875 switch (msg.what) {
876 case SHOW_ERROR_MSG: {
877 HashMap data = (HashMap) msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800878 synchronized (ActivityManagerService.this) {
879 ProcessRecord proc = (ProcessRecord)data.get("app");
880 if (proc != null && proc.crashDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800881 Slog.e(TAG, "App already has crash dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800882 return;
883 }
884 AppErrorResult res = (AppErrorResult) data.get("result");
Joe Onorato54a4a412011-11-02 20:50:08 -0700885 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Dan Egnorb7f03672009-12-09 16:22:32 -0800886 Dialog d = new AppErrorDialog(mContext, res, proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800887 d.show();
888 proc.crashDialog = d;
889 } else {
890 // The device is asleep, so just pretend that the user
891 // saw a crash dialog and hit "force quit".
892 res.set(0);
893 }
894 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700895
896 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800897 } break;
898 case SHOW_NOT_RESPONDING_MSG: {
899 synchronized (ActivityManagerService.this) {
900 HashMap data = (HashMap) msg.obj;
901 ProcessRecord proc = (ProcessRecord)data.get("app");
902 if (proc != null && proc.anrDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800903 Slog.e(TAG, "App already has anr dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800904 return;
905 }
The Android Open Source Project4df24232009-03-05 14:34:35 -0800906
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700907 Intent intent = new Intent("android.intent.action.ANR");
908 if (!mProcessesReady) {
Christopher Tatef46723b2012-01-26 14:19:24 -0800909 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
910 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700911 }
912 broadcastIntentLocked(null, null, intent,
The Android Open Source Project4df24232009-03-05 14:34:35 -0800913 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -0700914 false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
The Android Open Source Project4df24232009-03-05 14:34:35 -0800915
Justin Kohbc52ca22012-03-29 15:11:44 -0700916 if (mShowDialogs) {
917 Dialog d = new AppNotRespondingDialog(ActivityManagerService.this,
Mike Lockwood69ccdbd2012-04-03 11:53:47 -0700918 mContext, proc, (ActivityRecord)data.get("activity"));
Justin Kohbc52ca22012-03-29 15:11:44 -0700919 d.show();
920 proc.anrDialog = d;
921 } else {
922 // Just kill the app if there is no dialog to be shown.
923 killAppAtUsersRequest(proc, null);
924 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800925 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700926
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700927 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800928 } break;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700929 case SHOW_STRICT_MODE_VIOLATION_MSG: {
930 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj;
931 synchronized (ActivityManagerService.this) {
932 ProcessRecord proc = (ProcessRecord) data.get("app");
933 if (proc == null) {
934 Slog.e(TAG, "App not found when showing strict mode dialog.");
935 break;
936 }
937 if (proc.crashDialog != null) {
938 Slog.e(TAG, "App already has strict mode dialog: " + proc);
939 return;
940 }
941 AppErrorResult res = (AppErrorResult) data.get("result");
Joe Onorato54a4a412011-11-02 20:50:08 -0700942 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700943 Dialog d = new StrictModeViolationDialog(mContext, res, proc);
944 d.show();
945 proc.crashDialog = d;
946 } else {
947 // The device is asleep, so just pretend that the user
948 // saw a crash dialog and hit "force quit".
949 res.set(0);
950 }
951 }
952 ensureBootCompleted();
953 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800954 case SHOW_FACTORY_ERROR_MSG: {
955 Dialog d = new FactoryErrorDialog(
956 mContext, msg.getData().getCharSequence("msg"));
957 d.show();
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700958 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800959 } break;
960 case UPDATE_CONFIGURATION_MSG: {
961 final ContentResolver resolver = mContext.getContentResolver();
962 Settings.System.putConfiguration(resolver, (Configuration)msg.obj);
963 } break;
964 case GC_BACKGROUND_PROCESSES_MSG: {
965 synchronized (ActivityManagerService.this) {
966 performAppGcsIfAppropriateLocked();
967 }
968 } break;
969 case WAIT_FOR_DEBUGGER_MSG: {
970 synchronized (ActivityManagerService.this) {
971 ProcessRecord app = (ProcessRecord)msg.obj;
972 if (msg.arg1 != 0) {
973 if (!app.waitedForDebugger) {
974 Dialog d = new AppWaitingForDebuggerDialog(
975 ActivityManagerService.this,
976 mContext, app);
977 app.waitDialog = d;
978 app.waitedForDebugger = true;
979 d.show();
980 }
981 } else {
982 if (app.waitDialog != null) {
983 app.waitDialog.dismiss();
984 app.waitDialog = null;
985 }
986 }
987 }
988 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800989 case SERVICE_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700990 if (mDidDexOpt) {
991 mDidDexOpt = false;
992 Message nmsg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
993 nmsg.obj = msg.obj;
994 mHandler.sendMessageDelayed(nmsg, SERVICE_TIMEOUT);
995 return;
996 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800997 serviceTimeout((ProcessRecord)msg.obj);
998 } break;
999 case UPDATE_TIME_ZONE: {
1000 synchronized (ActivityManagerService.this) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001001 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1002 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001003 if (r.thread != null) {
1004 try {
1005 r.thread.updateTimeZone();
1006 } catch (RemoteException ex) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001007 Slog.w(TAG, "Failed to update time zone for: " + r.info.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001008 }
1009 }
1010 }
1011 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001012 } break;
Robert Greenwalt03595d02010-11-02 14:08:23 -07001013 case CLEAR_DNS_CACHE: {
1014 synchronized (ActivityManagerService.this) {
1015 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1016 ProcessRecord r = mLruProcesses.get(i);
1017 if (r.thread != null) {
1018 try {
1019 r.thread.clearDnsCache();
1020 } catch (RemoteException ex) {
1021 Slog.w(TAG, "Failed to clear dns cache for: " + r.info.processName);
1022 }
1023 }
1024 }
1025 }
1026 } break;
Robert Greenwalt434203a2010-10-11 16:00:27 -07001027 case UPDATE_HTTP_PROXY: {
1028 ProxyProperties proxy = (ProxyProperties)msg.obj;
1029 String host = "";
1030 String port = "";
1031 String exclList = "";
1032 if (proxy != null) {
1033 host = proxy.getHost();
1034 port = Integer.toString(proxy.getPort());
1035 exclList = proxy.getExclusionList();
1036 }
1037 synchronized (ActivityManagerService.this) {
1038 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1039 ProcessRecord r = mLruProcesses.get(i);
1040 if (r.thread != null) {
1041 try {
1042 r.thread.setHttpProxy(host, port, exclList);
1043 } catch (RemoteException ex) {
1044 Slog.w(TAG, "Failed to update http proxy for: " +
1045 r.info.processName);
1046 }
1047 }
1048 }
1049 }
1050 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001051 case SHOW_UID_ERROR_MSG: {
Joe Onorato54a4a412011-11-02 20:50:08 -07001052 String title = "System UIDs Inconsistent";
1053 String text = "UIDs on the system are inconsistent, you need to wipe your"
1054 + " data partition or your device will be unstable.";
1055 Log.e(TAG, title + ": " + text);
1056 if (mShowDialogs) {
1057 // XXX This is a temporary dialog, no need to localize.
1058 AlertDialog d = new BaseErrorDialog(mContext);
1059 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
1060 d.setCancelable(false);
1061 d.setTitle(title);
1062 d.setMessage(text);
1063 d.setButton(DialogInterface.BUTTON_POSITIVE, "I'm Feeling Lucky",
1064 mHandler.obtainMessage(IM_FEELING_LUCKY_MSG));
1065 mUidAlert = d;
1066 d.show();
1067 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001068 } break;
1069 case IM_FEELING_LUCKY_MSG: {
1070 if (mUidAlert != null) {
1071 mUidAlert.dismiss();
1072 mUidAlert = null;
1073 }
1074 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001075 case PROC_START_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001076 if (mDidDexOpt) {
1077 mDidDexOpt = false;
1078 Message nmsg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
1079 nmsg.obj = msg.obj;
1080 mHandler.sendMessageDelayed(nmsg, PROC_START_TIMEOUT);
1081 return;
1082 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001083 ProcessRecord app = (ProcessRecord)msg.obj;
1084 synchronized (ActivityManagerService.this) {
1085 processStartTimedOutLocked(app);
1086 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001087 } break;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07001088 case DO_PENDING_ACTIVITY_LAUNCHES_MSG: {
1089 synchronized (ActivityManagerService.this) {
1090 doPendingActivityLaunchesLocked(true);
1091 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001092 } break;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001093 case KILL_APPLICATION_MSG: {
1094 synchronized (ActivityManagerService.this) {
1095 int uid = msg.arg1;
1096 boolean restart = (msg.arg2 == 1);
1097 String pkg = (String) msg.obj;
Amith Yamasani483f3b02012-03-13 16:08:00 -07001098 forceStopPackageLocked(pkg, uid, restart, false, true, false,
1099 UserId.getUserId(uid));
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001100 }
1101 } break;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001102 case FINALIZE_PENDING_INTENT_MSG: {
1103 ((PendingIntentRecord)msg.obj).completeFinalize();
1104 } break;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001105 case POST_HEAVY_NOTIFICATION_MSG: {
1106 INotificationManager inm = NotificationManager.getService();
1107 if (inm == null) {
1108 return;
1109 }
1110
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001111 ActivityRecord root = (ActivityRecord)msg.obj;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001112 ProcessRecord process = root.app;
1113 if (process == null) {
1114 return;
1115 }
1116
1117 try {
1118 Context context = mContext.createPackageContext(process.info.packageName, 0);
1119 String text = mContext.getString(R.string.heavy_weight_notification,
1120 context.getApplicationInfo().loadLabel(context.getPackageManager()));
1121 Notification notification = new Notification();
1122 notification.icon = com.android.internal.R.drawable.stat_sys_adb; //context.getApplicationInfo().icon;
1123 notification.when = 0;
1124 notification.flags = Notification.FLAG_ONGOING_EVENT;
1125 notification.tickerText = text;
1126 notification.defaults = 0; // please be quiet
1127 notification.sound = null;
1128 notification.vibrate = null;
1129 notification.setLatestEventInfo(context, text,
1130 mContext.getText(R.string.heavy_weight_notification_detail),
1131 PendingIntent.getActivity(mContext, 0, root.intent,
1132 PendingIntent.FLAG_CANCEL_CURRENT));
1133
1134 try {
1135 int[] outId = new int[1];
1136 inm.enqueueNotification("android", R.string.heavy_weight_notification,
1137 notification, outId);
1138 } catch (RuntimeException e) {
1139 Slog.w(ActivityManagerService.TAG,
1140 "Error showing notification for heavy-weight app", e);
1141 } catch (RemoteException e) {
1142 }
1143 } catch (NameNotFoundException e) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07001144 Slog.w(TAG, "Unable to create context for heavy notification", e);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001145 }
1146 } break;
1147 case CANCEL_HEAVY_NOTIFICATION_MSG: {
1148 INotificationManager inm = NotificationManager.getService();
1149 if (inm == null) {
1150 return;
1151 }
1152 try {
1153 inm.cancelNotification("android",
1154 R.string.heavy_weight_notification);
1155 } catch (RuntimeException e) {
1156 Slog.w(ActivityManagerService.TAG,
1157 "Error canceling notification for service", e);
1158 } catch (RemoteException e) {
1159 }
1160 } break;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001161 case CHECK_EXCESSIVE_WAKE_LOCKS_MSG: {
1162 synchronized (ActivityManagerService.this) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001163 checkExcessivePowerUsageLocked(true);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07001164 removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001165 Message nmsg = obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
1166 sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001167 }
1168 } break;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001169 case SHOW_COMPAT_MODE_DIALOG_MSG: {
1170 synchronized (ActivityManagerService.this) {
1171 ActivityRecord ar = (ActivityRecord)msg.obj;
1172 if (mCompatModeDialog != null) {
1173 if (mCompatModeDialog.mAppInfo.packageName.equals(
1174 ar.info.applicationInfo.packageName)) {
1175 return;
1176 }
1177 mCompatModeDialog.dismiss();
1178 mCompatModeDialog = null;
1179 }
Dianne Hackborn29478262011-06-07 15:44:22 -07001180 if (ar != null && false) {
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001181 if (mCompatModePackages.getPackageAskCompatModeLocked(
1182 ar.packageName)) {
1183 int mode = mCompatModePackages.computeCompatModeLocked(
1184 ar.info.applicationInfo);
1185 if (mode == ActivityManager.COMPAT_MODE_DISABLED
1186 || mode == ActivityManager.COMPAT_MODE_ENABLED) {
1187 mCompatModeDialog = new CompatModeDialog(
1188 ActivityManagerService.this, mContext,
1189 ar.info.applicationInfo);
1190 mCompatModeDialog.show();
1191 }
1192 }
1193 }
1194 }
Dianne Hackborn36f80f32011-05-31 18:26:45 -07001195 break;
1196 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001197 case DISPATCH_FOREGROUND_ACTIVITIES_CHANGED: {
Jeff Sharkey287bd832011-05-28 19:36:26 -07001198 final int pid = msg.arg1;
1199 final int uid = msg.arg2;
1200 final boolean foregroundActivities = (Boolean) msg.obj;
1201 dispatchForegroundActivitiesChanged(pid, uid, foregroundActivities);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001202 break;
1203 }
1204 case DISPATCH_PROCESS_DIED: {
Jeff Sharkey287bd832011-05-28 19:36:26 -07001205 final int pid = msg.arg1;
1206 final int uid = msg.arg2;
1207 dispatchProcessDied(pid, uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001208 break;
1209 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001210 case REPORT_MEM_USAGE: {
1211 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
1212 if (!isDebuggable) {
1213 return;
1214 }
1215 synchronized (ActivityManagerService.this) {
1216 long now = SystemClock.uptimeMillis();
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001217 if (now < (mLastMemUsageReportTime+5*60*1000)) {
1218 // Don't report more than every 5 minutes to somewhat
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001219 // avoid spamming.
1220 return;
1221 }
1222 mLastMemUsageReportTime = now;
1223 }
1224 Thread thread = new Thread() {
1225 @Override public void run() {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001226 StringBuilder dropBuilder = new StringBuilder(1024);
1227 StringBuilder logBuilder = new StringBuilder(1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -08001228 StringWriter oomSw = new StringWriter();
1229 PrintWriter oomPw = new PrintWriter(oomSw);
1230 StringWriter catSw = new StringWriter();
1231 PrintWriter catPw = new PrintWriter(catSw);
1232 String[] emptyArgs = new String[] { };
1233 StringBuilder tag = new StringBuilder(128);
1234 StringBuilder stack = new StringBuilder(128);
1235 tag.append("Low on memory -- ");
1236 dumpApplicationMemoryUsage(null, oomPw, " ", emptyArgs, true, catPw,
1237 tag, stack);
1238 dropBuilder.append(stack);
1239 dropBuilder.append('\n');
1240 dropBuilder.append('\n');
1241 String oomString = oomSw.toString();
1242 dropBuilder.append(oomString);
1243 dropBuilder.append('\n');
1244 logBuilder.append(oomString);
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001245 try {
1246 java.lang.Process proc = Runtime.getRuntime().exec(new String[] {
1247 "procrank", });
1248 final InputStreamReader converter = new InputStreamReader(
1249 proc.getInputStream());
1250 BufferedReader in = new BufferedReader(converter);
1251 String line;
1252 while (true) {
1253 line = in.readLine();
1254 if (line == null) {
1255 break;
1256 }
1257 if (line.length() > 0) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001258 logBuilder.append(line);
1259 logBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001260 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001261 dropBuilder.append(line);
1262 dropBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001263 }
1264 converter.close();
1265 } catch (IOException e) {
1266 }
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001267 synchronized (ActivityManagerService.this) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08001268 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001269 dumpProcessesLocked(null, catPw, emptyArgs, 0, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001270 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001271 dumpServicesLocked(null, catPw, emptyArgs, 0, false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001272 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001273 dumpActivitiesLocked(null, catPw, emptyArgs, 0, false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001274 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001275 dropBuilder.append(catSw.toString());
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001276 addErrorToDropBox("lowmem", null, "system_server", null,
1277 null, tag.toString(), dropBuilder.toString(), null, null);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001278 Slog.i(TAG, logBuilder.toString());
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001279 synchronized (ActivityManagerService.this) {
1280 long now = SystemClock.uptimeMillis();
1281 if (mLastMemUsageReportTime < now) {
1282 mLastMemUsageReportTime = now;
1283 }
1284 }
1285 }
1286 };
1287 thread.start();
1288 break;
1289 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001290 }
1291 }
1292 };
1293
1294 public static void setSystemProcess() {
1295 try {
1296 ActivityManagerService m = mSelf;
1297
Dianne Hackborna573f6a2012-02-09 16:12:18 -08001298 ServiceManager.addService("activity", m, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001299 ServiceManager.addService("meminfo", new MemBinder(m));
Chet Haase9c1e23b2011-03-24 10:51:31 -07001300 ServiceManager.addService("gfxinfo", new GraphicsBinder(m));
Jeff Brown6754ba22011-12-14 20:20:01 -08001301 ServiceManager.addService("dbinfo", new DbBinder(m));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001302 if (MONITOR_CPU_USAGE) {
1303 ServiceManager.addService("cpuinfo", new CpuBinder(m));
1304 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001305 ServiceManager.addService("permission", new PermissionController(m));
1306
1307 ApplicationInfo info =
1308 mSelf.mContext.getPackageManager().getApplicationInfo(
Amith Yamasani483f3b02012-03-13 16:08:00 -07001309 "android", STOCK_PM_FLAGS);
Mike Cleron432b7132009-09-24 15:28:29 -07001310 mSystemThread.installSystemApplicationInfo(info);
1311
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001312 synchronized (mSelf) {
1313 ProcessRecord app = mSelf.newProcessRecordLocked(
1314 mSystemThread.getApplicationThread(), info,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001315 info.processName, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001316 app.persistent = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08001317 app.pid = MY_PID;
Dianne Hackborn7d608422011-08-07 16:24:18 -07001318 app.maxAdj = ProcessList.SYSTEM_ADJ;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001319 mSelf.mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001320 synchronized (mSelf.mPidsSelfLocked) {
1321 mSelf.mPidsSelfLocked.put(app.pid, app);
1322 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001323 mSelf.updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001324 }
1325 } catch (PackageManager.NameNotFoundException e) {
1326 throw new RuntimeException(
1327 "Unable to find android system package", e);
1328 }
1329 }
1330
1331 public void setWindowManager(WindowManagerService wm) {
1332 mWindowManager = wm;
1333 }
1334
1335 public static final Context main(int factoryTest) {
1336 AThread thr = new AThread();
1337 thr.start();
1338
1339 synchronized (thr) {
1340 while (thr.mService == null) {
1341 try {
1342 thr.wait();
1343 } catch (InterruptedException e) {
1344 }
1345 }
1346 }
1347
1348 ActivityManagerService m = thr.mService;
1349 mSelf = m;
1350 ActivityThread at = ActivityThread.systemMain();
1351 mSystemThread = at;
1352 Context context = at.getSystemContext();
Dianne Hackborn247fe742011-01-08 17:25:57 -08001353 context.setTheme(android.R.style.Theme_Holo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001354 m.mContext = context;
1355 m.mFactoryTest = factoryTest;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001356 m.mMainStack = new ActivityStack(m, context, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001357
1358 m.mBatteryStatsService.publish(context);
1359 m.mUsageStatsService.publish(context);
1360
1361 synchronized (thr) {
1362 thr.mReady = true;
1363 thr.notifyAll();
1364 }
1365
1366 m.startRunning(null, null, null, null);
1367
1368 return context;
1369 }
1370
1371 public static ActivityManagerService self() {
1372 return mSelf;
1373 }
1374
1375 static class AThread extends Thread {
1376 ActivityManagerService mService;
1377 boolean mReady = false;
1378
1379 public AThread() {
1380 super("ActivityManager");
1381 }
1382
1383 public void run() {
1384 Looper.prepare();
1385
1386 android.os.Process.setThreadPriority(
1387 android.os.Process.THREAD_PRIORITY_FOREGROUND);
Christopher Tate160edb32010-06-30 17:46:30 -07001388 android.os.Process.setCanSelfBackground(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001389
1390 ActivityManagerService m = new ActivityManagerService();
1391
1392 synchronized (this) {
1393 mService = m;
1394 notifyAll();
1395 }
1396
1397 synchronized (this) {
1398 while (!mReady) {
1399 try {
1400 wait();
1401 } catch (InterruptedException e) {
1402 }
1403 }
1404 }
1405
Brad Fitzpatrickec062f62010-11-03 09:56:54 -07001406 // For debug builds, log event loop stalls to dropbox for analysis.
1407 if (StrictMode.conditionallyEnableDebugLogging()) {
1408 Slog.i(TAG, "Enabled StrictMode logging for AThread's Looper");
1409 }
1410
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001411 Looper.loop();
1412 }
1413 }
1414
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001415 static class MemBinder extends Binder {
1416 ActivityManagerService mActivityManagerService;
1417 MemBinder(ActivityManagerService activityManagerService) {
1418 mActivityManagerService = activityManagerService;
1419 }
1420
1421 @Override
1422 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001423 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1424 != PackageManager.PERMISSION_GRANTED) {
1425 pw.println("Permission Denial: can't dump meminfo from from pid="
1426 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1427 + " without permission " + android.Manifest.permission.DUMP);
1428 return;
1429 }
1430
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001431 mActivityManagerService.dumpApplicationMemoryUsage(fd, pw, " ", args,
Dianne Hackborn672342c2011-11-29 11:29:02 -08001432 false, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001433 }
1434 }
1435
Chet Haase9c1e23b2011-03-24 10:51:31 -07001436 static class GraphicsBinder extends Binder {
1437 ActivityManagerService mActivityManagerService;
1438 GraphicsBinder(ActivityManagerService activityManagerService) {
1439 mActivityManagerService = activityManagerService;
1440 }
1441
1442 @Override
1443 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001444 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1445 != PackageManager.PERMISSION_GRANTED) {
1446 pw.println("Permission Denial: can't dump gfxinfo from from pid="
1447 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1448 + " without permission " + android.Manifest.permission.DUMP);
1449 return;
1450 }
1451
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001452 mActivityManagerService.dumpGraphicsHardwareUsage(fd, pw, args);
Chet Haase9c1e23b2011-03-24 10:51:31 -07001453 }
1454 }
1455
Jeff Brown6754ba22011-12-14 20:20:01 -08001456 static class DbBinder extends Binder {
1457 ActivityManagerService mActivityManagerService;
1458 DbBinder(ActivityManagerService activityManagerService) {
1459 mActivityManagerService = activityManagerService;
1460 }
1461
1462 @Override
1463 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1464 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1465 != PackageManager.PERMISSION_GRANTED) {
1466 pw.println("Permission Denial: can't dump dbinfo from from pid="
1467 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1468 + " without permission " + android.Manifest.permission.DUMP);
1469 return;
1470 }
1471
1472 mActivityManagerService.dumpDbInfo(fd, pw, args);
1473 }
1474 }
1475
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001476 static class CpuBinder extends Binder {
1477 ActivityManagerService mActivityManagerService;
1478 CpuBinder(ActivityManagerService activityManagerService) {
1479 mActivityManagerService = activityManagerService;
1480 }
1481
1482 @Override
1483 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001484 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1485 != PackageManager.PERMISSION_GRANTED) {
1486 pw.println("Permission Denial: can't dump cpuinfo from from pid="
1487 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1488 + " without permission " + android.Manifest.permission.DUMP);
1489 return;
1490 }
1491
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001492 synchronized (mActivityManagerService.mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07001493 pw.print(mActivityManagerService.mProcessStats.printCurrentLoad());
1494 pw.print(mActivityManagerService.mProcessStats.printCurrentState(
1495 SystemClock.uptimeMillis()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001496 }
1497 }
1498 }
1499
1500 private ActivityManagerService() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001501 Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
Dianne Hackborn2c6c5e62009-10-08 17:55:49 -07001502
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001503 mFgBroadcastQueue = new BroadcastQueue(this, "foreground", BROADCAST_FG_TIMEOUT);
1504 mBgBroadcastQueue = new BroadcastQueue(this, "background", BROADCAST_BG_TIMEOUT);
1505 mBroadcastQueues[0] = mFgBroadcastQueue;
1506 mBroadcastQueues[1] = mBgBroadcastQueue;
1507
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001508 File dataDir = Environment.getDataDirectory();
1509 File systemDir = new File(dataDir, "system");
1510 systemDir.mkdirs();
1511 mBatteryStatsService = new BatteryStatsService(new File(
1512 systemDir, "batterystats.bin").toString());
1513 mBatteryStatsService.getActiveStatistics().readLocked();
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001514 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
Dianne Hackborn287952c2010-09-22 22:34:31 -07001515 mOnBattery = DEBUG_POWER ? true
1516 : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001517 mBatteryStatsService.getActiveStatistics().setCallback(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001518
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001519 mUsageStatsService = new UsageStatsService(new File(
Dianne Hackborn6447ca32009-04-07 19:50:08 -07001520 systemDir, "usagestats").toString());
Mike Lockwood3a74bd32011-08-12 13:55:22 -07001521 mHeadless = "1".equals(SystemProperties.get("ro.config.headless", "0"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001522
Jack Palevichb90d28c2009-07-22 15:35:24 -07001523 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",
1524 ConfigurationInfo.GL_ES_VERSION_UNDEFINED);
1525
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001526 mConfiguration.setToDefaults();
1527 mConfiguration.locale = Locale.getDefault();
Dianne Hackborn813075a62011-11-14 17:45:19 -08001528 mConfigurationSeq = mConfiguration.seq = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001529 mProcessStats.init();
1530
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07001531 mCompatModePackages = new CompatModePackages(this, systemDir);
1532
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001533 // Add ourself to the Watchdog monitors.
1534 Watchdog.getInstance().addMonitor(this);
1535
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001536 mProcessStatsThread = new Thread("ProcessStats") {
1537 public void run() {
1538 while (true) {
1539 try {
1540 try {
1541 synchronized(this) {
1542 final long now = SystemClock.uptimeMillis();
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001543 long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001544 long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001545 //Slog.i(TAG, "Cpu delay=" + nextCpuDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001546 // + ", write delay=" + nextWriteDelay);
1547 if (nextWriteDelay < nextCpuDelay) {
1548 nextCpuDelay = nextWriteDelay;
1549 }
1550 if (nextCpuDelay > 0) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001551 mProcessStatsMutexFree.set(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001552 this.wait(nextCpuDelay);
1553 }
1554 }
1555 } catch (InterruptedException e) {
1556 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001557 updateCpuStatsNow();
1558 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001559 Slog.e(TAG, "Unexpected exception collecting process stats", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001560 }
1561 }
1562 }
1563 };
1564 mProcessStatsThread.start();
1565 }
1566
1567 @Override
1568 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1569 throws RemoteException {
1570 try {
1571 return super.onTransact(code, data, reply, flags);
1572 } catch (RuntimeException e) {
1573 // The activity manager only throws security exceptions, so let's
1574 // log all others.
1575 if (!(e instanceof SecurityException)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001576 Slog.e(TAG, "Activity Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001577 }
1578 throw e;
1579 }
1580 }
1581
1582 void updateCpuStats() {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001583 final long now = SystemClock.uptimeMillis();
1584 if (mLastCpuTime.get() >= now - MONITOR_CPU_MIN_TIME) {
1585 return;
1586 }
1587 if (mProcessStatsMutexFree.compareAndSet(true, false)) {
1588 synchronized (mProcessStatsThread) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001589 mProcessStatsThread.notify();
1590 }
1591 }
1592 }
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001593
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001594 void updateCpuStatsNow() {
1595 synchronized (mProcessStatsThread) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001596 mProcessStatsMutexFree.set(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001597 final long now = SystemClock.uptimeMillis();
1598 boolean haveNewCpuStats = false;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07001599
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001600 if (MONITOR_CPU_USAGE &&
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001601 mLastCpuTime.get() < (now-MONITOR_CPU_MIN_TIME)) {
1602 mLastCpuTime.set(now);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001603 haveNewCpuStats = true;
1604 mProcessStats.update();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001605 //Slog.i(TAG, mProcessStats.printCurrentState());
1606 //Slog.i(TAG, "Total CPU usage: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001607 // + mProcessStats.getTotalCpuPercent() + "%");
1608
Joe Onorato8a9b2202010-02-26 18:56:32 -08001609 // Slog the cpu usage if the property is set.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001610 if ("true".equals(SystemProperties.get("events.cpu"))) {
1611 int user = mProcessStats.getLastUserTime();
1612 int system = mProcessStats.getLastSystemTime();
1613 int iowait = mProcessStats.getLastIoWaitTime();
1614 int irq = mProcessStats.getLastIrqTime();
1615 int softIrq = mProcessStats.getLastSoftIrqTime();
1616 int idle = mProcessStats.getLastIdleTime();
1617
1618 int total = user + system + iowait + irq + softIrq + idle;
1619 if (total == 0) total = 1;
1620
Doug Zongker2bec3d42009-12-04 12:52:44 -08001621 EventLog.writeEvent(EventLogTags.CPU,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001622 ((user+system+iowait+irq+softIrq) * 100) / total,
1623 (user * 100) / total,
1624 (system * 100) / total,
1625 (iowait * 100) / total,
1626 (irq * 100) / total,
1627 (softIrq * 100) / total);
1628 }
1629 }
1630
Amith Yamasanie43530a2009-08-21 13:11:37 -07001631 long[] cpuSpeedTimes = mProcessStats.getLastCpuSpeedTimes();
Amith Yamasani819f9282009-06-24 23:18:15 -07001632 final BatteryStatsImpl bstats = mBatteryStatsService.getActiveStatistics();
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001633 synchronized(bstats) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001634 synchronized(mPidsSelfLocked) {
1635 if (haveNewCpuStats) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001636 if (mOnBattery) {
1637 int perc = bstats.startAddingCpuLocked();
1638 int totalUTime = 0;
1639 int totalSTime = 0;
Dianne Hackborn287952c2010-09-22 22:34:31 -07001640 final int N = mProcessStats.countStats();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001641 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001642 ProcessStats.Stats st = mProcessStats.getStats(i);
1643 if (!st.working) {
1644 continue;
1645 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001646 ProcessRecord pr = mPidsSelfLocked.get(st.pid);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001647 int otherUTime = (st.rel_utime*perc)/100;
1648 int otherSTime = (st.rel_stime*perc)/100;
1649 totalUTime += otherUTime;
1650 totalSTime += otherSTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001651 if (pr != null) {
1652 BatteryStatsImpl.Uid.Proc ps = pr.batteryStats;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001653 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1654 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001655 ps.addSpeedStepTimes(cpuSpeedTimes);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001656 pr.curCpuTime += (st.rel_utime+st.rel_stime) * 10;
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001657 } else {
1658 BatteryStatsImpl.Uid.Proc ps =
Amith Yamasani819f9282009-06-24 23:18:15 -07001659 bstats.getProcessStatsLocked(st.name, st.pid);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001660 if (ps != null) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001661 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1662 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001663 ps.addSpeedStepTimes(cpuSpeedTimes);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001664 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001665 }
1666 }
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001667 bstats.finishAddingCpuLocked(perc, totalUTime,
1668 totalSTime, cpuSpeedTimes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001669 }
1670 }
1671 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001672
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001673 if (mLastWriteTime < (now-BATTERY_STATS_TIME)) {
1674 mLastWriteTime = now;
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001675 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001676 }
1677 }
1678 }
1679 }
1680
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001681 @Override
1682 public void batteryNeedsCpuUpdate() {
1683 updateCpuStatsNow();
1684 }
1685
1686 @Override
1687 public void batteryPowerChanged(boolean onBattery) {
1688 // When plugging in, update the CPU stats first before changing
1689 // the plug state.
1690 updateCpuStatsNow();
1691 synchronized (this) {
1692 synchronized(mPidsSelfLocked) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001693 mOnBattery = DEBUG_POWER ? true : onBattery;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001694 }
1695 }
1696 }
1697
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001698 /**
1699 * Initialize the application bind args. These are passed to each
1700 * process when the bindApplication() IPC is sent to the process. They're
1701 * lazily setup to make sure the services are running when they're asked for.
1702 */
1703 private HashMap<String, IBinder> getCommonServicesLocked() {
1704 if (mAppBindArgs == null) {
1705 mAppBindArgs = new HashMap<String, IBinder>();
1706
1707 // Setup the application init args
1708 mAppBindArgs.put("package", ServiceManager.getService("package"));
1709 mAppBindArgs.put("window", ServiceManager.getService("window"));
1710 mAppBindArgs.put(Context.ALARM_SERVICE,
1711 ServiceManager.getService(Context.ALARM_SERVICE));
1712 }
1713 return mAppBindArgs;
1714 }
1715
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001716 final void setFocusedActivityLocked(ActivityRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001717 if (mFocusedActivity != r) {
1718 mFocusedActivity = r;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001719 if (r != null) {
1720 mWindowManager.setFocusedApp(r.appToken, true);
1721 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001722 }
1723 }
1724
Dianne Hackborn906497c2010-05-10 15:57:38 -07001725 private final void updateLruProcessInternalLocked(ProcessRecord app,
1726 boolean oomAdj, boolean updateActivityTime, int bestPos) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001727 // put it on the LRU to keep track of when it should be exited.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001728 int lrui = mLruProcesses.indexOf(app);
1729 if (lrui >= 0) mLruProcesses.remove(lrui);
1730
1731 int i = mLruProcesses.size()-1;
1732 int skipTop = 0;
1733
Dianne Hackborn906497c2010-05-10 15:57:38 -07001734 app.lruSeq = mLruSeq;
1735
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001736 // compute the new weight for this process.
1737 if (updateActivityTime) {
1738 app.lastActivityTime = SystemClock.uptimeMillis();
1739 }
1740 if (app.activities.size() > 0) {
1741 // If this process has activities, we more strongly want to keep
1742 // it around.
1743 app.lruWeight = app.lastActivityTime;
1744 } else if (app.pubProviders.size() > 0) {
1745 // If this process contains content providers, we want to keep
1746 // it a little more strongly.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001747 app.lruWeight = app.lastActivityTime - ProcessList.CONTENT_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001748 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001749 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001750 } else {
1751 // If this process doesn't have activities, we less strongly
1752 // want to keep it around, and generally want to avoid getting
1753 // in front of any very recently used activities.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001754 app.lruWeight = app.lastActivityTime - ProcessList.EMPTY_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001755 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001756 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001757 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001758
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001759 while (i >= 0) {
1760 ProcessRecord p = mLruProcesses.get(i);
1761 // If this app shouldn't be in front of the first N background
1762 // apps, then skip over that many that are currently hidden.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001763 if (skipTop > 0 && p.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001764 skipTop--;
1765 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001766 if (p.lruWeight <= app.lruWeight || i < bestPos) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001767 mLruProcesses.add(i+1, app);
1768 break;
1769 }
1770 i--;
1771 }
1772 if (i < 0) {
1773 mLruProcesses.add(0, app);
1774 }
1775
Dianne Hackborn906497c2010-05-10 15:57:38 -07001776 // If the app is currently using a content provider or service,
1777 // bump those processes as well.
1778 if (app.connections.size() > 0) {
1779 for (ConnectionRecord cr : app.connections) {
1780 if (cr.binding != null && cr.binding.service != null
1781 && cr.binding.service.app != null
1782 && cr.binding.service.app.lruSeq != mLruSeq) {
1783 updateLruProcessInternalLocked(cr.binding.service.app, oomAdj,
1784 updateActivityTime, i+1);
1785 }
1786 }
1787 }
1788 if (app.conProviders.size() > 0) {
1789 for (ContentProviderRecord cpr : app.conProviders.keySet()) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07001790 if (cpr.proc != null && cpr.proc.lruSeq != mLruSeq) {
1791 updateLruProcessInternalLocked(cpr.proc, oomAdj,
Dianne Hackborn906497c2010-05-10 15:57:38 -07001792 updateActivityTime, i+1);
1793 }
1794 }
1795 }
1796
Joe Onorato8a9b2202010-02-26 18:56:32 -08001797 //Slog.i(TAG, "Putting proc to front: " + app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001798 if (oomAdj) {
1799 updateOomAdjLocked();
1800 }
1801 }
1802
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001803 final void updateLruProcessLocked(ProcessRecord app,
Dianne Hackborn906497c2010-05-10 15:57:38 -07001804 boolean oomAdj, boolean updateActivityTime) {
1805 mLruSeq++;
1806 updateLruProcessInternalLocked(app, oomAdj, updateActivityTime, 0);
1807 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001808
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001809 final ProcessRecord getProcessRecordLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001810 String processName, int uid) {
Amith Yamasania4a54e22012-04-16 15:44:19 -07001811 if (uid == Process.SYSTEM_UID) {
Amith Yamasani0184ce92012-03-28 22:41:41 -07001812 // The system gets to run in any process. If there are multiple
1813 // processes with the same uid, just pick the first (this
1814 // should never happen).
1815 SparseArray<ProcessRecord> procs = mProcessNames.getMap().get(
1816 processName);
Amith Yamasania4a54e22012-04-16 15:44:19 -07001817 if (procs == null) return null;
1818 final int N = procs.size();
1819 for (int i = 0; i < N; i++) {
1820 if (UserId.isSameUser(procs.keyAt(i), uid)) return procs.valueAt(i);
1821 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001822 }
1823 ProcessRecord proc = mProcessNames.get(processName, uid);
1824 return proc;
1825 }
1826
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001827 void ensurePackageDexOpt(String packageName) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001828 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001829 try {
1830 if (pm.performDexOpt(packageName)) {
1831 mDidDexOpt = true;
1832 }
1833 } catch (RemoteException e) {
1834 }
1835 }
1836
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001837 boolean isNextTransitionForward() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001838 int transit = mWindowManager.getPendingAppTransition();
1839 return transit == WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
1840 || transit == WindowManagerPolicy.TRANSIT_TASK_OPEN
1841 || transit == WindowManagerPolicy.TRANSIT_TASK_TO_FRONT;
1842 }
1843
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001844 final ProcessRecord startProcessLocked(String processName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001845 ApplicationInfo info, boolean knownToBeDead, int intentFlags,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001846 String hostingType, ComponentName hostingName, boolean allowWhileBooting,
1847 boolean isolated) {
1848 ProcessRecord app;
1849 if (!isolated) {
1850 app = getProcessRecordLocked(processName, info.uid);
1851 } else {
1852 // If this is an isolated process, it can't re-use an existing process.
1853 app = null;
1854 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001855 // We don't have to do anything more if:
1856 // (1) There is an existing application record; and
1857 // (2) The caller doesn't think it is dead, OR there is no thread
1858 // object attached to it so we know it couldn't have crashed; and
1859 // (3) There is a pid assigned to it, so it is either starting or
1860 // already running.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001861 if (DEBUG_PROCESSES) Slog.v(TAG, "startProcess: name=" + processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001862 + " app=" + app + " knownToBeDead=" + knownToBeDead
1863 + " thread=" + (app != null ? app.thread : null)
1864 + " pid=" + (app != null ? app.pid : -1));
Magnus Edlund7bb25812010-02-24 15:45:06 +01001865 if (app != null && app.pid > 0) {
1866 if (!knownToBeDead || app.thread == null) {
Dianne Hackborn20cb56e2010-03-04 00:58:29 -08001867 // We already have the app running, or are waiting for it to
1868 // come up (we have a pid but not yet its thread), so keep it.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001869 if (DEBUG_PROCESSES) Slog.v(TAG, "App already running: " + app);
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001870 // If this is a new package in the process, add the package to the list
1871 app.addPackage(info.packageName);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001872 return app;
1873 } else {
1874 // An application record is attached to a previous process,
1875 // clean it up now.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001876 if (DEBUG_PROCESSES) Slog.v(TAG, "App died: " + app);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07001877 handleAppDiedLocked(app, true, true);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001878 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001879 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01001880
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001881 String hostingNameStr = hostingName != null
1882 ? hostingName.flattenToShortString() : null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001883
1884 if (!isolated) {
1885 if ((intentFlags&Intent.FLAG_FROM_BACKGROUND) != 0) {
1886 // If we are in the background, then check to see if this process
1887 // is bad. If so, we will just silently fail.
1888 if (mBadProcesses.get(info.processName, info.uid) != null) {
1889 if (DEBUG_PROCESSES) Slog.v(TAG, "Bad process: " + info.uid
1890 + "/" + info.processName);
1891 return null;
1892 }
1893 } else {
1894 // When the user is explicitly starting a process, then clear its
1895 // crash count so that we won't make it bad until they see at
1896 // least one crash dialog again, and make the process good again
1897 // if it had been bad.
1898 if (DEBUG_PROCESSES) Slog.v(TAG, "Clearing bad process: " + info.uid
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001899 + "/" + info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001900 mProcessCrashTimes.remove(info.processName, info.uid);
1901 if (mBadProcesses.get(info.processName, info.uid) != null) {
1902 EventLog.writeEvent(EventLogTags.AM_PROC_GOOD, info.uid,
1903 info.processName);
1904 mBadProcesses.remove(info.processName, info.uid);
1905 if (app != null) {
1906 app.bad = false;
1907 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001908 }
1909 }
1910 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001911
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001912 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001913 app = newProcessRecordLocked(null, info, processName, isolated);
1914 if (app == null) {
1915 Slog.w(TAG, "Failed making new process record for "
1916 + processName + "/" + info.uid + " isolated=" + isolated);
1917 return null;
1918 }
1919 mProcessNames.put(processName, app.uid, app);
1920 if (isolated) {
1921 mIsolatedProcesses.put(app.uid, app);
1922 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001923 } else {
1924 // If this is a new package in the process, add the package to the list
1925 app.addPackage(info.packageName);
1926 }
1927
1928 // If the system is not ready yet, then hold off on starting this
1929 // process until it is.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001930 if (!mProcessesReady
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001931 && !isAllowedWhileBooting(info)
1932 && !allowWhileBooting) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001933 if (!mProcessesOnHold.contains(app)) {
1934 mProcessesOnHold.add(app);
1935 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001936 if (DEBUG_PROCESSES) Slog.v(TAG, "System not ready, putting on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001937 return app;
1938 }
1939
1940 startProcessLocked(app, hostingType, hostingNameStr);
1941 return (app.pid != 0) ? app : null;
1942 }
1943
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001944 boolean isAllowedWhileBooting(ApplicationInfo ai) {
1945 return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0;
1946 }
1947
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001948 private final void startProcessLocked(ProcessRecord app,
1949 String hostingType, String hostingNameStr) {
1950 if (app.pid > 0 && app.pid != MY_PID) {
1951 synchronized (mPidsSelfLocked) {
1952 mPidsSelfLocked.remove(app.pid);
1953 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
1954 }
1955 app.pid = 0;
1956 }
1957
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001958 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
1959 "startProcessLocked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001960 mProcessesOnHold.remove(app);
1961
1962 updateCpuStats();
1963
1964 System.arraycopy(mProcDeaths, 0, mProcDeaths, 1, mProcDeaths.length-1);
1965 mProcDeaths[0] = 0;
1966
1967 try {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001968 int uid = app.uid;
Amith Yamasani742a6712011-05-04 14:49:28 -07001969
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001970 int[] gids = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001971 if (!app.isolated) {
1972 try {
1973 gids = mContext.getPackageManager().getPackageGids(
1974 app.info.packageName);
1975 } catch (PackageManager.NameNotFoundException e) {
1976 Slog.w(TAG, "Unable to retrieve gids", e);
1977 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001978 }
1979 if (mFactoryTest != SystemServer.FACTORY_TEST_OFF) {
1980 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
1981 && mTopComponent != null
1982 && app.processName.equals(mTopComponent.getPackageName())) {
1983 uid = 0;
1984 }
1985 if (mFactoryTest == SystemServer.FACTORY_TEST_HIGH_LEVEL
1986 && (app.info.flags&ApplicationInfo.FLAG_FACTORY_TEST) != 0) {
1987 uid = 0;
1988 }
1989 }
1990 int debugFlags = 0;
1991 if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
1992 debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;
Elliott Hughesfa36aee2011-06-17 14:39:41 -07001993 // Also turn on CheckJNI for debuggable apps. It's quite
1994 // awkward to turn on otherwise.
1995 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001996 }
Ben Cheng6c0afff2010-02-14 16:18:56 -08001997 // Run the app in safe mode if its manifest requests so or the
1998 // system is booted in safe mode.
1999 if ((app.info.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0 ||
2000 Zygote.systemInSafeMode == true) {
Ben Cheng23085b72010-02-08 16:06:32 -08002001 debugFlags |= Zygote.DEBUG_ENABLE_SAFEMODE;
2002 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002003 if ("1".equals(SystemProperties.get("debug.checkjni"))) {
2004 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
2005 }
Elliott Hughesae07ecf2011-07-06 17:33:27 -07002006 if ("1".equals(SystemProperties.get("debug.jni.logging"))) {
2007 debugFlags |= Zygote.DEBUG_ENABLE_JNI_LOGGING;
2008 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002009 if ("1".equals(SystemProperties.get("debug.assert"))) {
2010 debugFlags |= Zygote.DEBUG_ENABLE_ASSERT;
2011 }
Jeff Brown3f9dd282011-07-08 20:02:19 -07002012
2013 // Start the process. It will either succeed and return a result containing
2014 // the PID of the new process, or else throw a RuntimeException.
2015 Process.ProcessStartResult startResult = Process.start("android.app.ActivityThread",
Elliott Hughese1dfcb72011-07-08 11:08:07 -07002016 app.processName, uid, uid, gids, debugFlags,
2017 app.info.targetSdkVersion, null);
Jeff Brown3f9dd282011-07-08 20:02:19 -07002018
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002019 BatteryStatsImpl bs = app.batteryStats.getBatteryStats();
2020 synchronized (bs) {
2021 if (bs.isOnBattery()) {
2022 app.batteryStats.incStartsLocked();
2023 }
2024 }
2025
Jeff Brown3f9dd282011-07-08 20:02:19 -07002026 EventLog.writeEvent(EventLogTags.AM_PROC_START, startResult.pid, uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002027 app.processName, hostingType,
2028 hostingNameStr != null ? hostingNameStr : "");
2029
2030 if (app.persistent) {
Jeff Brown3f9dd282011-07-08 20:02:19 -07002031 Watchdog.getInstance().processStarted(app.processName, startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002032 }
2033
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07002034 StringBuilder buf = mStringBuilder;
2035 buf.setLength(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002036 buf.append("Start proc ");
2037 buf.append(app.processName);
2038 buf.append(" for ");
2039 buf.append(hostingType);
2040 if (hostingNameStr != null) {
2041 buf.append(" ");
2042 buf.append(hostingNameStr);
2043 }
2044 buf.append(": pid=");
Jeff Brown3f9dd282011-07-08 20:02:19 -07002045 buf.append(startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002046 buf.append(" uid=");
2047 buf.append(uid);
2048 buf.append(" gids={");
2049 if (gids != null) {
2050 for (int gi=0; gi<gids.length; gi++) {
2051 if (gi != 0) buf.append(", ");
2052 buf.append(gids[gi]);
2053
2054 }
2055 }
2056 buf.append("}");
Joe Onorato8a9b2202010-02-26 18:56:32 -08002057 Slog.i(TAG, buf.toString());
Jeff Brown3f9dd282011-07-08 20:02:19 -07002058 app.pid = startResult.pid;
2059 app.usingWrapper = startResult.usingWrapper;
2060 app.removed = false;
2061 synchronized (mPidsSelfLocked) {
2062 this.mPidsSelfLocked.put(startResult.pid, app);
2063 Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
2064 msg.obj = app;
2065 mHandler.sendMessageDelayed(msg, startResult.usingWrapper
2066 ? PROC_START_TIMEOUT_WITH_WRAPPER : PROC_START_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002067 }
2068 } catch (RuntimeException e) {
2069 // XXX do better error recovery.
2070 app.pid = 0;
Joe Onorato8a9b2202010-02-26 18:56:32 -08002071 Slog.e(TAG, "Failure starting process " + app.processName, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002072 }
2073 }
2074
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002075 void updateUsageStats(ActivityRecord resumedComponent, boolean resumed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002076 if (resumed) {
2077 mUsageStatsService.noteResumeComponent(resumedComponent.realActivity);
2078 } else {
2079 mUsageStatsService.notePauseComponent(resumedComponent.realActivity);
2080 }
2081 }
2082
Amith Yamasani742a6712011-05-04 14:49:28 -07002083 boolean startHomeActivityLocked(int userId) {
Mike Lockwooda8f767a2011-08-31 14:32:37 -04002084 if (mHeadless) {
2085 // Added because none of the other calls to ensureBootCompleted seem to fire
2086 // when running headless.
2087 ensureBootCompleted();
2088 return false;
2089 }
2090
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002091 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2092 && mTopAction == null) {
2093 // We are running in factory test mode, but unable to find
2094 // the factory test app, so just sit around displaying the
2095 // error message and don't try to start anything.
2096 return false;
2097 }
2098 Intent intent = new Intent(
2099 mTopAction,
2100 mTopData != null ? Uri.parse(mTopData) : null);
2101 intent.setComponent(mTopComponent);
2102 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
2103 intent.addCategory(Intent.CATEGORY_HOME);
2104 }
2105 ActivityInfo aInfo =
2106 intent.resolveActivityInfo(mContext.getPackageManager(),
2107 STOCK_PM_FLAGS);
2108 if (aInfo != null) {
2109 intent.setComponent(new ComponentName(
2110 aInfo.applicationInfo.packageName, aInfo.name));
2111 // Don't do this if the home app is currently being
2112 // instrumented.
Amith Yamasani742a6712011-05-04 14:49:28 -07002113 aInfo = new ActivityInfo(aInfo);
2114 aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002115 ProcessRecord app = getProcessRecordLocked(aInfo.processName,
2116 aInfo.applicationInfo.uid);
2117 if (app == null || app.instrumentationClass == null) {
2118 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002119 mMainStack.startActivityLocked(null, intent, null, aInfo,
2120 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002121 }
2122 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002123
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002124 return true;
2125 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002126
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002127 /**
2128 * Starts the "new version setup screen" if appropriate.
2129 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002130 void startSetupActivityLocked() {
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002131 // Only do this once per boot.
2132 if (mCheckedForSetup) {
2133 return;
2134 }
2135
2136 // We will show this screen if the current one is a different
2137 // version than the last one shown, and we are not running in
2138 // low-level factory test mode.
2139 final ContentResolver resolver = mContext.getContentResolver();
2140 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL &&
2141 Settings.Secure.getInt(resolver,
2142 Settings.Secure.DEVICE_PROVISIONED, 0) != 0) {
2143 mCheckedForSetup = true;
2144
2145 // See if we should be showing the platform update setup UI.
2146 Intent intent = new Intent(Intent.ACTION_UPGRADE_SETUP);
2147 List<ResolveInfo> ris = mSelf.mContext.getPackageManager()
2148 .queryIntentActivities(intent, PackageManager.GET_META_DATA);
2149
2150 // We don't allow third party apps to replace this.
2151 ResolveInfo ri = null;
2152 for (int i=0; ris != null && i<ris.size(); i++) {
2153 if ((ris.get(i).activityInfo.applicationInfo.flags
2154 & ApplicationInfo.FLAG_SYSTEM) != 0) {
2155 ri = ris.get(i);
2156 break;
2157 }
2158 }
2159
2160 if (ri != null) {
2161 String vers = ri.activityInfo.metaData != null
2162 ? ri.activityInfo.metaData.getString(Intent.METADATA_SETUP_VERSION)
2163 : null;
2164 if (vers == null && ri.activityInfo.applicationInfo.metaData != null) {
2165 vers = ri.activityInfo.applicationInfo.metaData.getString(
2166 Intent.METADATA_SETUP_VERSION);
2167 }
2168 String lastVers = Settings.Secure.getString(
2169 resolver, Settings.Secure.LAST_SETUP_SHOWN);
2170 if (vers != null && !vers.equals(lastVers)) {
2171 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2172 intent.setComponent(new ComponentName(
2173 ri.activityInfo.packageName, ri.activityInfo.name));
Dianne Hackborna4972e92012-03-14 10:38:05 -07002174 mMainStack.startActivityLocked(null, intent, null, ri.activityInfo,
2175 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002176 }
2177 }
2178 }
2179 }
2180
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002181 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002182 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002183 }
2184
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002185 void enforceNotIsolatedCaller(String caller) {
2186 if (UserId.isIsolated(Binder.getCallingUid())) {
2187 throw new SecurityException("Isolated process not allowed to call " + caller);
2188 }
2189 }
2190
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002191 public int getFrontActivityScreenCompatMode() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002192 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002193 synchronized (this) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002194 return mCompatModePackages.getFrontActivityScreenCompatModeLocked();
2195 }
2196 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002197
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002198 public void setFrontActivityScreenCompatMode(int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002199 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2200 "setFrontActivityScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002201 synchronized (this) {
2202 mCompatModePackages.setFrontActivityScreenCompatModeLocked(mode);
2203 }
2204 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002205
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002206 public int getPackageScreenCompatMode(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002207 enforceNotIsolatedCaller("getPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002208 synchronized (this) {
2209 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
2210 }
2211 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002212
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002213 public void setPackageScreenCompatMode(String packageName, int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002214 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2215 "setPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002216 synchronized (this) {
2217 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002218 }
2219 }
2220
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002221 public boolean getPackageAskScreenCompat(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002222 enforceNotIsolatedCaller("getPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002223 synchronized (this) {
2224 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
2225 }
2226 }
2227
2228 public void setPackageAskScreenCompat(String packageName, boolean ask) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002229 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2230 "setPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002231 synchronized (this) {
2232 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
2233 }
2234 }
2235
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002236 void reportResumedActivityLocked(ActivityRecord r) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002237 //Slog.i(TAG, "**** REPORT RESUME: " + r);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002238
2239 final int identHash = System.identityHashCode(r);
2240 updateUsageStats(r, true);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002241 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002242
Jeff Sharkeya4620792011-05-20 15:29:23 -07002243 private void dispatchForegroundActivitiesChanged(int pid, int uid, boolean foregroundActivities) {
2244 int i = mProcessObservers.beginBroadcast();
2245 while (i > 0) {
2246 i--;
2247 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2248 if (observer != null) {
2249 try {
2250 observer.onForegroundActivitiesChanged(pid, uid, foregroundActivities);
2251 } catch (RemoteException e) {
2252 }
2253 }
2254 }
2255 mProcessObservers.finishBroadcast();
2256 }
2257
2258 private void dispatchProcessDied(int pid, int uid) {
2259 int i = mProcessObservers.beginBroadcast();
2260 while (i > 0) {
2261 i--;
2262 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2263 if (observer != null) {
2264 try {
2265 observer.onProcessDied(pid, uid);
2266 } catch (RemoteException e) {
2267 }
2268 }
2269 }
2270 mProcessObservers.finishBroadcast();
2271 }
2272
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002273 final void doPendingActivityLaunchesLocked(boolean doResume) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002274 final int N = mPendingActivityLaunches.size();
2275 if (N <= 0) {
2276 return;
2277 }
2278 for (int i=0; i<N; i++) {
2279 PendingActivityLaunch pal = mPendingActivityLaunches.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002280 mMainStack.startActivityUncheckedLocked(pal.r, pal.sourceRecord,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002281 pal.startFlags, doResume && i == (N-1), null);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002282 }
2283 mPendingActivityLaunches.clear();
2284 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002285
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002286 public final int startActivity(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002287 Intent intent, String resolvedType, IBinder resultTo,
2288 String resultWho, int requestCode, int startFlags,
2289 String profileFile, ParcelFileDescriptor profileFd, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002290 enforceNotIsolatedCaller("startActivity");
Amith Yamasani742a6712011-05-04 14:49:28 -07002291 int userId = 0;
2292 if (intent.getCategories() != null && intent.getCategories().contains(Intent.CATEGORY_HOME)) {
2293 // Requesting home, set the identity to the current user
2294 // HACK!
2295 userId = mCurrentUserId;
2296 } else {
2297 // TODO: Fix this in a better way - calls coming from SystemUI should probably carry
2298 // the current user's userId
2299 if (Binder.getCallingUid() < Process.FIRST_APPLICATION_UID) {
2300 userId = 0;
2301 } else {
2302 userId = Binder.getOrigCallingUser();
2303 }
2304 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002305 return mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002306 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
2307 null, null, options, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002308 }
2309
2310 public final WaitResult startActivityAndWait(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002311 Intent intent, String resolvedType, IBinder resultTo,
2312 String resultWho, int requestCode, int startFlags, String profileFile,
2313 ParcelFileDescriptor profileFd, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002314 enforceNotIsolatedCaller("startActivityAndWait");
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002315 WaitResult res = new WaitResult();
Amith Yamasani742a6712011-05-04 14:49:28 -07002316 int userId = Binder.getOrigCallingUser();
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002317 mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002318 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
2319 res, null, options, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002320 return res;
2321 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08002322
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002323 public final int startActivityWithConfig(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002324 Intent intent, String resolvedType, IBinder resultTo,
2325 String resultWho, int requestCode, int startFlags, Configuration config,
2326 Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002327 enforceNotIsolatedCaller("startActivityWithConfig");
Amith Yamasani742a6712011-05-04 14:49:28 -07002328 int ret = mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002329 resultTo, resultWho, requestCode, startFlags,
2330 null, null, null, config, options, Binder.getOrigCallingUser());
Amith Yamasani742a6712011-05-04 14:49:28 -07002331 return ret;
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002332 }
2333
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002334 public int startActivityIntentSender(IApplicationThread caller,
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002335 IntentSender intent, Intent fillInIntent, String resolvedType,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002336 IBinder resultTo, String resultWho, int requestCode,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002337 int flagsMask, int flagsValues, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002338 enforceNotIsolatedCaller("startActivityIntentSender");
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002339 // Refuse possible leaked file descriptors
2340 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
2341 throw new IllegalArgumentException("File descriptors passed in Intent");
2342 }
2343
2344 IIntentSender sender = intent.getTarget();
2345 if (!(sender instanceof PendingIntentRecord)) {
2346 throw new IllegalArgumentException("Bad PendingIntent object");
2347 }
2348
2349 PendingIntentRecord pir = (PendingIntentRecord)sender;
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002350
2351 synchronized (this) {
2352 // If this is coming from the currently resumed activity, it is
2353 // effectively saying that app switches are allowed at this point.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002354 if (mMainStack.mResumedActivity != null
2355 && mMainStack.mResumedActivity.info.applicationInfo.uid ==
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002356 Binder.getCallingUid()) {
2357 mAppSwitchesAllowedTime = 0;
2358 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002359 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002360 int ret = pir.sendInner(0, fillInIntent, resolvedType, null, null,
2361 resultTo, resultWho, requestCode, flagsMask, flagsValues, options);
Amith Yamasani742a6712011-05-04 14:49:28 -07002362 return ret;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002363 }
2364
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002365 public boolean startNextMatchingActivity(IBinder callingActivity,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002366 Intent intent, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002367 // Refuse possible leaked file descriptors
2368 if (intent != null && intent.hasFileDescriptors() == true) {
2369 throw new IllegalArgumentException("File descriptors passed in Intent");
2370 }
2371
2372 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002373 ActivityRecord r = mMainStack.isInStackLocked(callingActivity);
2374 if (r == null) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002375 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002376 return false;
2377 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002378 if (r.app == null || r.app.thread == null) {
2379 // The caller is not running... d'oh!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002380 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002381 return false;
2382 }
2383 intent = new Intent(intent);
2384 // The caller is not allowed to change the data.
2385 intent.setDataAndType(r.intent.getData(), r.intent.getType());
2386 // And we are resetting to find the next component...
2387 intent.setComponent(null);
2388
2389 ActivityInfo aInfo = null;
2390 try {
2391 List<ResolveInfo> resolves =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002392 AppGlobals.getPackageManager().queryIntentActivities(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002393 intent, r.resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002394 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
2395 UserId.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002396
2397 // Look for the original activity in the list...
2398 final int N = resolves != null ? resolves.size() : 0;
2399 for (int i=0; i<N; i++) {
2400 ResolveInfo rInfo = resolves.get(i);
2401 if (rInfo.activityInfo.packageName.equals(r.packageName)
2402 && rInfo.activityInfo.name.equals(r.info.name)) {
2403 // We found the current one... the next matching is
2404 // after it.
2405 i++;
2406 if (i<N) {
2407 aInfo = resolves.get(i).activityInfo;
2408 }
2409 break;
2410 }
2411 }
2412 } catch (RemoteException e) {
2413 }
2414
2415 if (aInfo == null) {
2416 // Nobody who is next!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002417 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002418 return false;
2419 }
2420
2421 intent.setComponent(new ComponentName(
2422 aInfo.applicationInfo.packageName, aInfo.name));
2423 intent.setFlags(intent.getFlags()&~(
2424 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
2425 Intent.FLAG_ACTIVITY_CLEAR_TOP|
2426 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
2427 Intent.FLAG_ACTIVITY_NEW_TASK));
2428
2429 // Okay now we need to start the new activity, replacing the
2430 // currently running activity. This is a little tricky because
2431 // we want to start the new one as if the current one is finished,
2432 // but not finish the current one first so that there is no flicker.
2433 // And thus...
2434 final boolean wasFinishing = r.finishing;
2435 r.finishing = true;
2436
2437 // Propagate reply information over to the new activity.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002438 final ActivityRecord resultTo = r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002439 final String resultWho = r.resultWho;
2440 final int requestCode = r.requestCode;
2441 r.resultTo = null;
2442 if (resultTo != null) {
2443 resultTo.removeResultsLocked(r, resultWho, requestCode);
2444 }
2445
2446 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002447 int res = mMainStack.startActivityLocked(r.app.thread, intent,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002448 r.resolvedType, aInfo, resultTo != null ? resultTo.appToken : null,
2449 resultWho, requestCode, -1, r.launchedFromUid, 0,
2450 options, false, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002451 Binder.restoreCallingIdentity(origId);
2452
2453 r.finishing = wasFinishing;
Dianne Hackborna4972e92012-03-14 10:38:05 -07002454 if (res != ActivityManager.START_SUCCESS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002455 return false;
2456 }
2457 return true;
2458 }
2459 }
2460
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002461 public final int startActivityInPackage(int uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002462 Intent intent, String resolvedType, IBinder resultTo,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002463 String resultWho, int requestCode, int startFlags, Bundle options) {
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002464
2465 // This is so super not safe, that only the system (or okay root)
2466 // can do it.
Amith Yamasani742a6712011-05-04 14:49:28 -07002467 int userId = Binder.getOrigCallingUser();
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002468 final int callingUid = Binder.getCallingUid();
2469 if (callingUid != 0 && callingUid != Process.myUid()) {
2470 throw new SecurityException(
2471 "startActivityInPackage only available to the system");
2472 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002473
Amith Yamasani742a6712011-05-04 14:49:28 -07002474 int ret = mMainStack.startActivityMayWait(null, uid, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002475 resultTo, resultWho, requestCode, startFlags,
2476 null, null, null, null, options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002477 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002478 }
2479
2480 public final int startActivities(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002481 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002482 enforceNotIsolatedCaller("startActivities");
Amith Yamasani742a6712011-05-04 14:49:28 -07002483 int ret = mMainStack.startActivities(caller, -1, intents, resolvedTypes, resultTo,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002484 options, Binder.getOrigCallingUser());
Amith Yamasani742a6712011-05-04 14:49:28 -07002485 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002486 }
2487
2488 public final int startActivitiesInPackage(int uid,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002489 Intent[] intents, String[] resolvedTypes, IBinder resultTo,
2490 Bundle options) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002491
2492 // This is so super not safe, that only the system (or okay root)
2493 // can do it.
2494 final int callingUid = Binder.getCallingUid();
2495 if (callingUid != 0 && callingUid != Process.myUid()) {
2496 throw new SecurityException(
2497 "startActivityInPackage only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002498 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002499 int ret = mMainStack.startActivities(null, uid, intents, resolvedTypes, resultTo,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002500 options, UserId.getUserId(uid));
Amith Yamasani742a6712011-05-04 14:49:28 -07002501 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002502 }
2503
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002504 final void addRecentTaskLocked(TaskRecord task) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002505 int N = mRecentTasks.size();
Dianne Hackborn7c0e75e2010-12-21 19:15:40 -08002506 // Quick case: check if the top-most recent task is the same.
2507 if (N > 0 && mRecentTasks.get(0) == task) {
2508 return;
2509 }
2510 // Remove any existing entries that are the same kind of task.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002511 for (int i=0; i<N; i++) {
2512 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07002513 if (task.userId == tr.userId
2514 && ((task.affinity != null && task.affinity.equals(tr.affinity))
2515 || (task.intent != null && task.intent.filterEquals(tr.intent)))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002516 mRecentTasks.remove(i);
2517 i--;
2518 N--;
2519 if (task.intent == null) {
2520 // If the new recent task we are adding is not fully
2521 // specified, then replace it with the existing recent task.
2522 task = tr;
2523 }
2524 }
2525 }
2526 if (N >= MAX_RECENT_TASKS) {
2527 mRecentTasks.remove(N-1);
2528 }
2529 mRecentTasks.add(0, task);
2530 }
2531
2532 public void setRequestedOrientation(IBinder token,
2533 int requestedOrientation) {
2534 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002535 ActivityRecord r = mMainStack.isInStackLocked(token);
2536 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002537 return;
2538 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002539 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornbe707852011-11-11 14:32:10 -08002540 mWindowManager.setAppOrientation(r.appToken, requestedOrientation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002541 Configuration config = mWindowManager.updateOrientationFromAppTokens(
The Android Open Source Project10592532009-03-18 17:39:46 -07002542 mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -08002543 r.mayFreezeScreenLocked(r.app) ? r.appToken : null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002544 if (config != null) {
2545 r.frozenBeforeDestroy = true;
Dianne Hackborn813075a62011-11-14 17:45:19 -08002546 if (!updateConfigurationLocked(config, r, false, false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002547 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002548 }
2549 }
2550 Binder.restoreCallingIdentity(origId);
2551 }
2552 }
2553
2554 public int getRequestedOrientation(IBinder token) {
2555 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002556 ActivityRecord r = mMainStack.isInStackLocked(token);
2557 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002558 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
2559 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08002560 return mWindowManager.getAppOrientation(r.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002561 }
2562 }
2563
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002564 /**
2565 * This is the internal entry point for handling Activity.finish().
2566 *
2567 * @param token The Binder token referencing the Activity we want to finish.
2568 * @param resultCode Result code, if any, from this Activity.
2569 * @param resultData Result data (Intent), if any, from this Activity.
2570 *
Alexey Tarasov83bad3d2009-08-12 15:05:43 +11002571 * @return Returns true if the activity successfully finished, or false if it is still running.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002572 */
2573 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData) {
2574 // Refuse possible leaked file descriptors
2575 if (resultData != null && resultData.hasFileDescriptors() == true) {
2576 throw new IllegalArgumentException("File descriptors passed in Intent");
2577 }
2578
2579 synchronized(this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002580 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002581 // Find the first activity that is not finishing.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002582 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002583 if (next != null) {
2584 // ask watcher if this is allowed
2585 boolean resumeOK = true;
2586 try {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002587 resumeOK = mController.activityResuming(next.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002588 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002589 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002590 }
2591
2592 if (!resumeOK) {
2593 return false;
2594 }
2595 }
2596 }
2597 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002598 boolean res = mMainStack.requestFinishActivityLocked(token, resultCode,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002599 resultData, "app-request");
2600 Binder.restoreCallingIdentity(origId);
2601 return res;
2602 }
2603 }
2604
Dianne Hackborn860755f2010-06-03 18:47:52 -07002605 public final void finishHeavyWeightApp() {
2606 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2607 != PackageManager.PERMISSION_GRANTED) {
2608 String msg = "Permission Denial: finishHeavyWeightApp() from pid="
2609 + Binder.getCallingPid()
2610 + ", uid=" + Binder.getCallingUid()
2611 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2612 Slog.w(TAG, msg);
2613 throw new SecurityException(msg);
2614 }
2615
2616 synchronized(this) {
2617 if (mHeavyWeightProcess == null) {
2618 return;
2619 }
2620
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002621 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>(
Dianne Hackborn860755f2010-06-03 18:47:52 -07002622 mHeavyWeightProcess.activities);
2623 for (int i=0; i<activities.size(); i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002624 ActivityRecord r = activities.get(i);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002625 if (!r.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002626 int index = mMainStack.indexOfTokenLocked(r.appToken);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002627 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002628 mMainStack.finishActivityLocked(r, index, Activity.RESULT_CANCELED,
Dianne Hackborn860755f2010-06-03 18:47:52 -07002629 null, "finish-heavy");
2630 }
2631 }
2632 }
2633
2634 mHeavyWeightProcess = null;
2635 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
2636 }
2637 }
2638
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002639 public void crashApplication(int uid, int initialPid, String packageName,
2640 String message) {
2641 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2642 != PackageManager.PERMISSION_GRANTED) {
2643 String msg = "Permission Denial: crashApplication() from pid="
2644 + Binder.getCallingPid()
2645 + ", uid=" + Binder.getCallingUid()
2646 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2647 Slog.w(TAG, msg);
2648 throw new SecurityException(msg);
2649 }
2650
2651 synchronized(this) {
2652 ProcessRecord proc = null;
2653
2654 // Figure out which process to kill. We don't trust that initialPid
2655 // still has any relation to current pids, so must scan through the
2656 // list.
2657 synchronized (mPidsSelfLocked) {
2658 for (int i=0; i<mPidsSelfLocked.size(); i++) {
2659 ProcessRecord p = mPidsSelfLocked.valueAt(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002660 if (p.uid != uid) {
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002661 continue;
2662 }
2663 if (p.pid == initialPid) {
2664 proc = p;
2665 break;
2666 }
2667 for (String str : p.pkgList) {
2668 if (str.equals(packageName)) {
2669 proc = p;
2670 }
2671 }
2672 }
2673 }
2674
2675 if (proc == null) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07002676 Slog.w(TAG, "crashApplication: nothing for uid=" + uid
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002677 + " initialPid=" + initialPid
2678 + " packageName=" + packageName);
2679 return;
2680 }
2681
2682 if (proc.thread != null) {
Dianne Hackborn9f531192010-08-04 17:48:03 -07002683 if (proc.pid == Process.myPid()) {
2684 Log.w(TAG, "crashApplication: trying to crash self!");
2685 return;
2686 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002687 long ident = Binder.clearCallingIdentity();
2688 try {
2689 proc.thread.scheduleCrash(message);
2690 } catch (RemoteException e) {
2691 }
2692 Binder.restoreCallingIdentity(ident);
2693 }
2694 }
2695 }
2696
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002697 public final void finishSubActivity(IBinder token, String resultWho,
2698 int requestCode) {
2699 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002700 ActivityRecord self = mMainStack.isInStackLocked(token);
2701 if (self == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002702 return;
2703 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002704
2705 final long origId = Binder.clearCallingIdentity();
2706
2707 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002708 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2709 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002710 if (r.resultTo == self && r.requestCode == requestCode) {
2711 if ((r.resultWho == null && resultWho == null) ||
2712 (r.resultWho != null && r.resultWho.equals(resultWho))) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002713 mMainStack.finishActivityLocked(r, i,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002714 Activity.RESULT_CANCELED, null, "request-sub");
2715 }
2716 }
2717 }
2718
2719 Binder.restoreCallingIdentity(origId);
2720 }
2721 }
2722
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002723 public boolean willActivityBeVisible(IBinder token) {
2724 synchronized(this) {
2725 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002726 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2727 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08002728 if (r.appToken == token) {
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002729 return true;
2730 }
2731 if (r.fullscreen && !r.finishing) {
2732 return false;
2733 }
2734 }
2735 return true;
2736 }
2737 }
2738
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002739 public void overridePendingTransition(IBinder token, String packageName,
2740 int enterAnim, int exitAnim) {
2741 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002742 ActivityRecord self = mMainStack.isInStackLocked(token);
2743 if (self == null) {
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002744 return;
2745 }
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002746
2747 final long origId = Binder.clearCallingIdentity();
2748
2749 if (self.state == ActivityState.RESUMED
2750 || self.state == ActivityState.PAUSING) {
2751 mWindowManager.overridePendingAppTransition(packageName,
2752 enterAnim, exitAnim);
2753 }
2754
2755 Binder.restoreCallingIdentity(origId);
2756 }
2757 }
2758
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002759 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002760 * Main function for removing an existing process from the activity manager
2761 * as a result of that process going away. Clears out all connections
2762 * to the process.
2763 */
2764 private final void handleAppDiedLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002765 boolean restarting, boolean allowRestart) {
2766 cleanUpApplicationRecordLocked(app, restarting, allowRestart, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002767 if (!restarting) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002768 mLruProcesses.remove(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002769 }
2770
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002771 if (mProfileProc == app) {
2772 clearProfilerLocked();
2773 }
2774
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002775 // Just in case...
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002776 if (mMainStack.mPausingActivity != null && mMainStack.mPausingActivity.app == app) {
2777 if (DEBUG_PAUSE) Slog.v(TAG, "App died while pausing: " +mMainStack.mPausingActivity);
2778 mMainStack.mPausingActivity = null;
2779 }
2780 if (mMainStack.mLastPausedActivity != null && mMainStack.mLastPausedActivity.app == app) {
2781 mMainStack.mLastPausedActivity = null;
2782 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002783
2784 // Remove this application's activities from active lists.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002785 mMainStack.removeHistoryRecordsForAppLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002786
2787 boolean atTop = true;
2788 boolean hasVisibleActivities = false;
2789
2790 // Clean out the history list.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002791 int i = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08002792 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002793 TAG, "Removing app " + app + " from history with " + i + " entries");
2794 while (i > 0) {
2795 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002796 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002797 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002798 TAG, "Record #" + i + " " + r + ": app=" + r.app);
2799 if (r.app == app) {
2800 if ((!r.haveState && !r.stateNotNeeded) || r.finishing) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002801 if (ActivityStack.DEBUG_ADD_REMOVE) {
2802 RuntimeException here = new RuntimeException("here");
2803 here.fillInStackTrace();
2804 Slog.i(TAG, "Removing activity " + r + " from stack at " + i
2805 + ": haveState=" + r.haveState
2806 + " stateNotNeeded=" + r.stateNotNeeded
2807 + " finishing=" + r.finishing
2808 + " state=" + r.state, here);
2809 }
2810 if (!r.finishing) {
2811 Slog.w(TAG, "Force removing " + r + ": app died, no saved state");
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -08002812 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
2813 System.identityHashCode(r),
2814 r.task.taskId, r.shortComponentName,
2815 "proc died without state saved");
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002816 }
Dianne Hackborn5c607432012-02-28 14:44:19 -08002817 mMainStack.removeActivityFromHistoryLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002818
2819 } else {
2820 // We have the current state for this activity, so
2821 // it can be restarted later when needed.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002822 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002823 TAG, "Keeping entry, setting app to null");
2824 if (r.visible) {
2825 hasVisibleActivities = true;
2826 }
2827 r.app = null;
2828 r.nowVisible = false;
2829 if (!r.haveState) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002830 if (ActivityStack.DEBUG_SAVED_STATE) Slog.i(TAG,
2831 "App died, clearing saved state of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002832 r.icicle = null;
2833 }
2834 }
2835
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002836 r.stack.cleanUpActivityLocked(r, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002837 }
2838 atTop = false;
2839 }
2840
2841 app.activities.clear();
2842
2843 if (app.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002844 Slog.w(TAG, "Crash of app " + app.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002845 + " running instrumentation " + app.instrumentationClass);
2846 Bundle info = new Bundle();
2847 info.putString("shortMsg", "Process crashed.");
2848 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
2849 }
2850
2851 if (!restarting) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002852 if (!mMainStack.resumeTopActivityLocked(null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002853 // If there was nothing to resume, and we are not already
2854 // restarting this process, but there is a visible activity that
2855 // is hosted by the process... then make sure all visible
2856 // activities are running, taking care of restarting this
2857 // process.
2858 if (hasVisibleActivities) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002859 mMainStack.ensureActivitiesVisibleLocked(null, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002860 }
2861 }
2862 }
2863 }
2864
2865 private final int getLRURecordIndexForAppLocked(IApplicationThread thread) {
2866 IBinder threadBinder = thread.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002867 // Find the application record.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002868 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2869 ProcessRecord rec = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002870 if (rec.thread != null && rec.thread.asBinder() == threadBinder) {
2871 return i;
2872 }
2873 }
2874 return -1;
2875 }
2876
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002877 final ProcessRecord getRecordForAppLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002878 IApplicationThread thread) {
2879 if (thread == null) {
2880 return null;
2881 }
2882
2883 int appIndex = getLRURecordIndexForAppLocked(thread);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002884 return appIndex >= 0 ? mLruProcesses.get(appIndex) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002885 }
2886
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002887 final void appDiedLocked(ProcessRecord app, int pid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002888 IApplicationThread thread) {
2889
2890 mProcDeaths[0]++;
2891
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002892 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
2893 synchronized (stats) {
2894 stats.noteProcessDiedLocked(app.info.uid, pid);
2895 }
2896
Magnus Edlund7bb25812010-02-24 15:45:06 +01002897 // Clean up already done if the process has been re-started.
2898 if (app.pid == pid && app.thread != null &&
2899 app.thread.asBinder() == thread.asBinder()) {
Dianne Hackborn906497c2010-05-10 15:57:38 -07002900 if (!app.killedBackground) {
2901 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
2902 + ") has died.");
2903 }
Doug Zongker2bec3d42009-12-04 12:52:44 -08002904 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002905 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002906 TAG, "Dying app: " + app + ", pid: " + pid
2907 + ", thread: " + thread.asBinder());
2908 boolean doLowMem = app.instrumentationClass == null;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002909 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002910
2911 if (doLowMem) {
2912 // If there are no longer any background processes running,
2913 // and the app that died was not running instrumentation,
2914 // then tell everyone we are now low on memory.
2915 boolean haveBg = false;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002916 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2917 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -07002918 if (rec.thread != null && rec.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002919 haveBg = true;
2920 break;
2921 }
2922 }
2923
2924 if (!haveBg) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002925 EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mLruProcesses.size());
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002926 long now = SystemClock.uptimeMillis();
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002927 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2928 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn36124872009-10-08 16:22:03 -07002929 if (rec != app && rec.thread != null &&
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002930 (rec.lastLowMemory+GC_MIN_INTERVAL) <= now) {
2931 // The low memory report is overriding any current
2932 // state for a GC request. Make sure to do
Dianne Hackborn32907cf2010-06-10 17:50:20 -07002933 // heavy/important/visible/foreground processes first.
Dianne Hackborn7d608422011-08-07 16:24:18 -07002934 if (rec.setAdj <= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002935 rec.lastRequestedGc = 0;
2936 } else {
2937 rec.lastRequestedGc = rec.lastLowMemory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002938 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002939 rec.reportLowMemory = true;
2940 rec.lastLowMemory = now;
2941 mProcessesToGc.remove(rec);
2942 addProcessToGcListLocked(rec);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002943 }
2944 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07002945 mHandler.sendEmptyMessage(REPORT_MEM_USAGE);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002946 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002947 }
2948 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01002949 } else if (app.pid != pid) {
2950 // A new process has already been started.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002951 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
Magnus Edlund7bb25812010-02-24 15:45:06 +01002952 + ") has died and restarted (pid " + app.pid + ").");
Dianne Hackborn28a8c2b2010-03-01 11:30:02 -08002953 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08002954 } else if (DEBUG_PROCESSES) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002955 Slog.d(TAG, "Received spurious death notification for thread "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002956 + thread.asBinder());
2957 }
2958 }
2959
Dan Egnor42471dd2010-01-07 17:25:22 -08002960 /**
2961 * If a stack trace dump file is configured, dump process stack traces.
Christopher Tate6ee412d2010-05-28 12:01:56 -07002962 * @param clearTraces causes the dump file to be erased prior to the new
2963 * traces being written, if true; when false, the new traces will be
2964 * appended to any existing file content.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002965 * @param firstPids of dalvik VM processes to dump stack traces for first
2966 * @param lastPids of dalvik VM processes to dump stack traces for last
Dan Egnor42471dd2010-01-07 17:25:22 -08002967 * @return file containing stack traces, or null if no dump file is configured
2968 */
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002969 public static File dumpStackTraces(boolean clearTraces, ArrayList<Integer> firstPids,
2970 ProcessStats processStats, SparseArray<Boolean> lastPids) {
Dan Egnor42471dd2010-01-07 17:25:22 -08002971 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
2972 if (tracesPath == null || tracesPath.length() == 0) {
2973 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002974 }
Dan Egnor42471dd2010-01-07 17:25:22 -08002975
2976 File tracesFile = new File(tracesPath);
2977 try {
2978 File tracesDir = tracesFile.getParentFile();
2979 if (!tracesDir.exists()) tracesFile.mkdirs();
2980 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
2981
Christopher Tate6ee412d2010-05-28 12:01:56 -07002982 if (clearTraces && tracesFile.exists()) tracesFile.delete();
Dan Egnor42471dd2010-01-07 17:25:22 -08002983 tracesFile.createNewFile();
2984 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
2985 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002986 Slog.w(TAG, "Unable to prepare ANR traces file: " + tracesPath, e);
Dan Egnor42471dd2010-01-07 17:25:22 -08002987 return null;
2988 }
2989
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07002990 dumpStackTraces(tracesPath, firstPids, processStats, lastPids);
2991 return tracesFile;
2992 }
2993
2994 private static void dumpStackTraces(String tracesPath, ArrayList<Integer> firstPids,
2995 ProcessStats processStats, SparseArray<Boolean> lastPids) {
Dan Egnor42471dd2010-01-07 17:25:22 -08002996 // Use a FileObserver to detect when traces finish writing.
2997 // The order of traces is considered important to maintain for legibility.
2998 FileObserver observer = new FileObserver(tracesPath, FileObserver.CLOSE_WRITE) {
2999 public synchronized void onEvent(int event, String path) { notify(); }
3000 };
3001
3002 try {
3003 observer.startWatching();
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003004
3005 // First collect all of the stacks of the most important pids.
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003006 if (firstPids != null) {
3007 try {
3008 int num = firstPids.size();
3009 for (int i = 0; i < num; i++) {
3010 synchronized (observer) {
3011 Process.sendSignal(firstPids.get(i), Process.SIGNAL_QUIT);
3012 observer.wait(200); // Wait for write-close, give up after 200msec
3013 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003014 }
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003015 } catch (InterruptedException e) {
3016 Log.wtf(TAG, e);
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003017 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003018 }
3019
3020 // Next measure CPU usage.
3021 if (processStats != null) {
3022 processStats.init();
3023 System.gc();
3024 processStats.update();
3025 try {
3026 synchronized (processStats) {
3027 processStats.wait(500); // measure over 1/2 second.
3028 }
3029 } catch (InterruptedException e) {
3030 }
3031 processStats.update();
3032
3033 // We'll take the stack crawls of just the top apps using CPU.
3034 final int N = processStats.countWorkingStats();
3035 int numProcs = 0;
3036 for (int i=0; i<N && numProcs<5; i++) {
3037 ProcessStats.Stats stats = processStats.getWorkingStats(i);
3038 if (lastPids.indexOfKey(stats.pid) >= 0) {
3039 numProcs++;
3040 try {
3041 synchronized (observer) {
3042 Process.sendSignal(stats.pid, Process.SIGNAL_QUIT);
3043 observer.wait(200); // Wait for write-close, give up after 200msec
3044 }
3045 } catch (InterruptedException e) {
3046 Log.wtf(TAG, e);
3047 }
3048
3049 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003050 }
3051 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003052
Dan Egnor42471dd2010-01-07 17:25:22 -08003053 } finally {
3054 observer.stopWatching();
3055 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003056 }
3057
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003058 final void logAppTooSlow(ProcessRecord app, long startTime, String msg) {
Dianne Hackborn69dc66e2012-03-26 10:50:54 -07003059 if (true || IS_USER_BUILD) {
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003060 return;
3061 }
3062 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
3063 if (tracesPath == null || tracesPath.length() == 0) {
3064 return;
3065 }
3066
3067 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
3068 StrictMode.allowThreadDiskWrites();
3069 try {
3070 final File tracesFile = new File(tracesPath);
3071 final File tracesDir = tracesFile.getParentFile();
3072 final File tracesTmp = new File(tracesDir, "__tmp__");
3073 try {
3074 if (!tracesDir.exists()) tracesFile.mkdirs();
3075 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
3076
3077 if (tracesFile.exists()) {
3078 tracesTmp.delete();
3079 tracesFile.renameTo(tracesTmp);
3080 }
3081 StringBuilder sb = new StringBuilder();
3082 Time tobj = new Time();
3083 tobj.set(System.currentTimeMillis());
3084 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
3085 sb.append(": ");
3086 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
3087 sb.append(" since ");
3088 sb.append(msg);
3089 FileOutputStream fos = new FileOutputStream(tracesFile);
3090 fos.write(sb.toString().getBytes());
3091 if (app == null) {
3092 fos.write("\n*** No application process!".getBytes());
3093 }
3094 fos.close();
3095 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
3096 } catch (IOException e) {
3097 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesPath, e);
3098 return;
3099 }
3100
3101 if (app != null) {
3102 ArrayList<Integer> firstPids = new ArrayList<Integer>();
3103 firstPids.add(app.pid);
3104 dumpStackTraces(tracesPath, firstPids, null, null);
3105 }
3106
3107 File lastTracesFile = null;
3108 File curTracesFile = null;
3109 for (int i=9; i>=0; i--) {
3110 String name = String.format("slow%02d.txt", i);
3111 curTracesFile = new File(tracesDir, name);
3112 if (curTracesFile.exists()) {
3113 if (lastTracesFile != null) {
3114 curTracesFile.renameTo(lastTracesFile);
3115 } else {
3116 curTracesFile.delete();
3117 }
3118 }
3119 lastTracesFile = curTracesFile;
3120 }
3121 tracesFile.renameTo(curTracesFile);
3122 if (tracesTmp.exists()) {
3123 tracesTmp.renameTo(tracesFile);
3124 }
3125 } finally {
3126 StrictMode.setThreadPolicy(oldPolicy);
3127 }
3128 }
3129
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003130 final void appNotResponding(ProcessRecord app, ActivityRecord activity,
3131 ActivityRecord parent, final String annotation) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003132 ArrayList<Integer> firstPids = new ArrayList<Integer>(5);
3133 SparseArray<Boolean> lastPids = new SparseArray<Boolean>(20);
3134
Dianne Hackborn287952c2010-09-22 22:34:31 -07003135 if (mController != null) {
3136 try {
3137 // 0 == continue, -1 = kill process immediately
3138 int res = mController.appEarlyNotResponding(app.processName, app.pid, annotation);
3139 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3140 } catch (RemoteException e) {
3141 mController = null;
3142 }
3143 }
3144
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003145 long anrTime = SystemClock.uptimeMillis();
3146 if (MONITOR_CPU_USAGE) {
3147 updateCpuStatsNow();
3148 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003149
3150 synchronized (this) {
3151 // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down.
3152 if (mShuttingDown) {
3153 Slog.i(TAG, "During shutdown skipping ANR: " + app + " " + annotation);
3154 return;
3155 } else if (app.notResponding) {
3156 Slog.i(TAG, "Skipping duplicate ANR: " + app + " " + annotation);
3157 return;
3158 } else if (app.crashing) {
3159 Slog.i(TAG, "Crashing app skipping ANR: " + app + " " + annotation);
3160 return;
3161 }
3162
3163 // In case we come through here for the same app before completing
3164 // this one, mark as anring now so we will bail out.
3165 app.notResponding = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08003166
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003167 // Log the ANR to the event log.
3168 EventLog.writeEvent(EventLogTags.AM_ANR, app.pid, app.processName, app.info.flags,
3169 annotation);
Dan Egnor42471dd2010-01-07 17:25:22 -08003170
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003171 // Dump thread traces as quickly as we can, starting with "interesting" processes.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003172 firstPids.add(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003173
3174 int parentPid = app.pid;
3175 if (parent != null && parent.app != null && parent.app.pid > 0) parentPid = parent.app.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003176 if (parentPid != app.pid) firstPids.add(parentPid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003177
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003178 if (MY_PID != app.pid && MY_PID != parentPid) firstPids.add(MY_PID);
Dan Egnor42471dd2010-01-07 17:25:22 -08003179
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003180 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
3181 ProcessRecord r = mLruProcesses.get(i);
3182 if (r != null && r.thread != null) {
3183 int pid = r.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003184 if (pid > 0 && pid != app.pid && pid != parentPid && pid != MY_PID) {
3185 if (r.persistent) {
3186 firstPids.add(pid);
3187 } else {
3188 lastPids.put(pid, Boolean.TRUE);
3189 }
3190 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003191 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003192 }
3193 }
3194
Dan Egnor42471dd2010-01-07 17:25:22 -08003195 // Log the ANR to the main log.
Jeff Browndeb6ed82012-04-10 14:26:26 -07003196 StringBuilder info = new StringBuilder();
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07003197 info.setLength(0);
Dan Egnor42471dd2010-01-07 17:25:22 -08003198 info.append("ANR in ").append(app.processName);
3199 if (activity != null && activity.shortComponentName != null) {
3200 info.append(" (").append(activity.shortComponentName).append(")");
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07003201 }
Eric Rowe6f4f6192010-02-17 18:29:04 -08003202 info.append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003203 if (annotation != null) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003204 info.append("Reason: ").append(annotation).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003205 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003206 if (parent != null && parent != activity) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003207 info.append("Parent: ").append(parent.shortComponentName).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003208 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003209
Dianne Hackborn287952c2010-09-22 22:34:31 -07003210 final ProcessStats processStats = new ProcessStats(true);
3211
3212 File tracesFile = dumpStackTraces(true, firstPids, processStats, lastPids);
3213
Dan Egnor42471dd2010-01-07 17:25:22 -08003214 String cpuInfo = null;
3215 if (MONITOR_CPU_USAGE) {
3216 updateCpuStatsNow();
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003217 synchronized (mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003218 cpuInfo = mProcessStats.printCurrentState(anrTime);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003219 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003220 info.append(processStats.printCurrentLoad());
Dan Egnor42471dd2010-01-07 17:25:22 -08003221 info.append(cpuInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003222 }
3223
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003224 info.append(processStats.printCurrentState(anrTime));
3225
Joe Onorato8a9b2202010-02-26 18:56:32 -08003226 Slog.e(TAG, info.toString());
Dan Egnor42471dd2010-01-07 17:25:22 -08003227 if (tracesFile == null) {
3228 // There is no trace file, so dump (only) the alleged culprit's threads to the log
3229 Process.sendSignal(app.pid, Process.SIGNAL_QUIT);
3230 }
3231
Jeff Sharkeya353d262011-10-28 11:12:06 -07003232 addErrorToDropBox("anr", app, app.processName, activity, parent, annotation,
3233 cpuInfo, tracesFile, null);
Dan Egnor42471dd2010-01-07 17:25:22 -08003234
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003235 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003236 try {
Dan Egnor42471dd2010-01-07 17:25:22 -08003237 // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately
3238 int res = mController.appNotResponding(app.processName, app.pid, info.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003239 if (res != 0) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003240 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3241 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003242 }
3243 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003244 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003245 }
3246 }
3247
Dan Egnor42471dd2010-01-07 17:25:22 -08003248 // Unless configured otherwise, swallow ANRs in background processes & kill the process.
3249 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
3250 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003251
3252 synchronized (this) {
3253 if (!showBackground && !app.isInterestingToUserLocked() && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003254 Slog.w(TAG, "Killing " + app + ": background ANR");
3255 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
3256 app.processName, app.setAdj, "background ANR");
3257 Process.killProcessQuiet(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003258 return;
3259 }
3260
3261 // Set the app's notResponding state, and look up the errorReportReceiver
3262 makeAppNotRespondingLocked(app,
3263 activity != null ? activity.shortComponentName : null,
3264 annotation != null ? "ANR " + annotation : "ANR",
3265 info.toString());
3266
3267 // Bring up the infamous App Not Responding dialog
3268 Message msg = Message.obtain();
3269 HashMap map = new HashMap();
3270 msg.what = SHOW_NOT_RESPONDING_MSG;
3271 msg.obj = map;
3272 map.put("app", app);
3273 if (activity != null) {
3274 map.put("activity", activity);
3275 }
3276
3277 mHandler.sendMessage(msg);
Dan Egnor42471dd2010-01-07 17:25:22 -08003278 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003279 }
3280
Dianne Hackborn0dad3642010-09-09 21:25:35 -07003281 final void showLaunchWarningLocked(final ActivityRecord cur, final ActivityRecord next) {
3282 if (!mLaunchWarningShown) {
3283 mLaunchWarningShown = true;
3284 mHandler.post(new Runnable() {
3285 @Override
3286 public void run() {
3287 synchronized (ActivityManagerService.this) {
3288 final Dialog d = new LaunchWarningWindow(mContext, cur, next);
3289 d.show();
3290 mHandler.postDelayed(new Runnable() {
3291 @Override
3292 public void run() {
3293 synchronized (ActivityManagerService.this) {
3294 d.dismiss();
3295 mLaunchWarningShown = false;
3296 }
3297 }
3298 }, 4000);
3299 }
3300 }
3301 });
3302 }
3303 }
3304
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003305 public boolean clearApplicationUserData(final String packageName,
Amith Yamasani742a6712011-05-04 14:49:28 -07003306 final IPackageDataObserver observer, final int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003307 enforceNotIsolatedCaller("clearApplicationUserData");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003308 int uid = Binder.getCallingUid();
3309 int pid = Binder.getCallingPid();
3310 long callingId = Binder.clearCallingIdentity();
3311 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003312 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003313 int pkgUid = -1;
3314 synchronized(this) {
3315 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003316 pkgUid = pm.getPackageUid(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003317 } catch (RemoteException e) {
3318 }
3319 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003320 Slog.w(TAG, "Invalid packageName:" + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003321 return false;
3322 }
3323 if (uid == pkgUid || checkComponentPermission(
3324 android.Manifest.permission.CLEAR_APP_USER_DATA,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08003325 pid, uid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003326 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003327 forceStopPackageLocked(packageName, pkgUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003328 } else {
3329 throw new SecurityException(pid+" does not have permission:"+
3330 android.Manifest.permission.CLEAR_APP_USER_DATA+" to clear data" +
3331 "for process:"+packageName);
3332 }
3333 }
3334
3335 try {
3336 //clear application user data
Amith Yamasani483f3b02012-03-13 16:08:00 -07003337 pm.clearApplicationUserData(packageName, observer, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003338 Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED,
3339 Uri.fromParts("package", packageName, null));
3340 intent.putExtra(Intent.EXTRA_UID, pkgUid);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003341 broadcastIntentInPackage("android", Process.SYSTEM_UID, intent,
Amith Yamasani742a6712011-05-04 14:49:28 -07003342 null, null, 0, null, null, null, false, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003343 } catch (RemoteException e) {
3344 }
3345 } finally {
3346 Binder.restoreCallingIdentity(callingId);
3347 }
3348 return true;
3349 }
3350
Dianne Hackborn03abb812010-01-04 18:43:19 -08003351 public void killBackgroundProcesses(final String packageName) {
3352 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3353 != PackageManager.PERMISSION_GRANTED &&
3354 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES)
3355 != PackageManager.PERMISSION_GRANTED) {
3356 String msg = "Permission Denial: killBackgroundProcesses() from pid="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003357 + Binder.getCallingPid()
3358 + ", uid=" + Binder.getCallingUid()
Dianne Hackborn03abb812010-01-04 18:43:19 -08003359 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003360 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003361 throw new SecurityException(msg);
3362 }
3363
Amith Yamasani483f3b02012-03-13 16:08:00 -07003364 int userId = UserId.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003365 long callingId = Binder.clearCallingIdentity();
3366 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003367 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003368 int pkgUid = -1;
3369 synchronized(this) {
3370 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003371 pkgUid = pm.getPackageUid(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003372 } catch (RemoteException e) {
3373 }
3374 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003375 Slog.w(TAG, "Invalid packageName: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003376 return;
3377 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003378 killPackageProcessesLocked(packageName, pkgUid,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003379 ProcessList.SERVICE_ADJ, false, true, true, false, "kill background");
3380 }
3381 } finally {
3382 Binder.restoreCallingIdentity(callingId);
3383 }
3384 }
3385
3386 public void killAllBackgroundProcesses() {
3387 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3388 != PackageManager.PERMISSION_GRANTED) {
3389 String msg = "Permission Denial: killAllBackgroundProcesses() from pid="
3390 + Binder.getCallingPid()
3391 + ", uid=" + Binder.getCallingUid()
3392 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
3393 Slog.w(TAG, msg);
3394 throw new SecurityException(msg);
3395 }
3396
3397 long callingId = Binder.clearCallingIdentity();
3398 try {
3399 synchronized(this) {
3400 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
3401 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3402 final int NA = apps.size();
3403 for (int ia=0; ia<NA; ia++) {
3404 ProcessRecord app = apps.valueAt(ia);
3405 if (app.persistent) {
3406 // we don't kill persistent processes
3407 continue;
3408 }
3409 if (app.removed) {
3410 procs.add(app);
3411 } else if (app.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
3412 app.removed = true;
3413 procs.add(app);
3414 }
3415 }
3416 }
3417
3418 int N = procs.size();
3419 for (int i=0; i<N; i++) {
3420 removeProcessLocked(procs.get(i), false, true, "kill all background");
3421 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003422 }
3423 } finally {
3424 Binder.restoreCallingIdentity(callingId);
3425 }
3426 }
3427
3428 public void forceStopPackage(final String packageName) {
3429 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3430 != PackageManager.PERMISSION_GRANTED) {
3431 String msg = "Permission Denial: forceStopPackage() from pid="
3432 + Binder.getCallingPid()
3433 + ", uid=" + Binder.getCallingUid()
3434 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003435 Slog.w(TAG, msg);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003436 throw new SecurityException(msg);
3437 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07003438 final int userId = UserId.getCallingUserId();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003439 long callingId = Binder.clearCallingIdentity();
3440 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003441 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003442 int pkgUid = -1;
3443 synchronized(this) {
3444 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003445 pkgUid = pm.getPackageUid(packageName, userId);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003446 } catch (RemoteException e) {
3447 }
3448 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003449 Slog.w(TAG, "Invalid packageName: " + packageName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003450 return;
3451 }
3452 forceStopPackageLocked(packageName, pkgUid);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003453 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003454 pm.setPackageStoppedState(packageName, true, userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003455 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08003456 } catch (IllegalArgumentException e) {
3457 Slog.w(TAG, "Failed trying to unstop package "
3458 + packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003459 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003460 }
3461 } finally {
3462 Binder.restoreCallingIdentity(callingId);
3463 }
3464 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003465
3466 /*
3467 * The pkg name and uid have to be specified.
3468 * @see android.app.IActivityManager#killApplicationWithUid(java.lang.String, int)
3469 */
3470 public void killApplicationWithUid(String pkg, int uid) {
3471 if (pkg == null) {
3472 return;
3473 }
3474 // Make sure the uid is valid.
3475 if (uid < 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003476 Slog.w(TAG, "Invalid uid specified for pkg : " + pkg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003477 return;
3478 }
3479 int callerUid = Binder.getCallingUid();
3480 // Only the system server can kill an application
3481 if (callerUid == Process.SYSTEM_UID) {
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07003482 // Post an aysnc message to kill the application
3483 Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG);
3484 msg.arg1 = uid;
3485 msg.arg2 = 0;
3486 msg.obj = pkg;
Suchi Amalapurapud50066f2009-08-18 16:57:41 -07003487 mHandler.sendMessage(msg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003488 } else {
3489 throw new SecurityException(callerUid + " cannot kill pkg: " +
3490 pkg);
3491 }
3492 }
3493
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003494 public void closeSystemDialogs(String reason) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003495 enforceNotIsolatedCaller("closeSystemDialogs");
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003496 Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003497 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003498 if (reason != null) {
3499 intent.putExtra("reason", reason);
3500 }
3501
3502 final int uid = Binder.getCallingUid();
3503 final long origId = Binder.clearCallingIdentity();
3504 synchronized (this) {
Dianne Hackbornffa42482009-09-23 22:20:11 -07003505 mWindowManager.closeSystemDialogs(reason);
3506
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08003507 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003508 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornffa42482009-09-23 22:20:11 -07003509 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003510 r.stack.finishActivityLocked(r, i,
Dianne Hackbornffa42482009-09-23 22:20:11 -07003511 Activity.RESULT_CANCELED, null, "close-sys");
3512 }
3513 }
3514
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003515 broadcastIntentLocked(null, null, intent, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07003516 null, 0, null, null, null, false, false, -1, uid, 0 /* TODO: Verify */);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003517 }
3518 Binder.restoreCallingIdentity(origId);
3519 }
3520
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003521 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids)
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003522 throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003523 enforceNotIsolatedCaller("getProcessMemoryInfo");
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003524 Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length];
3525 for (int i=pids.length-1; i>=0; i--) {
3526 infos[i] = new Debug.MemoryInfo();
3527 Debug.getMemoryInfo(pids[i], infos[i]);
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003528 }
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003529 return infos;
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003530 }
Christopher Tate5e1ab332009-09-01 20:32:49 -07003531
Dianne Hackbornb437e092011-08-05 17:50:29 -07003532 public long[] getProcessPss(int[] pids) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003533 enforceNotIsolatedCaller("getProcessPss");
Dianne Hackbornb437e092011-08-05 17:50:29 -07003534 long[] pss = new long[pids.length];
3535 for (int i=pids.length-1; i>=0; i--) {
3536 pss[i] = Debug.getPss(pids[i]);
3537 }
3538 return pss;
3539 }
3540
Christopher Tate5e1ab332009-09-01 20:32:49 -07003541 public void killApplicationProcess(String processName, int uid) {
3542 if (processName == null) {
3543 return;
3544 }
3545
3546 int callerUid = Binder.getCallingUid();
3547 // Only the system server can kill an application
3548 if (callerUid == Process.SYSTEM_UID) {
3549 synchronized (this) {
3550 ProcessRecord app = getProcessRecordLocked(processName, uid);
Christopher Tate4a627c72011-04-01 14:43:32 -07003551 if (app != null && app.thread != null) {
Christopher Tate5e1ab332009-09-01 20:32:49 -07003552 try {
3553 app.thread.scheduleSuicide();
3554 } catch (RemoteException e) {
3555 // If the other end already died, then our work here is done.
3556 }
3557 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003558 Slog.w(TAG, "Process/uid not found attempting kill of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07003559 + processName + " / " + uid);
3560 }
3561 }
3562 } else {
3563 throw new SecurityException(callerUid + " cannot kill app process: " +
3564 processName);
3565 }
3566 }
3567
Dianne Hackborn03abb812010-01-04 18:43:19 -08003568 private void forceStopPackageLocked(final String packageName, int uid) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003569 forceStopPackageLocked(packageName, uid, false, false, true, false, UserId.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003570 Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED,
3571 Uri.fromParts("package", packageName, null));
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003572 if (!mProcessesReady) {
3573 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3574 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003575 intent.putExtra(Intent.EXTRA_UID, uid);
3576 broadcastIntentLocked(null, null, intent,
3577 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07003578 false, false,
3579 MY_PID, Process.SYSTEM_UID, UserId.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003580 }
3581
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003582 private final boolean killPackageProcessesLocked(String packageName, int uid,
Christopher Tate3dacd842011-08-19 14:56:15 -07003583 int minOomAdj, boolean callerWillRestart, boolean allowRestart, boolean doit,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003584 boolean evenPersistent, String reason) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003585 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003586
Dianne Hackborn03abb812010-01-04 18:43:19 -08003587 // Remove all processes this package may have touched: all with the
3588 // same UID (except for the system or root user), and all whose name
3589 // matches the package name.
3590 final String procNamePrefix = packageName + ":";
3591 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3592 final int NA = apps.size();
3593 for (int ia=0; ia<NA; ia++) {
3594 ProcessRecord app = apps.valueAt(ia);
Christopher Tate3dacd842011-08-19 14:56:15 -07003595 if (app.persistent && !evenPersistent) {
Christopher Tate064d8422011-07-26 15:38:07 -07003596 // we don't kill persistent processes
3597 continue;
3598 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003599 if (app.removed) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003600 if (doit) {
3601 procs.add(app);
3602 }
Amith Yamasani13593602012-03-22 16:16:17 -07003603 // If uid is specified and the uid and process name match
3604 // Or, the uid is not specified and the process name matches
3605 } else if (((uid > 0 && uid != Process.SYSTEM_UID && app.info.uid == uid)
Amith Yamasani34db3d62012-04-02 16:35:19 -07003606 || ((app.processName.equals(packageName)
3607 || app.processName.startsWith(procNamePrefix))
3608 && uid < 0))) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003609 if (app.setAdj >= minOomAdj) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003610 if (!doit) {
3611 return true;
3612 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003613 app.removed = true;
3614 procs.add(app);
3615 }
3616 }
3617 }
3618 }
3619
3620 int N = procs.size();
3621 for (int i=0; i<N; i++) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003622 removeProcessLocked(procs.get(i), callerWillRestart, allowRestart, reason);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003623 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003624 return N > 0;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003625 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003626
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003627 private final boolean forceStopPackageLocked(String name, int uid,
Christopher Tate3dacd842011-08-19 14:56:15 -07003628 boolean callerWillRestart, boolean purgeCache, boolean doit,
Amith Yamasani483f3b02012-03-13 16:08:00 -07003629 boolean evenPersistent, int userId) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003630 int i;
3631 int N;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003632
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003633 if (uid < 0) {
3634 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003635 uid = AppGlobals.getPackageManager().getPackageUid(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003636 } catch (RemoteException e) {
3637 }
3638 }
3639
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003640 if (doit) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003641 Slog.i(TAG, "Force stopping package " + name + " uid=" + uid);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003642
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003643 Iterator<SparseArray<Long>> badApps = mProcessCrashTimes.getMap().values().iterator();
3644 while (badApps.hasNext()) {
3645 SparseArray<Long> ba = badApps.next();
3646 if (ba.get(uid) != null) {
3647 badApps.remove();
3648 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003649 }
3650 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003651
3652 boolean didSomething = killPackageProcessesLocked(name, uid, -100,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003653 callerWillRestart, false, doit, evenPersistent, "force stop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003654
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003655 TaskRecord lastTask = null;
3656 for (i=0; i<mMainStack.mHistory.size(); i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003657 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003658 final boolean samePackage = r.packageName.equals(name);
Amith Yamasani13593602012-03-22 16:16:17 -07003659 if (r.userId == userId
3660 && (samePackage || r.task == lastTask)
Christopher Tate3dacd842011-08-19 14:56:15 -07003661 && (r.app == null || evenPersistent || !r.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003662 if (!doit) {
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003663 if (r.finishing) {
3664 // If this activity is just finishing, then it is not
3665 // interesting as far as something to stop.
3666 continue;
3667 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003668 return true;
3669 }
3670 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003671 Slog.i(TAG, " Force finishing activity " + r);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003672 if (samePackage) {
3673 if (r.app != null) {
3674 r.app.removed = true;
3675 }
3676 r.app = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003677 }
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003678 lastTask = r.task;
3679 if (r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003680 null, "force-stop", true)) {
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003681 i--;
3682 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003683 }
3684 }
3685
3686 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
Amith Yamasani742a6712011-05-04 14:49:28 -07003687 for (ServiceRecord service : mServiceMap.getAllServices(userId)) {
Christopher Tate064d8422011-07-26 15:38:07 -07003688 if (service.packageName.equals(name)
Christopher Tate3dacd842011-08-19 14:56:15 -07003689 && (service.app == null || evenPersistent || !service.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003690 if (!doit) {
3691 return true;
3692 }
3693 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003694 Slog.i(TAG, " Force stopping service " + service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003695 if (service.app != null) {
3696 service.app.removed = true;
3697 }
3698 service.app = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003699 service.isolatedProc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003700 services.add(service);
3701 }
3702 }
3703
3704 N = services.size();
3705 for (i=0; i<N; i++) {
3706 bringDownServiceLocked(services.get(i), true);
3707 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003708
3709 ArrayList<ContentProviderRecord> providers = new ArrayList<ContentProviderRecord>();
Amith Yamasani13593602012-03-22 16:16:17 -07003710 for (ContentProviderRecord provider : mProviderMap.getProvidersByClass(userId).values()) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003711 if (provider.info.packageName.equals(name)
3712 && (provider.proc == null || evenPersistent || !provider.proc.persistent)) {
3713 if (!doit) {
3714 return true;
3715 }
3716 didSomething = true;
3717 providers.add(provider);
3718 }
3719 }
3720
3721 N = providers.size();
3722 for (i=0; i<N; i++) {
3723 removeDyingProviderLocked(null, providers.get(i));
3724 }
3725
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003726 if (doit) {
3727 if (purgeCache) {
3728 AttributeCache ac = AttributeCache.instance();
3729 if (ac != null) {
3730 ac.removePackage(name);
3731 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003732 }
Dianne Hackborn38cc8962011-10-13 11:33:55 -07003733 if (mBooted) {
3734 mMainStack.resumeTopActivityLocked(null);
3735 mMainStack.scheduleIdleLocked();
3736 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003737 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003738
3739 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003740 }
3741
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003742 private final boolean removeProcessLocked(ProcessRecord app,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003743 boolean callerWillRestart, boolean allowRestart, String reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003744 final String name = app.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003745 final int uid = app.uid;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003746 if (DEBUG_PROCESSES) Slog.d(
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003747 TAG, "Force removing proc " + app.toShortString() + " (" + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003748 + "/" + uid + ")");
3749
3750 mProcessNames.remove(name, uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003751 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003752 if (mHeavyWeightProcess == app) {
3753 mHeavyWeightProcess = null;
3754 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3755 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003756 boolean needRestart = false;
3757 if (app.pid > 0 && app.pid != MY_PID) {
3758 int pid = app.pid;
3759 synchronized (mPidsSelfLocked) {
3760 mPidsSelfLocked.remove(pid);
3761 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3762 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003763 Slog.i(TAG, "Killing proc " + app.toShortString() + ": " + reason);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003764 handleAppDiedLocked(app, true, allowRestart);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003765 mLruProcesses.remove(app);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003766 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003767
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003768 if (app.persistent && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003769 if (!callerWillRestart) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003770 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003771 } else {
3772 needRestart = true;
3773 }
3774 }
3775 } else {
3776 mRemovedProcesses.add(app);
3777 }
3778
3779 return needRestart;
3780 }
3781
3782 private final void processStartTimedOutLocked(ProcessRecord app) {
3783 final int pid = app.pid;
3784 boolean gone = false;
3785 synchronized (mPidsSelfLocked) {
3786 ProcessRecord knownApp = mPidsSelfLocked.get(pid);
3787 if (knownApp != null && knownApp.thread == null) {
3788 mPidsSelfLocked.remove(pid);
3789 gone = true;
3790 }
3791 }
3792
3793 if (gone) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003794 Slog.w(TAG, "Process " + app + " failed to attach");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003795 EventLog.writeEvent(EventLogTags.AM_PROCESS_START_TIMEOUT, pid, app.uid,
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003796 app.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003797 mProcessNames.remove(app.processName, app.uid);
3798 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003799 if (mHeavyWeightProcess == app) {
3800 mHeavyWeightProcess = null;
3801 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3802 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003803 // Take care of any launching providers waiting for this process.
3804 checkAppInLaunchingProvidersLocked(app, true);
3805 // Take care of any services that are waiting for the process.
3806 for (int i=0; i<mPendingServices.size(); i++) {
3807 ServiceRecord sr = mPendingServices.get(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003808 if ((app.uid == sr.appInfo.uid
3809 && app.processName.equals(sr.processName))
3810 || sr.isolatedProc == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003811 Slog.w(TAG, "Forcing bringing down service: " + sr);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003812 sr.isolatedProc = null;
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003813 mPendingServices.remove(i);
3814 i--;
3815 bringDownServiceLocked(sr, true);
3816 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003817 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003818 EventLog.writeEvent(EventLogTags.AM_KILL, pid,
3819 app.processName, app.setAdj, "start timeout");
3820 Process.killProcessQuiet(pid);
Christopher Tate181fafa2009-05-14 11:12:14 -07003821 if (mBackupTarget != null && mBackupTarget.app.pid == pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003822 Slog.w(TAG, "Unattached app died before backup, skipping");
Christopher Tate181fafa2009-05-14 11:12:14 -07003823 try {
3824 IBackupManager bm = IBackupManager.Stub.asInterface(
3825 ServiceManager.getService(Context.BACKUP_SERVICE));
3826 bm.agentDisconnected(app.info.packageName);
3827 } catch (RemoteException e) {
3828 // Can't happen; the backup manager is local
3829 }
3830 }
Christopher Tatef46723b2012-01-26 14:19:24 -08003831 if (isPendingBroadcastProcessLocked(pid)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003832 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
Christopher Tatef46723b2012-01-26 14:19:24 -08003833 skipPendingBroadcastLocked(pid);
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003834 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003835 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003836 Slog.w(TAG, "Spurious process start timeout - pid not known for " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003837 }
3838 }
3839
3840 private final boolean attachApplicationLocked(IApplicationThread thread,
3841 int pid) {
3842
3843 // Find the application record that is being attached... either via
3844 // the pid if we are running in multiple processes, or just pull the
3845 // next app record if we are emulating process with anonymous threads.
3846 ProcessRecord app;
3847 if (pid != MY_PID && pid >= 0) {
3848 synchronized (mPidsSelfLocked) {
3849 app = mPidsSelfLocked.get(pid);
3850 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003851 } else {
3852 app = null;
3853 }
3854
3855 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003856 Slog.w(TAG, "No pending application record for pid " + pid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003857 + " (IApplicationThread " + thread + "); dropping process");
Doug Zongker2bec3d42009-12-04 12:52:44 -08003858 EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003859 if (pid > 0 && pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003860 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003861 } else {
3862 try {
3863 thread.scheduleExit();
3864 } catch (Exception e) {
3865 // Ignore exceptions.
3866 }
3867 }
3868 return false;
3869 }
3870
3871 // If this application record is still attached to a previous
3872 // process, clean it up now.
3873 if (app.thread != null) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003874 handleAppDiedLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003875 }
3876
3877 // Tell the process all about itself.
3878
Joe Onorato8a9b2202010-02-26 18:56:32 -08003879 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003880 TAG, "Binding process pid " + pid + " to record " + app);
3881
3882 String processName = app.processName;
3883 try {
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07003884 AppDeathRecipient adr = new AppDeathRecipient(
3885 app, pid, thread);
3886 thread.asBinder().linkToDeath(adr, 0);
3887 app.deathRecipient = adr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003888 } catch (RemoteException e) {
3889 app.resetPackageList();
3890 startProcessLocked(app, "link fail", processName);
3891 return false;
3892 }
3893
Doug Zongker2bec3d42009-12-04 12:52:44 -08003894 EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.pid, app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003895
3896 app.thread = thread;
3897 app.curAdj = app.setAdj = -100;
Dianne Hackborn09c916b2009-12-08 14:50:51 -08003898 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
3899 app.setSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003900 app.forcingToForeground = null;
3901 app.foregroundServices = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07003902 app.hasShownUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003903 app.debugging = false;
3904
3905 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3906
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003907 boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003908 List providers = normalMode ? generateApplicationProvidersLocked(app) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003909
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003910 if (!normalMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003911 Slog.i(TAG, "Launching preboot mode app: " + app);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003912 }
3913
Joe Onorato8a9b2202010-02-26 18:56:32 -08003914 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003915 TAG, "New app record " + app
3916 + " thread=" + thread.asBinder() + " pid=" + pid);
3917 try {
3918 int testMode = IApplicationThread.DEBUG_OFF;
3919 if (mDebugApp != null && mDebugApp.equals(processName)) {
3920 testMode = mWaitForDebugger
3921 ? IApplicationThread.DEBUG_WAIT
3922 : IApplicationThread.DEBUG_ON;
3923 app.debugging = true;
3924 if (mDebugTransient) {
3925 mDebugApp = mOrigDebugApp;
3926 mWaitForDebugger = mOrigWaitForDebugger;
3927 }
3928 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003929 String profileFile = app.instrumentationProfileFile;
3930 ParcelFileDescriptor profileFd = null;
3931 boolean profileAutoStop = false;
3932 if (mProfileApp != null && mProfileApp.equals(processName)) {
3933 mProfileProc = app;
3934 profileFile = mProfileFile;
3935 profileFd = mProfileFd;
3936 profileAutoStop = mAutoStopProfiler;
3937 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08003938 boolean enableOpenGlTrace = false;
3939 if (mOpenGlTraceApp != null && mOpenGlTraceApp.equals(processName)) {
3940 enableOpenGlTrace = true;
3941 mOpenGlTraceApp = null;
3942 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003943
Christopher Tate181fafa2009-05-14 11:12:14 -07003944 // If the app is being launched for restore or full backup, set it up specially
3945 boolean isRestrictedBackupMode = false;
3946 if (mBackupTarget != null && mBackupAppName.equals(processName)) {
3947 isRestrictedBackupMode = (mBackupTarget.backupMode == BackupRecord.RESTORE)
Christopher Tate75a99702011-05-18 16:28:19 -07003948 || (mBackupTarget.backupMode == BackupRecord.RESTORE_FULL)
Christopher Tate181fafa2009-05-14 11:12:14 -07003949 || (mBackupTarget.backupMode == BackupRecord.BACKUP_FULL);
3950 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003951
Dianne Hackbornd7f6daa2009-06-22 17:06:35 -07003952 ensurePackageDexOpt(app.instrumentationInfo != null
3953 ? app.instrumentationInfo.packageName
3954 : app.info.packageName);
3955 if (app.instrumentationClass != null) {
3956 ensurePackageDexOpt(app.instrumentationClass.getPackageName());
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003957 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08003958 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Binding proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003959 + processName + " with config " + mConfiguration);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003960 ApplicationInfo appInfo = app.instrumentationInfo != null
3961 ? app.instrumentationInfo : app.info;
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -07003962 app.compat = compatibilityInfoForPackageLocked(appInfo);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003963 if (profileFd != null) {
3964 profileFd = profileFd.dup();
3965 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003966 thread.bindApplication(processName, appInfo, providers,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003967 app.instrumentationClass, profileFile, profileFd, profileAutoStop,
Siva Velusamy92a8b222012-03-09 16:24:04 -08003968 app.instrumentationArguments, app.instrumentationWatcher, testMode,
3969 enableOpenGlTrace, isRestrictedBackupMode || !normalMode, app.persistent,
Dianne Hackborn813075a62011-11-14 17:45:19 -08003970 new Configuration(mConfiguration), app.compat, getCommonServicesLocked(),
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08003971 mCoreSettingsObserver.getCoreSettingsLocked());
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003972 updateLruProcessLocked(app, false, true);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003973 app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003974 } catch (Exception e) {
3975 // todo: Yikes! What should we do? For now we will try to
3976 // start another process, but that could easily get us in
3977 // an infinite loop of restarting processes...
Joe Onorato8a9b2202010-02-26 18:56:32 -08003978 Slog.w(TAG, "Exception thrown during bind!", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003979
3980 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07003981 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003982 startProcessLocked(app, "bind fail", processName);
3983 return false;
3984 }
3985
3986 // Remove this record from the list of starting applications.
3987 mPersistentStartingProcesses.remove(app);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003988 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
3989 "Attach application locked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003990 mProcessesOnHold.remove(app);
3991
3992 boolean badApp = false;
3993 boolean didSomething = false;
3994
3995 // See if the top visible activity is waiting to run in this process...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003996 ActivityRecord hr = mMainStack.topRunningActivityLocked(null);
Christopher Tate04c0af82010-06-07 18:35:20 -07003997 if (hr != null && normalMode) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003998 if (hr.app == null && app.uid == hr.info.applicationInfo.uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003999 && processName.equals(hr.processName)) {
4000 try {
Mike Lockwood3a74bd32011-08-12 13:55:22 -07004001 if (mHeadless) {
4002 Slog.e(TAG, "Starting activities not supported on headless device: " + hr);
4003 } else if (mMainStack.realStartActivityLocked(hr, app, true, true)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004004 didSomething = true;
4005 }
4006 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004007 Slog.w(TAG, "Exception in new application when starting activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004008 + hr.intent.getComponent().flattenToShortString(), e);
4009 badApp = true;
4010 }
4011 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004012 mMainStack.ensureActivitiesVisibleLocked(hr, null, processName, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004013 }
4014 }
4015
4016 // Find any services that should be running in this process...
4017 if (!badApp && mPendingServices.size() > 0) {
4018 ServiceRecord sr = null;
4019 try {
4020 for (int i=0; i<mPendingServices.size(); i++) {
4021 sr = mPendingServices.get(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004022 if (app != sr.isolatedProc && (app.uid != sr.appInfo.uid
4023 || !processName.equals(sr.processName))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004024 continue;
4025 }
4026
4027 mPendingServices.remove(i);
4028 i--;
4029 realStartServiceLocked(sr, app);
4030 didSomething = true;
4031 }
4032 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004033 Slog.w(TAG, "Exception in new application when starting service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004034 + sr.shortName, e);
4035 badApp = true;
4036 }
4037 }
4038
Christopher Tatef46723b2012-01-26 14:19:24 -08004039 // Check if a next-broadcast receiver is in this process...
4040 if (!badApp && isPendingBroadcastProcessLocked(pid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004041 try {
Christopher Tatef46723b2012-01-26 14:19:24 -08004042 didSomething = sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004043 } catch (Exception e) {
Christopher Tatef46723b2012-01-26 14:19:24 -08004044 // If the app died trying to launch the receiver we declare it 'bad'
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004045 badApp = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004046 }
4047 }
4048
Christopher Tate181fafa2009-05-14 11:12:14 -07004049 // Check whether the next backup agent is in this process...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004050 if (!badApp && mBackupTarget != null && mBackupTarget.appInfo.uid == app.uid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004051 if (DEBUG_BACKUP) Slog.v(TAG, "New app is backup target, launching agent for " + app);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004052 ensurePackageDexOpt(mBackupTarget.appInfo.packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07004053 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004054 thread.scheduleCreateBackupAgent(mBackupTarget.appInfo,
4055 compatibilityInfoForPackageLocked(mBackupTarget.appInfo),
4056 mBackupTarget.backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -07004057 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004058 Slog.w(TAG, "Exception scheduling backup agent creation: ");
Christopher Tate181fafa2009-05-14 11:12:14 -07004059 e.printStackTrace();
4060 }
4061 }
4062
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004063 if (badApp) {
4064 // todo: Also need to kill application to deal with all
4065 // kinds of exceptions.
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004066 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004067 return false;
4068 }
4069
4070 if (!didSomething) {
4071 updateOomAdjLocked();
4072 }
4073
4074 return true;
4075 }
4076
4077 public final void attachApplication(IApplicationThread thread) {
4078 synchronized (this) {
4079 int callingPid = Binder.getCallingPid();
4080 final long origId = Binder.clearCallingIdentity();
4081 attachApplicationLocked(thread, callingPid);
4082 Binder.restoreCallingIdentity(origId);
4083 }
4084 }
4085
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004086 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004087 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004088 ActivityRecord r = mMainStack.activityIdleInternal(token, false, config);
4089 if (stopProfiling) {
4090 synchronized (this) {
4091 if (mProfileProc == r.app) {
4092 if (mProfileFd != null) {
4093 try {
4094 mProfileFd.close();
4095 } catch (IOException e) {
4096 }
4097 clearProfilerLocked();
4098 }
4099 }
4100 }
4101 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004102 Binder.restoreCallingIdentity(origId);
4103 }
4104
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004105 void enableScreenAfterBoot() {
Doug Zongker2bec3d42009-12-04 12:52:44 -08004106 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004107 SystemClock.uptimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004108 mWindowManager.enableScreenAfterBoot();
4109 }
4110
Dianne Hackborn661cd522011-08-22 00:26:20 -07004111 public void showBootMessage(final CharSequence msg, final boolean always) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004112 enforceNotIsolatedCaller("showBootMessage");
Dianne Hackborn661cd522011-08-22 00:26:20 -07004113 mWindowManager.showBootMessage(msg, always);
4114 }
4115
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004116 public void dismissKeyguardOnNextActivity() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004117 enforceNotIsolatedCaller("dismissKeyguardOnNextActivity");
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004118 synchronized (this) {
Dianne Hackborn1e88e982012-04-24 18:35:55 -07004119 if (mLockScreenShown) {
4120 mLockScreenShown = false;
4121 comeOutOfSleepIfNeededLocked();
4122 }
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004123 mMainStack.dismissKeyguardOnNextActivityLocked();
4124 }
4125 }
4126
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004127 final void finishBooting() {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004128 IntentFilter pkgFilter = new IntentFilter();
4129 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
4130 pkgFilter.addDataScheme("package");
4131 mContext.registerReceiver(new BroadcastReceiver() {
4132 @Override
4133 public void onReceive(Context context, Intent intent) {
4134 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
4135 if (pkgs != null) {
4136 for (String pkg : pkgs) {
Vairavan Srinivasan61f07652010-07-22 13:36:40 -07004137 synchronized (ActivityManagerService.this) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07004138 if (forceStopPackageLocked(pkg, -1, false, false, false, false, 0)) {
4139 setResultCode(Activity.RESULT_OK);
4140 return;
4141 }
4142 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004143 }
4144 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004145 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004146 }, pkgFilter);
Amith Yamasani13593602012-03-22 16:16:17 -07004147
4148 IntentFilter userFilter = new IntentFilter();
4149 userFilter.addAction(Intent.ACTION_USER_REMOVED);
4150 mContext.registerReceiver(new BroadcastReceiver() {
4151 @Override
4152 public void onReceive(Context context, Intent intent) {
4153 onUserRemoved(intent);
4154 }
4155 }, userFilter);
4156
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004157 synchronized (this) {
4158 // Ensure that any processes we had put on hold are now started
4159 // up.
4160 final int NP = mProcessesOnHold.size();
4161 if (NP > 0) {
4162 ArrayList<ProcessRecord> procs =
4163 new ArrayList<ProcessRecord>(mProcessesOnHold);
4164 for (int ip=0; ip<NP; ip++) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004165 if (DEBUG_PROCESSES) Slog.v(TAG, "Starting process on hold: "
4166 + procs.get(ip));
4167 startProcessLocked(procs.get(ip), "on-hold", null);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004168 }
4169 }
4170
4171 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004172 // Start looking for apps that are abusing wake locks.
4173 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07004174 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004175 // Tell anyone interested that we are done booting!
Dianne Hackbornf4c454b2010-08-11 12:47:41 -07004176 SystemProperties.set("sys.boot_completed", "1");
Guang Zhu191713a2012-01-12 12:02:22 -08004177 SystemProperties.set("dev.bootcomplete", "1");
Amith Yamasani742a6712011-05-04 14:49:28 -07004178 /* TODO: Send this to all users that are to be logged in on startup */
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004179 broadcastIntentLocked(null, null,
4180 new Intent(Intent.ACTION_BOOT_COMPLETED, null),
4181 null, null, 0, null, null,
4182 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
Amith Yamasani742a6712011-05-04 14:49:28 -07004183 false, false, MY_PID, Process.SYSTEM_UID, Binder.getOrigCallingUser());
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004184 }
4185 }
4186 }
4187
4188 final void ensureBootCompleted() {
4189 boolean booting;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004190 boolean enableScreen;
4191 synchronized (this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004192 booting = mBooting;
4193 mBooting = false;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004194 enableScreen = !mBooted;
4195 mBooted = true;
4196 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004197
4198 if (booting) {
4199 finishBooting();
4200 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004201
4202 if (enableScreen) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004203 enableScreenAfterBoot();
4204 }
4205 }
4206
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004207 public final void activityPaused(IBinder token) {
4208 final long origId = Binder.clearCallingIdentity();
4209 mMainStack.activityPaused(token, false);
4210 Binder.restoreCallingIdentity(origId);
4211 }
4212
4213 public final void activityStopped(IBinder token, Bundle icicle, Bitmap thumbnail,
4214 CharSequence description) {
4215 if (localLOGV) Slog.v(
4216 TAG, "Activity stopped: token=" + token);
4217
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004218 // Refuse possible leaked file descriptors
4219 if (icicle != null && icicle.hasFileDescriptors()) {
4220 throw new IllegalArgumentException("File descriptors passed in Bundle");
4221 }
4222
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004223 ActivityRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004224
4225 final long origId = Binder.clearCallingIdentity();
4226
4227 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004228 r = mMainStack.isInStackLocked(token);
4229 if (r != null) {
4230 r.stack.activityStoppedLocked(r, icicle, thumbnail, description);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004231 }
4232 }
4233
4234 if (r != null) {
4235 sendPendingThumbnail(r, null, null, null, false);
4236 }
4237
4238 trimApplications();
4239
4240 Binder.restoreCallingIdentity(origId);
4241 }
4242
4243 public final void activityDestroyed(IBinder token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004244 if (DEBUG_SWITCH) Slog.v(TAG, "ACTIVITY DESTROYED: " + token);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004245 mMainStack.activityDestroyed(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004246 }
4247
4248 public String getCallingPackage(IBinder token) {
4249 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004250 ActivityRecord r = getCallingRecordLocked(token);
Dianne Hackborn9bbcb912009-10-20 15:42:38 -07004251 return r != null && r.app != null ? r.info.packageName : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004252 }
4253 }
4254
4255 public ComponentName getCallingActivity(IBinder token) {
4256 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004257 ActivityRecord r = getCallingRecordLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004258 return r != null ? r.intent.getComponent() : null;
4259 }
4260 }
4261
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004262 private ActivityRecord getCallingRecordLocked(IBinder token) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004263 ActivityRecord r = mMainStack.isInStackLocked(token);
4264 if (r == null) {
4265 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004266 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004267 return r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004268 }
4269
4270 public ComponentName getActivityClassForToken(IBinder token) {
4271 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004272 ActivityRecord r = mMainStack.isInStackLocked(token);
4273 if (r == null) {
4274 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004275 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004276 return r.intent.getComponent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004277 }
4278 }
4279
4280 public String getPackageForToken(IBinder token) {
4281 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004282 ActivityRecord r = mMainStack.isInStackLocked(token);
4283 if (r == null) {
4284 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004285 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004286 return r.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004287 }
4288 }
4289
4290 public IIntentSender getIntentSender(int type,
4291 String packageName, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004292 int requestCode, Intent[] intents, String[] resolvedTypes,
4293 int flags, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004294 enforceNotIsolatedCaller("getIntentSender");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004295 // Refuse possible leaked file descriptors
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004296 if (intents != null) {
4297 if (intents.length < 1) {
4298 throw new IllegalArgumentException("Intents array length must be >= 1");
4299 }
4300 for (int i=0; i<intents.length; i++) {
4301 Intent intent = intents[i];
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004302 if (intent != null) {
4303 if (intent.hasFileDescriptors()) {
4304 throw new IllegalArgumentException("File descriptors passed in Intent");
4305 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07004306 if (type == ActivityManager.INTENT_SENDER_BROADCAST &&
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004307 (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
4308 throw new IllegalArgumentException(
4309 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
4310 }
4311 intents[i] = new Intent(intent);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004312 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004313 }
4314 if (resolvedTypes != null && resolvedTypes.length != intents.length) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004315 throw new IllegalArgumentException(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004316 "Intent array length does not match resolvedTypes length");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004317 }
4318 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004319 if (options != null) {
4320 if (options.hasFileDescriptors()) {
4321 throw new IllegalArgumentException("File descriptors passed in options");
4322 }
4323 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004324
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004325 synchronized(this) {
4326 int callingUid = Binder.getCallingUid();
4327 try {
Jeff Brown10e89712011-07-08 18:52:57 -07004328 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004329 int uid = AppGlobals.getPackageManager()
Amith Yamasani483f3b02012-03-13 16:08:00 -07004330 .getPackageUid(packageName, UserId.getUserId(callingUid));
4331 if (!UserId.isSameApp(callingUid, uid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004332 String msg = "Permission Denial: getIntentSender() from pid="
4333 + Binder.getCallingPid()
4334 + ", uid=" + Binder.getCallingUid()
4335 + ", (need uid=" + uid + ")"
4336 + " is not allowed to send as package " + packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004337 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004338 throw new SecurityException(msg);
4339 }
4340 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004341
Amith Yamasani742a6712011-05-04 14:49:28 -07004342 if (DEBUG_MU)
4343 Slog.i(TAG_MU, "Getting intent sender for origCallingUid="
4344 + Binder.getOrigCallingUid());
4345 return getIntentSenderLocked(type, packageName, Binder.getOrigCallingUid(),
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004346 token, resultWho, requestCode, intents, resolvedTypes, flags, options);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004347
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004348 } catch (RemoteException e) {
4349 throw new SecurityException(e);
4350 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004351 }
4352 }
4353
4354 IIntentSender getIntentSenderLocked(int type,
4355 String packageName, int callingUid, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004356 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
4357 Bundle options) {
Amith Yamasani742a6712011-05-04 14:49:28 -07004358 if (DEBUG_MU)
4359 Slog.v(TAG_MU, "getIntentSenderLocked(): uid=" + callingUid);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004360 ActivityRecord activity = null;
Dianne Hackborna4972e92012-03-14 10:38:05 -07004361 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004362 activity = mMainStack.isInStackLocked(token);
4363 if (activity == null) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004364 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004365 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004366 if (activity.finishing) {
4367 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004368 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004369 }
4370
4371 final boolean noCreate = (flags&PendingIntent.FLAG_NO_CREATE) != 0;
4372 final boolean cancelCurrent = (flags&PendingIntent.FLAG_CANCEL_CURRENT) != 0;
4373 final boolean updateCurrent = (flags&PendingIntent.FLAG_UPDATE_CURRENT) != 0;
4374 flags &= ~(PendingIntent.FLAG_NO_CREATE|PendingIntent.FLAG_CANCEL_CURRENT
4375 |PendingIntent.FLAG_UPDATE_CURRENT);
4376
4377 PendingIntentRecord.Key key = new PendingIntentRecord.Key(
4378 type, packageName, activity, resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004379 requestCode, intents, resolvedTypes, flags, options);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004380 WeakReference<PendingIntentRecord> ref;
4381 ref = mIntentSenderRecords.get(key);
4382 PendingIntentRecord rec = ref != null ? ref.get() : null;
4383 if (rec != null) {
4384 if (!cancelCurrent) {
4385 if (updateCurrent) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004386 if (rec.key.requestIntent != null) {
4387 rec.key.requestIntent.replaceExtras(intents != null ? intents[0] : null);
4388 }
4389 if (intents != null) {
4390 intents[intents.length-1] = rec.key.requestIntent;
4391 rec.key.allIntents = intents;
4392 rec.key.allResolvedTypes = resolvedTypes;
4393 } else {
4394 rec.key.allIntents = null;
4395 rec.key.allResolvedTypes = null;
4396 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004397 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004398 return rec;
4399 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004400 rec.canceled = true;
4401 mIntentSenderRecords.remove(key);
4402 }
4403 if (noCreate) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004404 return rec;
4405 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004406 rec = new PendingIntentRecord(this, key, callingUid);
4407 mIntentSenderRecords.put(key, rec.ref);
Dianne Hackborna4972e92012-03-14 10:38:05 -07004408 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004409 if (activity.pendingResults == null) {
4410 activity.pendingResults
4411 = new HashSet<WeakReference<PendingIntentRecord>>();
4412 }
4413 activity.pendingResults.add(rec.ref);
4414 }
4415 return rec;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004416 }
4417
4418 public void cancelIntentSender(IIntentSender sender) {
4419 if (!(sender instanceof PendingIntentRecord)) {
4420 return;
4421 }
4422 synchronized(this) {
4423 PendingIntentRecord rec = (PendingIntentRecord)sender;
4424 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004425 int uid = AppGlobals.getPackageManager()
Amith Yamasani483f3b02012-03-13 16:08:00 -07004426 .getPackageUid(rec.key.packageName, UserId.getCallingUserId());
Amith Yamasani04e0d262012-02-14 11:50:53 -08004427 if (!UserId.isSameApp(uid, Binder.getCallingUid())) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004428 String msg = "Permission Denial: cancelIntentSender() from pid="
4429 + Binder.getCallingPid()
4430 + ", uid=" + Binder.getCallingUid()
4431 + " is not allowed to cancel packges "
4432 + rec.key.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004433 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004434 throw new SecurityException(msg);
4435 }
4436 } catch (RemoteException e) {
4437 throw new SecurityException(e);
4438 }
4439 cancelIntentSenderLocked(rec, true);
4440 }
4441 }
4442
4443 void cancelIntentSenderLocked(PendingIntentRecord rec, boolean cleanActivity) {
4444 rec.canceled = true;
4445 mIntentSenderRecords.remove(rec.key);
4446 if (cleanActivity && rec.key.activity != null) {
4447 rec.key.activity.pendingResults.remove(rec.ref);
4448 }
4449 }
4450
4451 public String getPackageForIntentSender(IIntentSender pendingResult) {
4452 if (!(pendingResult instanceof PendingIntentRecord)) {
4453 return null;
4454 }
Brad Fitzpatrickb213d102010-04-19 11:58:52 -07004455 try {
4456 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4457 return res.key.packageName;
4458 } catch (ClassCastException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004459 }
4460 return null;
4461 }
4462
Christopher Tatec4a07d12012-04-06 14:19:13 -07004463 public int getUidForIntentSender(IIntentSender sender) {
4464 if (sender instanceof PendingIntentRecord) {
4465 try {
4466 PendingIntentRecord res = (PendingIntentRecord)sender;
4467 return res.uid;
4468 } catch (ClassCastException e) {
4469 }
4470 }
4471 return -1;
4472 }
4473
Dianne Hackborn6c418d52011-06-29 14:05:33 -07004474 public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) {
4475 if (!(pendingResult instanceof PendingIntentRecord)) {
4476 return false;
4477 }
4478 try {
4479 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4480 if (res.key.allIntents == null) {
4481 return false;
4482 }
4483 for (int i=0; i<res.key.allIntents.length; i++) {
4484 Intent intent = res.key.allIntents[i];
4485 if (intent.getPackage() != null && intent.getComponent() != null) {
4486 return false;
4487 }
4488 }
4489 return true;
4490 } catch (ClassCastException e) {
4491 }
4492 return false;
4493 }
4494
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004495 public void setProcessLimit(int max) {
4496 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4497 "setProcessLimit()");
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004498 synchronized (this) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07004499 mProcessLimit = max < 0 ? ProcessList.MAX_HIDDEN_APPS : max;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004500 mProcessLimitOverride = max;
4501 }
4502 trimApplications();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004503 }
4504
4505 public int getProcessLimit() {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004506 synchronized (this) {
4507 return mProcessLimitOverride;
4508 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004509 }
4510
4511 void foregroundTokenDied(ForegroundToken token) {
4512 synchronized (ActivityManagerService.this) {
4513 synchronized (mPidsSelfLocked) {
4514 ForegroundToken cur
4515 = mForegroundProcesses.get(token.pid);
4516 if (cur != token) {
4517 return;
4518 }
4519 mForegroundProcesses.remove(token.pid);
4520 ProcessRecord pr = mPidsSelfLocked.get(token.pid);
4521 if (pr == null) {
4522 return;
4523 }
4524 pr.forcingToForeground = null;
4525 pr.foregroundServices = false;
4526 }
4527 updateOomAdjLocked();
4528 }
4529 }
4530
4531 public void setProcessForeground(IBinder token, int pid, boolean isForeground) {
4532 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4533 "setProcessForeground()");
4534 synchronized(this) {
4535 boolean changed = false;
4536
4537 synchronized (mPidsSelfLocked) {
4538 ProcessRecord pr = mPidsSelfLocked.get(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004539 if (pr == null && isForeground) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004540 Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004541 return;
4542 }
4543 ForegroundToken oldToken = mForegroundProcesses.get(pid);
4544 if (oldToken != null) {
4545 oldToken.token.unlinkToDeath(oldToken, 0);
4546 mForegroundProcesses.remove(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004547 if (pr != null) {
4548 pr.forcingToForeground = null;
4549 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004550 changed = true;
4551 }
4552 if (isForeground && token != null) {
4553 ForegroundToken newToken = new ForegroundToken() {
4554 public void binderDied() {
4555 foregroundTokenDied(this);
4556 }
4557 };
4558 newToken.pid = pid;
4559 newToken.token = token;
4560 try {
4561 token.linkToDeath(newToken, 0);
4562 mForegroundProcesses.put(pid, newToken);
4563 pr.forcingToForeground = token;
4564 changed = true;
4565 } catch (RemoteException e) {
4566 // If the process died while doing this, we will later
4567 // do the cleanup with the process death link.
4568 }
4569 }
4570 }
4571
4572 if (changed) {
4573 updateOomAdjLocked();
4574 }
4575 }
4576 }
4577
4578 // =========================================================
4579 // PERMISSIONS
4580 // =========================================================
4581
4582 static class PermissionController extends IPermissionController.Stub {
4583 ActivityManagerService mActivityManagerService;
4584 PermissionController(ActivityManagerService activityManagerService) {
4585 mActivityManagerService = activityManagerService;
4586 }
4587
4588 public boolean checkPermission(String permission, int pid, int uid) {
4589 return mActivityManagerService.checkPermission(permission, pid,
4590 uid) == PackageManager.PERMISSION_GRANTED;
4591 }
4592 }
4593
4594 /**
4595 * This can be called with or without the global lock held.
4596 */
4597 int checkComponentPermission(String permission, int pid, int uid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004598 int owningUid, boolean exported) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004599 // We might be performing an operation on behalf of an indirect binder
4600 // invocation, e.g. via {@link #openContentUri}. Check and adjust the
4601 // client identity accordingly before proceeding.
4602 Identity tlsIdentity = sCallerIdentity.get();
4603 if (tlsIdentity != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004604 Slog.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004605 + tlsIdentity.pid + "," + tlsIdentity.uid + "}");
4606 uid = tlsIdentity.uid;
4607 pid = tlsIdentity.pid;
4608 }
4609
4610 // Root, system server and our own process get to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07004611 if (uid == 0 || uid == Process.SYSTEM_UID || pid == MY_PID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004612 return PackageManager.PERMISSION_GRANTED;
4613 }
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004614 // Isolated processes don't get any permissions.
4615 if (UserId.isIsolated(uid)) {
4616 return PackageManager.PERMISSION_DENIED;
4617 }
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004618 // If there is a uid that owns whatever is being accessed, it has
4619 // blanket access to it regardless of the permissions it requires.
Amith Yamasani742a6712011-05-04 14:49:28 -07004620 if (owningUid >= 0 && UserId.isSameApp(uid, owningUid)) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004621 return PackageManager.PERMISSION_GRANTED;
4622 }
4623 // If the target is not exported, then nobody else can get to it.
4624 if (!exported) {
4625 Slog.w(TAG, "Permission denied: checkComponentPermission() owningUid=" + owningUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004626 return PackageManager.PERMISSION_DENIED;
4627 }
4628 if (permission == null) {
4629 return PackageManager.PERMISSION_GRANTED;
4630 }
4631 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004632 return AppGlobals.getPackageManager()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004633 .checkUidPermission(permission, uid);
4634 } catch (RemoteException e) {
4635 // Should never happen, but if it does... deny!
Joe Onorato8a9b2202010-02-26 18:56:32 -08004636 Slog.e(TAG, "PackageManager is dead?!?", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004637 }
4638 return PackageManager.PERMISSION_DENIED;
4639 }
4640
4641 /**
4642 * As the only public entry point for permissions checking, this method
4643 * can enforce the semantic that requesting a check on a null global
4644 * permission is automatically denied. (Internally a null permission
4645 * string is used when calling {@link #checkComponentPermission} in cases
4646 * when only uid-based security is needed.)
4647 *
4648 * This can be called with or without the global lock held.
4649 */
4650 public int checkPermission(String permission, int pid, int uid) {
4651 if (permission == null) {
4652 return PackageManager.PERMISSION_DENIED;
4653 }
Amith Yamasani742a6712011-05-04 14:49:28 -07004654 return checkComponentPermission(permission, pid, UserId.getAppId(uid), -1, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004655 }
4656
4657 /**
4658 * Binder IPC calls go through the public entry point.
4659 * This can be called with or without the global lock held.
4660 */
4661 int checkCallingPermission(String permission) {
4662 return checkPermission(permission,
4663 Binder.getCallingPid(),
Amith Yamasani742a6712011-05-04 14:49:28 -07004664 UserId.getAppId(Binder.getCallingUid()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004665 }
4666
4667 /**
4668 * This can be called with or without the global lock held.
4669 */
4670 void enforceCallingPermission(String permission, String func) {
4671 if (checkCallingPermission(permission)
4672 == PackageManager.PERMISSION_GRANTED) {
4673 return;
4674 }
4675
4676 String msg = "Permission Denial: " + func + " from pid="
4677 + Binder.getCallingPid()
4678 + ", uid=" + Binder.getCallingUid()
4679 + " requires " + permission;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004680 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004681 throw new SecurityException(msg);
4682 }
4683
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004684 /**
4685 * Determine if UID is holding permissions required to access {@link Uri} in
4686 * the given {@link ProviderInfo}. Final permission checking is always done
4687 * in {@link ContentProvider}.
4688 */
4689 private final boolean checkHoldingPermissionsLocked(
4690 IPackageManager pm, ProviderInfo pi, Uri uri, int uid, int modeFlags) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004691 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4692 "checkHoldingPermissionsLocked: uri=" + uri + " uid=" + uid);
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004693
4694 if (pi.applicationInfo.uid == uid) {
4695 return true;
4696 } else if (!pi.exported) {
4697 return false;
4698 }
4699
4700 boolean readMet = (modeFlags & Intent.FLAG_GRANT_READ_URI_PERMISSION) == 0;
4701 boolean writeMet = (modeFlags & Intent.FLAG_GRANT_WRITE_URI_PERMISSION) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004702 try {
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004703 // check if target holds top-level <provider> permissions
4704 if (!readMet && pi.readPermission != null
4705 && (pm.checkUidPermission(pi.readPermission, uid) == PERMISSION_GRANTED)) {
4706 readMet = true;
4707 }
4708 if (!writeMet && pi.writePermission != null
4709 && (pm.checkUidPermission(pi.writePermission, uid) == PERMISSION_GRANTED)) {
4710 writeMet = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004711 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004712
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004713 // track if unprotected read/write is allowed; any denied
4714 // <path-permission> below removes this ability
4715 boolean allowDefaultRead = pi.readPermission == null;
4716 boolean allowDefaultWrite = pi.writePermission == null;
Dianne Hackborn48058e82010-09-27 16:53:23 -07004717
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004718 // check if target holds any <path-permission> that match uri
4719 final PathPermission[] pps = pi.pathPermissions;
4720 if (pps != null) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004721 final String path = uri.getPath();
4722 int i = pps.length;
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004723 while (i > 0 && (!readMet || !writeMet)) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004724 i--;
4725 PathPermission pp = pps[i];
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004726 if (pp.match(path)) {
4727 if (!readMet) {
4728 final String pprperm = pp.getReadPermission();
4729 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking read perm for "
4730 + pprperm + " for " + pp.getPath()
4731 + ": match=" + pp.match(path)
4732 + " check=" + pm.checkUidPermission(pprperm, uid));
4733 if (pprperm != null) {
4734 if (pm.checkUidPermission(pprperm, uid) == PERMISSION_GRANTED) {
4735 readMet = true;
4736 } else {
4737 allowDefaultRead = false;
4738 }
4739 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004740 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004741 if (!writeMet) {
4742 final String ppwperm = pp.getWritePermission();
4743 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking write perm "
4744 + ppwperm + " for " + pp.getPath()
4745 + ": match=" + pp.match(path)
4746 + " check=" + pm.checkUidPermission(ppwperm, uid));
4747 if (ppwperm != null) {
4748 if (pm.checkUidPermission(ppwperm, uid) == PERMISSION_GRANTED) {
4749 writeMet = true;
4750 } else {
4751 allowDefaultWrite = false;
4752 }
4753 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004754 }
4755 }
4756 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07004757 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004758
4759 // grant unprotected <provider> read/write, if not blocked by
4760 // <path-permission> above
4761 if (allowDefaultRead) readMet = true;
4762 if (allowDefaultWrite) writeMet = true;
4763
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004764 } catch (RemoteException e) {
4765 return false;
4766 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004767
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004768 return readMet && writeMet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004769 }
4770
4771 private final boolean checkUriPermissionLocked(Uri uri, int uid,
4772 int modeFlags) {
4773 // Root gets to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07004774 if (uid == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004775 return true;
4776 }
4777 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(uid);
4778 if (perms == null) return false;
4779 UriPermission perm = perms.get(uri);
4780 if (perm == null) return false;
4781 return (modeFlags&perm.modeFlags) == modeFlags;
4782 }
4783
4784 public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004785 enforceNotIsolatedCaller("checkUriPermission");
4786
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004787 // Another redirected-binder-call permissions check as in
4788 // {@link checkComponentPermission}.
4789 Identity tlsIdentity = sCallerIdentity.get();
4790 if (tlsIdentity != null) {
4791 uid = tlsIdentity.uid;
4792 pid = tlsIdentity.pid;
4793 }
4794
Amith Yamasani742a6712011-05-04 14:49:28 -07004795 uid = UserId.getAppId(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004796 // Our own process gets to do everything.
4797 if (pid == MY_PID) {
4798 return PackageManager.PERMISSION_GRANTED;
4799 }
4800 synchronized(this) {
4801 return checkUriPermissionLocked(uri, uid, modeFlags)
4802 ? PackageManager.PERMISSION_GRANTED
4803 : PackageManager.PERMISSION_DENIED;
4804 }
4805 }
4806
Dianne Hackborn39792d22010-08-19 18:01:52 -07004807 /**
4808 * Check if the targetPkg can be granted permission to access uri by
4809 * the callingUid using the given modeFlags. Throws a security exception
4810 * if callingUid is not allowed to do this. Returns the uid of the target
4811 * if the URI permission grant should be performed; returns -1 if it is not
4812 * needed (for example targetPkg already has permission to access the URI).
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004813 * If you already know the uid of the target, you can supply it in
4814 * lastTargetUid else set that to -1.
Dianne Hackborn39792d22010-08-19 18:01:52 -07004815 */
4816 int checkGrantUriPermissionLocked(int callingUid, String targetPkg,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004817 Uri uri, int modeFlags, int lastTargetUid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004818 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4819 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4820 if (modeFlags == 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004821 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004822 }
4823
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004824 if (targetPkg != null) {
4825 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4826 "Checking grant " + targetPkg + " permission to " + uri);
4827 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004828
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004829 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004830
4831 // If this is not a content: uri, we can't do anything with it.
4832 if (!ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004833 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004834 "Can't grant URI permission for non-content URI: " + uri);
Dianne Hackborn39792d22010-08-19 18:01:52 -07004835 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004836 }
4837
4838 String name = uri.getAuthority();
4839 ProviderInfo pi = null;
Amith Yamasani742a6712011-05-04 14:49:28 -07004840 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
4841 UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004842 if (cpr != null) {
4843 pi = cpr.info;
4844 } else {
4845 try {
4846 pi = pm.resolveContentProvider(name,
Amith Yamasani483f3b02012-03-13 16:08:00 -07004847 PackageManager.GET_URI_PERMISSION_PATTERNS, UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004848 } catch (RemoteException ex) {
4849 }
4850 }
4851 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07004852 Slog.w(TAG, "No content provider found for permission check: " + uri.toSafeString());
Dianne Hackborn39792d22010-08-19 18:01:52 -07004853 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004854 }
4855
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004856 int targetUid = lastTargetUid;
4857 if (targetUid < 0 && targetPkg != null) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004858 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07004859 targetUid = pm.getPackageUid(targetPkg, UserId.getUserId(callingUid));
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004860 if (targetUid < 0) {
4861 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4862 "Can't grant URI permission no uid for: " + targetPkg);
4863 return -1;
4864 }
4865 } catch (RemoteException ex) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004866 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004867 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004868 }
4869
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004870 if (targetUid >= 0) {
4871 // First... does the target actually need this permission?
4872 if (checkHoldingPermissionsLocked(pm, pi, uri, targetUid, modeFlags)) {
4873 // No need to grant the target this permission.
4874 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4875 "Target " + targetPkg + " already has full permission to " + uri);
4876 return -1;
4877 }
4878 } else {
4879 // First... there is no target package, so can anyone access it?
4880 boolean allowed = pi.exported;
4881 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
4882 if (pi.readPermission != null) {
4883 allowed = false;
4884 }
4885 }
4886 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
4887 if (pi.writePermission != null) {
4888 allowed = false;
4889 }
4890 }
4891 if (allowed) {
4892 return -1;
4893 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004894 }
4895
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004896 // Second... is the provider allowing granting of URI permissions?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004897 if (!pi.grantUriPermissions) {
4898 throw new SecurityException("Provider " + pi.packageName
4899 + "/" + pi.name
4900 + " does not allow granting of Uri permissions (uri "
4901 + uri + ")");
4902 }
4903 if (pi.uriPermissionPatterns != null) {
4904 final int N = pi.uriPermissionPatterns.length;
4905 boolean allowed = false;
4906 for (int i=0; i<N; i++) {
4907 if (pi.uriPermissionPatterns[i] != null
4908 && pi.uriPermissionPatterns[i].match(uri.getPath())) {
4909 allowed = true;
4910 break;
4911 }
4912 }
4913 if (!allowed) {
4914 throw new SecurityException("Provider " + pi.packageName
4915 + "/" + pi.name
4916 + " does not allow granting of permission to path of Uri "
4917 + uri);
4918 }
4919 }
4920
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004921 // Third... does the caller itself have permission to access
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004922 // this uri?
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004923 if (callingUid != Process.myUid()) {
4924 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
4925 if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
4926 throw new SecurityException("Uid " + callingUid
4927 + " does not have permission to uri " + uri);
4928 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004929 }
4930 }
4931
Dianne Hackborn39792d22010-08-19 18:01:52 -07004932 return targetUid;
4933 }
4934
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004935 public int checkGrantUriPermission(int callingUid, String targetPkg,
4936 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004937 enforceNotIsolatedCaller("checkGrantUriPermission");
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004938 synchronized(this) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004939 return checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004940 }
4941 }
4942
Dianne Hackborn39792d22010-08-19 18:01:52 -07004943 void grantUriPermissionUncheckedLocked(int targetUid, String targetPkg,
4944 Uri uri, int modeFlags, UriPermissionOwner owner) {
4945 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4946 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4947 if (modeFlags == 0) {
4948 return;
4949 }
4950
4951 // So here we are: the caller has the assumed permission
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004952 // to the uri, and the target doesn't. Let's now give this to
4953 // the target.
4954
Joe Onorato8a9b2202010-02-26 18:56:32 -08004955 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn39792d22010-08-19 18:01:52 -07004956 "Granting " + targetPkg + "/" + targetUid + " permission to " + uri);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004957
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004958 HashMap<Uri, UriPermission> targetUris
4959 = mGrantedUriPermissions.get(targetUid);
4960 if (targetUris == null) {
4961 targetUris = new HashMap<Uri, UriPermission>();
4962 mGrantedUriPermissions.put(targetUid, targetUris);
4963 }
4964
4965 UriPermission perm = targetUris.get(uri);
4966 if (perm == null) {
4967 perm = new UriPermission(targetUid, uri);
4968 targetUris.put(uri, perm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004969 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07004970
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004971 perm.modeFlags |= modeFlags;
Dianne Hackborn39792d22010-08-19 18:01:52 -07004972 if (owner == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004973 perm.globalModeFlags |= modeFlags;
Vairavan Srinivasan91c12c22011-01-21 18:26:06 -08004974 } else {
4975 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
4976 perm.readOwners.add(owner);
4977 owner.addReadPermission(perm);
4978 }
4979 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
4980 perm.writeOwners.add(owner);
4981 owner.addWritePermission(perm);
4982 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004983 }
4984 }
4985
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004986 void grantUriPermissionLocked(int callingUid, String targetPkg, Uri uri,
4987 int modeFlags, UriPermissionOwner owner) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004988 if (targetPkg == null) {
4989 throw new NullPointerException("targetPkg");
4990 }
4991
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004992 int targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn39792d22010-08-19 18:01:52 -07004993 if (targetUid < 0) {
4994 return;
4995 }
4996
4997 grantUriPermissionUncheckedLocked(targetUid, targetPkg, uri, modeFlags, owner);
4998 }
4999
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005000 static class NeededUriGrants extends ArrayList<Uri> {
5001 final String targetPkg;
5002 final int targetUid;
5003 final int flags;
5004
5005 NeededUriGrants(String _targetPkg, int _targetUid, int _flags) {
5006 targetPkg = _targetPkg;
5007 targetUid = _targetUid;
5008 flags = _flags;
5009 }
5010 }
5011
Dianne Hackborn39792d22010-08-19 18:01:52 -07005012 /**
5013 * Like checkGrantUriPermissionLocked, but takes an Intent.
5014 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005015 NeededUriGrants checkGrantUriPermissionFromIntentLocked(int callingUid,
5016 String targetPkg, Intent intent, int mode, NeededUriGrants needed) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07005017 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005018 "Checking URI perm to data=" + (intent != null ? intent.getData() : null)
5019 + " clip=" + (intent != null ? intent.getClipData() : null)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005020 + " from " + intent + "; flags=0x"
5021 + Integer.toHexString(intent != null ? intent.getFlags() : 0));
5022
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005023 if (targetPkg == null) {
5024 throw new NullPointerException("targetPkg");
5025 }
5026
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005027 if (intent == null) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005028 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005029 }
5030 Uri data = intent.getData();
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005031 ClipData clip = intent.getClipData();
5032 if (data == null && clip == null) {
5033 return null;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005034 }
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005035 if (data != null) {
5036 int target = checkGrantUriPermissionLocked(callingUid, targetPkg, data,
5037 mode, needed != null ? needed.targetUid : -1);
5038 if (target > 0) {
5039 if (needed == null) {
5040 needed = new NeededUriGrants(targetPkg, target, mode);
5041 }
5042 needed.add(data);
5043 }
5044 }
5045 if (clip != null) {
5046 for (int i=0; i<clip.getItemCount(); i++) {
5047 Uri uri = clip.getItemAt(i).getUri();
5048 if (uri != null) {
5049 int target = -1;
5050 target = checkGrantUriPermissionLocked(callingUid, targetPkg, uri,
5051 mode, needed != null ? needed.targetUid : -1);
5052 if (target > 0) {
5053 if (needed == null) {
5054 needed = new NeededUriGrants(targetPkg, target, mode);
5055 }
5056 needed.add(uri);
5057 }
5058 } else {
5059 Intent clipIntent = clip.getItemAt(i).getIntent();
5060 if (clipIntent != null) {
5061 NeededUriGrants newNeeded = checkGrantUriPermissionFromIntentLocked(
5062 callingUid, targetPkg, clipIntent, mode, needed);
5063 if (newNeeded != null) {
5064 needed = newNeeded;
5065 }
5066 }
5067 }
5068 }
5069 }
5070
5071 return needed;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005072 }
5073
5074 /**
5075 * Like grantUriPermissionUncheckedLocked, but takes an Intent.
5076 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005077 void grantUriPermissionUncheckedFromIntentLocked(NeededUriGrants needed,
5078 UriPermissionOwner owner) {
5079 if (needed != null) {
5080 for (int i=0; i<needed.size(); i++) {
5081 grantUriPermissionUncheckedLocked(needed.targetUid, needed.targetPkg,
5082 needed.get(i), needed.flags, owner);
5083 }
5084 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005085 }
5086
5087 void grantUriPermissionFromIntentLocked(int callingUid,
5088 String targetPkg, Intent intent, UriPermissionOwner owner) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005089 NeededUriGrants needed = checkGrantUriPermissionFromIntentLocked(callingUid, targetPkg,
Dianne Hackbornd9781fe2012-03-08 18:04:18 -08005090 intent, intent != null ? intent.getFlags() : 0, null);
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005091 if (needed == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005092 return;
5093 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005094
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005095 grantUriPermissionUncheckedFromIntentLocked(needed, owner);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005096 }
5097
5098 public void grantUriPermission(IApplicationThread caller, String targetPkg,
5099 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005100 enforceNotIsolatedCaller("grantUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005101 synchronized(this) {
5102 final ProcessRecord r = getRecordForAppLocked(caller);
5103 if (r == null) {
5104 throw new SecurityException("Unable to find app for caller "
5105 + caller
5106 + " when granting permission to uri " + uri);
5107 }
5108 if (targetPkg == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005109 throw new IllegalArgumentException("null target");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005110 }
5111 if (uri == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005112 throw new IllegalArgumentException("null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005113 }
5114
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005115 grantUriPermissionLocked(r.uid, targetPkg, uri, modeFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005116 null);
5117 }
5118 }
5119
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005120 void removeUriPermissionIfNeededLocked(UriPermission perm) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005121 if ((perm.modeFlags&(Intent.FLAG_GRANT_READ_URI_PERMISSION
5122 |Intent.FLAG_GRANT_WRITE_URI_PERMISSION)) == 0) {
5123 HashMap<Uri, UriPermission> perms
5124 = mGrantedUriPermissions.get(perm.uid);
5125 if (perms != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005126 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005127 "Removing " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005128 perms.remove(perm.uri);
5129 if (perms.size() == 0) {
5130 mGrantedUriPermissions.remove(perm.uid);
5131 }
5132 }
5133 }
5134 }
5135
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005136 private void revokeUriPermissionLocked(int callingUid, Uri uri,
5137 int modeFlags) {
5138 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5139 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5140 if (modeFlags == 0) {
5141 return;
5142 }
5143
Joe Onorato8a9b2202010-02-26 18:56:32 -08005144 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005145 "Revoking all granted permissions to " + uri);
5146
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005147 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005148
5149 final String authority = uri.getAuthority();
5150 ProviderInfo pi = null;
Amith Yamasani483f3b02012-03-13 16:08:00 -07005151 int userId = UserId.getUserId(callingUid);
5152 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005153 if (cpr != null) {
5154 pi = cpr.info;
5155 } else {
5156 try {
5157 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005158 PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005159 } catch (RemoteException ex) {
5160 }
5161 }
5162 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005163 Slog.w(TAG, "No content provider found for permission revoke: " + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005164 return;
5165 }
5166
5167 // Does the caller have this permission on the URI?
Dianne Hackborn48058e82010-09-27 16:53:23 -07005168 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005169 // Right now, if you are not the original owner of the permission,
5170 // you are not allowed to revoke it.
5171 //if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5172 throw new SecurityException("Uid " + callingUid
5173 + " does not have permission to uri " + uri);
5174 //}
5175 }
5176
5177 // Go through all of the permissions and remove any that match.
5178 final List<String> SEGMENTS = uri.getPathSegments();
5179 if (SEGMENTS != null) {
5180 final int NS = SEGMENTS.size();
5181 int N = mGrantedUriPermissions.size();
5182 for (int i=0; i<N; i++) {
5183 HashMap<Uri, UriPermission> perms
5184 = mGrantedUriPermissions.valueAt(i);
5185 Iterator<UriPermission> it = perms.values().iterator();
5186 toploop:
5187 while (it.hasNext()) {
5188 UriPermission perm = it.next();
5189 Uri targetUri = perm.uri;
5190 if (!authority.equals(targetUri.getAuthority())) {
5191 continue;
5192 }
5193 List<String> targetSegments = targetUri.getPathSegments();
5194 if (targetSegments == null) {
5195 continue;
5196 }
5197 if (targetSegments.size() < NS) {
5198 continue;
5199 }
5200 for (int j=0; j<NS; j++) {
5201 if (!SEGMENTS.get(j).equals(targetSegments.get(j))) {
5202 continue toploop;
5203 }
5204 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08005205 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005206 "Revoking " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005207 perm.clearModes(modeFlags);
5208 if (perm.modeFlags == 0) {
5209 it.remove();
5210 }
5211 }
5212 if (perms.size() == 0) {
5213 mGrantedUriPermissions.remove(
5214 mGrantedUriPermissions.keyAt(i));
5215 N--;
5216 i--;
5217 }
5218 }
5219 }
5220 }
5221
5222 public void revokeUriPermission(IApplicationThread caller, Uri uri,
5223 int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005224 enforceNotIsolatedCaller("revokeUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005225 synchronized(this) {
5226 final ProcessRecord r = getRecordForAppLocked(caller);
5227 if (r == null) {
5228 throw new SecurityException("Unable to find app for caller "
5229 + caller
5230 + " when revoking permission to uri " + uri);
5231 }
5232 if (uri == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005233 Slog.w(TAG, "revokeUriPermission: null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005234 return;
5235 }
5236
5237 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5238 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5239 if (modeFlags == 0) {
5240 return;
5241 }
5242
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005243 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005244
5245 final String authority = uri.getAuthority();
5246 ProviderInfo pi = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005247 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005248 if (cpr != null) {
5249 pi = cpr.info;
5250 } else {
5251 try {
5252 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005253 PackageManager.GET_URI_PERMISSION_PATTERNS, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005254 } catch (RemoteException ex) {
5255 }
5256 }
5257 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005258 Slog.w(TAG, "No content provider found for permission revoke: "
5259 + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005260 return;
5261 }
5262
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005263 revokeUriPermissionLocked(r.uid, uri, modeFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005264 }
5265 }
5266
Dianne Hackborn7e269642010-08-25 19:50:20 -07005267 @Override
5268 public IBinder newUriPermissionOwner(String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005269 enforceNotIsolatedCaller("newUriPermissionOwner");
Dianne Hackborn7e269642010-08-25 19:50:20 -07005270 synchronized(this) {
5271 UriPermissionOwner owner = new UriPermissionOwner(this, name);
5272 return owner.getExternalTokenLocked();
5273 }
5274 }
5275
5276 @Override
5277 public void grantUriPermissionFromOwner(IBinder token, int fromUid, String targetPkg,
5278 Uri uri, int modeFlags) {
5279 synchronized(this) {
5280 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5281 if (owner == null) {
5282 throw new IllegalArgumentException("Unknown owner: " + token);
5283 }
5284 if (fromUid != Binder.getCallingUid()) {
5285 if (Binder.getCallingUid() != Process.myUid()) {
5286 // Only system code can grant URI permissions on behalf
5287 // of other users.
5288 throw new SecurityException("nice try");
5289 }
5290 }
5291 if (targetPkg == null) {
5292 throw new IllegalArgumentException("null target");
5293 }
5294 if (uri == null) {
5295 throw new IllegalArgumentException("null uri");
5296 }
5297
5298 grantUriPermissionLocked(fromUid, targetPkg, uri, modeFlags, owner);
5299 }
5300 }
5301
5302 @Override
5303 public void revokeUriPermissionFromOwner(IBinder token, Uri uri, int mode) {
5304 synchronized(this) {
5305 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5306 if (owner == null) {
5307 throw new IllegalArgumentException("Unknown owner: " + token);
5308 }
5309
5310 if (uri == null) {
5311 owner.removeUriPermissionsLocked(mode);
5312 } else {
5313 owner.removeUriPermissionLocked(uri, mode);
5314 }
5315 }
5316 }
5317
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005318 public void showWaitingForDebugger(IApplicationThread who, boolean waiting) {
5319 synchronized (this) {
5320 ProcessRecord app =
5321 who != null ? getRecordForAppLocked(who) : null;
5322 if (app == null) return;
5323
5324 Message msg = Message.obtain();
5325 msg.what = WAIT_FOR_DEBUGGER_MSG;
5326 msg.obj = app;
5327 msg.arg1 = waiting ? 1 : 0;
5328 mHandler.sendMessage(msg);
5329 }
5330 }
5331
5332 public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07005333 final long homeAppMem = mProcessList.getMemLevel(ProcessList.HOME_APP_ADJ);
5334 final long hiddenAppMem = mProcessList.getMemLevel(ProcessList.HIDDEN_APP_MIN_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005335 outInfo.availMem = Process.getFreeMemory();
Dianne Hackborn7d608422011-08-07 16:24:18 -07005336 outInfo.threshold = homeAppMem;
5337 outInfo.lowMemory = outInfo.availMem < (homeAppMem + ((hiddenAppMem-homeAppMem)/2));
5338 outInfo.hiddenAppThreshold = hiddenAppMem;
5339 outInfo.secondaryServerThreshold = mProcessList.getMemLevel(
Dianne Hackborne02c88a2011-10-28 13:58:15 -07005340 ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07005341 outInfo.visibleAppThreshold = mProcessList.getMemLevel(
5342 ProcessList.VISIBLE_APP_ADJ);
5343 outInfo.foregroundAppThreshold = mProcessList.getMemLevel(
5344 ProcessList.FOREGROUND_APP_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005345 }
5346
5347 // =========================================================
5348 // TASK MANAGEMENT
5349 // =========================================================
5350
5351 public List getTasks(int maxNum, int flags,
5352 IThumbnailReceiver receiver) {
5353 ArrayList list = new ArrayList();
5354
5355 PendingThumbnailsRecord pending = null;
5356 IApplicationThread topThumbnail = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005357 ActivityRecord topRecord = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005358
5359 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005360 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005361 TAG, "getTasks: max=" + maxNum + ", flags=" + flags
5362 + ", receiver=" + receiver);
5363
5364 if (checkCallingPermission(android.Manifest.permission.GET_TASKS)
5365 != PackageManager.PERMISSION_GRANTED) {
5366 if (receiver != null) {
5367 // If the caller wants to wait for pending thumbnails,
5368 // it ain't gonna get them.
5369 try {
5370 receiver.finished();
5371 } catch (RemoteException ex) {
5372 }
5373 }
5374 String msg = "Permission Denial: getTasks() from pid="
5375 + Binder.getCallingPid()
5376 + ", uid=" + Binder.getCallingUid()
5377 + " requires " + android.Manifest.permission.GET_TASKS;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005378 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005379 throw new SecurityException(msg);
5380 }
5381
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005382 int pos = mMainStack.mHistory.size()-1;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005383 ActivityRecord next =
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005384 pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005385 ActivityRecord top = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005386 TaskRecord curTask = null;
5387 int numActivities = 0;
5388 int numRunning = 0;
5389 while (pos >= 0 && maxNum > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005390 final ActivityRecord r = next;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005391 pos--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005392 next = pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005393
5394 // Initialize state for next task if needed.
5395 if (top == null ||
5396 (top.state == ActivityState.INITIALIZING
5397 && top.task == r.task)) {
5398 top = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005399 curTask = r.task;
5400 numActivities = numRunning = 0;
5401 }
5402
5403 // Add 'r' into the current task.
5404 numActivities++;
5405 if (r.app != null && r.app.thread != null) {
5406 numRunning++;
5407 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005408
Joe Onorato8a9b2202010-02-26 18:56:32 -08005409 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005410 TAG, r.intent.getComponent().flattenToShortString()
5411 + ": task=" + r.task);
5412
5413 // If the next one is a different task, generate a new
5414 // TaskInfo entry for what we have.
5415 if (next == null || next.task != curTask) {
5416 ActivityManager.RunningTaskInfo ci
5417 = new ActivityManager.RunningTaskInfo();
5418 ci.id = curTask.taskId;
5419 ci.baseActivity = r.intent.getComponent();
5420 ci.topActivity = top.intent.getComponent();
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005421 if (top.thumbHolder != null) {
5422 ci.description = top.thumbHolder.lastDescription;
5423 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005424 ci.numActivities = numActivities;
5425 ci.numRunning = numRunning;
5426 //System.out.println(
5427 // "#" + maxNum + ": " + " descr=" + ci.description);
5428 if (ci.thumbnail == null && receiver != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005429 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005430 TAG, "State=" + top.state + "Idle=" + top.idle
5431 + " app=" + top.app
5432 + " thr=" + (top.app != null ? top.app.thread : null));
5433 if (top.state == ActivityState.RESUMED
5434 || top.state == ActivityState.PAUSING) {
5435 if (top.idle && top.app != null
5436 && top.app.thread != null) {
5437 topRecord = top;
5438 topThumbnail = top.app.thread;
5439 } else {
5440 top.thumbnailNeeded = true;
5441 }
5442 }
5443 if (pending == null) {
5444 pending = new PendingThumbnailsRecord(receiver);
5445 }
5446 pending.pendingRecords.add(top);
5447 }
5448 list.add(ci);
5449 maxNum--;
5450 top = null;
5451 }
5452 }
5453
5454 if (pending != null) {
5455 mPendingThumbnails.add(pending);
5456 }
5457 }
5458
Joe Onorato8a9b2202010-02-26 18:56:32 -08005459 if (localLOGV) Slog.v(TAG, "We have pending thumbnails: " + pending);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005460
5461 if (topThumbnail != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005462 if (localLOGV) Slog.v(TAG, "Requesting top thumbnail");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005463 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08005464 topThumbnail.requestThumbnail(topRecord.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005465 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005466 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005467 sendPendingThumbnail(null, topRecord.appToken, null, null, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005468 }
5469 }
5470
5471 if (pending == null && receiver != null) {
5472 // In this case all thumbnails were available and the client
5473 // is being asked to be told when the remaining ones come in...
5474 // which is unusually, since the top-most currently running
5475 // activity should never have a canned thumbnail! Oh well.
5476 try {
5477 receiver.finished();
5478 } catch (RemoteException ex) {
5479 }
5480 }
5481
5482 return list;
5483 }
5484
5485 public List<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum,
5486 int flags) {
Amith Yamasani742a6712011-05-04 14:49:28 -07005487 final int callingUid = Binder.getCallingUid();
5488 // If it's the system uid asking, then use the current user id.
5489 // TODO: Make sure that there aren't any other legitimate calls from the system uid that
5490 // require the entire list.
5491 final int callingUserId = callingUid == Process.SYSTEM_UID
5492 ? mCurrentUserId : UserId.getUserId(callingUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005493 synchronized (this) {
5494 enforceCallingPermission(android.Manifest.permission.GET_TASKS,
5495 "getRecentTasks()");
Dianne Hackborn8238e712012-04-24 11:15:40 -07005496 final boolean detailed = checkCallingPermission(
5497 android.Manifest.permission.GET_DETAILED_TASKS)
5498 == PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005499
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005500 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005501
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005502 final int N = mRecentTasks.size();
5503 ArrayList<ActivityManager.RecentTaskInfo> res
5504 = new ArrayList<ActivityManager.RecentTaskInfo>(
5505 maxNum < N ? maxNum : N);
5506 for (int i=0; i<N && maxNum > 0; i++) {
5507 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005508 // Only add calling user's recent tasks
5509 if (tr.userId != callingUserId) continue;
Dianne Hackborn905577f2011-09-07 18:31:28 -07005510 // Return the entry if desired by the caller. We always return
5511 // the first entry, because callers always expect this to be the
Amith Yamasani742a6712011-05-04 14:49:28 -07005512 // foreground app. We may filter others if the caller has
Dianne Hackborn905577f2011-09-07 18:31:28 -07005513 // not supplied RECENT_WITH_EXCLUDED and there is some reason
5514 // we should exclude the entry.
Amith Yamasani742a6712011-05-04 14:49:28 -07005515
Dianne Hackborn905577f2011-09-07 18:31:28 -07005516 if (i == 0
5517 || ((flags&ActivityManager.RECENT_WITH_EXCLUDED) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005518 || (tr.intent == null)
5519 || ((tr.intent.getFlags()
5520 &Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) == 0)) {
5521 ActivityManager.RecentTaskInfo rti
5522 = new ActivityManager.RecentTaskInfo();
5523 rti.id = tr.numActivities > 0 ? tr.taskId : -1;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005524 rti.persistentId = tr.taskId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005525 rti.baseIntent = new Intent(
5526 tr.intent != null ? tr.intent : tr.affinityIntent);
Dianne Hackborn8238e712012-04-24 11:15:40 -07005527 if (!detailed) {
5528 rti.baseIntent.replaceExtras((Bundle)null);
5529 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005530 rti.origActivity = tr.origActivity;
Dianne Hackbornd2835932010-12-13 16:28:46 -08005531 rti.description = tr.lastDescription;
5532
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005533 if ((flags&ActivityManager.RECENT_IGNORE_UNAVAILABLE) != 0) {
5534 // Check whether this activity is currently available.
5535 try {
5536 if (rti.origActivity != null) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07005537 if (pm.getActivityInfo(rti.origActivity, 0, callingUserId)
5538 == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005539 continue;
5540 }
5541 } else if (rti.baseIntent != null) {
5542 if (pm.queryIntentActivities(rti.baseIntent,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005543 null, 0, callingUserId) == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005544 continue;
5545 }
5546 }
5547 } catch (RemoteException e) {
5548 // Will never happen.
5549 }
5550 }
5551
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005552 res.add(rti);
5553 maxNum--;
5554 }
5555 }
5556 return res;
5557 }
5558 }
5559
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005560 private TaskRecord taskForIdLocked(int id) {
5561 final int N = mRecentTasks.size();
5562 for (int i=0; i<N; i++) {
5563 TaskRecord tr = mRecentTasks.get(i);
5564 if (tr.taskId == id) {
5565 return tr;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005566 }
5567 }
5568 return null;
5569 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005570
5571 public ActivityManager.TaskThumbnails getTaskThumbnails(int id) {
5572 synchronized (this) {
5573 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
5574 "getTaskThumbnails()");
5575 TaskRecord tr = taskForIdLocked(id);
5576 if (tr != null) {
5577 return mMainStack.getTaskThumbnailsLocked(tr);
5578 }
5579 }
5580 return null;
5581 }
5582
5583 public boolean removeSubTask(int taskId, int subTaskIndex) {
5584 synchronized (this) {
5585 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5586 "removeSubTask()");
5587 long ident = Binder.clearCallingIdentity();
5588 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005589 return mMainStack.removeTaskActivitiesLocked(taskId, subTaskIndex,
5590 true) != null;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005591 } finally {
5592 Binder.restoreCallingIdentity(ident);
5593 }
5594 }
5595 }
5596
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005597 private void cleanUpRemovedTaskLocked(TaskRecord tr, int flags) {
5598 final boolean killProcesses = (flags&ActivityManager.REMOVE_TASK_KILL_PROCESS) != 0;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005599 Intent baseIntent = new Intent(
5600 tr.intent != null ? tr.intent : tr.affinityIntent);
5601 ComponentName component = baseIntent.getComponent();
5602 if (component == null) {
5603 Slog.w(TAG, "Now component for base intent of task: " + tr);
5604 return;
5605 }
5606
5607 // Find any running services associated with this app.
5608 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005609 for (ServiceRecord sr : mServiceMap.getAllServices(tr.userId)) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005610 if (sr.packageName.equals(component.getPackageName())) {
5611 services.add(sr);
5612 }
5613 }
5614
5615 // Take care of any running services associated with the app.
5616 for (int i=0; i<services.size(); i++) {
5617 ServiceRecord sr = services.get(i);
5618 if (sr.startRequested) {
5619 if ((sr.serviceInfo.flags&ServiceInfo.FLAG_STOP_WITH_TASK) != 0) {
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005620 Slog.i(TAG, "Stopping service " + sr.shortName + ": remove task");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005621 stopServiceLocked(sr);
5622 } else {
5623 sr.pendingStarts.add(new ServiceRecord.StartItem(sr, true,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005624 sr.makeNextStartId(), baseIntent, null));
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005625 if (sr.app != null && sr.app.thread != null) {
5626 sendServiceArgsLocked(sr, false);
5627 }
5628 }
5629 }
5630 }
5631
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005632 if (killProcesses) {
5633 // Find any running processes associated with this app.
5634 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
5635 SparseArray<ProcessRecord> appProcs
5636 = mProcessNames.getMap().get(component.getPackageName());
5637 if (appProcs != null) {
5638 for (int i=0; i<appProcs.size(); i++) {
5639 procs.add(appProcs.valueAt(i));
5640 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005641 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005642
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005643 // Kill the running processes.
5644 for (int i=0; i<procs.size(); i++) {
5645 ProcessRecord pr = procs.get(i);
5646 if (pr.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
5647 Slog.i(TAG, "Killing " + pr.toShortString() + ": remove task");
5648 EventLog.writeEvent(EventLogTags.AM_KILL, pr.pid,
5649 pr.processName, pr.setAdj, "remove task");
5650 Process.killProcessQuiet(pr.pid);
5651 } else {
5652 pr.waitingToKill = "remove task";
5653 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005654 }
5655 }
5656 }
5657
5658 public boolean removeTask(int taskId, int flags) {
5659 synchronized (this) {
5660 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5661 "removeTask()");
5662 long ident = Binder.clearCallingIdentity();
5663 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005664 ActivityRecord r = mMainStack.removeTaskActivitiesLocked(taskId, -1,
5665 false);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005666 if (r != null) {
5667 mRecentTasks.remove(r.task);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005668 cleanUpRemovedTaskLocked(r.task, flags);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005669 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005670 } else {
5671 TaskRecord tr = null;
5672 int i=0;
5673 while (i < mRecentTasks.size()) {
5674 TaskRecord t = mRecentTasks.get(i);
5675 if (t.taskId == taskId) {
5676 tr = t;
5677 break;
5678 }
5679 i++;
5680 }
5681 if (tr != null) {
5682 if (tr.numActivities <= 0) {
5683 // Caller is just removing a recent task that is
5684 // not actively running. That is easy!
5685 mRecentTasks.remove(i);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005686 cleanUpRemovedTaskLocked(tr, flags);
5687 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005688 } else {
5689 Slog.w(TAG, "removeTask: task " + taskId
5690 + " does not have activities to remove, "
5691 + " but numActivities=" + tr.numActivities
5692 + ": " + tr);
5693 }
5694 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005695 }
5696 } finally {
5697 Binder.restoreCallingIdentity(ident);
5698 }
5699 }
5700 return false;
5701 }
Dianne Hackbornd94df452011-02-16 18:53:31 -08005702
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005703 private final int findAffinityTaskTopLocked(int startIndex, String affinity) {
5704 int j;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005705 TaskRecord startTask = ((ActivityRecord)mMainStack.mHistory.get(startIndex)).task;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005706 TaskRecord jt = startTask;
5707
5708 // First look backwards
5709 for (j=startIndex-1; j>=0; j--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005710 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005711 if (r.task != jt) {
5712 jt = r.task;
5713 if (affinity.equals(jt.affinity)) {
5714 return j;
5715 }
5716 }
5717 }
5718
5719 // Now look forwards
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005720 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005721 jt = startTask;
5722 for (j=startIndex+1; j<N; j++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005723 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005724 if (r.task != jt) {
5725 if (affinity.equals(jt.affinity)) {
5726 return j;
5727 }
5728 jt = r.task;
5729 }
5730 }
5731
5732 // Might it be at the top?
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005733 if (affinity.equals(((ActivityRecord)mMainStack.mHistory.get(N-1)).task.affinity)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005734 return N-1;
5735 }
5736
5737 return -1;
5738 }
5739
5740 /**
Dianne Hackbornb06ea702009-07-13 13:07:51 -07005741 * TODO: Add mController hook
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005742 */
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005743 public void moveTaskToFront(int task, int flags, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005744 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5745 "moveTaskToFront()");
5746
5747 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005748 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5749 Binder.getCallingUid(), "Task to front")) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005750 ActivityOptions.abort(options);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005751 return;
5752 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005753 final long origId = Binder.clearCallingIdentity();
5754 try {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005755 TaskRecord tr = taskForIdLocked(task);
5756 if (tr != null) {
5757 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5758 mMainStack.mUserLeaving = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005759 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005760 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5761 // Caller wants the home activity moved with it. To accomplish this,
5762 // we'll just move the home task to the top first.
5763 mMainStack.moveHomeToFrontLocked();
5764 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005765 mMainStack.moveTaskToFrontLocked(tr, null, options);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005766 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005767 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005768 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
5769 ActivityRecord hr = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005770 if (hr.task.taskId == task) {
Dianne Hackbornd94df452011-02-16 18:53:31 -08005771 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5772 mMainStack.mUserLeaving = true;
5773 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005774 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5775 // Caller wants the home activity moved with it. To accomplish this,
5776 // we'll just move the home task to the top first.
5777 mMainStack.moveHomeToFrontLocked();
5778 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005779 mMainStack.moveTaskToFrontLocked(hr.task, null, options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005780 return;
5781 }
5782 }
5783 } finally {
5784 Binder.restoreCallingIdentity(origId);
5785 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005786 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005787 }
5788 }
5789
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005790 public void moveTaskToBack(int task) {
5791 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5792 "moveTaskToBack()");
5793
5794 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005795 if (mMainStack.mResumedActivity != null
5796 && mMainStack.mResumedActivity.task.taskId == task) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005797 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5798 Binder.getCallingUid(), "Task to back")) {
5799 return;
5800 }
5801 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005802 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005803 mMainStack.moveTaskToBackLocked(task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005804 Binder.restoreCallingIdentity(origId);
5805 }
5806 }
5807
5808 /**
5809 * Moves an activity, and all of the other activities within the same task, to the bottom
5810 * of the history stack. The activity's order within the task is unchanged.
5811 *
5812 * @param token A reference to the activity we wish to move
5813 * @param nonRoot If false then this only works if the activity is the root
5814 * of a task; if true it will work for any activity in a task.
5815 * @return Returns true if the move completed, false if not.
5816 */
5817 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005818 enforceNotIsolatedCaller("moveActivityTaskToBack");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005819 synchronized(this) {
5820 final long origId = Binder.clearCallingIdentity();
5821 int taskId = getTaskForActivityLocked(token, !nonRoot);
5822 if (taskId >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005823 return mMainStack.moveTaskToBackLocked(taskId, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005824 }
5825 Binder.restoreCallingIdentity(origId);
5826 }
5827 return false;
5828 }
5829
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005830 public void moveTaskBackwards(int task) {
5831 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5832 "moveTaskBackwards()");
5833
5834 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005835 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5836 Binder.getCallingUid(), "Task backwards")) {
5837 return;
5838 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005839 final long origId = Binder.clearCallingIdentity();
5840 moveTaskBackwardsLocked(task);
5841 Binder.restoreCallingIdentity(origId);
5842 }
5843 }
5844
5845 private final void moveTaskBackwardsLocked(int task) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005846 Slog.e(TAG, "moveTaskBackwards not yet implemented!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005847 }
5848
5849 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
5850 synchronized(this) {
5851 return getTaskForActivityLocked(token, onlyRoot);
5852 }
5853 }
5854
5855 int getTaskForActivityLocked(IBinder token, boolean onlyRoot) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005856 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005857 TaskRecord lastTask = null;
5858 for (int i=0; i<N; i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005859 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005860 if (r.appToken == token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005861 if (!onlyRoot || lastTask != r.task) {
5862 return r.task.taskId;
5863 }
5864 return -1;
5865 }
5866 lastTask = r.task;
5867 }
5868
5869 return -1;
5870 }
5871
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005872 // =========================================================
5873 // THUMBNAILS
5874 // =========================================================
5875
5876 public void reportThumbnail(IBinder token,
5877 Bitmap thumbnail, CharSequence description) {
5878 //System.out.println("Report thumbnail for " + token + ": " + thumbnail);
5879 final long origId = Binder.clearCallingIdentity();
5880 sendPendingThumbnail(null, token, thumbnail, description, true);
5881 Binder.restoreCallingIdentity(origId);
5882 }
5883
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005884 final void sendPendingThumbnail(ActivityRecord r, IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005885 Bitmap thumbnail, CharSequence description, boolean always) {
5886 TaskRecord task = null;
5887 ArrayList receivers = null;
5888
5889 //System.out.println("Send pending thumbnail: " + r);
5890
5891 synchronized(this) {
5892 if (r == null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07005893 r = mMainStack.isInStackLocked(token);
5894 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005895 return;
5896 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005897 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005898 if (thumbnail == null && r.thumbHolder != null) {
5899 thumbnail = r.thumbHolder.lastThumbnail;
5900 description = r.thumbHolder.lastDescription;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005901 }
5902 if (thumbnail == null && !always) {
5903 // If there is no thumbnail, and this entry is not actually
5904 // going away, then abort for now and pick up the next
5905 // thumbnail we get.
5906 return;
5907 }
5908 task = r.task;
5909
5910 int N = mPendingThumbnails.size();
5911 int i=0;
5912 while (i<N) {
5913 PendingThumbnailsRecord pr =
5914 (PendingThumbnailsRecord)mPendingThumbnails.get(i);
5915 //System.out.println("Looking in " + pr.pendingRecords);
5916 if (pr.pendingRecords.remove(r)) {
5917 if (receivers == null) {
5918 receivers = new ArrayList();
5919 }
5920 receivers.add(pr);
5921 if (pr.pendingRecords.size() == 0) {
5922 pr.finished = true;
5923 mPendingThumbnails.remove(i);
5924 N--;
5925 continue;
5926 }
5927 }
5928 i++;
5929 }
5930 }
5931
5932 if (receivers != null) {
5933 final int N = receivers.size();
5934 for (int i=0; i<N; i++) {
5935 try {
5936 PendingThumbnailsRecord pr =
5937 (PendingThumbnailsRecord)receivers.get(i);
5938 pr.receiver.newThumbnail(
5939 task != null ? task.taskId : -1, thumbnail, description);
5940 if (pr.finished) {
5941 pr.receiver.finished();
5942 }
5943 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005944 Slog.w(TAG, "Exception thrown when sending thumbnail", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005945 }
5946 }
5947 }
5948 }
5949
5950 // =========================================================
5951 // CONTENT PROVIDERS
5952 // =========================================================
5953
Jeff Brown10e89712011-07-08 18:52:57 -07005954 private final List<ProviderInfo> generateApplicationProvidersLocked(ProcessRecord app) {
5955 List<ProviderInfo> providers = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005956 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005957 providers = AppGlobals.getPackageManager().
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005958 queryContentProviders(app.processName, app.uid,
Dianne Hackborn1655be42009-05-08 14:29:01 -07005959 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005960 } catch (RemoteException ex) {
5961 }
Amith Yamasani742a6712011-05-04 14:49:28 -07005962 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005963 Slog.v(TAG_MU, "generateApplicationProvidersLocked, app.info.uid = " + app.uid);
5964 int userId = app.userId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005965 if (providers != null) {
5966 final int N = providers.size();
5967 for (int i=0; i<N; i++) {
5968 ProviderInfo cpi =
5969 (ProviderInfo)providers.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005970
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07005971 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07005972 ContentProviderRecord cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005973 if (cpr == null) {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08005974 cpr = new ContentProviderRecord(this, cpi, app.info, comp);
Amith Yamasani742a6712011-05-04 14:49:28 -07005975 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005976 }
Amith Yamasani742a6712011-05-04 14:49:28 -07005977 if (DEBUG_MU)
5978 Slog.v(TAG_MU, "generateApplicationProvidersLocked, cpi.uid = " + cpr.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005979 app.pubProviders.put(cpi.name, cpr);
5980 app.addPackage(cpi.applicationInfo.packageName);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07005981 ensurePackageDexOpt(cpi.applicationInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005982 }
5983 }
5984 return providers;
5985 }
5986
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005987 /**
5988 * Check if {@link ProcessRecord} has a possible chance at accessing the
5989 * given {@link ProviderInfo}. Final permission checking is always done
5990 * in {@link ContentProvider}.
5991 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005992 private final String checkContentProviderPermissionLocked(
Dianne Hackbornb424b632010-08-18 15:59:05 -07005993 ProviderInfo cpi, ProcessRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005994 final int callingPid = (r != null) ? r.pid : Binder.getCallingPid();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005995 final int callingUid = (r != null) ? r.uid : Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005996 if (checkComponentPermission(cpi.readPermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005997 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005998 == PackageManager.PERMISSION_GRANTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005999 return null;
6000 }
6001 if (checkComponentPermission(cpi.writePermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006002 cpi.applicationInfo.uid, cpi.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006003 == PackageManager.PERMISSION_GRANTED) {
6004 return null;
6005 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006006
6007 PathPermission[] pps = cpi.pathPermissions;
6008 if (pps != null) {
6009 int i = pps.length;
6010 while (i > 0) {
6011 i--;
6012 PathPermission pp = pps[i];
6013 if (checkComponentPermission(pp.getReadPermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006014 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006015 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006016 return null;
6017 }
6018 if (checkComponentPermission(pp.getWritePermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006019 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006020 == PackageManager.PERMISSION_GRANTED) {
6021 return null;
6022 }
6023 }
6024 }
6025
Dianne Hackbornb424b632010-08-18 15:59:05 -07006026 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(callingUid);
6027 if (perms != null) {
6028 for (Map.Entry<Uri, UriPermission> uri : perms.entrySet()) {
6029 if (uri.getKey().getAuthority().equals(cpi.authority)) {
6030 return null;
6031 }
6032 }
6033 }
6034
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006035 String msg;
6036 if (!cpi.exported) {
6037 msg = "Permission Denial: opening provider " + cpi.name
6038 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6039 + ", uid=" + callingUid + ") that is not exported from uid "
6040 + cpi.applicationInfo.uid;
6041 } else {
6042 msg = "Permission Denial: opening provider " + cpi.name
6043 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6044 + ", uid=" + callingUid + ") requires "
6045 + cpi.readPermission + " or " + cpi.writePermission;
6046 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08006047 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006048 return msg;
6049 }
6050
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006051 boolean incProviderCount(ProcessRecord r, final ContentProviderRecord cpr,
6052 IBinder externalProcessToken) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006053 if (r != null) {
6054 Integer cnt = r.conProviders.get(cpr);
6055 if (DEBUG_PROVIDER) Slog.v(TAG,
6056 "Adding provider requested by "
6057 + r.processName + " from process "
6058 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
6059 + " cnt=" + (cnt == null ? 1 : cnt));
6060 if (cnt == null) {
6061 cpr.clients.add(r);
6062 r.conProviders.put(cpr, new Integer(1));
6063 return true;
6064 } else {
6065 r.conProviders.put(cpr, new Integer(cnt.intValue()+1));
6066 }
6067 } else {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006068 cpr.addExternalProcessHandleLocked(externalProcessToken);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006069 }
6070 return false;
6071 }
6072
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006073 boolean decProviderCount(ProcessRecord r, final ContentProviderRecord cpr,
6074 IBinder externalProcessToken) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006075 if (r != null) {
6076 Integer cnt = r.conProviders.get(cpr);
6077 if (DEBUG_PROVIDER) Slog.v(TAG,
6078 "Removing provider requested by "
6079 + r.processName + " from process "
6080 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
6081 + " cnt=" + cnt);
6082 if (cnt == null || cnt.intValue() <= 1) {
6083 cpr.clients.remove(r);
6084 r.conProviders.remove(cpr);
6085 return true;
6086 } else {
6087 r.conProviders.put(cpr, new Integer(cnt.intValue()-1));
6088 }
6089 } else {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006090 cpr.removeExternalProcessHandleLocked(externalProcessToken);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006091 }
6092 return false;
6093 }
6094
Amith Yamasani742a6712011-05-04 14:49:28 -07006095 private final ContentProviderHolder getContentProviderImpl(IApplicationThread caller,
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006096 String name, IBinder token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006097 ContentProviderRecord cpr;
6098 ProviderInfo cpi = null;
6099
6100 synchronized(this) {
6101 ProcessRecord r = null;
6102 if (caller != null) {
6103 r = getRecordForAppLocked(caller);
6104 if (r == null) {
6105 throw new SecurityException(
6106 "Unable to find app for caller " + caller
6107 + " (pid=" + Binder.getCallingPid()
6108 + ") when getting content provider " + name);
6109 }
6110 }
6111
6112 // First check if this content provider has been published...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006113 int userId = UserId.getUserId(r != null ? r.uid : Binder.getCallingUid());
Amith Yamasani742a6712011-05-04 14:49:28 -07006114 cpr = mProviderMap.getProviderByName(name, userId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006115 boolean providerRunning = cpr != null;
6116 if (providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006117 cpi = cpr.info;
Dianne Hackbornb424b632010-08-18 15:59:05 -07006118 String msg;
6119 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6120 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006121 }
6122
6123 if (r != null && cpr.canRunHere(r)) {
6124 // This provider has been published or is in the process
6125 // of being published... but it is also allowed to run
6126 // in the caller's process, so don't make a connection
6127 // and just let the caller instantiate its own instance.
6128 if (cpr.provider != null) {
6129 // don't give caller the provider object, it needs
6130 // to make its own.
6131 cpr = new ContentProviderRecord(cpr);
6132 }
6133 return cpr;
6134 }
6135
6136 final long origId = Binder.clearCallingIdentity();
6137
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006138 // In this case the provider instance already exists, so we can
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006139 // return it right away.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006140 final boolean countChanged = incProviderCount(r, cpr, token);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006141 if (countChanged) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006142 if (cpr.proc != null && r.setAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006143 // If this is a perceptible app accessing the provider,
Dianne Hackborn906497c2010-05-10 15:57:38 -07006144 // make sure to count it as being accessed and thus
6145 // back up on the LRU list. This is good because
6146 // content providers are often expensive to start.
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006147 updateLruProcessLocked(cpr.proc, false, true);
Dianne Hackborn906497c2010-05-10 15:57:38 -07006148 }
Dianne Hackborn6f86c0e2010-05-11 14:20:52 -07006149 }
6150
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006151 if (cpr.proc != null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006152 if (false) {
6153 if (cpr.name.flattenToShortString().equals(
6154 "com.android.providers.calendar/.CalendarProvider2")) {
6155 Slog.v(TAG, "****************** KILLING "
6156 + cpr.name.flattenToShortString());
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006157 Process.killProcess(cpr.proc.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006158 }
6159 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006160 boolean success = updateOomAdjLocked(cpr.proc);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006161 if (DEBUG_PROVIDER) Slog.i(TAG, "Adjust success: " + success);
6162 // NOTE: there is still a race here where a signal could be
6163 // pending on the process even though we managed to update its
6164 // adj level. Not sure what to do about this, but at least
6165 // the race is now smaller.
6166 if (!success) {
6167 // Uh oh... it looks like the provider's process
6168 // has been killed on us. We need to wait for a new
6169 // process to be started, and make sure its death
6170 // doesn't kill our process.
6171 Slog.i(TAG,
6172 "Existing provider " + cpr.name.flattenToShortString()
6173 + " is crashing; detaching " + r);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006174 boolean lastRef = decProviderCount(r, cpr, token);
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006175 appDiedLocked(cpr.proc, cpr.proc.pid, cpr.proc.thread);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006176 if (!lastRef) {
6177 // This wasn't the last ref our process had on
6178 // the provider... we have now been killed, bail.
6179 return null;
6180 }
6181 providerRunning = false;
6182 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006183 }
6184
6185 Binder.restoreCallingIdentity(origId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006186 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006187
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006188 if (!providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006189 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006190 cpi = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07006191 resolveContentProvider(name,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006192 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006193 } catch (RemoteException ex) {
6194 }
6195 if (cpi == null) {
6196 return null;
6197 }
Amith Yamasania4a54e22012-04-16 15:44:19 -07006198 if (isSingleton(cpi.processName, cpi.applicationInfo)) {
6199 userId = 0;
6200 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006201 cpi.applicationInfo = getAppInfoForUser(cpi.applicationInfo, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07006202
Dianne Hackbornb424b632010-08-18 15:59:05 -07006203 String msg;
6204 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6205 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006206 }
6207
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07006208 if (!mProcessesReady && !mDidUpdate && !mWaitingUpdate
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006209 && !cpi.processName.equals("system")) {
6210 // If this content provider does not run in the system
6211 // process, and the system is not yet ready to run other
6212 // processes, then fail fast instead of hanging.
6213 throw new IllegalArgumentException(
6214 "Attempt to launch content provider before system ready");
6215 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006216
6217 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani483f3b02012-03-13 16:08:00 -07006218 cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006219 final boolean firstClass = cpr == null;
6220 if (firstClass) {
6221 try {
6222 ApplicationInfo ai =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006223 AppGlobals.getPackageManager().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006224 getApplicationInfo(
6225 cpi.applicationInfo.packageName,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006226 STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006227 if (ai == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006228 Slog.w(TAG, "No package info for content provider "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006229 + cpi.name);
6230 return null;
6231 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006232 ai = getAppInfoForUser(ai, userId);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006233 cpr = new ContentProviderRecord(this, cpi, ai, comp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006234 } catch (RemoteException ex) {
6235 // pm is in same process, this will never happen.
6236 }
6237 }
6238
6239 if (r != null && cpr.canRunHere(r)) {
6240 // If this is a multiprocess provider, then just return its
6241 // info and allow the caller to instantiate it. Only do
6242 // this if the provider is the same user as the caller's
6243 // process, or can run as root (so can be in any process).
6244 return cpr;
6245 }
6246
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006247 if (DEBUG_PROVIDER) {
6248 RuntimeException e = new RuntimeException("here");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006249 Slog.w(TAG, "LAUNCHING REMOTE PROVIDER (myuid " + r.uid
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006250 + " pruid " + cpr.appInfo.uid + "): " + cpr.info.name, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006251 }
6252
6253 // This is single process, and our app is now connecting to it.
6254 // See if we are already in the process of launching this
6255 // provider.
6256 final int N = mLaunchingProviders.size();
6257 int i;
6258 for (i=0; i<N; i++) {
6259 if (mLaunchingProviders.get(i) == cpr) {
6260 break;
6261 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006262 }
6263
6264 // If the provider is not already being launched, then get it
6265 // started.
6266 if (i >= N) {
6267 final long origId = Binder.clearCallingIdentity();
Dianne Hackborne7f97212011-02-24 14:40:20 -08006268
6269 try {
6270 // Content provider is now in use, its package can't be stopped.
6271 try {
6272 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07006273 cpr.appInfo.packageName, false, userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006274 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006275 } catch (IllegalArgumentException e) {
6276 Slog.w(TAG, "Failed trying to unstop package "
6277 + cpr.appInfo.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006278 }
6279
6280 ProcessRecord proc = startProcessLocked(cpi.processName,
6281 cpr.appInfo, false, 0, "content provider",
6282 new ComponentName(cpi.applicationInfo.packageName,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006283 cpi.name), false, false);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006284 if (proc == null) {
6285 Slog.w(TAG, "Unable to launch app "
6286 + cpi.applicationInfo.packageName + "/"
6287 + cpi.applicationInfo.uid + " for provider "
6288 + name + ": process is bad");
6289 return null;
6290 }
6291 cpr.launchingApp = proc;
6292 mLaunchingProviders.add(cpr);
6293 } finally {
6294 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006295 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006296 }
6297
6298 // Make sure the provider is published (the same provider class
6299 // may be published under multiple names).
6300 if (firstClass) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006301 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006302 }
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006303
Amith Yamasani742a6712011-05-04 14:49:28 -07006304 mProviderMap.putProviderByName(name, cpr);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006305 incProviderCount(r, cpr, token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006306 }
6307 }
6308
6309 // Wait for the provider to be published...
6310 synchronized (cpr) {
6311 while (cpr.provider == null) {
6312 if (cpr.launchingApp == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006313 Slog.w(TAG, "Unable to launch app "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006314 + cpi.applicationInfo.packageName + "/"
6315 + cpi.applicationInfo.uid + " for provider "
6316 + name + ": launching app became null");
Doug Zongker2bec3d42009-12-04 12:52:44 -08006317 EventLog.writeEvent(EventLogTags.AM_PROVIDER_LOST_PROCESS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006318 cpi.applicationInfo.packageName,
6319 cpi.applicationInfo.uid, name);
6320 return null;
6321 }
6322 try {
Amith Yamasani742a6712011-05-04 14:49:28 -07006323 if (DEBUG_MU) {
6324 Slog.v(TAG_MU, "Waiting to start provider " + cpr + " launchingApp="
6325 + cpr.launchingApp);
6326 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006327 cpr.wait();
6328 } catch (InterruptedException ex) {
6329 }
6330 }
6331 }
6332 return cpr;
6333 }
6334
6335 public final ContentProviderHolder getContentProvider(
6336 IApplicationThread caller, String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006337 enforceNotIsolatedCaller("getContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006338 if (caller == null) {
6339 String msg = "null IApplicationThread when getting content provider "
6340 + name;
Joe Onorato8a9b2202010-02-26 18:56:32 -08006341 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006342 throw new SecurityException(msg);
6343 }
6344
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006345 return getContentProviderImpl(caller, name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006346 }
6347
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006348 public ContentProviderHolder getContentProviderExternal(String name, IBinder token) {
6349 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6350 "Do not have permission in call getContentProviderExternal()");
6351 return getContentProviderExternalUnchecked(name, token);
6352 }
6353
6354 private ContentProviderHolder getContentProviderExternalUnchecked(String name,IBinder token) {
6355 return getContentProviderImpl(null, name, token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006356 }
6357
6358 /**
6359 * Drop a content provider from a ProcessRecord's bookkeeping
6360 * @param cpr
6361 */
6362 public void removeContentProvider(IApplicationThread caller, String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006363 enforceNotIsolatedCaller("removeContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006364 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006365 int userId = UserId.getUserId(Binder.getCallingUid());
6366 ContentProviderRecord cpr = mProviderMap.getProviderByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006367 if(cpr == null) {
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006368 // remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006369 if (DEBUG_PROVIDER) Slog.v(TAG, name +
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006370 " provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006371 return;
6372 }
6373 final ProcessRecord r = getRecordForAppLocked(caller);
6374 if (r == null) {
6375 throw new SecurityException(
6376 "Unable to find app for caller " + caller +
6377 " when removing content provider " + name);
6378 }
6379 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006380 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006381 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp, userId);
6382 if (DEBUG_PROVIDER) Slog.v(TAG, "Removing provider requested by "
6383 + r.info.processName + " from process "
6384 + localCpr.appInfo.processName);
6385 if (localCpr.launchingApp == r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006386 //should not happen. taken care of as a local provider
Joe Onorato8a9b2202010-02-26 18:56:32 -08006387 Slog.w(TAG, "removeContentProvider called on local provider: "
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006388 + cpr.info.name + " in process " + r.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006389 return;
6390 } else {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006391 if (decProviderCount(r, localCpr, null)) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006392 updateOomAdjLocked();
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07006393 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006394 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006395 }
6396 }
6397
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006398 public void removeContentProviderExternal(String name, IBinder token) {
6399 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6400 "Do not have permission in call removeContentProviderExternal()");
6401 removeContentProviderExternalUnchecked(name, token);
6402 }
6403
6404 private void removeContentProviderExternalUnchecked(String name, IBinder token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006405 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006406 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
6407 Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006408 if(cpr == null) {
6409 //remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006410 if(localLOGV) Slog.v(TAG, name+" content provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006411 return;
6412 }
6413
6414 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006415 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006416 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp,
6417 Binder.getOrigCallingUser());
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006418 if (localCpr.hasExternalProcessHandles()) {
6419 if (localCpr.removeExternalProcessHandleLocked(token)) {
6420 updateOomAdjLocked();
6421 } else {
6422 Slog.e(TAG, "Attmpt to remove content provider " + localCpr
6423 + " with no external reference for token: "
6424 + token + ".");
6425 }
6426 } else {
6427 Slog.e(TAG, "Attmpt to remove content provider: " + localCpr
6428 + " with no external references.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006429 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006430 }
6431 }
6432
6433 public final void publishContentProviders(IApplicationThread caller,
6434 List<ContentProviderHolder> providers) {
6435 if (providers == null) {
6436 return;
6437 }
6438
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006439 enforceNotIsolatedCaller("publishContentProviders");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006440 synchronized(this) {
6441 final ProcessRecord r = getRecordForAppLocked(caller);
Amith Yamasani742a6712011-05-04 14:49:28 -07006442 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006443 Slog.v(TAG_MU, "ProcessRecord uid = " + r.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006444 if (r == null) {
6445 throw new SecurityException(
6446 "Unable to find app for caller " + caller
6447 + " (pid=" + Binder.getCallingPid()
6448 + ") when publishing content providers");
6449 }
6450
6451 final long origId = Binder.clearCallingIdentity();
6452
6453 final int N = providers.size();
6454 for (int i=0; i<N; i++) {
6455 ContentProviderHolder src = providers.get(i);
6456 if (src == null || src.info == null || src.provider == null) {
6457 continue;
6458 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07006459 ContentProviderRecord dst = r.pubProviders.get(src.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006460 if (DEBUG_MU)
6461 Slog.v(TAG_MU, "ContentProviderRecord uid = " + dst.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006462 if (dst != null) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006463 ComponentName comp = new ComponentName(dst.info.packageName, dst.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006464 mProviderMap.putProviderByClass(comp, dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006465 String names[] = dst.info.authority.split(";");
6466 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006467 mProviderMap.putProviderByName(names[j], dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006468 }
6469
6470 int NL = mLaunchingProviders.size();
6471 int j;
6472 for (j=0; j<NL; j++) {
6473 if (mLaunchingProviders.get(j) == dst) {
6474 mLaunchingProviders.remove(j);
6475 j--;
6476 NL--;
6477 }
6478 }
6479 synchronized (dst) {
6480 dst.provider = src.provider;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006481 dst.proc = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006482 dst.notifyAll();
6483 }
6484 updateOomAdjLocked(r);
6485 }
6486 }
6487
6488 Binder.restoreCallingIdentity(origId);
6489 }
6490 }
6491
6492 public static final void installSystemProviders() {
Jeff Brown10e89712011-07-08 18:52:57 -07006493 List<ProviderInfo> providers;
Josh Bartel2ecce342010-02-25 10:55:48 -06006494 synchronized (mSelf) {
6495 ProcessRecord app = mSelf.mProcessNames.get("system", Process.SYSTEM_UID);
6496 providers = mSelf.generateApplicationProvidersLocked(app);
Dianne Hackborn5c83a5f2010-03-12 16:46:46 -08006497 if (providers != null) {
6498 for (int i=providers.size()-1; i>=0; i--) {
6499 ProviderInfo pi = (ProviderInfo)providers.get(i);
6500 if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6501 Slog.w(TAG, "Not installing system proc provider " + pi.name
6502 + ": not system .apk");
6503 providers.remove(i);
6504 }
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006505 }
6506 }
6507 }
Josh Bartel2ecce342010-02-25 10:55:48 -06006508 if (providers != null) {
6509 mSystemThread.installSystemProviders(providers);
6510 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08006511
6512 mSelf.mCoreSettingsObserver = new CoreSettingsObserver(mSelf);
Mark Brophyc6350272011-08-05 16:16:39 +01006513
6514 mSelf.mUsageStatsService.monitorPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006515 }
6516
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006517 /**
6518 * Allows app to retrieve the MIME type of a URI without having permission
6519 * to access its content provider.
6520 *
6521 * CTS tests for this functionality can be run with "runtest cts-appsecurity".
6522 *
6523 * Test cases are at cts/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/
6524 * src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java
6525 */
6526 public String getProviderMimeType(Uri uri) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006527 enforceNotIsolatedCaller("getProviderMimeType");
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006528 final String name = uri.getAuthority();
6529 final long ident = Binder.clearCallingIdentity();
6530 ContentProviderHolder holder = null;
6531
6532 try {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006533 holder = getContentProviderExternalUnchecked(name, null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006534 if (holder != null) {
6535 return holder.provider.getType(uri);
6536 }
6537 } catch (RemoteException e) {
6538 Log.w(TAG, "Content provider dead retrieving " + uri, e);
6539 return null;
6540 } finally {
6541 if (holder != null) {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006542 removeContentProviderExternalUnchecked(name, null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006543 }
6544 Binder.restoreCallingIdentity(ident);
6545 }
6546
6547 return null;
6548 }
6549
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006550 // =========================================================
6551 // GLOBAL MANAGEMENT
6552 // =========================================================
6553
6554 final ProcessRecord newProcessRecordLocked(IApplicationThread thread,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006555 ApplicationInfo info, String customProcess, boolean isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006556 String proc = customProcess != null ? customProcess : info.processName;
6557 BatteryStatsImpl.Uid.Proc ps = null;
6558 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006559 int uid = info.uid;
6560 if (isolated) {
6561 int userId = UserId.getUserId(uid);
6562 int stepsLeft = Process.LAST_ISOLATED_UID - Process.FIRST_ISOLATED_UID + 1;
6563 uid = 0;
6564 while (true) {
6565 if (mNextIsolatedProcessUid < Process.FIRST_ISOLATED_UID
6566 || mNextIsolatedProcessUid > Process.LAST_ISOLATED_UID) {
6567 mNextIsolatedProcessUid = Process.FIRST_ISOLATED_UID;
6568 }
6569 uid = UserId.getUid(userId, mNextIsolatedProcessUid);
6570 mNextIsolatedProcessUid++;
6571 if (mIsolatedProcesses.indexOfKey(uid) < 0) {
6572 // No process for this uid, use it.
6573 break;
6574 }
6575 stepsLeft--;
6576 if (stepsLeft <= 0) {
6577 return null;
6578 }
6579 }
6580 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006581 synchronized (stats) {
6582 ps = stats.getProcessStatsLocked(info.uid, proc);
6583 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006584 return new ProcessRecord(ps, thread, info, proc, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006585 }
6586
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006587 final ProcessRecord addAppLocked(ApplicationInfo info, boolean isolated) {
6588 ProcessRecord app;
6589 if (!isolated) {
6590 app = getProcessRecordLocked(info.processName, info.uid);
6591 } else {
6592 app = null;
6593 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006594
6595 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006596 app = newProcessRecordLocked(null, info, null, isolated);
6597 mProcessNames.put(info.processName, app.uid, app);
6598 if (isolated) {
6599 mIsolatedProcesses.put(app.uid, app);
6600 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08006601 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006602 }
6603
Dianne Hackborne7f97212011-02-24 14:40:20 -08006604 // This package really, really can not be stopped.
6605 try {
6606 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07006607 info.packageName, false, UserId.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -08006608 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006609 } catch (IllegalArgumentException e) {
6610 Slog.w(TAG, "Failed trying to unstop package "
6611 + info.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006612 }
6613
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006614 if ((info.flags&(ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT))
6615 == (ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT)) {
6616 app.persistent = true;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07006617 app.maxAdj = ProcessList.PERSISTENT_PROC_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006618 }
6619 if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) {
6620 mPersistentStartingProcesses.add(app);
6621 startProcessLocked(app, "added application", app.processName);
6622 }
6623
6624 return app;
6625 }
6626
6627 public void unhandledBack() {
6628 enforceCallingPermission(android.Manifest.permission.FORCE_BACK,
6629 "unhandledBack()");
6630
6631 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006632 int count = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08006633 if (DEBUG_SWITCH) Slog.d(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006634 TAG, "Performing unhandledBack(): stack size = " + count);
6635 if (count > 1) {
6636 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006637 mMainStack.finishActivityLocked((ActivityRecord)mMainStack.mHistory.get(count-1),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006638 count-1, Activity.RESULT_CANCELED, null, "unhandled-back");
6639 Binder.restoreCallingIdentity(origId);
6640 }
6641 }
6642 }
6643
6644 public ParcelFileDescriptor openContentUri(Uri uri) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006645 enforceNotIsolatedCaller("openContentUri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006646 String name = uri.getAuthority();
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006647 ContentProviderHolder cph = getContentProviderExternalUnchecked(name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006648 ParcelFileDescriptor pfd = null;
6649 if (cph != null) {
6650 // We record the binder invoker's uid in thread-local storage before
6651 // going to the content provider to open the file. Later, in the code
6652 // that handles all permissions checks, we look for this uid and use
6653 // that rather than the Activity Manager's own uid. The effect is that
6654 // we do the check against the caller's permissions even though it looks
6655 // to the content provider like the Activity Manager itself is making
6656 // the request.
6657 sCallerIdentity.set(new Identity(
6658 Binder.getCallingPid(), Binder.getCallingUid()));
6659 try {
6660 pfd = cph.provider.openFile(uri, "r");
6661 } catch (FileNotFoundException e) {
6662 // do nothing; pfd will be returned null
6663 } finally {
6664 // Ensure that whatever happens, we clean up the identity state
6665 sCallerIdentity.remove();
6666 }
6667
6668 // We've got the fd now, so we're done with the provider.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006669 removeContentProviderExternalUnchecked(name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006670 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006671 Slog.d(TAG, "Failed to get provider for authority '" + name + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006672 }
6673 return pfd;
6674 }
6675
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006676 // Actually is sleeping or shutting down or whatever else in the future
6677 // is an inactive state.
6678 public boolean isSleeping() {
6679 return mSleeping || mShuttingDown;
6680 }
6681
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006682 public void goingToSleep() {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006683 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
6684 != PackageManager.PERMISSION_GRANTED) {
6685 throw new SecurityException("Requires permission "
6686 + android.Manifest.permission.DEVICE_POWER);
6687 }
6688
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006689 synchronized(this) {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006690 mWentToSleep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006691 mWindowManager.setEventDispatching(false);
6692
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006693 if (!mSleeping) {
6694 mSleeping = true;
6695 mMainStack.stopIfSleepingLocked();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006696
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006697 // Initialize the wake times of all processes.
6698 checkExcessivePowerUsageLocked(false);
6699 mHandler.removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
6700 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
6701 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
6702 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006703 }
6704 }
6705
Dianne Hackborn55280a92009-05-07 15:53:46 -07006706 public boolean shutdown(int timeout) {
6707 if (checkCallingPermission(android.Manifest.permission.SHUTDOWN)
6708 != PackageManager.PERMISSION_GRANTED) {
6709 throw new SecurityException("Requires permission "
6710 + android.Manifest.permission.SHUTDOWN);
6711 }
6712
6713 boolean timedout = false;
6714
6715 synchronized(this) {
6716 mShuttingDown = true;
6717 mWindowManager.setEventDispatching(false);
6718
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006719 if (mMainStack.mResumedActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006720 mMainStack.stopIfSleepingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07006721 final long endTime = System.currentTimeMillis() + timeout;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006722 while (mMainStack.mResumedActivity != null
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08006723 || mMainStack.mPausingActivity != null) {
Dianne Hackborn55280a92009-05-07 15:53:46 -07006724 long delay = endTime - System.currentTimeMillis();
6725 if (delay <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006726 Slog.w(TAG, "Activity manager shutdown timed out");
Dianne Hackborn55280a92009-05-07 15:53:46 -07006727 timedout = true;
6728 break;
6729 }
6730 try {
6731 this.wait();
6732 } catch (InterruptedException e) {
6733 }
6734 }
6735 }
6736 }
6737
6738 mUsageStatsService.shutdown();
6739 mBatteryStatsService.shutdown();
6740
6741 return timedout;
6742 }
6743
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006744 public final void activitySlept(IBinder token) {
6745 if (localLOGV) Slog.v(
6746 TAG, "Activity slept: token=" + token);
6747
6748 ActivityRecord r = null;
6749
6750 final long origId = Binder.clearCallingIdentity();
6751
6752 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006753 r = mMainStack.isInStackLocked(token);
6754 if (r != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006755 mMainStack.activitySleptLocked(r);
6756 }
6757 }
6758
6759 Binder.restoreCallingIdentity(origId);
6760 }
6761
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006762 private void comeOutOfSleepIfNeededLocked() {
6763 if (!mWentToSleep && !mLockScreenShown) {
6764 if (mSleeping) {
6765 mSleeping = false;
6766 mMainStack.awakeFromSleepingLocked();
6767 mMainStack.resumeTopActivityLocked(null);
6768 }
6769 }
6770 }
6771
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006772 public void wakingUp() {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006773 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
6774 != PackageManager.PERMISSION_GRANTED) {
6775 throw new SecurityException("Requires permission "
6776 + android.Manifest.permission.DEVICE_POWER);
6777 }
6778
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006779 synchronized(this) {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006780 mWentToSleep = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006781 mWindowManager.setEventDispatching(true);
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006782 comeOutOfSleepIfNeededLocked();
6783 }
6784 }
6785
6786 public void setLockScreenShown(boolean shown) {
6787 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
6788 != PackageManager.PERMISSION_GRANTED) {
6789 throw new SecurityException("Requires permission "
6790 + android.Manifest.permission.DEVICE_POWER);
6791 }
6792
6793 synchronized(this) {
6794 mLockScreenShown = shown;
6795 comeOutOfSleepIfNeededLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006796 }
6797 }
6798
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006799 public void stopAppSwitches() {
6800 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
6801 != PackageManager.PERMISSION_GRANTED) {
6802 throw new SecurityException("Requires permission "
6803 + android.Manifest.permission.STOP_APP_SWITCHES);
6804 }
6805
6806 synchronized(this) {
6807 mAppSwitchesAllowedTime = SystemClock.uptimeMillis()
6808 + APP_SWITCH_DELAY_TIME;
6809 mDidAppSwitch = false;
6810 mHandler.removeMessages(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
6811 Message msg = mHandler.obtainMessage(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
6812 mHandler.sendMessageDelayed(msg, APP_SWITCH_DELAY_TIME);
6813 }
6814 }
6815
6816 public void resumeAppSwitches() {
6817 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
6818 != PackageManager.PERMISSION_GRANTED) {
6819 throw new SecurityException("Requires permission "
6820 + android.Manifest.permission.STOP_APP_SWITCHES);
6821 }
6822
6823 synchronized(this) {
6824 // Note that we don't execute any pending app switches... we will
6825 // let those wait until either the timeout, or the next start
6826 // activity request.
6827 mAppSwitchesAllowedTime = 0;
6828 }
6829 }
6830
6831 boolean checkAppSwitchAllowedLocked(int callingPid, int callingUid,
6832 String name) {
6833 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
6834 return true;
6835 }
6836
6837 final int perm = checkComponentPermission(
6838 android.Manifest.permission.STOP_APP_SWITCHES, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006839 callingUid, -1, true);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006840 if (perm == PackageManager.PERMISSION_GRANTED) {
6841 return true;
6842 }
6843
Joe Onorato8a9b2202010-02-26 18:56:32 -08006844 Slog.w(TAG, name + " request from " + callingUid + " stopped");
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006845 return false;
6846 }
6847
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006848 public void setDebugApp(String packageName, boolean waitForDebugger,
6849 boolean persistent) {
6850 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
6851 "setDebugApp()");
6852
6853 // Note that this is not really thread safe if there are multiple
6854 // callers into it at the same time, but that's not a situation we
6855 // care about.
6856 if (persistent) {
6857 final ContentResolver resolver = mContext.getContentResolver();
6858 Settings.System.putString(
6859 resolver, Settings.System.DEBUG_APP,
6860 packageName);
6861 Settings.System.putInt(
6862 resolver, Settings.System.WAIT_FOR_DEBUGGER,
6863 waitForDebugger ? 1 : 0);
6864 }
6865
6866 synchronized (this) {
6867 if (!persistent) {
6868 mOrigDebugApp = mDebugApp;
6869 mOrigWaitForDebugger = mWaitForDebugger;
6870 }
6871 mDebugApp = packageName;
6872 mWaitForDebugger = waitForDebugger;
6873 mDebugTransient = !persistent;
6874 if (packageName != null) {
6875 final long origId = Binder.clearCallingIdentity();
Amith Yamasani483f3b02012-03-13 16:08:00 -07006876 forceStopPackageLocked(packageName, -1, false, false, true, true, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006877 Binder.restoreCallingIdentity(origId);
6878 }
6879 }
6880 }
6881
Siva Velusamy92a8b222012-03-09 16:24:04 -08006882 void setOpenGlTraceApp(ApplicationInfo app, String processName) {
6883 synchronized (this) {
6884 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
6885 if (!isDebuggable) {
6886 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
6887 throw new SecurityException("Process not debuggable: " + app.packageName);
6888 }
6889 }
6890
6891 mOpenGlTraceApp = processName;
6892 }
6893 }
6894
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07006895 void setProfileApp(ApplicationInfo app, String processName, String profileFile,
6896 ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
6897 synchronized (this) {
6898 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
6899 if (!isDebuggable) {
6900 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
6901 throw new SecurityException("Process not debuggable: " + app.packageName);
6902 }
6903 }
6904 mProfileApp = processName;
6905 mProfileFile = profileFile;
6906 if (mProfileFd != null) {
6907 try {
6908 mProfileFd.close();
6909 } catch (IOException e) {
6910 }
6911 mProfileFd = null;
6912 }
6913 mProfileFd = profileFd;
6914 mProfileType = 0;
6915 mAutoStopProfiler = autoStopProfiler;
6916 }
6917 }
6918
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006919 public void setAlwaysFinish(boolean enabled) {
6920 enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH,
6921 "setAlwaysFinish()");
6922
6923 Settings.System.putInt(
6924 mContext.getContentResolver(),
6925 Settings.System.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0);
6926
6927 synchronized (this) {
6928 mAlwaysFinishActivities = enabled;
6929 }
6930 }
6931
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006932 public void setActivityController(IActivityController controller) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006933 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006934 "setActivityController()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006935 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006936 mController = controller;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006937 }
6938 }
6939
Dianne Hackborn9327f4f2010-01-29 10:38:29 -08006940 public boolean isUserAMonkey() {
6941 // For now the fact that there is a controller implies
6942 // we have a monkey.
6943 synchronized (this) {
6944 return mController != null;
6945 }
6946 }
6947
Jeff Sharkeya4620792011-05-20 15:29:23 -07006948 public void registerProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08006949 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
6950 "registerProcessObserver()");
6951 synchronized (this) {
6952 mProcessObservers.register(observer);
6953 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07006954 }
6955
6956 public void unregisterProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08006957 synchronized (this) {
6958 mProcessObservers.unregister(observer);
6959 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07006960 }
6961
Daniel Sandler69a48172010-06-23 16:29:36 -04006962 public void setImmersive(IBinder token, boolean immersive) {
6963 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006964 ActivityRecord r = mMainStack.isInStackLocked(token);
6965 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04006966 throw new IllegalArgumentException();
6967 }
Daniel Sandler69a48172010-06-23 16:29:36 -04006968 r.immersive = immersive;
6969 }
6970 }
6971
6972 public boolean isImmersive(IBinder token) {
6973 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006974 ActivityRecord r = mMainStack.isInStackLocked(token);
6975 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04006976 throw new IllegalArgumentException();
6977 }
Daniel Sandler69a48172010-06-23 16:29:36 -04006978 return r.immersive;
6979 }
6980 }
6981
6982 public boolean isTopActivityImmersive() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006983 enforceNotIsolatedCaller("startActivity");
Daniel Sandler69a48172010-06-23 16:29:36 -04006984 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006985 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Daniel Sandler69a48172010-06-23 16:29:36 -04006986 return (r != null) ? r.immersive : false;
6987 }
6988 }
6989
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006990 public final void enterSafeMode() {
6991 synchronized(this) {
6992 // It only makes sense to do this before the system is ready
6993 // and started launching other packages.
6994 if (!mSystemReady) {
6995 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006996 AppGlobals.getPackageManager().enterSafeMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006997 } catch (RemoteException e) {
6998 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006999 }
7000 }
7001 }
7002
Jeff Brownb09abc12011-01-13 21:08:27 -08007003 public final void showSafeModeOverlay() {
7004 View v = LayoutInflater.from(mContext).inflate(
7005 com.android.internal.R.layout.safe_mode, null);
7006 WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
7007 lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
7008 lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
7009 lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
7010 lp.gravity = Gravity.BOTTOM | Gravity.LEFT;
7011 lp.format = v.getBackground().getOpacity();
7012 lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
7013 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
7014 ((WindowManager)mContext.getSystemService(
7015 Context.WINDOW_SERVICE)).addView(v, lp);
7016 }
7017
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007018 public void noteWakeupAlarm(IIntentSender sender) {
7019 if (!(sender instanceof PendingIntentRecord)) {
7020 return;
7021 }
7022 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
7023 synchronized (stats) {
7024 if (mBatteryStatsService.isOnBattery()) {
7025 mBatteryStatsService.enforceCallingPermission();
7026 PendingIntentRecord rec = (PendingIntentRecord)sender;
7027 int MY_UID = Binder.getCallingUid();
7028 int uid = rec.uid == MY_UID ? Process.SYSTEM_UID : rec.uid;
7029 BatteryStatsImpl.Uid.Pkg pkg =
7030 stats.getPackageStatsLocked(uid, rec.key.packageName);
7031 pkg.incWakeupsLocked();
7032 }
7033 }
7034 }
7035
Dianne Hackborn64825172011-03-02 21:32:58 -08007036 public boolean killPids(int[] pids, String pReason, boolean secure) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007037 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007038 throw new SecurityException("killPids only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007039 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007040 String reason = (pReason == null) ? "Unknown" : pReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007041 // XXX Note: don't acquire main activity lock here, because the window
7042 // manager calls in with its locks held.
7043
7044 boolean killed = false;
7045 synchronized (mPidsSelfLocked) {
7046 int[] types = new int[pids.length];
7047 int worstType = 0;
7048 for (int i=0; i<pids.length; i++) {
7049 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7050 if (proc != null) {
7051 int type = proc.setAdj;
7052 types[i] = type;
7053 if (type > worstType) {
7054 worstType = type;
7055 }
7056 }
7057 }
7058
Dianne Hackborn64825172011-03-02 21:32:58 -08007059 // If the worst oom_adj is somewhere in the hidden proc LRU range,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007060 // then constrain it so we will kill all hidden procs.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007061 if (worstType < ProcessList.HIDDEN_APP_MAX_ADJ
7062 && worstType > ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07007063 worstType = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007064 }
Dianne Hackborn64825172011-03-02 21:32:58 -08007065
7066 // If this is not a secure call, don't let it kill processes that
7067 // are important.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007068 if (!secure && worstType < ProcessList.SERVICE_ADJ) {
7069 worstType = ProcessList.SERVICE_ADJ;
Dianne Hackborn64825172011-03-02 21:32:58 -08007070 }
7071
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007072 Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007073 for (int i=0; i<pids.length; i++) {
7074 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7075 if (proc == null) {
7076 continue;
7077 }
7078 int adj = proc.setAdj;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007079 if (adj >= worstType && !proc.killedBackground) {
Dianne Hackborn8633e682010-04-22 16:03:41 -07007080 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007081 EventLog.writeEvent(EventLogTags.AM_KILL, proc.pid,
7082 proc.processName, adj, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007083 killed = true;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007084 proc.killedBackground = true;
7085 Process.killProcessQuiet(pids[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007086 }
7087 }
7088 }
7089 return killed;
7090 }
Jeff Sharkeyb9a07012012-03-22 17:00:04 -07007091
7092 @Override
7093 public boolean killProcessesBelowForeground(String reason) {
7094 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7095 throw new SecurityException("killProcessesBelowForeground() only available to system");
7096 }
7097
7098 return killProcessesBelowAdj(ProcessList.FOREGROUND_APP_ADJ, reason);
7099 }
7100
7101 private boolean killProcessesBelowAdj(int belowAdj, String reason) {
7102 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7103 throw new SecurityException("killProcessesBelowAdj() only available to system");
7104 }
7105
7106 boolean killed = false;
7107 synchronized (mPidsSelfLocked) {
7108 final int size = mPidsSelfLocked.size();
7109 for (int i = 0; i < size; i++) {
7110 final int pid = mPidsSelfLocked.keyAt(i);
7111 final ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7112 if (proc == null) continue;
7113
7114 final int adj = proc.setAdj;
7115 if (adj > belowAdj && !proc.killedBackground) {
7116 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
7117 EventLog.writeEvent(
7118 EventLogTags.AM_KILL, proc.pid, proc.processName, adj, reason);
7119 killed = true;
7120 proc.killedBackground = true;
7121 Process.killProcessQuiet(pid);
7122 }
7123 }
7124 }
7125 return killed;
7126 }
7127
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007128 public final void startRunning(String pkg, String cls, String action,
7129 String data) {
7130 synchronized(this) {
7131 if (mStartRunning) {
7132 return;
7133 }
7134 mStartRunning = true;
7135 mTopComponent = pkg != null && cls != null
7136 ? new ComponentName(pkg, cls) : null;
7137 mTopAction = action != null ? action : Intent.ACTION_MAIN;
7138 mTopData = data;
7139 if (!mSystemReady) {
7140 return;
7141 }
7142 }
7143
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007144 systemReady(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007145 }
7146
7147 private void retrieveSettings() {
7148 final ContentResolver resolver = mContext.getContentResolver();
7149 String debugApp = Settings.System.getString(
7150 resolver, Settings.System.DEBUG_APP);
7151 boolean waitForDebugger = Settings.System.getInt(
7152 resolver, Settings.System.WAIT_FOR_DEBUGGER, 0) != 0;
7153 boolean alwaysFinishActivities = Settings.System.getInt(
7154 resolver, Settings.System.ALWAYS_FINISH_ACTIVITIES, 0) != 0;
7155
7156 Configuration configuration = new Configuration();
7157 Settings.System.getConfiguration(resolver, configuration);
7158
7159 synchronized (this) {
7160 mDebugApp = mOrigDebugApp = debugApp;
7161 mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger;
7162 mAlwaysFinishActivities = alwaysFinishActivities;
7163 // This happens before any activities are started, so we can
7164 // change mConfiguration in-place.
Dianne Hackborn813075a62011-11-14 17:45:19 -08007165 updateConfigurationLocked(configuration, null, false, true);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007166 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Initial config: " + mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007167 }
7168 }
7169
7170 public boolean testIsSystemReady() {
7171 // no need to synchronize(this) just to read & return the value
7172 return mSystemReady;
7173 }
7174
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007175 private static File getCalledPreBootReceiversFile() {
7176 File dataDir = Environment.getDataDirectory();
7177 File systemDir = new File(dataDir, "system");
7178 File fname = new File(systemDir, "called_pre_boots.dat");
7179 return fname;
7180 }
Dianne Hackborn661cd522011-08-22 00:26:20 -07007181
7182 static final int LAST_DONE_VERSION = 10000;
7183
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007184 private static ArrayList<ComponentName> readLastDonePreBootReceivers() {
7185 ArrayList<ComponentName> lastDoneReceivers = new ArrayList<ComponentName>();
7186 File file = getCalledPreBootReceiversFile();
7187 FileInputStream fis = null;
7188 try {
7189 fis = new FileInputStream(file);
7190 DataInputStream dis = new DataInputStream(new BufferedInputStream(fis, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007191 int fvers = dis.readInt();
7192 if (fvers == LAST_DONE_VERSION) {
7193 String vers = dis.readUTF();
7194 String codename = dis.readUTF();
7195 String build = dis.readUTF();
7196 if (android.os.Build.VERSION.RELEASE.equals(vers)
7197 && android.os.Build.VERSION.CODENAME.equals(codename)
7198 && android.os.Build.VERSION.INCREMENTAL.equals(build)) {
7199 int num = dis.readInt();
7200 while (num > 0) {
7201 num--;
7202 String pkg = dis.readUTF();
7203 String cls = dis.readUTF();
7204 lastDoneReceivers.add(new ComponentName(pkg, cls));
7205 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007206 }
7207 }
7208 } catch (FileNotFoundException e) {
7209 } catch (IOException e) {
7210 Slog.w(TAG, "Failure reading last done pre-boot receivers", e);
7211 } finally {
7212 if (fis != null) {
7213 try {
7214 fis.close();
7215 } catch (IOException e) {
7216 }
7217 }
7218 }
7219 return lastDoneReceivers;
7220 }
7221
7222 private static void writeLastDonePreBootReceivers(ArrayList<ComponentName> list) {
7223 File file = getCalledPreBootReceiversFile();
7224 FileOutputStream fos = null;
7225 DataOutputStream dos = null;
7226 try {
7227 Slog.i(TAG, "Writing new set of last done pre-boot receivers...");
7228 fos = new FileOutputStream(file);
7229 dos = new DataOutputStream(new BufferedOutputStream(fos, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007230 dos.writeInt(LAST_DONE_VERSION);
7231 dos.writeUTF(android.os.Build.VERSION.RELEASE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007232 dos.writeUTF(android.os.Build.VERSION.CODENAME);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007233 dos.writeUTF(android.os.Build.VERSION.INCREMENTAL);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007234 dos.writeInt(list.size());
7235 for (int i=0; i<list.size(); i++) {
7236 dos.writeUTF(list.get(i).getPackageName());
7237 dos.writeUTF(list.get(i).getClassName());
7238 }
7239 } catch (IOException e) {
7240 Slog.w(TAG, "Failure writing last done pre-boot receivers", e);
7241 file.delete();
7242 } finally {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07007243 FileUtils.sync(fos);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007244 if (dos != null) {
7245 try {
7246 dos.close();
7247 } catch (IOException e) {
7248 // TODO Auto-generated catch block
7249 e.printStackTrace();
7250 }
7251 }
7252 }
7253 }
7254
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007255 public void systemReady(final Runnable goingCallback) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007256 synchronized(this) {
7257 if (mSystemReady) {
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007258 if (goingCallback != null) goingCallback.run();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007259 return;
7260 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007261
7262 // Check to see if there are any update receivers to run.
7263 if (!mDidUpdate) {
7264 if (mWaitingUpdate) {
7265 return;
7266 }
7267 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
7268 List<ResolveInfo> ris = null;
7269 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007270 ris = AppGlobals.getPackageManager().queryIntentReceivers(
Amith Yamasani483f3b02012-03-13 16:08:00 -07007271 intent, null, 0, 0);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007272 } catch (RemoteException e) {
7273 }
7274 if (ris != null) {
7275 for (int i=ris.size()-1; i>=0; i--) {
7276 if ((ris.get(i).activityInfo.applicationInfo.flags
7277 &ApplicationInfo.FLAG_SYSTEM) == 0) {
7278 ris.remove(i);
7279 }
7280 }
7281 intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007282
7283 ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers();
7284
7285 final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007286 for (int i=0; i<ris.size(); i++) {
7287 ActivityInfo ai = ris.get(i).activityInfo;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007288 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7289 if (lastDoneReceivers.contains(comp)) {
7290 ris.remove(i);
7291 i--;
7292 }
7293 }
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07007294
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007295 for (int i=0; i<ris.size(); i++) {
7296 ActivityInfo ai = ris.get(i).activityInfo;
7297 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7298 doneReceivers.add(comp);
7299 intent.setComponent(comp);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007300 IIntentReceiver finisher = null;
Dianne Hackbornd6847842010-01-12 18:14:19 -08007301 if (i == ris.size()-1) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007302 finisher = new IIntentReceiver.Stub() {
7303 public void performReceive(Intent intent, int resultCode,
Dianne Hackborn68d881c2009-10-05 13:58:17 -07007304 String data, Bundle extras, boolean ordered,
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007305 boolean sticky) {
7306 // The raw IIntentReceiver interface is called
7307 // with the AM lock held, so redispatch to
7308 // execute our code without the lock.
7309 mHandler.post(new Runnable() {
7310 public void run() {
7311 synchronized (ActivityManagerService.this) {
7312 mDidUpdate = true;
7313 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007314 writeLastDonePreBootReceivers(doneReceivers);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007315 showBootMessage(mContext.getText(
7316 R.string.android_upgrading_complete),
7317 false);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007318 systemReady(goingCallback);
7319 }
7320 });
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007321 }
7322 };
7323 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08007324 Slog.i(TAG, "Sending system update to: " + intent.getComponent());
Amith Yamasani742a6712011-05-04 14:49:28 -07007325 /* TODO: Send this to all users */
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007326 broadcastIntentLocked(null, null, intent, null, finisher,
Amith Yamasani742a6712011-05-04 14:49:28 -07007327 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID,
Amith Yamasanic600e21f2012-02-14 16:08:07 -08007328 0 /* UserId zero */);
Dianne Hackbornd6847842010-01-12 18:14:19 -08007329 if (finisher != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007330 mWaitingUpdate = true;
7331 }
7332 }
7333 }
7334 if (mWaitingUpdate) {
7335 return;
7336 }
7337 mDidUpdate = true;
7338 }
7339
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007340 mSystemReady = true;
7341 if (!mStartRunning) {
7342 return;
7343 }
7344 }
7345
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007346 ArrayList<ProcessRecord> procsToKill = null;
7347 synchronized(mPidsSelfLocked) {
7348 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
7349 ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7350 if (!isAllowedWhileBooting(proc.info)){
7351 if (procsToKill == null) {
7352 procsToKill = new ArrayList<ProcessRecord>();
7353 }
7354 procsToKill.add(proc);
7355 }
7356 }
7357 }
7358
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007359 synchronized(this) {
7360 if (procsToKill != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007361 for (int i=procsToKill.size()-1; i>=0; i--) {
7362 ProcessRecord proc = procsToKill.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007363 Slog.i(TAG, "Removing system update proc: " + proc);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007364 removeProcessLocked(proc, true, false, "system update done");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007365 }
7366 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007367
7368 // Now that we have cleaned up any update processes, we
7369 // are ready to start launching real processes and know that
7370 // we won't trample on them any more.
7371 mProcessesReady = true;
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007372 }
7373
Joe Onorato8a9b2202010-02-26 18:56:32 -08007374 Slog.i(TAG, "System now ready");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007375 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007376 SystemClock.uptimeMillis());
7377
7378 synchronized(this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007379 // Make sure we have no pre-ready processes sitting around.
7380
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007381 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
7382 ResolveInfo ri = mContext.getPackageManager()
7383 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST),
Dianne Hackborn1655be42009-05-08 14:29:01 -07007384 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007385 CharSequence errorMsg = null;
7386 if (ri != null) {
7387 ActivityInfo ai = ri.activityInfo;
7388 ApplicationInfo app = ai.applicationInfo;
7389 if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7390 mTopAction = Intent.ACTION_FACTORY_TEST;
7391 mTopData = null;
7392 mTopComponent = new ComponentName(app.packageName,
7393 ai.name);
7394 } else {
7395 errorMsg = mContext.getResources().getText(
7396 com.android.internal.R.string.factorytest_not_system);
7397 }
7398 } else {
7399 errorMsg = mContext.getResources().getText(
7400 com.android.internal.R.string.factorytest_no_action);
7401 }
7402 if (errorMsg != null) {
7403 mTopAction = null;
7404 mTopData = null;
7405 mTopComponent = null;
7406 Message msg = Message.obtain();
7407 msg.what = SHOW_FACTORY_ERROR_MSG;
7408 msg.getData().putCharSequence("msg", errorMsg);
7409 mHandler.sendMessage(msg);
7410 }
7411 }
7412 }
7413
7414 retrieveSettings();
7415
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007416 if (goingCallback != null) goingCallback.run();
7417
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007418 synchronized (this) {
7419 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
7420 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007421 List apps = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07007422 getPersistentApplications(STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007423 if (apps != null) {
7424 int N = apps.size();
7425 int i;
7426 for (i=0; i<N; i++) {
7427 ApplicationInfo info
7428 = (ApplicationInfo)apps.get(i);
7429 if (info != null &&
7430 !info.packageName.equals("android")) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007431 addAppLocked(info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007432 }
7433 }
7434 }
7435 } catch (RemoteException ex) {
7436 // pm is in same process, this will never happen.
7437 }
7438 }
7439
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007440 // Start up initial activity.
7441 mBooting = true;
7442
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007443 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007444 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007445 Message msg = Message.obtain();
7446 msg.what = SHOW_UID_ERROR_MSG;
7447 mHandler.sendMessage(msg);
7448 }
7449 } catch (RemoteException e) {
7450 }
7451
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007452 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007453 }
7454 }
7455
Dan Egnorb7f03672009-12-09 16:22:32 -08007456 private boolean makeAppCrashingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007457 String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007458 app.crashing = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007459 app.crashingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007460 ActivityManager.ProcessErrorStateInfo.CRASHED, null, shortMsg, longMsg, stackTrace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007461 startAppProblemLocked(app);
7462 app.stopFreezingAllLocked();
7463 return handleAppCrashLocked(app);
7464 }
7465
Dan Egnorb7f03672009-12-09 16:22:32 -08007466 private void makeAppNotRespondingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007467 String activity, String shortMsg, String longMsg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007468 app.notResponding = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007469 app.notRespondingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007470 ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING,
7471 activity, shortMsg, longMsg, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007472 startAppProblemLocked(app);
7473 app.stopFreezingAllLocked();
7474 }
7475
7476 /**
7477 * Generate a process error record, suitable for attachment to a ProcessRecord.
7478 *
7479 * @param app The ProcessRecord in which the error occurred.
7480 * @param condition Crashing, Application Not Responding, etc. Values are defined in
7481 * ActivityManager.AppErrorStateInfo
Dan Egnor60d87622009-12-16 16:32:58 -08007482 * @param activity The activity associated with the crash, if known.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007483 * @param shortMsg Short message describing the crash.
7484 * @param longMsg Long message describing the crash.
Dan Egnorb7f03672009-12-09 16:22:32 -08007485 * @param stackTrace Full crash stack trace, may be null.
7486 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007487 * @return Returns a fully-formed AppErrorStateInfo record.
7488 */
7489 private ActivityManager.ProcessErrorStateInfo generateProcessError(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007490 int condition, String activity, String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007491 ActivityManager.ProcessErrorStateInfo report = new ActivityManager.ProcessErrorStateInfo();
Dan Egnorb7f03672009-12-09 16:22:32 -08007492
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007493 report.condition = condition;
7494 report.processName = app.processName;
7495 report.pid = app.pid;
7496 report.uid = app.info.uid;
Dan Egnor60d87622009-12-16 16:32:58 -08007497 report.tag = activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007498 report.shortMsg = shortMsg;
7499 report.longMsg = longMsg;
Dan Egnorb7f03672009-12-09 16:22:32 -08007500 report.stackTrace = stackTrace;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007501
7502 return report;
7503 }
7504
Dan Egnor42471dd2010-01-07 17:25:22 -08007505 void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007506 synchronized (this) {
7507 app.crashing = false;
7508 app.crashingReport = null;
7509 app.notResponding = false;
7510 app.notRespondingReport = null;
7511 if (app.anrDialog == fromDialog) {
7512 app.anrDialog = null;
7513 }
7514 if (app.waitDialog == fromDialog) {
7515 app.waitDialog = null;
7516 }
7517 if (app.pid > 0 && app.pid != MY_PID) {
Dan Egnor42471dd2010-01-07 17:25:22 -08007518 handleAppCrashLocked(app);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007519 Slog.i(ActivityManagerService.TAG, "Killing " + app + ": user's request");
Dianne Hackborn8633e682010-04-22 16:03:41 -07007520 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
7521 app.processName, app.setAdj, "user's request after error");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007522 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007523 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007524 }
7525 }
Dan Egnor42471dd2010-01-07 17:25:22 -08007526
Dan Egnorb7f03672009-12-09 16:22:32 -08007527 private boolean handleAppCrashLocked(ProcessRecord app) {
Mike Lockwood86548c42011-09-13 17:21:46 -04007528 if (mHeadless) {
7529 Log.e(TAG, "handleAppCrashLocked: " + app.processName);
7530 return false;
7531 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007532 long now = SystemClock.uptimeMillis();
7533
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007534 Long crashTime;
7535 if (!app.isolated) {
7536 crashTime = mProcessCrashTimes.get(app.info.processName, app.uid);
7537 } else {
7538 crashTime = null;
7539 }
Dianne Hackborn7d608422011-08-07 16:24:18 -07007540 if (crashTime != null && now < crashTime+ProcessList.MIN_CRASH_INTERVAL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007541 // This process loses!
Joe Onorato8a9b2202010-02-26 18:56:32 -08007542 Slog.w(TAG, "Process " + app.info.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007543 + " has crashed too many times: killing!");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007544 EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007545 app.info.processName, app.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007546 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
7547 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007548 if (r.app == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007549 Slog.w(TAG, " Force finishing activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007550 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007551 r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED, null, "crashed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007552 }
7553 }
7554 if (!app.persistent) {
7555 // We don't want to start this process again until the user
7556 // explicitly does so... but for persistent process, we really
7557 // need to keep it running. If a persistent process is actually
7558 // repeatedly crashing, then badness for everyone.
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007559 EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007560 app.info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007561 if (!app.isolated) {
7562 // XXX We don't have a way to mark isolated processes
7563 // as bad, since they don't have a peristent identity.
7564 mBadProcesses.put(app.info.processName, app.uid, now);
7565 mProcessCrashTimes.remove(app.info.processName, app.uid);
7566 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007567 app.bad = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007568 app.removed = true;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07007569 // Don't let services in this process be restarted and potentially
7570 // annoy the user repeatedly. Unless it is persistent, since those
7571 // processes run critical code.
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007572 removeProcessLocked(app, false, false, "crash");
Dianne Hackborncb44d962011-03-10 17:02:27 -08007573 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007574 return false;
7575 }
Dianne Hackborncb44d962011-03-10 17:02:27 -08007576 mMainStack.resumeTopActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007577 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007578 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Kevin Hester-Chowd87a9be2012-03-05 08:01:00 -08007579 if (r != null && r.app == app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007580 // If the top running activity is from this crashing
7581 // process, then terminate it to avoid getting in a loop.
7582 Slog.w(TAG, " Force finishing activity "
7583 + r.intent.getComponent().flattenToShortString());
Dianne Hackbornbe707852011-11-11 14:32:10 -08007584 int index = mMainStack.indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007585 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007586 Activity.RESULT_CANCELED, null, "crashed");
Dianne Hackborn070783f2010-12-29 16:46:28 -08007587 // Also terminate any activities below it that aren't yet
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007588 // stopped, to avoid a situation where one will get
7589 // re-start our crashing activity once it gets resumed again.
7590 index--;
7591 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007592 r = (ActivityRecord)mMainStack.mHistory.get(index);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007593 if (r.state == ActivityState.RESUMED
7594 || r.state == ActivityState.PAUSING
7595 || r.state == ActivityState.PAUSED) {
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08007596 if (!r.isHomeActivity || mHomeProcess != r.app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007597 Slog.w(TAG, " Force finishing activity "
7598 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007599 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007600 Activity.RESULT_CANCELED, null, "crashed");
7601 }
7602 }
7603 }
7604 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007605 }
7606
7607 // Bump up the crash count of any services currently running in the proc.
7608 if (app.services.size() != 0) {
7609 // Any services running in the application need to be placed
7610 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -07007611 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007612 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07007613 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007614 sr.crashCount++;
7615 }
7616 }
Mattias Larssona4fd0072010-06-22 22:37:03 +02007617
7618 // If the crashing process is what we consider to be the "home process" and it has been
7619 // replaced by a third-party app, clear the package preferred activities from packages
7620 // with a home activity running in the process to prevent a repeatedly crashing app
7621 // from blocking the user to manually clear the list.
7622 if (app == mHomeProcess && mHomeProcess.activities.size() > 0
7623 && (mHomeProcess.info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
7624 Iterator it = mHomeProcess.activities.iterator();
7625 while (it.hasNext()) {
Jean-Baptiste Queru5ea89f72010-07-30 09:30:31 -07007626 ActivityRecord r = (ActivityRecord)it.next();
Mattias Larssona4fd0072010-06-22 22:37:03 +02007627 if (r.isHomeActivity) {
7628 Log.i(TAG, "Clearing package preferred activities from " + r.packageName);
7629 try {
7630 ActivityThread.getPackageManager()
7631 .clearPackagePreferredActivities(r.packageName);
7632 } catch (RemoteException c) {
7633 // pm is in same process, this will never happen.
7634 }
7635 }
7636 }
7637 }
7638
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007639 if (!app.isolated) {
7640 // XXX Can't keep track of crash times for isolated processes,
7641 // because they don't have a perisistent identity.
7642 mProcessCrashTimes.put(app.info.processName, app.uid, now);
7643 }
7644
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007645 return true;
7646 }
7647
7648 void startAppProblemLocked(ProcessRecord app) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08007649 app.errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver(
7650 mContext, app.info.packageName, app.info.flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007651 skipCurrentReceiverLocked(app);
7652 }
7653
7654 void skipCurrentReceiverLocked(ProcessRecord app) {
Christopher Tatef46723b2012-01-26 14:19:24 -08007655 for (BroadcastQueue queue : mBroadcastQueues) {
7656 queue.skipCurrentReceiverLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007657 }
7658 }
7659
Dan Egnor60d87622009-12-16 16:32:58 -08007660 /**
7661 * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes.
7662 * The application process will exit immediately after this call returns.
7663 * @param app object of the crashing app, null for the system server
7664 * @param crashInfo describing the exception
7665 */
7666 public void handleApplicationCrash(IBinder app, ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007667 ProcessRecord r = findAppProcess(app, "Crash");
Jeff Sharkeya353d262011-10-28 11:12:06 -07007668 final String processName = app == null ? "system_server"
7669 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08007670
7671 EventLog.writeEvent(EventLogTags.AM_CRASH, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07007672 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08007673 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08007674 crashInfo.exceptionClassName,
7675 crashInfo.exceptionMessage,
7676 crashInfo.throwFileName,
7677 crashInfo.throwLineNumber);
7678
Jeff Sharkeya353d262011-10-28 11:12:06 -07007679 addErrorToDropBox("crash", r, processName, null, null, null, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08007680
7681 crashApplication(r, crashInfo);
7682 }
7683
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007684 public void handleApplicationStrictModeViolation(
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007685 IBinder app,
7686 int violationMask,
7687 StrictMode.ViolationInfo info) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007688 ProcessRecord r = findAppProcess(app, "StrictMode");
7689 if (r == null) {
7690 return;
7691 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007692
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007693 if ((violationMask & StrictMode.PENALTY_DROPBOX) != 0) {
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08007694 Integer stackFingerprint = info.hashCode();
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007695 boolean logIt = true;
7696 synchronized (mAlreadyLoggedViolatedStacks) {
7697 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) {
7698 logIt = false;
7699 // TODO: sub-sample into EventLog for these, with
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007700 // the info.durationMillis? Then we'd get
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007701 // the relative pain numbers, without logging all
7702 // the stack traces repeatedly. We'd want to do
7703 // likewise in the client code, which also does
7704 // dup suppression, before the Binder call.
7705 } else {
7706 if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) {
7707 mAlreadyLoggedViolatedStacks.clear();
7708 }
7709 mAlreadyLoggedViolatedStacks.add(stackFingerprint);
7710 }
7711 }
7712 if (logIt) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007713 logStrictModeViolationToDropBox(r, info);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007714 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007715 }
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007716
7717 if ((violationMask & StrictMode.PENALTY_DIALOG) != 0) {
7718 AppErrorResult result = new AppErrorResult();
7719 synchronized (this) {
7720 final long origId = Binder.clearCallingIdentity();
7721
7722 Message msg = Message.obtain();
7723 msg.what = SHOW_STRICT_MODE_VIOLATION_MSG;
7724 HashMap<String, Object> data = new HashMap<String, Object>();
7725 data.put("result", result);
7726 data.put("app", r);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007727 data.put("violationMask", violationMask);
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007728 data.put("info", info);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007729 msg.obj = data;
7730 mHandler.sendMessage(msg);
7731
7732 Binder.restoreCallingIdentity(origId);
7733 }
7734 int res = result.get();
Dianne Hackbornb424b632010-08-18 15:59:05 -07007735 Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007736 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007737 }
7738
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007739 // Depending on the policy in effect, there could be a bunch of
7740 // these in quick succession so we try to batch these together to
7741 // minimize disk writes, number of dropbox entries, and maximize
7742 // compression, by having more fewer, larger records.
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007743 private void logStrictModeViolationToDropBox(
7744 ProcessRecord process,
7745 StrictMode.ViolationInfo info) {
7746 if (info == null) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007747 return;
7748 }
7749 final boolean isSystemApp = process == null ||
7750 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM |
7751 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07007752 final String processName = process == null ? "unknown" : process.processName;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007753 final String dropboxTag = isSystemApp ? "system_app_strictmode" : "data_app_strictmode";
7754 final DropBoxManager dbox = (DropBoxManager)
7755 mContext.getSystemService(Context.DROPBOX_SERVICE);
7756
7757 // Exit early if the dropbox isn't configured to accept this report type.
7758 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
7759
7760 boolean bufferWasEmpty;
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007761 boolean needsFlush;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007762 final StringBuilder sb = isSystemApp ? mStrictModeBuffer : new StringBuilder(1024);
7763 synchronized (sb) {
7764 bufferWasEmpty = sb.length() == 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07007765 appendDropBoxProcessHeaders(process, processName, sb);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007766 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
7767 sb.append("System-App: ").append(isSystemApp).append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007768 sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n");
7769 if (info.violationNumThisLoop != 0) {
7770 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n");
7771 }
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07007772 if (info.numAnimationsRunning != 0) {
7773 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n");
7774 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07007775 if (info.broadcastIntentAction != null) {
7776 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n");
7777 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08007778 if (info.durationMillis != -1) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007779 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n");
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007780 }
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08007781 if (info.numInstances != -1) {
7782 sb.append("Instance-Count: ").append(info.numInstances).append("\n");
7783 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08007784 if (info.tags != null) {
7785 for (String tag : info.tags) {
7786 sb.append("Span-Tag: ").append(tag).append("\n");
7787 }
7788 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007789 sb.append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007790 if (info.crashInfo != null && info.crashInfo.stackTrace != null) {
7791 sb.append(info.crashInfo.stackTrace);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007792 }
7793 sb.append("\n");
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007794
7795 // Only buffer up to ~64k. Various logging bits truncate
7796 // things at 128k.
7797 needsFlush = (sb.length() > 64 * 1024);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007798 }
7799
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007800 // Flush immediately if the buffer's grown too large, or this
7801 // is a non-system app. Non-system apps are isolated with a
7802 // different tag & policy and not batched.
7803 //
7804 // Batching is useful during internal testing with
7805 // StrictMode settings turned up high. Without batching,
7806 // thousands of separate files could be created on boot.
7807 if (!isSystemApp || needsFlush) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007808 new Thread("Error dump: " + dropboxTag) {
7809 @Override
7810 public void run() {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007811 String report;
7812 synchronized (sb) {
7813 report = sb.toString();
7814 sb.delete(0, sb.length());
7815 sb.trimToSize();
7816 }
7817 if (report.length() != 0) {
7818 dbox.addText(dropboxTag, report);
7819 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007820 }
7821 }.start();
7822 return;
7823 }
7824
7825 // System app batching:
7826 if (!bufferWasEmpty) {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007827 // An existing dropbox-writing thread is outstanding, so
7828 // we don't need to start it up. The existing thread will
7829 // catch the buffer appends we just did.
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007830 return;
7831 }
7832
7833 // Worker thread to both batch writes and to avoid blocking the caller on I/O.
7834 // (After this point, we shouldn't access AMS internal data structures.)
7835 new Thread("Error dump: " + dropboxTag) {
7836 @Override
7837 public void run() {
7838 // 5 second sleep to let stacks arrive and be batched together
7839 try {
7840 Thread.sleep(5000); // 5 seconds
7841 } catch (InterruptedException e) {}
7842
7843 String errorReport;
7844 synchronized (mStrictModeBuffer) {
7845 errorReport = mStrictModeBuffer.toString();
7846 if (errorReport.length() == 0) {
7847 return;
7848 }
7849 mStrictModeBuffer.delete(0, mStrictModeBuffer.length());
7850 mStrictModeBuffer.trimToSize();
7851 }
7852 dbox.addText(dropboxTag, errorReport);
7853 }
7854 }.start();
7855 }
7856
Dan Egnor60d87622009-12-16 16:32:58 -08007857 /**
7858 * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors.
7859 * @param app object of the crashing app, null for the system server
7860 * @param tag reported by the caller
7861 * @param crashInfo describing the context of the error
7862 * @return true if the process should exit immediately (WTF is fatal)
7863 */
7864 public boolean handleApplicationWtf(IBinder app, String tag,
Dan Egnorb7f03672009-12-09 16:22:32 -08007865 ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007866 ProcessRecord r = findAppProcess(app, "WTF");
Jeff Sharkeya353d262011-10-28 11:12:06 -07007867 final String processName = app == null ? "system_server"
7868 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08007869
7870 EventLog.writeEvent(EventLogTags.AM_WTF, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07007871 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08007872 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08007873 tag, crashInfo.exceptionMessage);
7874
Jeff Sharkeya353d262011-10-28 11:12:06 -07007875 addErrorToDropBox("wtf", r, processName, null, null, tag, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08007876
Dianne Hackborn1ab43772011-03-15 14:38:02 -07007877 if (r != null && r.pid != Process.myPid() &&
7878 Settings.Secure.getInt(mContext.getContentResolver(),
7879 Settings.Secure.WTF_IS_FATAL, 0) != 0) {
Dan Egnor60d87622009-12-16 16:32:58 -08007880 crashApplication(r, crashInfo);
7881 return true;
7882 } else {
7883 return false;
7884 }
7885 }
7886
7887 /**
7888 * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit})
7889 * @return the corresponding {@link ProcessRecord} object, or null if none could be found
7890 */
Dianne Hackborncb44d962011-03-10 17:02:27 -08007891 private ProcessRecord findAppProcess(IBinder app, String reason) {
Dan Egnor60d87622009-12-16 16:32:58 -08007892 if (app == null) {
7893 return null;
7894 }
7895
7896 synchronized (this) {
7897 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
7898 final int NA = apps.size();
7899 for (int ia=0; ia<NA; ia++) {
7900 ProcessRecord p = apps.valueAt(ia);
7901 if (p.thread != null && p.thread.asBinder() == app) {
7902 return p;
7903 }
7904 }
7905 }
7906
Dianne Hackborncb44d962011-03-10 17:02:27 -08007907 Slog.w(TAG, "Can't find mystery application for " + reason
7908 + " from pid=" + Binder.getCallingPid()
7909 + " uid=" + Binder.getCallingUid() + ": " + app);
Dan Egnor60d87622009-12-16 16:32:58 -08007910 return null;
7911 }
7912 }
7913
7914 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007915 * Utility function for addErrorToDropBox and handleStrictModeViolation's logging
7916 * to append various headers to the dropbox log text.
Dan Egnor60d87622009-12-16 16:32:58 -08007917 */
Jeff Sharkeya353d262011-10-28 11:12:06 -07007918 private void appendDropBoxProcessHeaders(ProcessRecord process, String processName,
7919 StringBuilder sb) {
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08007920 // Watchdog thread ends up invoking this function (with
7921 // a null ProcessRecord) to add the stack file to dropbox.
7922 // Do not acquire a lock on this (am) in such cases, as it
7923 // could cause a potential deadlock, if and when watchdog
7924 // is invoked due to unavailability of lock on am and it
7925 // would prevent watchdog from killing system_server.
7926 if (process == null) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07007927 sb.append("Process: ").append(processName).append("\n");
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08007928 return;
7929 }
Brad Fitzpatrick1e02d362010-09-10 09:19:50 -07007930 // Note: ProcessRecord 'process' is guarded by the service
7931 // instance. (notably process.pkgList, which could otherwise change
7932 // concurrently during execution of this method)
7933 synchronized (this) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07007934 sb.append("Process: ").append(processName).append("\n");
Dan Egnora455d192010-03-12 08:52:28 -08007935 int flags = process.info.flags;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007936 IPackageManager pm = AppGlobals.getPackageManager();
Dan Egnora455d192010-03-12 08:52:28 -08007937 sb.append("Flags: 0x").append(Integer.toString(flags, 16)).append("\n");
7938 for (String pkg : process.pkgList) {
7939 sb.append("Package: ").append(pkg);
Dan Egnor42471dd2010-01-07 17:25:22 -08007940 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07007941 PackageInfo pi = pm.getPackageInfo(pkg, 0, 0);
Dan Egnora455d192010-03-12 08:52:28 -08007942 if (pi != null) {
7943 sb.append(" v").append(pi.versionCode);
7944 if (pi.versionName != null) {
7945 sb.append(" (").append(pi.versionName).append(")");
7946 }
7947 }
7948 } catch (RemoteException e) {
7949 Slog.e(TAG, "Error getting package info: " + pkg, e);
Dan Egnor60d87622009-12-16 16:32:58 -08007950 }
Dan Egnora455d192010-03-12 08:52:28 -08007951 sb.append("\n");
Dan Egnor60d87622009-12-16 16:32:58 -08007952 }
Dan Egnora455d192010-03-12 08:52:28 -08007953 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007954 }
7955
7956 private static String processClass(ProcessRecord process) {
7957 if (process == null || process.pid == MY_PID) {
7958 return "system_server";
7959 } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
7960 return "system_app";
7961 } else {
7962 return "data_app";
7963 }
7964 }
7965
7966 /**
7967 * Write a description of an error (crash, WTF, ANR) to the drop box.
7968 * @param eventType to include in the drop box tag ("crash", "wtf", etc.)
7969 * @param process which caused the error, null means the system server
7970 * @param activity which triggered the error, null if unknown
7971 * @param parent activity related to the error, null if unknown
7972 * @param subject line related to the error, null if absent
7973 * @param report in long form describing the error, null if absent
7974 * @param logFile to include in the report, null if none
7975 * @param crashInfo giving an application stack trace, null if absent
7976 */
7977 public void addErrorToDropBox(String eventType,
Jeff Sharkeya353d262011-10-28 11:12:06 -07007978 ProcessRecord process, String processName, ActivityRecord activity,
7979 ActivityRecord parent, String subject,
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007980 final String report, final File logFile,
7981 final ApplicationErrorReport.CrashInfo crashInfo) {
7982 // NOTE -- this must never acquire the ActivityManagerService lock,
7983 // otherwise the watchdog may be prevented from resetting the system.
7984
7985 final String dropboxTag = processClass(process) + "_" + eventType;
7986 final DropBoxManager dbox = (DropBoxManager)
7987 mContext.getSystemService(Context.DROPBOX_SERVICE);
7988
7989 // Exit early if the dropbox isn't configured to accept this report type.
7990 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
7991
7992 final StringBuilder sb = new StringBuilder(1024);
Jeff Sharkeya353d262011-10-28 11:12:06 -07007993 appendDropBoxProcessHeaders(process, processName, sb);
Dan Egnora455d192010-03-12 08:52:28 -08007994 if (activity != null) {
7995 sb.append("Activity: ").append(activity.shortComponentName).append("\n");
7996 }
7997 if (parent != null && parent.app != null && parent.app.pid != process.pid) {
7998 sb.append("Parent-Process: ").append(parent.app.processName).append("\n");
7999 }
8000 if (parent != null && parent != activity) {
8001 sb.append("Parent-Activity: ").append(parent.shortComponentName).append("\n");
8002 }
8003 if (subject != null) {
8004 sb.append("Subject: ").append(subject).append("\n");
8005 }
8006 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
Christian Lindeberg03d2ca62010-09-28 14:52:20 +02008007 if (Debug.isDebuggerConnected()) {
8008 sb.append("Debugger: Connected\n");
8009 }
Dan Egnora455d192010-03-12 08:52:28 -08008010 sb.append("\n");
8011
8012 // Do the rest in a worker thread to avoid blocking the caller on I/O
8013 // (After this point, we shouldn't access AMS internal data structures.)
8014 Thread worker = new Thread("Error dump: " + dropboxTag) {
8015 @Override
8016 public void run() {
8017 if (report != null) {
8018 sb.append(report);
8019 }
8020 if (logFile != null) {
8021 try {
8022 sb.append(FileUtils.readTextFile(logFile, 128 * 1024, "\n\n[[TRUNCATED]]"));
8023 } catch (IOException e) {
8024 Slog.e(TAG, "Error reading " + logFile, e);
8025 }
8026 }
8027 if (crashInfo != null && crashInfo.stackTrace != null) {
8028 sb.append(crashInfo.stackTrace);
8029 }
8030
8031 String setting = Settings.Secure.ERROR_LOGCAT_PREFIX + dropboxTag;
8032 int lines = Settings.Secure.getInt(mContext.getContentResolver(), setting, 0);
8033 if (lines > 0) {
8034 sb.append("\n");
8035
8036 // Merge several logcat streams, and take the last N lines
8037 InputStreamReader input = null;
8038 try {
8039 java.lang.Process logcat = new ProcessBuilder("/system/bin/logcat",
8040 "-v", "time", "-b", "events", "-b", "system", "-b", "main",
8041 "-t", String.valueOf(lines)).redirectErrorStream(true).start();
8042
8043 try { logcat.getOutputStream().close(); } catch (IOException e) {}
8044 try { logcat.getErrorStream().close(); } catch (IOException e) {}
8045 input = new InputStreamReader(logcat.getInputStream());
8046
8047 int num;
8048 char[] buf = new char[8192];
8049 while ((num = input.read(buf)) > 0) sb.append(buf, 0, num);
8050 } catch (IOException e) {
8051 Slog.e(TAG, "Error running logcat", e);
8052 } finally {
8053 if (input != null) try { input.close(); } catch (IOException e) {}
8054 }
8055 }
8056
8057 dbox.addText(dropboxTag, sb.toString());
Dan Egnor60d87622009-12-16 16:32:58 -08008058 }
Dan Egnora455d192010-03-12 08:52:28 -08008059 };
8060
8061 if (process == null || process.pid == MY_PID) {
8062 worker.run(); // We may be about to die -- need to run this synchronously
8063 } else {
8064 worker.start();
Dan Egnor60d87622009-12-16 16:32:58 -08008065 }
8066 }
8067
8068 /**
8069 * Bring up the "unexpected error" dialog box for a crashing app.
8070 * Deal with edge cases (intercepts from instrumented applications,
8071 * ActivityController, error intent receivers, that sort of thing).
8072 * @param r the application crashing
8073 * @param crashInfo describing the failure
8074 */
8075 private void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008076 long timeMillis = System.currentTimeMillis();
8077 String shortMsg = crashInfo.exceptionClassName;
8078 String longMsg = crashInfo.exceptionMessage;
8079 String stackTrace = crashInfo.stackTrace;
8080 if (shortMsg != null && longMsg != null) {
8081 longMsg = shortMsg + ": " + longMsg;
8082 } else if (shortMsg != null) {
8083 longMsg = shortMsg;
8084 }
8085
Dan Egnor60d87622009-12-16 16:32:58 -08008086 AppErrorResult result = new AppErrorResult();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008087 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008088 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008089 try {
8090 String name = r != null ? r.processName : null;
8091 int pid = r != null ? r.pid : Binder.getCallingPid();
Dan Egnor60d87622009-12-16 16:32:58 -08008092 if (!mController.appCrashed(name, pid,
Dan Egnorb7f03672009-12-09 16:22:32 -08008093 shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008094 Slog.w(TAG, "Force-killing crashed app " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008095 + " at watcher's request");
8096 Process.killProcess(pid);
Dan Egnorb7f03672009-12-09 16:22:32 -08008097 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008098 }
8099 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008100 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008101 }
8102 }
8103
8104 final long origId = Binder.clearCallingIdentity();
8105
8106 // If this process is running instrumentation, finish it.
8107 if (r != null && r.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008108 Slog.w(TAG, "Error in app " + r.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008109 + " running instrumentation " + r.instrumentationClass + ":");
Joe Onorato8a9b2202010-02-26 18:56:32 -08008110 if (shortMsg != null) Slog.w(TAG, " " + shortMsg);
8111 if (longMsg != null) Slog.w(TAG, " " + longMsg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008112 Bundle info = new Bundle();
8113 info.putString("shortMsg", shortMsg);
8114 info.putString("longMsg", longMsg);
8115 finishInstrumentationLocked(r, Activity.RESULT_CANCELED, info);
8116 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008117 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008118 }
8119
Dan Egnor60d87622009-12-16 16:32:58 -08008120 // If we can't identify the process or it's already exceeded its crash quota,
8121 // quit right away without showing a crash dialog.
8122 if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008123 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008124 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008125 }
8126
8127 Message msg = Message.obtain();
8128 msg.what = SHOW_ERROR_MSG;
8129 HashMap data = new HashMap();
8130 data.put("result", result);
8131 data.put("app", r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008132 msg.obj = data;
8133 mHandler.sendMessage(msg);
8134
8135 Binder.restoreCallingIdentity(origId);
8136 }
8137
8138 int res = result.get();
8139
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008140 Intent appErrorIntent = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008141 synchronized (this) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008142 if (r != null && !r.isolated) {
8143 // XXX Can't keep track of crash time for isolated processes,
8144 // since they don't have a persistent identity.
8145 mProcessCrashTimes.put(r.info.processName, r.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008146 SystemClock.uptimeMillis());
8147 }
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008148 if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008149 appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008150 }
8151 }
8152
8153 if (appErrorIntent != null) {
8154 try {
8155 mContext.startActivity(appErrorIntent);
8156 } catch (ActivityNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008157 Slog.w(TAG, "bug report receiver dissappeared", e);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008158 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008159 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008160 }
Dan Egnorb7f03672009-12-09 16:22:32 -08008161
8162 Intent createAppErrorIntentLocked(ProcessRecord r,
8163 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
8164 ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008165 if (report == null) {
8166 return null;
8167 }
8168 Intent result = new Intent(Intent.ACTION_APP_ERROR);
8169 result.setComponent(r.errorReportReceiver);
8170 result.putExtra(Intent.EXTRA_BUG_REPORT, report);
8171 result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
8172 return result;
8173 }
8174
Dan Egnorb7f03672009-12-09 16:22:32 -08008175 private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r,
8176 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008177 if (r.errorReportReceiver == null) {
8178 return null;
8179 }
8180
8181 if (!r.crashing && !r.notResponding) {
8182 return null;
8183 }
8184
Dan Egnorb7f03672009-12-09 16:22:32 -08008185 ApplicationErrorReport report = new ApplicationErrorReport();
8186 report.packageName = r.info.packageName;
8187 report.installerPackageName = r.errorReportReceiver.getPackageName();
8188 report.processName = r.processName;
8189 report.time = timeMillis;
Jacek Surazskie0ee6ef2010-01-07 16:23:03 +01008190 report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008191
Dan Egnorb7f03672009-12-09 16:22:32 -08008192 if (r.crashing) {
8193 report.type = ApplicationErrorReport.TYPE_CRASH;
8194 report.crashInfo = crashInfo;
8195 } else if (r.notResponding) {
8196 report.type = ApplicationErrorReport.TYPE_ANR;
8197 report.anrInfo = new ApplicationErrorReport.AnrInfo();
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008198
Dan Egnorb7f03672009-12-09 16:22:32 -08008199 report.anrInfo.activity = r.notRespondingReport.tag;
8200 report.anrInfo.cause = r.notRespondingReport.shortMsg;
8201 report.anrInfo.info = r.notRespondingReport.longMsg;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008202 }
8203
Dan Egnorb7f03672009-12-09 16:22:32 -08008204 return report;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008205 }
8206
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008207 public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008208 enforceNotIsolatedCaller("getProcessesInErrorState");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008209 // assume our apps are happy - lazy create the list
8210 List<ActivityManager.ProcessErrorStateInfo> errList = null;
8211
8212 synchronized (this) {
8213
8214 // iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008215 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8216 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008217 if ((app.thread != null) && (app.crashing || app.notResponding)) {
8218 // This one's in trouble, so we'll generate a report for it
8219 // crashes are higher priority (in case there's a crash *and* an anr)
8220 ActivityManager.ProcessErrorStateInfo report = null;
8221 if (app.crashing) {
8222 report = app.crashingReport;
8223 } else if (app.notResponding) {
8224 report = app.notRespondingReport;
8225 }
8226
8227 if (report != null) {
8228 if (errList == null) {
8229 errList = new ArrayList<ActivityManager.ProcessErrorStateInfo>(1);
8230 }
8231 errList.add(report);
8232 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008233 Slog.w(TAG, "Missing app error report, app = " + app.processName +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008234 " crashing = " + app.crashing +
8235 " notResponding = " + app.notResponding);
8236 }
8237 }
8238 }
8239 }
8240
8241 return errList;
8242 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07008243
8244 static int oomAdjToImportance(int adj, ActivityManager.RunningAppProcessInfo currApp) {
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008245 if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008246 if (currApp != null) {
8247 currApp.lru = adj - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
8248 }
8249 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008250 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
8251 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008252 } else if (adj >= ProcessList.HOME_APP_ADJ) {
8253 if (currApp != null) {
8254 currApp.lru = 0;
8255 }
8256 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008257 } else if (adj >= ProcessList.SERVICE_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008258 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
8259 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
8260 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
8261 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
8262 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
8263 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
8264 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
8265 } else {
8266 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
8267 }
8268 }
8269
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008270 private void fillInProcMemInfo(ProcessRecord app,
8271 ActivityManager.RunningAppProcessInfo outInfo) {
8272 outInfo.pid = app.pid;
8273 outInfo.uid = app.info.uid;
8274 if (mHeavyWeightProcess == app) {
8275 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_CANT_SAVE_STATE;
8276 }
8277 if (app.persistent) {
8278 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_PERSISTENT;
8279 }
8280 outInfo.lastTrimLevel = app.trimMemoryLevel;
8281 int adj = app.curAdj;
8282 outInfo.importance = oomAdjToImportance(adj, outInfo);
8283 outInfo.importanceReasonCode = app.adjTypeCode;
8284 }
8285
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008286 public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008287 enforceNotIsolatedCaller("getRunningAppProcesses");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008288 // Lazy instantiation of list
8289 List<ActivityManager.RunningAppProcessInfo> runList = null;
8290 synchronized (this) {
8291 // Iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008292 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8293 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008294 if ((app.thread != null) && (!app.crashing && !app.notResponding)) {
8295 // Generate process state info for running application
8296 ActivityManager.RunningAppProcessInfo currApp =
8297 new ActivityManager.RunningAppProcessInfo(app.processName,
8298 app.pid, app.getPackageList());
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008299 fillInProcMemInfo(app, currApp);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008300 if (app.adjSource instanceof ProcessRecord) {
8301 currApp.importanceReasonPid = ((ProcessRecord)app.adjSource).pid;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008302 currApp.importanceReasonImportance = oomAdjToImportance(
8303 app.adjSourceOom, null);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008304 } else if (app.adjSource instanceof ActivityRecord) {
8305 ActivityRecord r = (ActivityRecord)app.adjSource;
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008306 if (r.app != null) currApp.importanceReasonPid = r.app.pid;
8307 }
8308 if (app.adjTarget instanceof ComponentName) {
8309 currApp.importanceReasonComponent = (ComponentName)app.adjTarget;
8310 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08008311 //Slog.v(TAG, "Proc " + app.processName + ": imp=" + currApp.importance
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008312 // + " lru=" + currApp.lru);
8313 if (runList == null) {
8314 runList = new ArrayList<ActivityManager.RunningAppProcessInfo>();
8315 }
8316 runList.add(currApp);
8317 }
8318 }
8319 }
8320 return runList;
8321 }
8322
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008323 public List<ApplicationInfo> getRunningExternalApplications() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008324 enforceNotIsolatedCaller("getRunningExternalApplications");
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008325 List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses();
8326 List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>();
8327 if (runningApps != null && runningApps.size() > 0) {
8328 Set<String> extList = new HashSet<String>();
8329 for (ActivityManager.RunningAppProcessInfo app : runningApps) {
8330 if (app.pkgList != null) {
8331 for (String pkg : app.pkgList) {
8332 extList.add(pkg);
8333 }
8334 }
8335 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008336 IPackageManager pm = AppGlobals.getPackageManager();
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008337 for (String pkg : extList) {
8338 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07008339 ApplicationInfo info = pm.getApplicationInfo(pkg, 0, UserId.getCallingUserId());
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008340 if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
8341 retList.add(info);
8342 }
8343 } catch (RemoteException e) {
8344 }
8345 }
8346 }
8347 return retList;
8348 }
8349
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008350 @Override
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008351 public void getMyMemoryState(ActivityManager.RunningAppProcessInfo outInfo) {
8352 enforceNotIsolatedCaller("getMyMemoryState");
8353 synchronized (this) {
8354 ProcessRecord proc;
8355 synchronized (mPidsSelfLocked) {
8356 proc = mPidsSelfLocked.get(Binder.getCallingPid());
8357 }
8358 fillInProcMemInfo(proc, outInfo);
8359 }
8360 }
8361
8362 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008363 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008364 if (checkCallingPermission(android.Manifest.permission.DUMP)
8365 != PackageManager.PERMISSION_GRANTED) {
8366 pw.println("Permission Denial: can't dump ActivityManager from from pid="
8367 + Binder.getCallingPid()
8368 + ", uid=" + Binder.getCallingUid()
8369 + " without permission "
8370 + android.Manifest.permission.DUMP);
8371 return;
8372 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008373
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008374 boolean dumpAll = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008375 boolean dumpClient = false;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008376 String dumpPackage = null;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008377
8378 int opti = 0;
8379 while (opti < args.length) {
8380 String opt = args[opti];
8381 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
8382 break;
8383 }
8384 opti++;
8385 if ("-a".equals(opt)) {
8386 dumpAll = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008387 } else if ("-c".equals(opt)) {
8388 dumpClient = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008389 } else if ("-h".equals(opt)) {
8390 pw.println("Activity manager dump options:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008391 pw.println(" [-a] [-c] [-h] [cmd] ...");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008392 pw.println(" cmd may be one of:");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008393 pw.println(" a[ctivities]: activity stack state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008394 pw.println(" b[roadcasts] [PACKAGE_NAME]: broadcast state");
8395 pw.println(" i[ntents] [PACKAGE_NAME]: pending intent state");
8396 pw.println(" p[rocesses] [PACKAGE_NAME]: process state");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008397 pw.println(" o[om]: out of memory management");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008398 pw.println(" prov[iders] [COMP_SPEC ...]: content provider state");
Marco Nelissen18cb2872011-11-15 11:19:53 -08008399 pw.println(" provider [COMP_SPEC]: provider client-side state");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008400 pw.println(" s[ervices] [COMP_SPEC ...]: service state");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008401 pw.println(" service [COMP_SPEC]: service client-side state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008402 pw.println(" package [PACKAGE_NAME]: all state related to given package");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008403 pw.println(" all: dump all activities");
8404 pw.println(" top: dump the top activity");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008405 pw.println(" cmd may also be a COMP_SPEC to dump activities.");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008406 pw.println(" COMP_SPEC may be a component name (com.foo/.myApp),");
8407 pw.println(" a partial substring in a component name, a");
8408 pw.println(" hex object identifier.");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008409 pw.println(" -a: include all available server state.");
8410 pw.println(" -c: include client state.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008411 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008412 } else {
8413 pw.println("Unknown argument: " + opt + "; use -h for help");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008414 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008415 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008416
8417 long origId = Binder.clearCallingIdentity();
8418 boolean more = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008419 // Is the caller requesting to dump a particular piece of data?
8420 if (opti < args.length) {
8421 String cmd = args[opti];
8422 opti++;
8423 if ("activities".equals(cmd) || "a".equals(cmd)) {
8424 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008425 dumpActivitiesLocked(fd, pw, args, opti, true, dumpClient, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008426 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008427 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008428 String[] newArgs;
8429 String name;
8430 if (opti >= args.length) {
8431 name = null;
8432 newArgs = EMPTY_STRING_ARRAY;
8433 } else {
8434 name = args[opti];
8435 opti++;
8436 newArgs = new String[args.length - opti];
8437 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8438 args.length - opti);
8439 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008440 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008441 dumpBroadcastsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008442 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008443 } else if ("intents".equals(cmd) || "i".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008444 String[] newArgs;
8445 String name;
8446 if (opti >= args.length) {
8447 name = null;
8448 newArgs = EMPTY_STRING_ARRAY;
8449 } else {
8450 name = args[opti];
8451 opti++;
8452 newArgs = new String[args.length - opti];
8453 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8454 args.length - opti);
8455 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008456 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008457 dumpPendingIntentsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008458 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008459 } else if ("processes".equals(cmd) || "p".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008460 String[] newArgs;
8461 String name;
8462 if (opti >= args.length) {
8463 name = null;
8464 newArgs = EMPTY_STRING_ARRAY;
8465 } else {
8466 name = args[opti];
8467 opti++;
8468 newArgs = new String[args.length - opti];
8469 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8470 args.length - opti);
8471 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008472 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008473 dumpProcessesLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008474 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008475 } else if ("oom".equals(cmd) || "o".equals(cmd)) {
8476 synchronized (this) {
8477 dumpOomLocked(fd, pw, args, opti, true);
8478 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08008479 } else if ("provider".equals(cmd)) {
8480 String[] newArgs;
8481 String name;
8482 if (opti >= args.length) {
8483 name = null;
8484 newArgs = EMPTY_STRING_ARRAY;
8485 } else {
8486 name = args[opti];
8487 opti++;
8488 newArgs = new String[args.length - opti];
8489 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
8490 }
8491 if (!dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) {
8492 pw.println("No providers match: " + name);
8493 pw.println("Use -h for help.");
8494 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008495 } else if ("providers".equals(cmd) || "prov".equals(cmd)) {
8496 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008497 dumpProvidersLocked(fd, pw, args, opti, true, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008498 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008499 } else if ("service".equals(cmd)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008500 String[] newArgs;
8501 String name;
8502 if (opti >= args.length) {
8503 name = null;
8504 newArgs = EMPTY_STRING_ARRAY;
8505 } else {
8506 name = args[opti];
8507 opti++;
8508 newArgs = new String[args.length - opti];
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008509 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8510 args.length - opti);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008511 }
8512 if (!dumpService(fd, pw, name, newArgs, 0, dumpAll)) {
8513 pw.println("No services match: " + name);
8514 pw.println("Use -h for help.");
8515 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008516 } else if ("package".equals(cmd)) {
8517 String[] newArgs;
8518 if (opti >= args.length) {
8519 pw.println("package: no package name specified");
8520 pw.println("Use -h for help.");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008521 } else {
8522 dumpPackage = args[opti];
8523 opti++;
8524 newArgs = new String[args.length - opti];
8525 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8526 args.length - opti);
8527 args = newArgs;
8528 opti = 0;
Amith Yamasani7463ada2012-04-11 15:02:39 -07008529 more = true;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008530 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008531 } else if ("services".equals(cmd) || "s".equals(cmd)) {
8532 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008533 dumpServicesLocked(fd, pw, args, opti, true, dumpClient, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008534 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07008535 } else {
8536 // Dumping a single activity?
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008537 if (!dumpActivity(fd, pw, cmd, args, opti, dumpAll)) {
8538 pw.println("Bad activity command, or no activities match: " + cmd);
8539 pw.println("Use -h for help.");
Dianne Hackborn625ac272010-09-17 18:29:22 -07008540 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008541 }
8542 if (!more) {
8543 Binder.restoreCallingIdentity(origId);
Dianne Hackborn30d71892010-12-11 10:37:55 -08008544 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008545 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008546 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008547
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008548 // No piece of data specified, dump everything.
8549 synchronized (this) {
8550 boolean needSep;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008551 needSep = dumpPendingIntentsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008552 if (needSep) {
8553 pw.println(" ");
8554 }
8555 if (dumpAll) {
8556 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008557 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008558 needSep = dumpBroadcastsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008559 if (needSep) {
8560 pw.println(" ");
8561 }
8562 if (dumpAll) {
8563 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008564 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008565 needSep = dumpProvidersLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008566 if (needSep) {
8567 pw.println(" ");
8568 }
8569 if (dumpAll) {
8570 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008571 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008572 needSep = dumpServicesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008573 if (needSep) {
8574 pw.println(" ");
8575 }
8576 if (dumpAll) {
8577 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008578 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008579 needSep = dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008580 if (needSep) {
8581 pw.println(" ");
8582 }
8583 if (dumpAll) {
8584 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008585 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008586 dumpProcessesLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008587 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008588 Binder.restoreCallingIdentity(origId);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008589 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008590
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008591 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008592 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008593 pw.println("ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
8594 pw.println(" Main stack:");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008595 dumpHistoryList(fd, pw, mMainStack.mHistory, " ", "Hist", true, !dumpAll, dumpClient,
8596 dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008597 pw.println(" ");
8598 pw.println(" Running activities (most recent first):");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008599 dumpHistoryList(fd, pw, mMainStack.mLRUActivities, " ", "Run", false, !dumpAll, false,
8600 dumpPackage);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008601 if (mMainStack.mWaitingVisibleActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008602 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008603 pw.println(" Activities waiting for another to become visible:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008604 dumpHistoryList(fd, pw, mMainStack.mWaitingVisibleActivities, " ", "Wait", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008605 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008606 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008607 if (mMainStack.mStoppingActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008608 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008609 pw.println(" Activities waiting to stop:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008610 dumpHistoryList(fd, pw, mMainStack.mStoppingActivities, " ", "Stop", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008611 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008612 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008613 if (mMainStack.mGoingToSleepActivities.size() > 0) {
8614 pw.println(" ");
8615 pw.println(" Activities waiting to sleep:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008616 dumpHistoryList(fd, pw, mMainStack.mGoingToSleepActivities, " ", "Sleep", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008617 !dumpAll, false, dumpPackage);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008618 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008619 if (mMainStack.mFinishingActivities.size() > 0) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008620 pw.println(" ");
8621 pw.println(" Activities waiting to finish:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008622 dumpHistoryList(fd, pw, mMainStack.mFinishingActivities, " ", "Fin", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008623 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008624 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008625
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008626 pw.println(" ");
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08008627 if (mMainStack.mPausingActivity != null) {
8628 pw.println(" mPausingActivity: " + mMainStack.mPausingActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008629 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008630 pw.println(" mResumedActivity: " + mMainStack.mResumedActivity);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008631 pw.println(" mFocusedActivity: " + mFocusedActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008632 if (dumpAll) {
8633 pw.println(" mLastPausedActivity: " + mMainStack.mLastPausedActivity);
8634 pw.println(" mSleepTimeout: " + mMainStack.mSleepTimeout);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07008635 pw.println(" mDismissKeyguardOnNextActivity: "
8636 + mMainStack.mDismissKeyguardOnNextActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008637 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008638
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008639 if (mRecentTasks.size() > 0) {
8640 pw.println();
8641 pw.println(" Recent tasks:");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008642
8643 final int N = mRecentTasks.size();
8644 for (int i=0; i<N; i++) {
8645 TaskRecord tr = mRecentTasks.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008646 if (dumpPackage != null) {
8647 if (tr.realActivity == null ||
8648 !dumpPackage.equals(tr.realActivity)) {
8649 continue;
8650 }
8651 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008652 pw.print(" * Recent #"); pw.print(i); pw.print(": ");
8653 pw.println(tr);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008654 if (dumpAll) {
8655 mRecentTasks.get(i).dump(pw, " ");
8656 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008657 }
8658 }
8659
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008660 if (dumpAll) {
8661 pw.println(" ");
8662 pw.println(" mCurTask: " + mCurTask);
8663 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008664
8665 return true;
8666 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008667
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008668 boolean dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008669 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008670 boolean needSep = false;
8671 int numPers = 0;
8672
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008673 pw.println("ACTIVITY MANAGER RUNNING PROCESSES (dumpsys activity processes)");
8674
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008675 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008676 for (SparseArray<ProcessRecord> procs : mProcessNames.getMap().values()) {
8677 final int NA = procs.size();
8678 for (int ia=0; ia<NA; ia++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008679 ProcessRecord r = procs.valueAt(ia);
8680 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8681 continue;
8682 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008683 if (!needSep) {
8684 pw.println(" All known processes:");
8685 needSep = true;
8686 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008687 pw.print(r.persistent ? " *PERS*" : " *APP*");
8688 pw.print(" UID "); pw.print(procs.keyAt(ia));
8689 pw.print(" "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008690 r.dump(pw, " ");
8691 if (r.persistent) {
8692 numPers++;
8693 }
8694 }
8695 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008696 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008697
8698 if (mIsolatedProcesses.size() > 0) {
8699 if (needSep) pw.println(" ");
8700 needSep = true;
8701 pw.println(" Isolated process list (sorted by uid):");
8702 for (int i=0; i<mIsolatedProcesses.size(); i++) {
8703 ProcessRecord r = mIsolatedProcesses.valueAt(i);
8704 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8705 continue;
8706 }
8707 pw.println(String.format("%sIsolated #%2d: %s",
8708 " ", i, r.toString()));
8709 }
8710 }
8711
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008712 if (mLruProcesses.size() > 0) {
8713 if (needSep) pw.println(" ");
8714 needSep = true;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008715 pw.println(" Process LRU list (sorted by oom_adj):");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008716 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008717 "Proc", "PERS", false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008718 needSep = true;
8719 }
8720
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008721 if (dumpAll) {
8722 synchronized (mPidsSelfLocked) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008723 boolean printed = false;
8724 for (int i=0; i<mPidsSelfLocked.size(); i++) {
8725 ProcessRecord r = mPidsSelfLocked.valueAt(i);
8726 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8727 continue;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008728 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008729 if (!printed) {
8730 if (needSep) pw.println(" ");
8731 needSep = true;
8732 pw.println(" PID mappings:");
8733 printed = true;
8734 }
8735 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i));
8736 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008737 }
8738 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008739 }
8740
8741 if (mForegroundProcesses.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008742 synchronized (mPidsSelfLocked) {
8743 boolean printed = false;
8744 for (int i=0; i<mForegroundProcesses.size(); i++) {
8745 ProcessRecord r = mPidsSelfLocked.get(
8746 mForegroundProcesses.valueAt(i).pid);
8747 if (dumpPackage != null && (r == null
8748 || !dumpPackage.equals(r.info.packageName))) {
8749 continue;
8750 }
8751 if (!printed) {
8752 if (needSep) pw.println(" ");
8753 needSep = true;
8754 pw.println(" Foreground Processes:");
8755 printed = true;
8756 }
8757 pw.print(" PID #"); pw.print(mForegroundProcesses.keyAt(i));
8758 pw.print(": "); pw.println(mForegroundProcesses.valueAt(i));
8759 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008760 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008761 }
8762
8763 if (mPersistentStartingProcesses.size() > 0) {
8764 if (needSep) pw.println(" ");
8765 needSep = true;
8766 pw.println(" Persisent processes that are starting:");
8767 dumpProcessList(pw, this, mPersistentStartingProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008768 "Starting Norm", "Restarting PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008769 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008770
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008771 if (mRemovedProcesses.size() > 0) {
8772 if (needSep) pw.println(" ");
8773 needSep = true;
8774 pw.println(" Processes that are being removed:");
8775 dumpProcessList(pw, this, mRemovedProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008776 "Removed Norm", "Removed PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008777 }
8778
8779 if (mProcessesOnHold.size() > 0) {
8780 if (needSep) pw.println(" ");
8781 needSep = true;
8782 pw.println(" Processes that are on old until the system is ready:");
8783 dumpProcessList(pw, this, mProcessesOnHold, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008784 "OnHold Norm", "OnHold PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008785 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008786
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008787 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008788
8789 if (mProcessCrashTimes.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008790 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008791 long now = SystemClock.uptimeMillis();
8792 for (Map.Entry<String, SparseArray<Long>> procs
8793 : mProcessCrashTimes.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008794 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008795 SparseArray<Long> uids = procs.getValue();
8796 final int N = uids.size();
8797 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008798 int puid = uids.keyAt(i);
8799 ProcessRecord r = mProcessNames.get(pname, puid);
8800 if (dumpPackage != null && (r == null
8801 || !dumpPackage.equals(r.info.packageName))) {
8802 continue;
8803 }
8804 if (!printed) {
8805 if (needSep) pw.println(" ");
8806 needSep = true;
8807 pw.println(" Time since processes crashed:");
8808 printed = true;
8809 }
8810 pw.print(" Process "); pw.print(pname);
8811 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008812 pw.print(": last crashed ");
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008813 TimeUtils.formatDuration(now-uids.valueAt(i), pw);
8814 pw.println(" ago");
Dianne Hackbornfd12af42009-08-27 00:44:33 -07008815 }
8816 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008817 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008818
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008819 if (mBadProcesses.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008820 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008821 for (Map.Entry<String, SparseArray<Long>> procs
8822 : mBadProcesses.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008823 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008824 SparseArray<Long> uids = procs.getValue();
8825 final int N = uids.size();
8826 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008827 int puid = uids.keyAt(i);
8828 ProcessRecord r = mProcessNames.get(pname, puid);
8829 if (dumpPackage != null && (r == null
8830 || !dumpPackage.equals(r.info.packageName))) {
8831 continue;
8832 }
8833 if (!printed) {
8834 if (needSep) pw.println(" ");
8835 needSep = true;
8836 pw.println(" Bad processes:");
8837 }
8838 pw.print(" Bad process "); pw.print(pname);
8839 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008840 pw.print(": crashed at time ");
8841 pw.println(uids.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008842 }
8843 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008844 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008845
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008846 pw.println();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008847 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07008848 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn50685602011-12-01 12:23:37 -08008849 if (dumpAll) {
8850 StringBuilder sb = new StringBuilder(128);
8851 sb.append(" mPreviousProcessVisibleTime: ");
8852 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
8853 pw.println(sb);
8854 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07008855 if (mHeavyWeightProcess != null) {
8856 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
8857 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008858 pw.println(" mConfiguration: " + mConfiguration);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008859 if (dumpAll) {
8860 pw.println(" mConfigWillChange: " + mMainStack.mConfigWillChange);
Dianne Hackborn3d0724d2011-05-12 15:39:41 -07008861 if (mCompatModePackages.getPackages().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008862 boolean printed = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07008863 for (Map.Entry<String, Integer> entry
8864 : mCompatModePackages.getPackages().entrySet()) {
8865 String pkg = entry.getKey();
8866 int mode = entry.getValue();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008867 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
8868 continue;
8869 }
8870 if (!printed) {
8871 pw.println(" mScreenCompatPackages:");
8872 printed = true;
8873 }
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07008874 pw.print(" "); pw.print(pkg); pw.print(": ");
8875 pw.print(mode); pw.println();
8876 }
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07008877 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008878 }
Dianne Hackbornff5b1582012-04-12 17:24:07 -07008879 if (mSleeping || mWentToSleep || mLockScreenShown) {
8880 pw.println(" mSleeping=" + mSleeping + " mWentToSleep=" + mWentToSleep
8881 + " mLockScreenShown " + mLockScreenShown);
8882 }
8883 if (mShuttingDown) {
8884 pw.println(" mShuttingDown=" + mShuttingDown);
8885 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008886 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
8887 || mOrigWaitForDebugger) {
8888 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp
8889 + " mDebugTransient=" + mDebugTransient
8890 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger);
8891 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08008892 if (mOpenGlTraceApp != null) {
8893 pw.println(" mOpenGlTraceApp=" + mOpenGlTraceApp);
8894 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07008895 if (mProfileApp != null || mProfileProc != null || mProfileFile != null
8896 || mProfileFd != null) {
8897 pw.println(" mProfileApp=" + mProfileApp + " mProfileProc=" + mProfileProc);
8898 pw.println(" mProfileFile=" + mProfileFile + " mProfileFd=" + mProfileFd);
8899 pw.println(" mProfileType=" + mProfileType + " mAutoStopProfiler="
8900 + mAutoStopProfiler);
8901 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008902 if (mAlwaysFinishActivities || mController != null) {
8903 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities
8904 + " mController=" + mController);
8905 }
8906 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008907 pw.println(" Total persistent processes: " + numPers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008908 pw.println(" mStartRunning=" + mStartRunning
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07008909 + " mProcessesReady=" + mProcessesReady
8910 + " mSystemReady=" + mSystemReady);
8911 pw.println(" mBooting=" + mBooting
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008912 + " mBooted=" + mBooted
8913 + " mFactoryTest=" + mFactoryTest);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008914 pw.print(" mLastPowerCheckRealtime=");
8915 TimeUtils.formatDuration(mLastPowerCheckRealtime, pw);
8916 pw.println("");
8917 pw.print(" mLastPowerCheckUptime=");
8918 TimeUtils.formatDuration(mLastPowerCheckUptime, pw);
8919 pw.println("");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008920 pw.println(" mGoingToSleep=" + mMainStack.mGoingToSleep);
8921 pw.println(" mLaunchingActivity=" + mMainStack.mLaunchingActivity);
Dianne Hackborn906497c2010-05-10 15:57:38 -07008922 pw.println(" mAdjSeq=" + mAdjSeq + " mLruSeq=" + mLruSeq);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008923 pw.println(" mNumServiceProcs=" + mNumServiceProcs
8924 + " mNewNumServiceProcs=" + mNewNumServiceProcs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008925 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008926
8927 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008928 }
8929
Dianne Hackborn287952c2010-09-22 22:34:31 -07008930 boolean dumpProcessesToGc(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008931 int opti, boolean needSep, boolean dumpAll, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07008932 if (mProcessesToGc.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008933 boolean printed = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -07008934 long now = SystemClock.uptimeMillis();
8935 for (int i=0; i<mProcessesToGc.size(); i++) {
8936 ProcessRecord proc = mProcessesToGc.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008937 if (dumpPackage != null && !dumpPackage.equals(proc.info.packageName)) {
8938 continue;
8939 }
8940 if (!printed) {
8941 if (needSep) pw.println(" ");
8942 needSep = true;
8943 pw.println(" Processes that are waiting to GC:");
8944 printed = true;
8945 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008946 pw.print(" Process "); pw.println(proc);
8947 pw.print(" lowMem="); pw.print(proc.reportLowMemory);
8948 pw.print(", last gced=");
8949 pw.print(now-proc.lastRequestedGc);
8950 pw.print(" ms ago, last lowMem=");
8951 pw.print(now-proc.lastLowMemory);
8952 pw.println(" ms ago");
8953
8954 }
8955 }
8956 return needSep;
8957 }
8958
8959 boolean dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args,
8960 int opti, boolean dumpAll) {
8961 boolean needSep = false;
8962
8963 if (mLruProcesses.size() > 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07008964 if (needSep) pw.println(" ");
8965 needSep = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -07008966 pw.println(" OOM levels:");
Dianne Hackborn7d608422011-08-07 16:24:18 -07008967 pw.print(" SYSTEM_ADJ: "); pw.println(ProcessList.SYSTEM_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008968 pw.print(" PERSISTENT_PROC_ADJ: "); pw.println(ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07008969 pw.print(" FOREGROUND_APP_ADJ: "); pw.println(ProcessList.FOREGROUND_APP_ADJ);
8970 pw.print(" VISIBLE_APP_ADJ: "); pw.println(ProcessList.VISIBLE_APP_ADJ);
8971 pw.print(" PERCEPTIBLE_APP_ADJ: "); pw.println(ProcessList.PERCEPTIBLE_APP_ADJ);
8972 pw.print(" HEAVY_WEIGHT_APP_ADJ: "); pw.println(ProcessList.HEAVY_WEIGHT_APP_ADJ);
8973 pw.print(" BACKUP_APP_ADJ: "); pw.println(ProcessList.BACKUP_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008974 pw.print(" SERVICE_ADJ: "); pw.println(ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07008975 pw.print(" HOME_APP_ADJ: "); pw.println(ProcessList.HOME_APP_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07008976 pw.print(" PREVIOUS_APP_ADJ: "); pw.println(ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008977 pw.print(" SERVICE_B_ADJ: "); pw.println(ProcessList.SERVICE_B_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07008978 pw.print(" HIDDEN_APP_MIN_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008979 pw.print(" HIDDEN_APP_MAX_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MAX_ADJ);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07008980
8981 if (needSep) pw.println(" ");
8982 needSep = true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07008983 pw.println(" Process OOM control:");
Dianne Hackborn905577f2011-09-07 18:31:28 -07008984 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008985 "Proc", "PERS", true, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008986 needSep = true;
8987 }
8988
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008989 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008990
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008991 pw.println();
Dianne Hackborn287952c2010-09-22 22:34:31 -07008992 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07008993 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008994 if (mHeavyWeightProcess != null) {
8995 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
8996 }
8997
8998 return true;
8999 }
9000
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009001 /**
9002 * There are three ways to call this:
9003 * - no service specified: dump all the services
9004 * - a flattened component name that matched an existing service was specified as the
9005 * first arg: dump that one service
9006 * - the first arg isn't the flattened component name of an existing service:
9007 * dump all services whose component contains the first arg as a substring
9008 */
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009009 protected boolean dumpService(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9010 int opti, boolean dumpAll) {
9011 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009012
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009013 if ("all".equals(name)) {
Dianne Hackborn14bfa392010-07-24 19:58:06 -07009014 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07009015 try {
9016 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
9017 for (UserInfo user : users) {
9018 for (ServiceRecord r1 : mServiceMap.getAllServices(user.id)) {
9019 services.add(r1);
9020 }
9021 }
9022 } catch (RemoteException re) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009023 }
9024 }
9025 } else {
9026 ComponentName componentName = name != null
9027 ? ComponentName.unflattenFromString(name) : null;
9028 int objectId = 0;
9029 if (componentName == null) {
9030 // Not a '/' separated full component name; maybe an object ID?
9031 try {
9032 objectId = Integer.parseInt(name, 16);
9033 name = null;
9034 componentName = null;
9035 } catch (RuntimeException e) {
9036 }
9037 }
9038
9039 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07009040 try {
9041 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
9042 for (UserInfo user : users) {
9043 for (ServiceRecord r1 : mServiceMap.getAllServices(user.id)) {
9044 if (componentName != null) {
9045 if (r1.name.equals(componentName)) {
9046 services.add(r1);
9047 }
9048 } else if (name != null) {
9049 if (r1.name.flattenToString().contains(name)) {
9050 services.add(r1);
9051 }
9052 } else if (System.identityHashCode(r1) == objectId) {
9053 services.add(r1);
9054 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009055 }
Dianne Hackborn14bfa392010-07-24 19:58:06 -07009056 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009057 } catch (RemoteException re) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009058 }
9059 }
9060 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009061
9062 if (services.size() <= 0) {
9063 return false;
9064 }
9065
9066 boolean needSep = false;
9067 for (int i=0; i<services.size(); i++) {
9068 if (needSep) {
9069 pw.println();
9070 }
9071 needSep = true;
9072 dumpService("", fd, pw, services.get(i), args, dumpAll);
9073 }
9074 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009075 }
9076
9077 /**
9078 * Invokes IApplicationThread.dumpService() on the thread of the specified service if
9079 * there is a thread associated with the service.
9080 */
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009081 private void dumpService(String prefix, FileDescriptor fd, PrintWriter pw,
9082 final ServiceRecord r, String[] args, boolean dumpAll) {
9083 String innerPrefix = prefix + " ";
9084 synchronized (this) {
9085 pw.print(prefix); pw.print("SERVICE ");
9086 pw.print(r.shortName); pw.print(" ");
9087 pw.print(Integer.toHexString(System.identityHashCode(r)));
9088 pw.print(" pid=");
9089 if (r.app != null) pw.println(r.app.pid);
9090 else pw.println("(not running)");
9091 if (dumpAll) {
9092 r.dump(pw, innerPrefix);
9093 }
9094 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009095 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009096 pw.print(prefix); pw.println(" Client:");
9097 pw.flush();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009098 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009099 TransferPipe tp = new TransferPipe();
9100 try {
9101 r.app.thread.dumpService(tp.getWriteFd().getFileDescriptor(), r, args);
9102 tp.setBufferPrefix(prefix + " ");
9103 tp.go(fd);
9104 } finally {
9105 tp.kill();
9106 }
9107 } catch (IOException e) {
9108 pw.println(prefix + " Failure while dumping the service: " + e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009109 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009110 pw.println(prefix + " Got a RemoteException while dumping the service");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009111 }
9112 }
9113 }
9114
Marco Nelissen18cb2872011-11-15 11:19:53 -08009115 /**
9116 * There are three ways to call this:
9117 * - no provider specified: dump all the providers
9118 * - a flattened component name that matched an existing provider was specified as the
9119 * first arg: dump that one provider
9120 * - the first arg isn't the flattened component name of an existing provider:
9121 * dump all providers whose component contains the first arg as a substring
9122 */
9123 protected boolean dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9124 int opti, boolean dumpAll) {
Marco Nelissende7408c2012-02-08 14:57:38 -08009125 return mProviderMap.dumpProvider(fd, pw, name, args, opti, dumpAll);
Marco Nelissen18cb2872011-11-15 11:19:53 -08009126 }
9127
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009128 static class ItemMatcher {
9129 ArrayList<ComponentName> components;
9130 ArrayList<String> strings;
9131 ArrayList<Integer> objects;
9132 boolean all;
9133
9134 ItemMatcher() {
9135 all = true;
9136 }
9137
9138 void build(String name) {
9139 ComponentName componentName = ComponentName.unflattenFromString(name);
9140 if (componentName != null) {
9141 if (components == null) {
9142 components = new ArrayList<ComponentName>();
9143 }
9144 components.add(componentName);
9145 all = false;
9146 } else {
9147 int objectId = 0;
9148 // Not a '/' separated full component name; maybe an object ID?
9149 try {
9150 objectId = Integer.parseInt(name, 16);
9151 if (objects == null) {
9152 objects = new ArrayList<Integer>();
9153 }
9154 objects.add(objectId);
9155 all = false;
9156 } catch (RuntimeException e) {
9157 // Not an integer; just do string match.
9158 if (strings == null) {
9159 strings = new ArrayList<String>();
9160 }
9161 strings.add(name);
9162 all = false;
9163 }
9164 }
9165 }
9166
9167 int build(String[] args, int opti) {
9168 for (; opti<args.length; opti++) {
9169 String name = args[opti];
9170 if ("--".equals(name)) {
9171 return opti+1;
9172 }
9173 build(name);
9174 }
9175 return opti;
9176 }
9177
9178 boolean match(Object object, ComponentName comp) {
9179 if (all) {
9180 return true;
9181 }
9182 if (components != null) {
9183 for (int i=0; i<components.size(); i++) {
9184 if (components.get(i).equals(comp)) {
9185 return true;
9186 }
9187 }
9188 }
9189 if (objects != null) {
9190 for (int i=0; i<objects.size(); i++) {
9191 if (System.identityHashCode(object) == objects.get(i)) {
9192 return true;
9193 }
9194 }
9195 }
9196 if (strings != null) {
9197 String flat = comp.flattenToString();
9198 for (int i=0; i<strings.size(); i++) {
9199 if (flat.contains(strings.get(i))) {
9200 return true;
9201 }
9202 }
9203 }
9204 return false;
9205 }
9206 }
9207
Dianne Hackborn625ac272010-09-17 18:29:22 -07009208 /**
9209 * There are three things that cmd can be:
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009210 * - a flattened component name that matches an existing activity
Dianne Hackborn625ac272010-09-17 18:29:22 -07009211 * - the cmd arg isn't the flattened component name of an existing activity:
9212 * dump all activity whose component contains the cmd as a substring
9213 * - A hex number of the ActivityRecord object instance.
9214 */
9215 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9216 int opti, boolean dumpAll) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009217 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009218
9219 if ("all".equals(name)) {
9220 synchronized (this) {
9221 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009222 activities.add(r1);
9223 }
9224 }
Dianne Hackbornf9302322011-06-14 18:36:14 -07009225 } else if ("top".equals(name)) {
9226 synchronized (this) {
9227 final int N = mMainStack.mHistory.size();
9228 if (N > 0) {
9229 activities.add((ActivityRecord)mMainStack.mHistory.get(N-1));
9230 }
9231 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009232 } else {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009233 ItemMatcher matcher = new ItemMatcher();
9234 matcher.build(name);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009235
9236 synchronized (this) {
9237 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009238 if (matcher.match(r1, r1.intent.getComponent())) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009239 activities.add(r1);
9240 }
9241 }
9242 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009243 }
9244
9245 if (activities.size() <= 0) {
9246 return false;
9247 }
9248
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009249 String[] newArgs = new String[args.length - opti];
9250 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
9251
Dianne Hackborn30d71892010-12-11 10:37:55 -08009252 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009253 boolean needSep = false;
Dianne Hackborn30d71892010-12-11 10:37:55 -08009254 for (int i=activities.size()-1; i>=0; i--) {
9255 ActivityRecord r = (ActivityRecord)activities.get(i);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009256 if (needSep) {
9257 pw.println();
9258 }
9259 needSep = true;
9260 synchronized (this) {
9261 if (lastTask != r.task) {
9262 lastTask = r.task;
9263 pw.print("TASK "); pw.print(lastTask.affinity);
9264 pw.print(" id="); pw.println(lastTask.taskId);
9265 if (dumpAll) {
9266 lastTask.dump(pw, " ");
9267 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08009268 }
9269 }
9270 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009271 }
9272 return true;
9273 }
9274
9275 /**
9276 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
9277 * there is a thread associated with the activity.
9278 */
Dianne Hackborn30d71892010-12-11 10:37:55 -08009279 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009280 final ActivityRecord r, String[] args, boolean dumpAll) {
9281 String innerPrefix = prefix + " ";
Dianne Hackborn30d71892010-12-11 10:37:55 -08009282 synchronized (this) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009283 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
9284 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
9285 pw.print(" pid=");
Dianne Hackborn30d71892010-12-11 10:37:55 -08009286 if (r.app != null) pw.println(r.app.pid);
9287 else pw.println("(not running)");
9288 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009289 r.dump(pw, innerPrefix);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009290 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009291 }
9292 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009293 // flush anything that is already in the PrintWriter since the thread is going
9294 // to write to the file descriptor directly
9295 pw.flush();
Dianne Hackborn625ac272010-09-17 18:29:22 -07009296 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009297 TransferPipe tp = new TransferPipe();
9298 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009299 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9300 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009301 tp.go(fd);
9302 } finally {
9303 tp.kill();
9304 }
9305 } catch (IOException e) {
9306 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009307 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009308 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
Dianne Hackborn625ac272010-09-17 18:29:22 -07009309 }
9310 }
9311 }
9312
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009313 boolean dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009314 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009315 boolean needSep = false;
9316
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009317 pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009318 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009319 if (mRegisteredReceivers.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009320 boolean printed = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009321 Iterator it = mRegisteredReceivers.values().iterator();
9322 while (it.hasNext()) {
9323 ReceiverList r = (ReceiverList)it.next();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009324 if (dumpPackage != null && (r.app == null ||
9325 !dumpPackage.equals(r.app.info.packageName))) {
9326 continue;
9327 }
9328 if (!printed) {
9329 pw.println(" Registered Receivers:");
9330 needSep = true;
9331 printed = true;
9332 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009333 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009334 r.dump(pw, " ");
9335 }
9336 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009337
9338 if (mReceiverResolver.dump(pw, needSep ?
9339 "\n Receiver Resolver Table:" : " Receiver Resolver Table:",
9340 " ", dumpPackage, false)) {
9341 needSep = true;
9342 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009343 }
Christopher Tatef46723b2012-01-26 14:19:24 -08009344
9345 for (BroadcastQueue q : mBroadcastQueues) {
9346 needSep = q.dumpLocked(fd, pw, args, opti, dumpAll, dumpPackage, needSep);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009347 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009348
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009349 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009350
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009351 if (mStickyBroadcasts != null && dumpPackage == null) {
9352 if (needSep) {
9353 pw.println();
9354 }
9355 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009356 pw.println(" Sticky broadcasts:");
9357 StringBuilder sb = new StringBuilder(128);
9358 for (Map.Entry<String, ArrayList<Intent>> ent
9359 : mStickyBroadcasts.entrySet()) {
9360 pw.print(" * Sticky action "); pw.print(ent.getKey());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009361 if (dumpAll) {
9362 pw.println(":");
9363 ArrayList<Intent> intents = ent.getValue();
9364 final int N = intents.size();
9365 for (int i=0; i<N; i++) {
9366 sb.setLength(0);
9367 sb.append(" Intent: ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009368 intents.get(i).toShortString(sb, false, true, false, false);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009369 pw.println(sb.toString());
9370 Bundle bundle = intents.get(i).getExtras();
9371 if (bundle != null) {
9372 pw.print(" ");
9373 pw.println(bundle.toString());
9374 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009375 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009376 } else {
9377 pw.println("");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009378 }
9379 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009380 needSep = true;
9381 }
9382
9383 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009384 pw.println();
Christopher Tatef46723b2012-01-26 14:19:24 -08009385 for (BroadcastQueue queue : mBroadcastQueues) {
9386 pw.println(" mBroadcastsScheduled [" + queue.mQueueName + "]="
9387 + queue.mBroadcastsScheduled);
9388 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009389 pw.println(" mHandler:");
9390 mHandler.dump(new PrintWriterPrinter(pw), " ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009391 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009392 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009393
9394 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009395 }
9396
Marco Nelissen18cb2872011-11-15 11:19:53 -08009397 /**
9398 * Prints a list of ServiceRecords (dumpsys activity services)
9399 */
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009400 boolean dumpServicesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009401 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009402 boolean needSep = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009403
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009404 ItemMatcher matcher = new ItemMatcher();
9405 matcher.build(args, opti);
9406
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009407 pw.println("ACTIVITY MANAGER SERVICES (dumpsys activity services)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009408 try {
9409 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
9410 for (UserInfo user : users) {
9411 if (mServiceMap.getAllServices(user.id).size() > 0) {
9412 boolean printed = false;
9413 long nowReal = SystemClock.elapsedRealtime();
9414 Iterator<ServiceRecord> it = mServiceMap.getAllServices(
9415 user.id).iterator();
9416 needSep = false;
9417 while (it.hasNext()) {
9418 ServiceRecord r = it.next();
9419 if (!matcher.match(r, r.name)) {
9420 continue;
9421 }
9422 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9423 continue;
9424 }
9425 if (!printed) {
9426 pw.println(" Active services:");
9427 printed = true;
9428 }
9429 if (needSep) {
9430 pw.println();
9431 }
9432 pw.print(" * ");
9433 pw.println(r);
9434 if (dumpAll) {
9435 r.dump(pw, " ");
9436 needSep = true;
9437 } else {
9438 pw.print(" app=");
9439 pw.println(r.app);
9440 pw.print(" created=");
9441 TimeUtils.formatDuration(r.createTime, nowReal, pw);
9442 pw.print(" started=");
9443 pw.print(r.startRequested);
9444 pw.print(" connections=");
9445 pw.println(r.connections.size());
9446 if (r.connections.size() > 0) {
9447 pw.println(" Connections:");
9448 for (ArrayList<ConnectionRecord> clist : r.connections.values()) {
9449 for (int i = 0; i < clist.size(); i++) {
9450 ConnectionRecord conn = clist.get(i);
9451 pw.print(" ");
9452 pw.print(conn.binding.intent.intent.getIntent()
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009453 .toShortString(false, false, false, false));
Amith Yamasani742a6712011-05-04 14:49:28 -07009454 pw.print(" -> ");
9455 ProcessRecord proc = conn.binding.client;
9456 pw.println(proc != null ? proc.toShortString() : "null");
9457 }
9458 }
Dianne Hackborn8ec8d412011-11-14 18:27:24 -08009459 }
9460 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009461 if (dumpClient && r.app != null && r.app.thread != null) {
9462 pw.println(" Client:");
9463 pw.flush();
9464 try {
9465 TransferPipe tp = new TransferPipe();
9466 try {
9467 r.app.thread.dumpService(tp.getWriteFd().getFileDescriptor(),
9468 r, args);
9469 tp.setBufferPrefix(" ");
9470 // Short timeout, since blocking here can
9471 // deadlock with the application.
9472 tp.go(fd, 2000);
9473 } finally {
9474 tp.kill();
9475 }
9476 } catch (IOException e) {
9477 pw.println(" Failure while dumping the service: " + e);
9478 } catch (RemoteException e) {
9479 pw.println(" Got a RemoteException while dumping the service");
9480 }
9481 needSep = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009482 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009483 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009484 needSep = printed;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009485 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009486 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009487 } catch (RemoteException re) {
9488
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009489 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009490
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009491 if (mPendingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009492 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009493 for (int i=0; i<mPendingServices.size(); i++) {
9494 ServiceRecord r = mPendingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009495 if (!matcher.match(r, r.name)) {
9496 continue;
9497 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009498 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9499 continue;
9500 }
9501 if (!printed) {
9502 if (needSep) pw.println(" ");
9503 needSep = true;
9504 pw.println(" Pending services:");
9505 printed = true;
9506 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009507 pw.print(" * Pending "); pw.println(r);
9508 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009509 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009510 needSep = true;
9511 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009512
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009513 if (mRestartingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009514 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009515 for (int i=0; i<mRestartingServices.size(); i++) {
9516 ServiceRecord r = mRestartingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009517 if (!matcher.match(r, r.name)) {
9518 continue;
9519 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009520 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9521 continue;
9522 }
9523 if (!printed) {
9524 if (needSep) pw.println(" ");
9525 needSep = true;
9526 pw.println(" Restarting services:");
9527 printed = true;
9528 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009529 pw.print(" * Restarting "); pw.println(r);
9530 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009531 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009532 needSep = true;
9533 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009534
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009535 if (mStoppingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009536 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009537 for (int i=0; i<mStoppingServices.size(); i++) {
9538 ServiceRecord r = mStoppingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009539 if (!matcher.match(r, r.name)) {
9540 continue;
9541 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009542 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9543 continue;
9544 }
9545 if (!printed) {
9546 if (needSep) pw.println(" ");
9547 needSep = true;
9548 pw.println(" Stopping services:");
9549 printed = true;
9550 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009551 pw.print(" * Stopping "); pw.println(r);
9552 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009553 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009554 needSep = true;
9555 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009556
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009557 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009558 if (mServiceConnections.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009559 boolean printed = false;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009560 Iterator<ArrayList<ConnectionRecord>> it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009561 = mServiceConnections.values().iterator();
9562 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009563 ArrayList<ConnectionRecord> r = it.next();
9564 for (int i=0; i<r.size(); i++) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009565 ConnectionRecord cr = r.get(i);
9566 if (!matcher.match(cr.binding.service, cr.binding.service.name)) {
9567 continue;
9568 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009569 if (dumpPackage != null && (cr.binding.client == null
9570 || !dumpPackage.equals(cr.binding.client.info.packageName))) {
9571 continue;
9572 }
9573 if (!printed) {
9574 if (needSep) pw.println(" ");
9575 needSep = true;
9576 pw.println(" Connection bindings to services:");
9577 printed = true;
9578 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009579 pw.print(" * "); pw.println(cr);
9580 cr.dump(pw, " ");
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009581 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009582 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009583 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009584 }
9585 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009586
9587 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009588 }
9589
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009590 boolean dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009591 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07009592 boolean needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009593
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009594 ItemMatcher matcher = new ItemMatcher();
9595 matcher.build(args, opti);
9596
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009597 pw.println("ACTIVITY MANAGER CONTENT PROVIDERS (dumpsys activity providers)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009598
9599 mProviderMap.dumpProvidersLocked(pw, dumpAll);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009600
9601 if (mLaunchingProviders.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009602 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009603 for (int i=mLaunchingProviders.size()-1; i>=0; i--) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009604 ContentProviderRecord r = mLaunchingProviders.get(i);
9605 if (dumpPackage != null && !dumpPackage.equals(r.name.getPackageName())) {
9606 continue;
9607 }
9608 if (!printed) {
9609 if (needSep) pw.println(" ");
9610 needSep = true;
9611 pw.println(" Launching content providers:");
9612 printed = true;
9613 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009614 pw.print(" Launching #"); pw.print(i); pw.print(": ");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009615 pw.println(r);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009616 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009617 }
9618
9619 if (mGrantedUriPermissions.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009620 if (needSep) pw.println();
9621 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009622 pw.println("Granted Uri Permissions:");
9623 for (int i=0; i<mGrantedUriPermissions.size(); i++) {
9624 int uid = mGrantedUriPermissions.keyAt(i);
9625 HashMap<Uri, UriPermission> perms
9626 = mGrantedUriPermissions.valueAt(i);
9627 pw.print(" * UID "); pw.print(uid);
9628 pw.println(" holds:");
9629 for (UriPermission perm : perms.values()) {
9630 pw.print(" "); pw.println(perm);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009631 if (dumpAll) {
9632 perm.dump(pw, " ");
9633 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009634 }
9635 }
9636 needSep = true;
9637 }
9638
9639 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009640 }
9641
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009642 boolean dumpPendingIntentsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009643 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009644 boolean needSep = false;
9645
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009646 if (mIntentSenderRecords.size() > 0) {
9647 boolean printed = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009648 Iterator<WeakReference<PendingIntentRecord>> it
9649 = mIntentSenderRecords.values().iterator();
9650 while (it.hasNext()) {
9651 WeakReference<PendingIntentRecord> ref = it.next();
9652 PendingIntentRecord rec = ref != null ? ref.get(): null;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009653 if (dumpPackage != null && (rec == null
9654 || !dumpPackage.equals(rec.key.packageName))) {
9655 continue;
9656 }
9657 if (!printed) {
9658 pw.println("ACTIVITY MANAGER PENDING INTENTS (dumpsys activity intents)");
9659 printed = true;
9660 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009661 needSep = true;
9662 if (rec != null) {
9663 pw.print(" * "); pw.println(rec);
9664 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009665 rec.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009666 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009667 } else {
9668 pw.print(" * "); pw.println(ref);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009669 }
9670 }
9671 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009672
9673 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009674 }
9675
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009676 private static final void dumpHistoryList(FileDescriptor fd, PrintWriter pw, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009677 String prefix, String label, boolean complete, boolean brief, boolean client,
9678 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009679 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009680 boolean needNL = false;
9681 final String innerPrefix = prefix + " ";
9682 final String[] args = new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009683 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009684 final ActivityRecord r = (ActivityRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009685 if (dumpPackage != null && !dumpPackage.equals(r.packageName)) {
9686 continue;
9687 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07009688 final boolean full = !brief && (complete || !r.isInHistory());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009689 if (needNL) {
9690 pw.println(" ");
9691 needNL = false;
9692 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009693 if (lastTask != r.task) {
9694 lastTask = r.task;
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009695 pw.print(prefix);
9696 pw.print(full ? "* " : " ");
9697 pw.println(lastTask);
9698 if (full) {
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009699 lastTask.dump(pw, prefix + " ");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009700 } else if (complete) {
9701 // Complete + brief == give a summary. Isn't that obvious?!?
9702 if (lastTask.intent != null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009703 pw.print(prefix); pw.print(" ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009704 pw.println(lastTask.intent.toInsecureStringWithClip());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009705 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009706 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009707 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009708 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label);
9709 pw.print(" #"); pw.print(i); pw.print(": ");
9710 pw.println(r);
9711 if (full) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009712 r.dump(pw, innerPrefix);
9713 } else if (complete) {
9714 // Complete + brief == give a summary. Isn't that obvious?!?
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009715 pw.print(innerPrefix); pw.println(r.intent.toInsecureString());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009716 if (r.app != null) {
9717 pw.print(innerPrefix); pw.println(r.app);
9718 }
9719 }
9720 if (client && r.app != null && r.app.thread != null) {
9721 // flush anything that is already in the PrintWriter since the thread is going
9722 // to write to the file descriptor directly
9723 pw.flush();
9724 try {
9725 TransferPipe tp = new TransferPipe();
9726 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009727 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9728 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009729 // Short timeout, since blocking here can
9730 // deadlock with the application.
9731 tp.go(fd, 2000);
9732 } finally {
9733 tp.kill();
9734 }
9735 } catch (IOException e) {
9736 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
9737 } catch (RemoteException e) {
9738 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
9739 }
9740 needNL = true;
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009741 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009742 }
9743 }
9744
Dianne Hackborn09c916b2009-12-08 14:50:51 -08009745 private static String buildOomTag(String prefix, String space, int val, int base) {
9746 if (val == base) {
9747 if (space == null) return prefix;
9748 return prefix + " ";
9749 }
9750 return prefix + "+" + Integer.toString(val-base);
9751 }
9752
9753 private static final int dumpProcessList(PrintWriter pw,
9754 ActivityManagerService service, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009755 String prefix, String normalLabel, String persistentLabel,
9756 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009757 int numPers = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07009758 final int N = list.size()-1;
9759 for (int i=N; i>=0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009760 ProcessRecord r = (ProcessRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009761 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9762 continue;
9763 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009764 pw.println(String.format("%s%s #%2d: %s",
9765 prefix, (r.persistent ? persistentLabel : normalLabel),
9766 i, r.toString()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009767 if (r.persistent) {
9768 numPers++;
9769 }
9770 }
9771 return numPers;
9772 }
9773
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009774 private static final boolean dumpProcessOomList(PrintWriter pw,
Dianne Hackborn905577f2011-09-07 18:31:28 -07009775 ActivityManagerService service, List<ProcessRecord> origList,
Dianne Hackborn287952c2010-09-22 22:34:31 -07009776 String prefix, String normalLabel, String persistentLabel,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009777 boolean inclDetails, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009778
Dianne Hackborn905577f2011-09-07 18:31:28 -07009779 ArrayList<Pair<ProcessRecord, Integer>> list
9780 = new ArrayList<Pair<ProcessRecord, Integer>>(origList.size());
9781 for (int i=0; i<origList.size(); i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009782 ProcessRecord r = origList.get(i);
9783 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9784 continue;
9785 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07009786 list.add(new Pair<ProcessRecord, Integer>(origList.get(i), i));
9787 }
9788
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009789 if (list.size() <= 0) {
9790 return false;
9791 }
9792
Dianne Hackborn905577f2011-09-07 18:31:28 -07009793 Comparator<Pair<ProcessRecord, Integer>> comparator
9794 = new Comparator<Pair<ProcessRecord, Integer>>() {
9795 @Override
9796 public int compare(Pair<ProcessRecord, Integer> object1,
9797 Pair<ProcessRecord, Integer> object2) {
9798 if (object1.first.setAdj != object2.first.setAdj) {
9799 return object1.first.setAdj > object2.first.setAdj ? -1 : 1;
9800 }
9801 if (object1.second.intValue() != object2.second.intValue()) {
9802 return object1.second.intValue() > object2.second.intValue() ? -1 : 1;
9803 }
9804 return 0;
9805 }
9806 };
9807
9808 Collections.sort(list, comparator);
9809
Dianne Hackborn287952c2010-09-22 22:34:31 -07009810 final long curRealtime = SystemClock.elapsedRealtime();
9811 final long realtimeSince = curRealtime - service.mLastPowerCheckRealtime;
9812 final long curUptime = SystemClock.uptimeMillis();
9813 final long uptimeSince = curUptime - service.mLastPowerCheckUptime;
9814
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009815 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07009816 ProcessRecord r = list.get(i).first;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009817 String oomAdj;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009818 if (r.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07009819 oomAdj = buildOomTag("bak", " ", r.setAdj, ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009820 } else if (r.setAdj >= ProcessList.SERVICE_B_ADJ) {
9821 oomAdj = buildOomTag("svcb ", null, r.setAdj, ProcessList.SERVICE_B_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009822 } else if (r.setAdj >= ProcessList.PREVIOUS_APP_ADJ) {
9823 oomAdj = buildOomTag("prev ", null, r.setAdj, ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009824 } else if (r.setAdj >= ProcessList.HOME_APP_ADJ) {
9825 oomAdj = buildOomTag("home ", null, r.setAdj, ProcessList.HOME_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009826 } else if (r.setAdj >= ProcessList.SERVICE_ADJ) {
9827 oomAdj = buildOomTag("svc ", null, r.setAdj, ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009828 } else if (r.setAdj >= ProcessList.BACKUP_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08009829 oomAdj = buildOomTag("bkup ", null, r.setAdj, ProcessList.BACKUP_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009830 } else if (r.setAdj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
9831 oomAdj = buildOomTag("hvy ", null, r.setAdj, ProcessList.HEAVY_WEIGHT_APP_ADJ);
9832 } else if (r.setAdj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
9833 oomAdj = buildOomTag("prcp ", null, r.setAdj, ProcessList.PERCEPTIBLE_APP_ADJ);
9834 } else if (r.setAdj >= ProcessList.VISIBLE_APP_ADJ) {
9835 oomAdj = buildOomTag("vis ", null, r.setAdj, ProcessList.VISIBLE_APP_ADJ);
9836 } else if (r.setAdj >= ProcessList.FOREGROUND_APP_ADJ) {
9837 oomAdj = buildOomTag("fore ", null, r.setAdj, ProcessList.FOREGROUND_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009838 } else if (r.setAdj >= ProcessList.PERSISTENT_PROC_ADJ) {
9839 oomAdj = buildOomTag("pers ", null, r.setAdj, ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009840 } else if (r.setAdj >= ProcessList.SYSTEM_ADJ) {
9841 oomAdj = buildOomTag("sys ", null, r.setAdj, ProcessList.SYSTEM_ADJ);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009842 } else {
9843 oomAdj = Integer.toString(r.setAdj);
9844 }
9845 String schedGroup;
9846 switch (r.setSchedGroup) {
9847 case Process.THREAD_GROUP_BG_NONINTERACTIVE:
9848 schedGroup = "B";
9849 break;
9850 case Process.THREAD_GROUP_DEFAULT:
9851 schedGroup = "F";
9852 break;
9853 default:
9854 schedGroup = Integer.toString(r.setSchedGroup);
9855 break;
9856 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07009857 String foreground;
9858 if (r.foregroundActivities) {
9859 foreground = "A";
9860 } else if (r.foregroundServices) {
9861 foreground = "S";
9862 } else {
9863 foreground = " ";
9864 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07009865 pw.println(String.format("%s%s #%2d: adj=%s/%s%s trm=%2d %s (%s)",
Dianne Hackborn287952c2010-09-22 22:34:31 -07009866 prefix, (r.persistent ? persistentLabel : normalLabel),
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009867 (origList.size()-1)-list.get(i).second, oomAdj, schedGroup,
9868 foreground, r.trimMemoryLevel, r.toShortString(), r.adjType));
Dianne Hackborn287952c2010-09-22 22:34:31 -07009869 if (r.adjSource != null || r.adjTarget != null) {
9870 pw.print(prefix);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009871 pw.print(" ");
Dianne Hackborn287952c2010-09-22 22:34:31 -07009872 if (r.adjTarget instanceof ComponentName) {
9873 pw.print(((ComponentName)r.adjTarget).flattenToShortString());
9874 } else if (r.adjTarget != null) {
9875 pw.print(r.adjTarget.toString());
9876 } else {
9877 pw.print("{null}");
9878 }
9879 pw.print("<=");
9880 if (r.adjSource instanceof ProcessRecord) {
9881 pw.print("Proc{");
9882 pw.print(((ProcessRecord)r.adjSource).toShortString());
9883 pw.println("}");
9884 } else if (r.adjSource != null) {
9885 pw.println(r.adjSource.toString());
9886 } else {
9887 pw.println("{null}");
9888 }
9889 }
9890 if (inclDetails) {
9891 pw.print(prefix);
9892 pw.print(" ");
9893 pw.print("oom: max="); pw.print(r.maxAdj);
9894 pw.print(" hidden="); pw.print(r.hiddenAdj);
9895 pw.print(" curRaw="); pw.print(r.curRawAdj);
9896 pw.print(" setRaw="); pw.print(r.setRawAdj);
9897 pw.print(" cur="); pw.print(r.curAdj);
9898 pw.print(" set="); pw.println(r.setAdj);
9899 pw.print(prefix);
9900 pw.print(" ");
9901 pw.print("keeping="); pw.print(r.keeping);
9902 pw.print(" hidden="); pw.print(r.hidden);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009903 pw.print(" empty="); pw.print(r.empty);
9904 pw.print(" hasAboveClient="); pw.println(r.hasAboveClient);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009905
9906 if (!r.keeping) {
9907 if (r.lastWakeTime != 0) {
9908 long wtime;
9909 BatteryStatsImpl stats = service.mBatteryStatsService.getActiveStatistics();
9910 synchronized (stats) {
9911 wtime = stats.getProcessWakeTime(r.info.uid,
9912 r.pid, curRealtime);
9913 }
9914 long timeUsed = wtime - r.lastWakeTime;
9915 pw.print(prefix);
9916 pw.print(" ");
9917 pw.print("keep awake over ");
9918 TimeUtils.formatDuration(realtimeSince, pw);
9919 pw.print(" used ");
9920 TimeUtils.formatDuration(timeUsed, pw);
9921 pw.print(" (");
9922 pw.print((timeUsed*100)/realtimeSince);
9923 pw.println("%)");
9924 }
9925 if (r.lastCpuTime != 0) {
9926 long timeUsed = r.curCpuTime - r.lastCpuTime;
9927 pw.print(prefix);
9928 pw.print(" ");
9929 pw.print("run cpu over ");
9930 TimeUtils.formatDuration(uptimeSince, pw);
9931 pw.print(" used ");
9932 TimeUtils.formatDuration(timeUsed, pw);
9933 pw.print(" (");
9934 pw.print((timeUsed*100)/uptimeSince);
9935 pw.println("%)");
9936 }
9937 }
9938 }
9939 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009940 return true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009941 }
9942
Dianne Hackbornb437e092011-08-05 17:50:29 -07009943 ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, String[] args) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009944 ArrayList<ProcessRecord> procs;
9945 synchronized (this) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009946 if (args != null && args.length > start
9947 && args[start].charAt(0) != '-') {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009948 procs = new ArrayList<ProcessRecord>();
9949 int pid = -1;
9950 try {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009951 pid = Integer.parseInt(args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009952 } catch (NumberFormatException e) {
9953
9954 }
9955 for (int i=mLruProcesses.size()-1; i>=0; i--) {
9956 ProcessRecord proc = mLruProcesses.get(i);
9957 if (proc.pid == pid) {
9958 procs.add(proc);
Dianne Hackbornb437e092011-08-05 17:50:29 -07009959 } else if (proc.processName.equals(args[start])) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009960 procs.add(proc);
9961 }
9962 }
9963 if (procs.size() <= 0) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009964 pw.println("No process found for: " + args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009965 return null;
9966 }
9967 } else {
9968 procs = new ArrayList<ProcessRecord>(mLruProcesses);
9969 }
9970 }
9971 return procs;
9972 }
9973
9974 final void dumpGraphicsHardwareUsage(FileDescriptor fd,
9975 PrintWriter pw, String[] args) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009976 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009977 if (procs == null) {
9978 return;
9979 }
9980
9981 long uptime = SystemClock.uptimeMillis();
9982 long realtime = SystemClock.elapsedRealtime();
9983 pw.println("Applications Graphics Acceleration Info:");
9984 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
9985
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009986 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
9987 ProcessRecord r = procs.get(i);
Chet Haase9c1e23b2011-03-24 10:51:31 -07009988 if (r.thread != null) {
9989 pw.println("\n** Graphics info for pid " + r.pid + " [" + r.processName + "] **");
9990 pw.flush();
9991 try {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009992 TransferPipe tp = new TransferPipe();
9993 try {
9994 r.thread.dumpGfxInfo(tp.getWriteFd().getFileDescriptor(), args);
9995 tp.go(fd);
9996 } finally {
9997 tp.kill();
9998 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009999 } catch (IOException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010000 pw.println("Failure while dumping the app: " + r);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010001 pw.flush();
Chet Haase9c1e23b2011-03-24 10:51:31 -070010002 } catch (RemoteException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010003 pw.println("Got a RemoteException while dumping the app " + r);
Chet Haase9c1e23b2011-03-24 10:51:31 -070010004 pw.flush();
10005 }
10006 }
10007 }
Chet Haase9c1e23b2011-03-24 10:51:31 -070010008 }
10009
Jeff Brown6754ba22011-12-14 20:20:01 -080010010 final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) {
10011 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
10012 if (procs == null) {
10013 return;
10014 }
10015
10016 pw.println("Applications Database Info:");
10017
10018 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10019 ProcessRecord r = procs.get(i);
10020 if (r.thread != null) {
10021 pw.println("\n** Database info for pid " + r.pid + " [" + r.processName + "] **");
10022 pw.flush();
10023 try {
10024 TransferPipe tp = new TransferPipe();
10025 try {
10026 r.thread.dumpDbInfo(tp.getWriteFd().getFileDescriptor(), args);
10027 tp.go(fd);
10028 } finally {
10029 tp.kill();
10030 }
10031 } catch (IOException e) {
10032 pw.println("Failure while dumping the app: " + r);
10033 pw.flush();
10034 } catch (RemoteException e) {
10035 pw.println("Got a RemoteException while dumping the app " + r);
10036 pw.flush();
10037 }
10038 }
10039 }
10040 }
10041
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010042 final static class MemItem {
10043 final String label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010044 final String shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010045 final long pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010046 final int id;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010047 ArrayList<MemItem> subitems;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010048
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010049 public MemItem(String _label, String _shortLabel, long _pss, int _id) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010050 label = _label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010051 shortLabel = _shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010052 pss = _pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010053 id = _id;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010054 }
10055 }
10056
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010057 static final void dumpMemItems(PrintWriter pw, String prefix, ArrayList<MemItem> items,
Dianne Hackbornb437e092011-08-05 17:50:29 -070010058 boolean sort) {
10059 if (sort) {
10060 Collections.sort(items, new Comparator<MemItem>() {
10061 @Override
10062 public int compare(MemItem lhs, MemItem rhs) {
10063 if (lhs.pss < rhs.pss) {
10064 return 1;
10065 } else if (lhs.pss > rhs.pss) {
10066 return -1;
10067 }
10068 return 0;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010069 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010070 });
10071 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010072
10073 for (int i=0; i<items.size(); i++) {
10074 MemItem mi = items.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010075 pw.print(prefix); pw.printf("%7d kB: ", mi.pss); pw.println(mi.label);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010076 if (mi.subitems != null) {
10077 dumpMemItems(pw, prefix + " ", mi.subitems, true);
10078 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010079 }
10080 }
10081
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010082 // These are in KB.
10083 static final long[] DUMP_MEM_BUCKETS = new long[] {
10084 5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024,
10085 120*1024, 160*1024, 200*1024,
10086 250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024,
10087 1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024
10088 };
10089
Dianne Hackborn672342c2011-11-29 11:29:02 -080010090 static final void appendMemBucket(StringBuilder out, long memKB, String label,
10091 boolean stackLike) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010092 int start = label.lastIndexOf('.');
10093 if (start >= 0) start++;
10094 else start = 0;
10095 int end = label.length();
10096 for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) {
10097 if (DUMP_MEM_BUCKETS[i] >= memKB) {
10098 long bucket = DUMP_MEM_BUCKETS[i]/1024;
10099 out.append(bucket);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010100 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010101 out.append(label, start, end);
10102 return;
10103 }
10104 }
10105 out.append(memKB/1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010106 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010107 out.append(label, start, end);
10108 }
10109
10110 static final int[] DUMP_MEM_OOM_ADJ = new int[] {
10111 ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ, ProcessList.FOREGROUND_APP_ADJ,
10112 ProcessList.VISIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ,
10113 ProcessList.BACKUP_APP_ADJ, ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ,
10114 ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.HIDDEN_APP_MAX_ADJ
10115 };
10116 static final String[] DUMP_MEM_OOM_LABEL = new String[] {
10117 "System", "Persistent", "Foreground",
10118 "Visible", "Perceptible", "Heavy Weight",
10119 "Backup", "A Services", "Home", "Previous",
10120 "B Services", "Background"
10121 };
10122
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010123 final void dumpApplicationMemoryUsage(FileDescriptor fd,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010124 PrintWriter pw, String prefix, String[] args, boolean brief,
Dianne Hackborn672342c2011-11-29 11:29:02 -080010125 PrintWriter categoryPw, StringBuilder outTag, StringBuilder outStack) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010126 boolean dumpAll = false;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010127 boolean oomOnly = false;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010128
10129 int opti = 0;
10130 while (opti < args.length) {
10131 String opt = args[opti];
10132 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
10133 break;
10134 }
10135 opti++;
10136 if ("-a".equals(opt)) {
10137 dumpAll = true;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010138 } else if ("--oom".equals(opt)) {
10139 oomOnly = true;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010140 } else if ("-h".equals(opt)) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010141 pw.println("meminfo dump options: [-a] [--oom] [process]");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010142 pw.println(" -a: include all available information for each process.");
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010143 pw.println(" --oom: only show processes organized by oom adj.");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010144 pw.println("If [process] is specified it can be the name or ");
10145 pw.println("pid of a specific process to dump.");
10146 return;
10147 } else {
10148 pw.println("Unknown argument: " + opt + "; use -h for help");
10149 }
10150 }
10151
10152 ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010153 if (procs == null) {
10154 return;
10155 }
10156
Dianne Hackborn6447ca32009-04-07 19:50:08 -070010157 final boolean isCheckinRequest = scanArgs(args, "--checkin");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010158 long uptime = SystemClock.uptimeMillis();
10159 long realtime = SystemClock.elapsedRealtime();
Dianne Hackbornb437e092011-08-05 17:50:29 -070010160
10161 if (procs.size() == 1 || isCheckinRequest) {
10162 dumpAll = true;
10163 }
10164
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010165 if (isCheckinRequest) {
10166 // short checkin version
10167 pw.println(uptime + "," + realtime);
10168 pw.flush();
10169 } else {
10170 pw.println("Applications Memory Usage (kB):");
10171 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10172 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010173
Dianne Hackbornb437e092011-08-05 17:50:29 -070010174 String[] innerArgs = new String[args.length-opti];
10175 System.arraycopy(args, opti, innerArgs, 0, args.length-opti);
10176
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010177 ArrayList<MemItem> procMems = new ArrayList<MemItem>();
10178 long nativePss=0, dalvikPss=0, otherPss=0;
10179 long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
10180
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010181 long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length];
10182 ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[])
10183 new ArrayList[DUMP_MEM_OOM_LABEL.length];
Dianne Hackbornb437e092011-08-05 17:50:29 -070010184
10185 long totalPss = 0;
10186
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010187 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10188 ProcessRecord r = procs.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010189 if (r.thread != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010190 if (!isCheckinRequest && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010191 pw.println("\n** MEMINFO in pid " + r.pid + " [" + r.processName + "] **");
10192 pw.flush();
10193 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010194 Debug.MemoryInfo mi = null;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010195 if (dumpAll) {
10196 try {
10197 mi = r.thread.dumpMemInfo(fd, isCheckinRequest, dumpAll, innerArgs);
10198 } catch (RemoteException e) {
10199 if (!isCheckinRequest) {
10200 pw.println("Got RemoteException!");
10201 pw.flush();
10202 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010203 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010204 } else {
10205 mi = new Debug.MemoryInfo();
10206 Debug.getMemoryInfo(r.pid, mi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010207 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010208
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010209 if (!isCheckinRequest && mi != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010210 long myTotalPss = mi.getTotalPss();
10211 totalPss += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010212 MemItem pssItem = new MemItem(r.processName + " (pid " + r.pid + ")",
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010213 r.processName, myTotalPss, 0);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010214 procMems.add(pssItem);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010215
10216 nativePss += mi.nativePss;
10217 dalvikPss += mi.dalvikPss;
10218 otherPss += mi.otherPss;
10219 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
10220 long mem = mi.getOtherPss(j);
10221 miscPss[j] += mem;
10222 otherPss -= mem;
10223 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010224
10225 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010226 if (r.setAdj <= DUMP_MEM_OOM_ADJ[oomIndex]
10227 || oomIndex == (oomPss.length-1)) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010228 oomPss[oomIndex] += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010229 if (oomProcs[oomIndex] == null) {
10230 oomProcs[oomIndex] = new ArrayList<MemItem>();
10231 }
10232 oomProcs[oomIndex].add(pssItem);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010233 break;
10234 }
10235 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010236 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010237 }
10238 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010239
10240 if (!isCheckinRequest && procs.size() > 1) {
10241 ArrayList<MemItem> catMems = new ArrayList<MemItem>();
10242
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010243 catMems.add(new MemItem("Native", "Native", nativePss, -1));
10244 catMems.add(new MemItem("Dalvik", "Dalvik", dalvikPss, -2));
10245 catMems.add(new MemItem("Unknown", "Unknown", otherPss, -3));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010246 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010247 String label = Debug.MemoryInfo.getOtherLabel(j);
10248 catMems.add(new MemItem(label, label, miscPss[j], j));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010249 }
10250
Dianne Hackbornb437e092011-08-05 17:50:29 -070010251 ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
10252 for (int j=0; j<oomPss.length; j++) {
10253 if (oomPss[j] != 0) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010254 String label = DUMP_MEM_OOM_LABEL[j];
10255 MemItem item = new MemItem(label, label, oomPss[j],
10256 DUMP_MEM_OOM_ADJ[j]);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010257 item.subitems = oomProcs[j];
10258 oomMems.add(item);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010259 }
10260 }
10261
Dianne Hackborn672342c2011-11-29 11:29:02 -080010262 if (outTag != null || outStack != null) {
10263 if (outTag != null) {
10264 appendMemBucket(outTag, totalPss, "total", false);
10265 }
10266 if (outStack != null) {
10267 appendMemBucket(outStack, totalPss, "total", true);
10268 }
10269 boolean firstLine = true;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010270 for (int i=0; i<oomMems.size(); i++) {
10271 MemItem miCat = oomMems.get(i);
10272 if (miCat.subitems == null || miCat.subitems.size() < 1) {
10273 continue;
10274 }
10275 if (miCat.id < ProcessList.SERVICE_ADJ
10276 || miCat.id == ProcessList.HOME_APP_ADJ
10277 || miCat.id == ProcessList.PREVIOUS_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010278 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10279 outTag.append(" / ");
10280 }
10281 if (outStack != null) {
10282 if (miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10283 if (firstLine) {
10284 outStack.append(":");
10285 firstLine = false;
10286 }
10287 outStack.append("\n\t at ");
10288 } else {
10289 outStack.append("$");
10290 }
10291 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010292 for (int j=0; j<miCat.subitems.size(); j++) {
10293 MemItem mi = miCat.subitems.get(j);
10294 if (j > 0) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010295 if (outTag != null) {
10296 outTag.append(" ");
10297 }
10298 if (outStack != null) {
10299 outStack.append("$");
10300 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010301 }
Dianne Hackborn672342c2011-11-29 11:29:02 -080010302 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10303 appendMemBucket(outTag, mi.pss, mi.shortLabel, false);
10304 }
10305 if (outStack != null) {
10306 appendMemBucket(outStack, mi.pss, mi.shortLabel, true);
10307 }
10308 }
10309 if (outStack != null && miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10310 outStack.append("(");
10311 for (int k=0; k<DUMP_MEM_OOM_ADJ.length; k++) {
10312 if (DUMP_MEM_OOM_ADJ[k] == miCat.id) {
10313 outStack.append(DUMP_MEM_OOM_LABEL[k]);
10314 outStack.append(":");
10315 outStack.append(DUMP_MEM_OOM_ADJ[k]);
10316 }
10317 }
10318 outStack.append(")");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010319 }
10320 }
10321 }
10322 }
10323
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010324 if (!brief && !oomOnly) {
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010325 pw.println();
10326 pw.println("Total PSS by process:");
10327 dumpMemItems(pw, " ", procMems, true);
10328 pw.println();
10329 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010330 pw.println("Total PSS by OOM adjustment:");
10331 dumpMemItems(pw, " ", oomMems, false);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010332 if (!oomOnly) {
10333 PrintWriter out = categoryPw != null ? categoryPw : pw;
10334 out.println();
10335 out.println("Total PSS by category:");
10336 dumpMemItems(out, " ", catMems, true);
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010337 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010338 pw.println();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010339 pw.print("Total PSS: "); pw.print(totalPss); pw.println(" kB");
Dianne Hackbornd3e677b2012-04-05 14:58:18 -070010340 final int[] SINGLE_LONG_FORMAT = new int[] {
10341 Process.PROC_SPACE_TERM|Process.PROC_OUT_LONG
10342 };
10343 long[] longOut = new long[1];
10344 Process.readProcFile("/sys/kernel/mm/ksm/pages_shared",
10345 SINGLE_LONG_FORMAT, null, longOut, null);
10346 long shared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10347 longOut[0] = 0;
10348 Process.readProcFile("/sys/kernel/mm/ksm/pages_sharing",
10349 SINGLE_LONG_FORMAT, null, longOut, null);
10350 long sharing = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10351 longOut[0] = 0;
10352 Process.readProcFile("/sys/kernel/mm/ksm/pages_unshared",
10353 SINGLE_LONG_FORMAT, null, longOut, null);
10354 long unshared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10355 longOut[0] = 0;
10356 Process.readProcFile("/sys/kernel/mm/ksm/pages_volatile",
10357 SINGLE_LONG_FORMAT, null, longOut, null);
10358 long voltile = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10359 pw.print(" KSM: "); pw.print(sharing); pw.print(" kB saved from shared ");
10360 pw.print(shared); pw.println(" kB");
10361 pw.print(" "); pw.print(unshared); pw.print(" kB unshared; ");
10362 pw.print(voltile); pw.println(" kB volatile");
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010363 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010364 }
10365
10366 /**
10367 * Searches array of arguments for the specified string
10368 * @param args array of argument strings
10369 * @param value value to search for
10370 * @return true if the value is contained in the array
10371 */
10372 private static boolean scanArgs(String[] args, String value) {
10373 if (args != null) {
10374 for (String arg : args) {
10375 if (value.equals(arg)) {
10376 return true;
10377 }
10378 }
10379 }
10380 return false;
10381 }
10382
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010383 private final void killServicesLocked(ProcessRecord app,
10384 boolean allowRestart) {
10385 // Report disconnected services.
10386 if (false) {
10387 // XXX we are letting the client link to the service for
10388 // death notifications.
10389 if (app.services.size() > 0) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010390 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010391 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010392 ServiceRecord r = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010393 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010394 Iterator<ArrayList<ConnectionRecord>> jt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010395 = r.connections.values().iterator();
10396 while (jt.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010397 ArrayList<ConnectionRecord> cl = jt.next();
10398 for (int i=0; i<cl.size(); i++) {
10399 ConnectionRecord c = cl.get(i);
10400 if (c.binding.client != app) {
10401 try {
10402 //c.conn.connected(r.className, null);
10403 } catch (Exception e) {
10404 // todo: this should be asynchronous!
10405 Slog.w(TAG, "Exception thrown disconnected servce "
10406 + r.shortName
10407 + " from app " + app.processName, e);
10408 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010409 }
10410 }
10411 }
10412 }
10413 }
10414 }
10415 }
10416
10417 // Clean up any connections this application has to other services.
10418 if (app.connections.size() > 0) {
10419 Iterator<ConnectionRecord> it = app.connections.iterator();
10420 while (it.hasNext()) {
10421 ConnectionRecord r = it.next();
10422 removeConnectionLocked(r, app, null);
10423 }
10424 }
10425 app.connections.clear();
10426
10427 if (app.services.size() != 0) {
10428 // Any services running in the application need to be placed
10429 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -070010430 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010431 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010432 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010433 synchronized (sr.stats.getBatteryStats()) {
10434 sr.stats.stopLaunchedLocked();
10435 }
10436 sr.app = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010437 sr.isolatedProc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010438 sr.executeNesting = 0;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010439 if (mStoppingServices.remove(sr)) {
10440 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
10441 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010442
10443 boolean hasClients = sr.bindings.size() > 0;
10444 if (hasClients) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010445 Iterator<IntentBindRecord> bindings
10446 = sr.bindings.values().iterator();
10447 while (bindings.hasNext()) {
10448 IntentBindRecord b = bindings.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -080010449 if (DEBUG_SERVICE) Slog.v(TAG, "Killing binding " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010450 + ": shouldUnbind=" + b.hasBound);
10451 b.binder = null;
10452 b.requested = b.received = b.hasBound = false;
10453 }
10454 }
10455
Dianne Hackborn070783f2010-12-29 16:46:28 -080010456 if (sr.crashCount >= 2 && (sr.serviceInfo.applicationInfo.flags
10457 &ApplicationInfo.FLAG_PERSISTENT) == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010458 Slog.w(TAG, "Service crashed " + sr.crashCount
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010459 + " times, stopping: " + sr);
Doug Zongker2bec3d42009-12-04 12:52:44 -080010460 EventLog.writeEvent(EventLogTags.AM_SERVICE_CRASHED_TOO_MUCH,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010461 sr.crashCount, sr.shortName, app.pid);
10462 bringDownServiceLocked(sr, true);
10463 } else if (!allowRestart) {
10464 bringDownServiceLocked(sr, true);
10465 } else {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010466 boolean canceled = scheduleServiceRestartLocked(sr, true);
10467
10468 // Should the service remain running? Note that in the
10469 // extreme case of so many attempts to deliver a command
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010470 // that it failed we also will stop it here.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010471 if (sr.startRequested && (sr.stopIfKilled || canceled)) {
10472 if (sr.pendingStarts.size() == 0) {
10473 sr.startRequested = false;
10474 if (!hasClients) {
10475 // Whoops, no reason to restart!
10476 bringDownServiceLocked(sr, true);
10477 }
10478 }
10479 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010480 }
10481 }
10482
10483 if (!allowRestart) {
10484 app.services.clear();
10485 }
10486 }
10487
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010488 // Make sure we have no more records on the stopping list.
10489 int i = mStoppingServices.size();
10490 while (i > 0) {
10491 i--;
10492 ServiceRecord sr = mStoppingServices.get(i);
10493 if (sr.app == app) {
10494 mStoppingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010495 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010496 }
10497 }
10498
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010499 app.executingServices.clear();
10500 }
10501
10502 private final void removeDyingProviderLocked(ProcessRecord proc,
10503 ContentProviderRecord cpr) {
10504 synchronized (cpr) {
10505 cpr.launchingApp = null;
10506 cpr.notifyAll();
10507 }
10508
Amith Yamasani742a6712011-05-04 14:49:28 -070010509 mProviderMap.removeProviderByClass(cpr.name, UserId.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010510 String names[] = cpr.info.authority.split(";");
10511 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010512 mProviderMap.removeProviderByName(names[j], UserId.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010513 }
10514
10515 Iterator<ProcessRecord> cit = cpr.clients.iterator();
10516 while (cit.hasNext()) {
10517 ProcessRecord capp = cit.next();
10518 if (!capp.persistent && capp.thread != null
10519 && capp.pid != 0
10520 && capp.pid != MY_PID) {
Dianne Hackborn8633e682010-04-22 16:03:41 -070010521 Slog.i(TAG, "Kill " + capp.processName
10522 + " (pid " + capp.pid + "): provider " + cpr.info.name
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010523 + " in dying process " + (proc != null ? proc.processName : "??"));
Dianne Hackborn8633e682010-04-22 16:03:41 -070010524 EventLog.writeEvent(EventLogTags.AM_KILL, capp.pid,
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010525 capp.processName, capp.setAdj, "dying provider "
10526 + cpr.name.toShortString());
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070010527 Process.killProcessQuiet(capp.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010528 }
10529 }
10530
10531 mLaunchingProviders.remove(cpr);
10532 }
10533
10534 /**
10535 * Main code for cleaning up a process when it has gone away. This is
10536 * called both as a result of the process dying, or directly when stopping
10537 * a process when running in single process mode.
10538 */
10539 private final void cleanUpApplicationRecordLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010540 boolean restarting, boolean allowRestart, int index) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010541 if (index >= 0) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010542 mLruProcesses.remove(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010543 }
10544
Dianne Hackborn36124872009-10-08 16:22:03 -070010545 mProcessesToGc.remove(app);
10546
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010547 // Dismiss any open dialogs.
10548 if (app.crashDialog != null) {
10549 app.crashDialog.dismiss();
10550 app.crashDialog = null;
10551 }
10552 if (app.anrDialog != null) {
10553 app.anrDialog.dismiss();
10554 app.anrDialog = null;
10555 }
10556 if (app.waitDialog != null) {
10557 app.waitDialog.dismiss();
10558 app.waitDialog = null;
10559 }
10560
10561 app.crashing = false;
10562 app.notResponding = false;
10563
10564 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -070010565 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010566 app.thread = null;
10567 app.forcingToForeground = null;
10568 app.foregroundServices = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010569 app.foregroundActivities = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070010570 app.hasShownUi = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010571 app.hasAboveClient = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010572
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010573 killServicesLocked(app, allowRestart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010574
10575 boolean restart = false;
10576
10577 int NL = mLaunchingProviders.size();
10578
10579 // Remove published content providers.
10580 if (!app.pubProviders.isEmpty()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010581 Iterator<ContentProviderRecord> it = app.pubProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010582 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010583 ContentProviderRecord cpr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010584 cpr.provider = null;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010585 cpr.proc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010586
10587 // See if someone is waiting for this provider... in which
10588 // case we don't remove it, but just let it restart.
10589 int i = 0;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010590 if (!app.bad && allowRestart) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010591 for (; i<NL; i++) {
10592 if (mLaunchingProviders.get(i) == cpr) {
10593 restart = true;
10594 break;
10595 }
10596 }
10597 } else {
10598 i = NL;
10599 }
10600
10601 if (i >= NL) {
10602 removeDyingProviderLocked(app, cpr);
10603 NL = mLaunchingProviders.size();
10604 }
10605 }
10606 app.pubProviders.clear();
10607 }
10608
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010609 // Take care of any launching providers waiting for this process.
10610 if (checkAppInLaunchingProvidersLocked(app, false)) {
10611 restart = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010612 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010613
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010614 // Unregister from connected content providers.
10615 if (!app.conProviders.isEmpty()) {
Dianne Hackborn0c3154d2009-10-06 17:18:05 -070010616 Iterator it = app.conProviders.keySet().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010617 while (it.hasNext()) {
10618 ContentProviderRecord cpr = (ContentProviderRecord)it.next();
10619 cpr.clients.remove(app);
10620 }
10621 app.conProviders.clear();
10622 }
10623
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010624 // At this point there may be remaining entries in mLaunchingProviders
10625 // where we were the only one waiting, so they are no longer of use.
10626 // Look for these and clean up if found.
10627 // XXX Commented out for now. Trying to figure out a way to reproduce
10628 // the actual situation to identify what is actually going on.
10629 if (false) {
10630 for (int i=0; i<NL; i++) {
10631 ContentProviderRecord cpr = (ContentProviderRecord)
10632 mLaunchingProviders.get(i);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080010633 if (cpr.clients.size() <= 0 && !cpr.hasExternalProcessHandles()) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010634 synchronized (cpr) {
10635 cpr.launchingApp = null;
10636 cpr.notifyAll();
10637 }
10638 }
10639 }
10640 }
10641
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010642 skipCurrentReceiverLocked(app);
10643
10644 // Unregister any receivers.
10645 if (app.receivers.size() > 0) {
10646 Iterator<ReceiverList> it = app.receivers.iterator();
10647 while (it.hasNext()) {
10648 removeReceiverLocked(it.next());
10649 }
10650 app.receivers.clear();
10651 }
10652
Christopher Tate181fafa2009-05-14 11:12:14 -070010653 // If the app is undergoing backup, tell the backup manager about it
10654 if (mBackupTarget != null && app.pid == mBackupTarget.app.pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010655 if (DEBUG_BACKUP) Slog.d(TAG, "App " + mBackupTarget.appInfo + " died during backup");
Christopher Tate181fafa2009-05-14 11:12:14 -070010656 try {
10657 IBackupManager bm = IBackupManager.Stub.asInterface(
10658 ServiceManager.getService(Context.BACKUP_SERVICE));
10659 bm.agentDisconnected(app.info.packageName);
10660 } catch (RemoteException e) {
10661 // can't happen; backup manager is local
10662 }
10663 }
10664
Jeff Sharkey287bd832011-05-28 19:36:26 -070010665 mHandler.obtainMessage(DISPATCH_PROCESS_DIED, app.pid, app.info.uid, null).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010666
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010667 // If the caller is restarting this app, then leave it in its
10668 // current lists and let the caller take care of it.
10669 if (restarting) {
10670 return;
10671 }
10672
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010673 if (!app.persistent || app.isolated) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010674 if (DEBUG_PROCESSES) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010675 "Removing non-persistent process during cleanup: " + app);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010676 mProcessNames.remove(app.processName, app.uid);
10677 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -070010678 if (mHeavyWeightProcess == app) {
10679 mHeavyWeightProcess = null;
10680 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
10681 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010682 } else if (!app.removed) {
10683 // This app is persistent, so we need to keep its record around.
10684 // If it is not already on the pending app list, add it there
10685 // and start a new process for it.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010686 if (mPersistentStartingProcesses.indexOf(app) < 0) {
10687 mPersistentStartingProcesses.add(app);
10688 restart = true;
10689 }
10690 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070010691 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
10692 "Clean-up removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010693 mProcessesOnHold.remove(app);
10694
The Android Open Source Project4df24232009-03-05 14:34:35 -080010695 if (app == mHomeProcess) {
10696 mHomeProcess = null;
10697 }
Dianne Hackbornf35fe232011-11-01 19:25:20 -070010698 if (app == mPreviousProcess) {
10699 mPreviousProcess = null;
10700 }
10701
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010702 if (restart && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010703 // We have components that still need to be running in the
10704 // process, so re-launch it.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010705 mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010706 startProcessLocked(app, "restart", app.processName);
10707 } else if (app.pid > 0 && app.pid != MY_PID) {
10708 // Goodbye!
10709 synchronized (mPidsSelfLocked) {
10710 mPidsSelfLocked.remove(app.pid);
10711 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
10712 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010713 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010714 }
10715 }
10716
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010717 boolean checkAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) {
10718 // Look through the content providers we are waiting to have launched,
10719 // and if any run in this process then either schedule a restart of
10720 // the process or kill the client waiting for it if this process has
10721 // gone bad.
10722 int NL = mLaunchingProviders.size();
10723 boolean restart = false;
10724 for (int i=0; i<NL; i++) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010725 ContentProviderRecord cpr = mLaunchingProviders.get(i);
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010726 if (cpr.launchingApp == app) {
10727 if (!alwaysBad && !app.bad) {
10728 restart = true;
10729 } else {
10730 removeDyingProviderLocked(app, cpr);
10731 NL = mLaunchingProviders.size();
10732 }
10733 }
10734 }
10735 return restart;
10736 }
10737
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010738 // =========================================================
10739 // SERVICES
10740 // =========================================================
10741
10742 ActivityManager.RunningServiceInfo makeRunningServiceInfoLocked(ServiceRecord r) {
10743 ActivityManager.RunningServiceInfo info =
10744 new ActivityManager.RunningServiceInfo();
10745 info.service = r.name;
10746 if (r.app != null) {
10747 info.pid = r.app.pid;
10748 }
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010749 info.uid = r.appInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010750 info.process = r.processName;
10751 info.foreground = r.isForeground;
10752 info.activeSince = r.createTime;
10753 info.started = r.startRequested;
10754 info.clientCount = r.connections.size();
10755 info.crashCount = r.crashCount;
10756 info.lastActivityTime = r.lastActivity;
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010757 if (r.isForeground) {
10758 info.flags |= ActivityManager.RunningServiceInfo.FLAG_FOREGROUND;
10759 }
10760 if (r.startRequested) {
10761 info.flags |= ActivityManager.RunningServiceInfo.FLAG_STARTED;
10762 }
Dan Egnor42471dd2010-01-07 17:25:22 -080010763 if (r.app != null && r.app.pid == MY_PID) {
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010764 info.flags |= ActivityManager.RunningServiceInfo.FLAG_SYSTEM_PROCESS;
10765 }
10766 if (r.app != null && r.app.persistent) {
10767 info.flags |= ActivityManager.RunningServiceInfo.FLAG_PERSISTENT_PROCESS;
10768 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010769
10770 for (ArrayList<ConnectionRecord> connl : r.connections.values()) {
10771 for (int i=0; i<connl.size(); i++) {
10772 ConnectionRecord conn = connl.get(i);
10773 if (conn.clientLabel != 0) {
10774 info.clientPackage = conn.binding.client.info.packageName;
10775 info.clientLabel = conn.clientLabel;
10776 return info;
10777 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010778 }
10779 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010780 return info;
10781 }
10782
10783 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum,
10784 int flags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010785 enforceNotIsolatedCaller("getServices");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010786 synchronized (this) {
10787 ArrayList<ActivityManager.RunningServiceInfo> res
10788 = new ArrayList<ActivityManager.RunningServiceInfo>();
10789
Amith Yamasani742a6712011-05-04 14:49:28 -070010790 int userId = UserId.getUserId(Binder.getCallingUid());
10791 if (mServiceMap.getAllServices(userId).size() > 0) {
10792 Iterator<ServiceRecord> it
10793 = mServiceMap.getAllServices(userId).iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010794 while (it.hasNext() && res.size() < maxNum) {
10795 res.add(makeRunningServiceInfoLocked(it.next()));
10796 }
10797 }
10798
10799 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
10800 ServiceRecord r = mRestartingServices.get(i);
10801 ActivityManager.RunningServiceInfo info =
10802 makeRunningServiceInfoLocked(r);
10803 info.restarting = r.nextRestartTime;
10804 res.add(info);
10805 }
10806
10807 return res;
10808 }
10809 }
10810
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010811 public PendingIntent getRunningServiceControlPanel(ComponentName name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010812 enforceNotIsolatedCaller("getRunningServiceControlPanel");
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010813 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010814 int userId = UserId.getUserId(Binder.getCallingUid());
10815 ServiceRecord r = mServiceMap.getServiceByName(name, userId);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010816 if (r != null) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010817 for (ArrayList<ConnectionRecord> conn : r.connections.values()) {
10818 for (int i=0; i<conn.size(); i++) {
10819 if (conn.get(i).clientIntent != null) {
10820 return conn.get(i).clientIntent;
10821 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010822 }
10823 }
10824 }
10825 }
10826 return null;
10827 }
10828
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010829 private final ServiceRecord findServiceLocked(ComponentName name,
10830 IBinder token) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010831 ServiceRecord r = mServiceMap.getServiceByName(name, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010832 return r == token ? r : null;
10833 }
10834
10835 private final class ServiceLookupResult {
10836 final ServiceRecord record;
10837 final String permission;
10838
10839 ServiceLookupResult(ServiceRecord _record, String _permission) {
10840 record = _record;
10841 permission = _permission;
10842 }
10843 };
10844
10845 private ServiceLookupResult findServiceLocked(Intent service,
Amith Yamasani483f3b02012-03-13 16:08:00 -070010846 String resolvedType, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010847 ServiceRecord r = null;
10848 if (service.getComponent() != null) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070010849 r = mServiceMap.getServiceByName(service.getComponent(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010850 }
10851 if (r == null) {
10852 Intent.FilterComparison filter = new Intent.FilterComparison(service);
Amith Yamasani483f3b02012-03-13 16:08:00 -070010853 r = mServiceMap.getServiceByIntent(filter, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010854 }
10855
10856 if (r == null) {
10857 try {
10858 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070010859 AppGlobals.getPackageManager().resolveService(
Amith Yamasani483f3b02012-03-13 16:08:00 -070010860 service, resolvedType, 0, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010861 ServiceInfo sInfo =
10862 rInfo != null ? rInfo.serviceInfo : null;
10863 if (sInfo == null) {
10864 return null;
10865 }
10866
10867 ComponentName name = new ComponentName(
10868 sInfo.applicationInfo.packageName, sInfo.name);
Amith Yamasani742a6712011-05-04 14:49:28 -070010869 r = mServiceMap.getServiceByName(name, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010870 } catch (RemoteException ex) {
10871 // pm is in same process, this will never happen.
10872 }
10873 }
10874 if (r != null) {
10875 int callingPid = Binder.getCallingPid();
10876 int callingUid = Binder.getCallingUid();
10877 if (checkComponentPermission(r.permission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010878 callingPid, callingUid, r.appInfo.uid, r.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010879 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010880 if (!r.exported) {
10881 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
10882 + " from pid=" + callingPid
10883 + ", uid=" + callingUid
10884 + " that is not exported from uid " + r.appInfo.uid);
10885 return new ServiceLookupResult(null, "not exported from uid "
10886 + r.appInfo.uid);
10887 }
Joe Onorato8a9b2202010-02-26 18:56:32 -080010888 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010889 + " from pid=" + callingPid
10890 + ", uid=" + callingUid
10891 + " requires " + r.permission);
10892 return new ServiceLookupResult(null, r.permission);
10893 }
10894 return new ServiceLookupResult(r, null);
10895 }
10896 return null;
10897 }
10898
10899 private class ServiceRestarter implements Runnable {
10900 private ServiceRecord mService;
10901
10902 void setService(ServiceRecord service) {
10903 mService = service;
10904 }
10905
10906 public void run() {
10907 synchronized(ActivityManagerService.this) {
10908 performServiceRestartLocked(mService);
10909 }
10910 }
10911 }
10912
10913 private ServiceLookupResult retrieveServiceLocked(Intent service,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010914 String resolvedType, int callingPid, int callingUid, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010915 ServiceRecord r = null;
Amith Yamasani742a6712011-05-04 14:49:28 -070010916 if (DEBUG_SERVICE)
10917 Slog.v(TAG, "retrieveServiceLocked: " + service + " type=" + resolvedType
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010918 + " callingUid=" + callingUid);
Amith Yamasani742a6712011-05-04 14:49:28 -070010919
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010920 if (service.getComponent() != null) {
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010921 r = mServiceMap.getServiceByName(service.getComponent(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010922 }
Amith Yamasani742a6712011-05-04 14:49:28 -070010923 if (r == null) {
10924 Intent.FilterComparison filter = new Intent.FilterComparison(service);
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010925 r = mServiceMap.getServiceByIntent(filter, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -070010926 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010927 if (r == null) {
10928 try {
10929 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070010930 AppGlobals.getPackageManager().resolveService(
Amith Yamasani483f3b02012-03-13 16:08:00 -070010931 service, resolvedType, STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010932 ServiceInfo sInfo =
10933 rInfo != null ? rInfo.serviceInfo : null;
10934 if (sInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010935 Slog.w(TAG, "Unable to start service " + service +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010936 ": not found");
10937 return null;
10938 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010939 if (userId > 0) {
Amith Yamasania4a54e22012-04-16 15:44:19 -070010940 if (isSingleton(sInfo.processName, sInfo.applicationInfo)) {
10941 userId = 0;
10942 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010943 sInfo.applicationInfo = getAppInfoForUser(sInfo.applicationInfo, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -070010944 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010945 ComponentName name = new ComponentName(
10946 sInfo.applicationInfo.packageName, sInfo.name);
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010947 r = mServiceMap.getServiceByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010948 if (r == null) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010949 Intent.FilterComparison filter = new Intent.FilterComparison(
10950 service.cloneFilter());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010951 ServiceRestarter res = new ServiceRestarter();
10952 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
10953 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
10954 synchronized (stats) {
10955 ss = stats.getServiceStatsLocked(
10956 sInfo.applicationInfo.uid, sInfo.packageName,
10957 sInfo.name);
10958 }
Dianne Hackbornb1c4a2a2010-01-19 15:36:42 -080010959 r = new ServiceRecord(this, ss, name, filter, sInfo, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010960 res.setService(r);
Amith Yamasani742a6712011-05-04 14:49:28 -070010961 mServiceMap.putServiceByName(name, UserId.getUserId(r.appInfo.uid), r);
10962 mServiceMap.putServiceByIntent(filter, UserId.getUserId(r.appInfo.uid), r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010963
10964 // Make sure this component isn't in the pending list.
10965 int N = mPendingServices.size();
10966 for (int i=0; i<N; i++) {
10967 ServiceRecord pr = mPendingServices.get(i);
10968 if (pr.name.equals(name)) {
10969 mPendingServices.remove(i);
10970 i--;
10971 N--;
10972 }
10973 }
10974 }
10975 } catch (RemoteException ex) {
10976 // pm is in same process, this will never happen.
10977 }
10978 }
10979 if (r != null) {
10980 if (checkComponentPermission(r.permission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010981 callingPid, callingUid, r.appInfo.uid, r.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010982 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010983 if (!r.exported) {
10984 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
10985 + " from pid=" + callingPid
10986 + ", uid=" + callingUid
10987 + " that is not exported from uid " + r.appInfo.uid);
10988 return new ServiceLookupResult(null, "not exported from uid "
10989 + r.appInfo.uid);
10990 }
Joe Onorato8a9b2202010-02-26 18:56:32 -080010991 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010992 + " from pid=" + callingPid
10993 + ", uid=" + callingUid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010994 + " requires " + r.permission);
10995 return new ServiceLookupResult(null, r.permission);
10996 }
10997 return new ServiceLookupResult(r, null);
10998 }
10999 return null;
11000 }
11001
Dianne Hackborn287952c2010-09-22 22:34:31 -070011002 private final void bumpServiceExecutingLocked(ServiceRecord r, String why) {
11003 if (DEBUG_SERVICE) Log.v(TAG, ">>> EXECUTING "
11004 + why + " of " + r + " in app " + r.app);
11005 else if (DEBUG_SERVICE_EXECUTING) Log.v(TAG, ">>> EXECUTING "
11006 + why + " of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011007 long now = SystemClock.uptimeMillis();
11008 if (r.executeNesting == 0 && r.app != null) {
11009 if (r.app.executingServices.size() == 0) {
11010 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
11011 msg.obj = r.app;
11012 mHandler.sendMessageAtTime(msg, now+SERVICE_TIMEOUT);
11013 }
11014 r.app.executingServices.add(r);
11015 }
11016 r.executeNesting++;
11017 r.executingStart = now;
11018 }
11019
11020 private final void sendServiceArgsLocked(ServiceRecord r,
11021 boolean oomAdjusted) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011022 final int N = r.pendingStarts.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011023 if (N == 0) {
11024 return;
11025 }
11026
Dianne Hackborn39792d22010-08-19 18:01:52 -070011027 while (r.pendingStarts.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011028 try {
Dianne Hackborn39792d22010-08-19 18:01:52 -070011029 ServiceRecord.StartItem si = r.pendingStarts.remove(0);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011030 if (DEBUG_SERVICE) Slog.v(TAG, "Sending arguments to: "
11031 + r + " " + r.intent + " args=" + si.intent);
Dianne Hackborn3a28f222011-03-01 12:25:54 -080011032 if (si.intent == null && N > 1) {
11033 // If somehow we got a dummy null intent in the middle,
11034 // then skip it. DO NOT skip a null intent when it is
11035 // the only one in the list -- this is to support the
11036 // onStartCommand(null) case.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011037 continue;
11038 }
Dianne Hackborn39792d22010-08-19 18:01:52 -070011039 si.deliveredTime = SystemClock.uptimeMillis();
11040 r.deliveredStarts.add(si);
11041 si.deliveryCount++;
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011042 if (si.neededGrants != null) {
11043 grantUriPermissionUncheckedFromIntentLocked(si.neededGrants,
11044 si.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -070011045 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070011046 bumpServiceExecutingLocked(r, "start");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011047 if (!oomAdjusted) {
11048 oomAdjusted = true;
11049 updateOomAdjLocked(r.app);
11050 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011051 int flags = 0;
11052 if (si.deliveryCount > 0) {
11053 flags |= Service.START_FLAG_RETRY;
11054 }
11055 if (si.doneExecutingCount > 0) {
11056 flags |= Service.START_FLAG_REDELIVERY;
11057 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011058 r.app.thread.scheduleServiceArgs(r, si.taskRemoved, si.id, flags, si.intent);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011059 } catch (RemoteException e) {
11060 // Remote process gone... we'll let the normal cleanup take
11061 // care of this.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011062 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while scheduling start: " + r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011063 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011064 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011065 Slog.w(TAG, "Unexpected exception", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011066 break;
11067 }
11068 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011069 }
11070
11071 private final boolean requestServiceBindingLocked(ServiceRecord r,
11072 IntentBindRecord i, boolean rebind) {
11073 if (r.app == null || r.app.thread == null) {
11074 // If service is not currently running, can't yet bind.
11075 return false;
11076 }
11077 if ((!i.requested || rebind) && i.apps.size() > 0) {
11078 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011079 bumpServiceExecutingLocked(r, "bind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011080 r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind);
11081 if (!rebind) {
11082 i.requested = true;
11083 }
11084 i.hasBound = true;
11085 i.doRebind = false;
11086 } catch (RemoteException e) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011087 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while binding " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011088 return false;
11089 }
11090 }
11091 return true;
11092 }
11093
11094 private final void requestServiceBindingsLocked(ServiceRecord r) {
11095 Iterator<IntentBindRecord> bindings = r.bindings.values().iterator();
11096 while (bindings.hasNext()) {
11097 IntentBindRecord i = bindings.next();
11098 if (!requestServiceBindingLocked(r, i, false)) {
11099 break;
11100 }
11101 }
11102 }
11103
11104 private final void realStartServiceLocked(ServiceRecord r,
11105 ProcessRecord app) throws RemoteException {
11106 if (app.thread == null) {
11107 throw new RemoteException();
11108 }
Amith Yamasani742a6712011-05-04 14:49:28 -070011109 if (DEBUG_MU)
11110 Slog.v(TAG_MU, "realStartServiceLocked, ServiceRecord.uid = " + r.appInfo.uid
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011111 + ", ProcessRecord.uid = " + app.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011112 r.app = app;
The Android Open Source Project10592532009-03-18 17:39:46 -070011113 r.restartTime = r.lastActivity = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011114
11115 app.services.add(r);
Dianne Hackborn287952c2010-09-22 22:34:31 -070011116 bumpServiceExecutingLocked(r, "create");
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011117 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011118
11119 boolean created = false;
11120 try {
Dianne Hackborna33e3f72009-09-29 17:28:24 -070011121 mStringBuilder.setLength(0);
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011122 r.intent.getIntent().toShortString(mStringBuilder, true, false, true, false);
Doug Zongker2bec3d42009-12-04 12:52:44 -080011123 EventLog.writeEvent(EventLogTags.AM_CREATE_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011124 System.identityHashCode(r), r.shortName,
Dianne Hackborna33e3f72009-09-29 17:28:24 -070011125 mStringBuilder.toString(), r.app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011126 synchronized (r.stats.getBatteryStats()) {
11127 r.stats.startLaunchedLocked();
11128 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -070011129 ensurePackageDexOpt(r.serviceInfo.packageName);
Dianne Hackborne2515ee2011-04-27 18:52:56 -040011130 app.thread.scheduleCreateService(r, r.serviceInfo,
11131 compatibilityInfoForPackageLocked(r.serviceInfo.applicationInfo));
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011132 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011133 created = true;
11134 } finally {
11135 if (!created) {
11136 app.services.remove(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011137 scheduleServiceRestartLocked(r, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011138 }
11139 }
11140
11141 requestServiceBindingsLocked(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011142
11143 // If the service is in the started state, and there are no
11144 // pending arguments, then fake up one so its onStartCommand() will
11145 // be called.
11146 if (r.startRequested && r.callStart && r.pendingStarts.size() == 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011147 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011148 null, null));
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011149 }
11150
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011151 sendServiceArgsLocked(r, true);
11152 }
11153
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011154 private final boolean scheduleServiceRestartLocked(ServiceRecord r,
11155 boolean allowCancel) {
11156 boolean canceled = false;
11157
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011158 final long now = SystemClock.uptimeMillis();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011159 long minDuration = SERVICE_RESTART_DURATION;
Dianne Hackborn6ccd2af2009-08-27 12:26:44 -070011160 long resetTime = SERVICE_RESET_RUN_DURATION;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011161
Dianne Hackborn070783f2010-12-29 16:46:28 -080011162 if ((r.serviceInfo.applicationInfo.flags
11163 &ApplicationInfo.FLAG_PERSISTENT) != 0) {
11164 minDuration /= 4;
11165 }
11166
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011167 // Any delivered but not yet finished starts should be put back
11168 // on the pending list.
11169 final int N = r.deliveredStarts.size();
11170 if (N > 0) {
11171 for (int i=N-1; i>=0; i--) {
11172 ServiceRecord.StartItem si = r.deliveredStarts.get(i);
Dianne Hackborn39792d22010-08-19 18:01:52 -070011173 si.removeUriPermissionsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011174 if (si.intent == null) {
11175 // We'll generate this again if needed.
11176 } else if (!allowCancel || (si.deliveryCount < ServiceRecord.MAX_DELIVERY_COUNT
11177 && si.doneExecutingCount < ServiceRecord.MAX_DONE_EXECUTING_COUNT)) {
11178 r.pendingStarts.add(0, si);
11179 long dur = SystemClock.uptimeMillis() - si.deliveredTime;
11180 dur *= 2;
11181 if (minDuration < dur) minDuration = dur;
11182 if (resetTime < dur) resetTime = dur;
11183 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011184 Slog.w(TAG, "Canceling start item " + si.intent + " in service "
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011185 + r.name);
11186 canceled = true;
11187 }
11188 }
11189 r.deliveredStarts.clear();
11190 }
11191
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011192 r.totalRestartCount++;
11193 if (r.restartDelay == 0) {
11194 r.restartCount++;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011195 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011196 } else {
11197 // If it has been a "reasonably long time" since the service
11198 // was started, then reset our restart duration back to
11199 // the beginning, so we don't infinitely increase the duration
11200 // on a service that just occasionally gets killed (which is
11201 // a normal case, due to process being killed to reclaim memory).
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011202 if (now > (r.restartTime+resetTime)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011203 r.restartCount = 1;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011204 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011205 } else {
Dianne Hackborn070783f2010-12-29 16:46:28 -080011206 if ((r.serviceInfo.applicationInfo.flags
11207 &ApplicationInfo.FLAG_PERSISTENT) != 0) {
11208 // Services in peristent processes will restart much more
11209 // quickly, since they are pretty important. (Think SystemUI).
11210 r.restartDelay += minDuration/2;
11211 } else {
11212 r.restartDelay *= SERVICE_RESTART_DURATION_FACTOR;
11213 if (r.restartDelay < minDuration) {
11214 r.restartDelay = minDuration;
11215 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011216 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011217 }
11218 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011219
11220 r.nextRestartTime = now + r.restartDelay;
11221
11222 // Make sure that we don't end up restarting a bunch of services
11223 // all at the same time.
11224 boolean repeat;
11225 do {
11226 repeat = false;
11227 for (int i=mRestartingServices.size()-1; i>=0; i--) {
11228 ServiceRecord r2 = mRestartingServices.get(i);
11229 if (r2 != r && r.nextRestartTime
11230 >= (r2.nextRestartTime-SERVICE_MIN_RESTART_TIME_BETWEEN)
11231 && r.nextRestartTime
11232 < (r2.nextRestartTime+SERVICE_MIN_RESTART_TIME_BETWEEN)) {
11233 r.nextRestartTime = r2.nextRestartTime + SERVICE_MIN_RESTART_TIME_BETWEEN;
11234 r.restartDelay = r.nextRestartTime - now;
11235 repeat = true;
11236 break;
11237 }
11238 }
11239 } while (repeat);
11240
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011241 if (!mRestartingServices.contains(r)) {
11242 mRestartingServices.add(r);
11243 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011244
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011245 r.cancelNotification();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011246
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011247 mHandler.removeCallbacks(r.restarter);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011248 mHandler.postAtTime(r.restarter, r.nextRestartTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011249 r.nextRestartTime = SystemClock.uptimeMillis() + r.restartDelay;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011250 Slog.w(TAG, "Scheduling restart of crashed service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011251 + r.shortName + " in " + r.restartDelay + "ms");
Doug Zongker2bec3d42009-12-04 12:52:44 -080011252 EventLog.writeEvent(EventLogTags.AM_SCHEDULE_SERVICE_RESTART,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011253 r.shortName, r.restartDelay);
11254
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011255 return canceled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011256 }
11257
11258 final void performServiceRestartLocked(ServiceRecord r) {
11259 if (!mRestartingServices.contains(r)) {
11260 return;
11261 }
11262 bringUpServiceLocked(r, r.intent.getIntent().getFlags(), true);
11263 }
11264
11265 private final boolean unscheduleServiceRestartLocked(ServiceRecord r) {
11266 if (r.restartDelay == 0) {
11267 return false;
11268 }
11269 r.resetRestartCounter();
11270 mRestartingServices.remove(r);
11271 mHandler.removeCallbacks(r.restarter);
11272 return true;
11273 }
11274
11275 private final boolean bringUpServiceLocked(ServiceRecord r,
11276 int intentFlags, boolean whileRestarting) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011277 //Slog.i(TAG, "Bring up service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011278 //r.dump(" ");
11279
Dianne Hackborn36124872009-10-08 16:22:03 -070011280 if (r.app != null && r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011281 sendServiceArgsLocked(r, false);
11282 return true;
11283 }
11284
11285 if (!whileRestarting && r.restartDelay > 0) {
11286 // If waiting for a restart, then do nothing.
11287 return true;
11288 }
11289
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011290 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing up " + r + " " + r.intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011291
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011292 // We are now bringing the service up, so no longer in the
11293 // restarting state.
11294 mRestartingServices.remove(r);
11295
Dianne Hackborne7f97212011-02-24 14:40:20 -080011296 // Service is now being launched, its package can't be stopped.
11297 try {
11298 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -070011299 r.packageName, false, r.userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -080011300 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080011301 } catch (IllegalArgumentException e) {
11302 Slog.w(TAG, "Failed trying to unstop package "
11303 + r.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080011304 }
11305
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011306 final boolean isolated = (r.serviceInfo.flags&ServiceInfo.FLAG_ISOLATED_PROCESS) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011307 final String appName = r.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011308 ProcessRecord app;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011309
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011310 if (!isolated) {
11311 app = getProcessRecordLocked(appName, r.appInfo.uid);
11312 if (DEBUG_MU)
11313 Slog.v(TAG_MU, "bringUpServiceLocked: appInfo.uid=" + r.appInfo.uid + " app=" + app);
11314 if (app != null && app.thread != null) {
11315 try {
11316 app.addPackage(r.appInfo.packageName);
11317 realStartServiceLocked(r, app);
11318 return true;
11319 } catch (RemoteException e) {
11320 Slog.w(TAG, "Exception when starting service " + r.shortName, e);
11321 }
11322
11323 // If a dead object exception was thrown -- fall through to
11324 // restart the application.
11325 }
11326 } else {
11327 // If this service runs in an isolated process, then each time
11328 // we call startProcessLocked() we will get a new isolated
11329 // process, starting another process if we are currently waiting
11330 // for a previous process to come up. To deal with this, we store
11331 // in the service any current isolated process it is running in or
11332 // waiting to have come up.
11333 app = r.isolatedProc;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011334 }
11335
Dianne Hackborn36124872009-10-08 16:22:03 -070011336 // Not running -- get it started, and enqueue this service record
11337 // to be executed when the app comes up.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011338 if (app == null) {
11339 if ((app=startProcessLocked(appName, r.appInfo, true, intentFlags,
11340 "service", r.name, false, isolated)) == null) {
11341 Slog.w(TAG, "Unable to launch app "
11342 + r.appInfo.packageName + "/"
11343 + r.appInfo.uid + " for service "
11344 + r.intent.getIntent() + ": process is bad");
11345 bringDownServiceLocked(r, true);
11346 return false;
11347 }
11348 if (isolated) {
11349 r.isolatedProc = app;
11350 }
Dianne Hackborn36124872009-10-08 16:22:03 -070011351 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011352
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011353 if (!mPendingServices.contains(r)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011354 mPendingServices.add(r);
11355 }
Dianne Hackborn36124872009-10-08 16:22:03 -070011356
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011357 return true;
11358 }
11359
11360 private final void bringDownServiceLocked(ServiceRecord r, boolean force) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011361 //Slog.i(TAG, "Bring down service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011362 //r.dump(" ");
11363
11364 // Does it still need to run?
11365 if (!force && r.startRequested) {
11366 return;
11367 }
11368 if (r.connections.size() > 0) {
11369 if (!force) {
11370 // XXX should probably keep a count of the number of auto-create
11371 // connections directly in the service.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011372 Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011373 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011374 ArrayList<ConnectionRecord> cr = it.next();
11375 for (int i=0; i<cr.size(); i++) {
11376 if ((cr.get(i).flags&Context.BIND_AUTO_CREATE) != 0) {
11377 return;
11378 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011379 }
11380 }
11381 }
11382
11383 // Report to all of the connections that the service is no longer
11384 // available.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011385 Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011386 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011387 ArrayList<ConnectionRecord> c = it.next();
11388 for (int i=0; i<c.size(); i++) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011389 ConnectionRecord cr = c.get(i);
11390 // There is still a connection to the service that is
11391 // being brought down. Mark it as dead.
11392 cr.serviceDead = true;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011393 try {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011394 cr.conn.connected(r.name, null);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011395 } catch (Exception e) {
11396 Slog.w(TAG, "Failure disconnecting service " + r.name +
11397 " to connection " + c.get(i).conn.asBinder() +
11398 " (in " + c.get(i).binding.client.processName + ")", e);
11399 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011400 }
11401 }
11402 }
11403
11404 // Tell the service that it has been unbound.
11405 if (r.bindings.size() > 0 && r.app != null && r.app.thread != null) {
11406 Iterator<IntentBindRecord> it = r.bindings.values().iterator();
11407 while (it.hasNext()) {
11408 IntentBindRecord ibr = it.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -080011409 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down binding " + ibr
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011410 + ": hasBound=" + ibr.hasBound);
11411 if (r.app != null && r.app.thread != null && ibr.hasBound) {
11412 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011413 bumpServiceExecutingLocked(r, "bring down unbind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011414 updateOomAdjLocked(r.app);
11415 ibr.hasBound = false;
11416 r.app.thread.scheduleUnbindService(r,
11417 ibr.intent.getIntent());
11418 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011419 Slog.w(TAG, "Exception when unbinding service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011420 + r.shortName, e);
11421 serviceDoneExecutingLocked(r, true);
11422 }
11423 }
11424 }
11425 }
11426
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011427 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down " + r + " " + r.intent);
Doug Zongker2bec3d42009-12-04 12:52:44 -080011428 EventLog.writeEvent(EventLogTags.AM_DESTROY_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011429 System.identityHashCode(r), r.shortName,
11430 (r.app != null) ? r.app.pid : -1);
11431
Amith Yamasani742a6712011-05-04 14:49:28 -070011432 mServiceMap.removeServiceByName(r.name, r.userId);
11433 mServiceMap.removeServiceByIntent(r.intent, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011434 r.totalRestartCount = 0;
11435 unscheduleServiceRestartLocked(r);
11436
11437 // Also make sure it is not on the pending list.
11438 int N = mPendingServices.size();
11439 for (int i=0; i<N; i++) {
11440 if (mPendingServices.get(i) == r) {
11441 mPendingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011442 if (DEBUG_SERVICE) Slog.v(TAG, "Removed pending: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011443 i--;
11444 N--;
11445 }
11446 }
11447
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011448 r.cancelNotification();
11449 r.isForeground = false;
11450 r.foregroundId = 0;
11451 r.foregroundNoti = null;
11452
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011453 // Clear start entries.
Dianne Hackborn39792d22010-08-19 18:01:52 -070011454 r.clearDeliveredStartsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011455 r.pendingStarts.clear();
11456
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011457 if (r.app != null) {
11458 synchronized (r.stats.getBatteryStats()) {
11459 r.stats.stopLaunchedLocked();
11460 }
11461 r.app.services.remove(r);
11462 if (r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011463 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011464 bumpServiceExecutingLocked(r, "stop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011465 mStoppingServices.add(r);
11466 updateOomAdjLocked(r.app);
11467 r.app.thread.scheduleStopService(r);
11468 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011469 Slog.w(TAG, "Exception when stopping service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011470 + r.shortName, e);
11471 serviceDoneExecutingLocked(r, true);
11472 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011473 updateServiceForegroundLocked(r.app, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011474 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011475 if (DEBUG_SERVICE) Slog.v(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011476 TAG, "Removed service that has no process: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011477 }
11478 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011479 if (DEBUG_SERVICE) Slog.v(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011480 TAG, "Removed service that is not running: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011481 }
Vairavan Srinivasana207ce22010-12-23 13:51:48 -080011482
11483 if (r.bindings.size() > 0) {
11484 r.bindings.clear();
11485 }
11486
11487 if (r.restarter instanceof ServiceRestarter) {
11488 ((ServiceRestarter)r.restarter).setService(null);
11489 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011490 }
11491
11492 ComponentName startServiceLocked(IApplicationThread caller,
11493 Intent service, String resolvedType,
11494 int callingPid, int callingUid) {
11495 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011496 if (DEBUG_SERVICE) Slog.v(TAG, "startService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011497 + " type=" + resolvedType + " args=" + service.getExtras());
11498
11499 if (caller != null) {
11500 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11501 if (callerApp == null) {
11502 throw new SecurityException(
11503 "Unable to find app for caller " + caller
11504 + " (pid=" + Binder.getCallingPid()
11505 + ") when starting service " + service);
11506 }
11507 }
11508
11509 ServiceLookupResult res =
11510 retrieveServiceLocked(service, resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011511 callingPid, callingUid, UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011512 if (res == null) {
11513 return null;
11514 }
11515 if (res.record == null) {
11516 return new ComponentName("!", res.permission != null
11517 ? res.permission : "private to package");
11518 }
11519 ServiceRecord r = res.record;
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011520 NeededUriGrants neededGrants = checkGrantUriPermissionFromIntentLocked(
11521 callingUid, r.packageName, service, service.getFlags(), null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011522 if (unscheduleServiceRestartLocked(r)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011523 if (DEBUG_SERVICE) Slog.v(TAG, "START SERVICE WHILE RESTART PENDING: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011524 }
11525 r.startRequested = true;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011526 r.callStart = false;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011527 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011528 service, neededGrants));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011529 r.lastActivity = SystemClock.uptimeMillis();
11530 synchronized (r.stats.getBatteryStats()) {
11531 r.stats.startRunningLocked();
11532 }
11533 if (!bringUpServiceLocked(r, service.getFlags(), false)) {
11534 return new ComponentName("!", "Service process is bad");
11535 }
11536 return r.name;
11537 }
11538 }
11539
11540 public ComponentName startService(IApplicationThread caller, Intent service,
11541 String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011542 enforceNotIsolatedCaller("startService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011543 // Refuse possible leaked file descriptors
11544 if (service != null && service.hasFileDescriptors() == true) {
11545 throw new IllegalArgumentException("File descriptors passed in Intent");
11546 }
11547
Amith Yamasani742a6712011-05-04 14:49:28 -070011548 if (DEBUG_SERVICE)
11549 Slog.v(TAG, "startService: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011550 synchronized(this) {
11551 final int callingPid = Binder.getCallingPid();
11552 final int callingUid = Binder.getCallingUid();
11553 final long origId = Binder.clearCallingIdentity();
11554 ComponentName res = startServiceLocked(caller, service,
11555 resolvedType, callingPid, callingUid);
11556 Binder.restoreCallingIdentity(origId);
11557 return res;
11558 }
11559 }
11560
11561 ComponentName startServiceInPackage(int uid,
11562 Intent service, String resolvedType) {
11563 synchronized(this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070011564 if (DEBUG_SERVICE)
11565 Slog.v(TAG, "startServiceInPackage: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011566 final long origId = Binder.clearCallingIdentity();
11567 ComponentName res = startServiceLocked(null, service,
11568 resolvedType, -1, uid);
11569 Binder.restoreCallingIdentity(origId);
11570 return res;
11571 }
11572 }
11573
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011574 private void stopServiceLocked(ServiceRecord service) {
11575 synchronized (service.stats.getBatteryStats()) {
11576 service.stats.stopRunningLocked();
11577 }
11578 service.startRequested = false;
11579 service.callStart = false;
11580 bringDownServiceLocked(service, false);
11581 }
11582
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011583 public int stopService(IApplicationThread caller, Intent service,
11584 String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011585 enforceNotIsolatedCaller("stopService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011586 // Refuse possible leaked file descriptors
11587 if (service != null && service.hasFileDescriptors() == true) {
11588 throw new IllegalArgumentException("File descriptors passed in Intent");
11589 }
11590
11591 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011592 if (DEBUG_SERVICE) Slog.v(TAG, "stopService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011593 + " type=" + resolvedType);
11594
11595 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11596 if (caller != null && callerApp == null) {
11597 throw new SecurityException(
11598 "Unable to find app for caller " + caller
11599 + " (pid=" + Binder.getCallingPid()
11600 + ") when stopping service " + service);
11601 }
11602
11603 // If this service is active, make sure it is stopped.
Amith Yamasani483f3b02012-03-13 16:08:00 -070011604 ServiceLookupResult r = findServiceLocked(service, resolvedType,
11605 callerApp == null ? UserId.getCallingUserId() : callerApp.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011606 if (r != null) {
11607 if (r.record != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011608 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011609 try {
11610 stopServiceLocked(r.record);
11611 } finally {
11612 Binder.restoreCallingIdentity(origId);
11613 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011614 return 1;
11615 }
11616 return -1;
11617 }
11618 }
11619
11620 return 0;
11621 }
11622
11623 public IBinder peekService(Intent service, String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011624 enforceNotIsolatedCaller("peekService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011625 // Refuse possible leaked file descriptors
11626 if (service != null && service.hasFileDescriptors() == true) {
11627 throw new IllegalArgumentException("File descriptors passed in Intent");
11628 }
11629
11630 IBinder ret = null;
11631
11632 synchronized(this) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070011633 ServiceLookupResult r = findServiceLocked(service, resolvedType,
11634 UserId.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011635
11636 if (r != null) {
11637 // r.record is null if findServiceLocked() failed the caller permission check
11638 if (r.record == null) {
11639 throw new SecurityException(
11640 "Permission Denial: Accessing service " + r.record.name
11641 + " from pid=" + Binder.getCallingPid()
11642 + ", uid=" + Binder.getCallingUid()
11643 + " requires " + r.permission);
11644 }
11645 IntentBindRecord ib = r.record.bindings.get(r.record.intent);
11646 if (ib != null) {
11647 ret = ib.binder;
11648 }
11649 }
11650 }
11651
11652 return ret;
11653 }
11654
11655 public boolean stopServiceToken(ComponentName className, IBinder token,
11656 int startId) {
11657 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011658 if (DEBUG_SERVICE) Slog.v(TAG, "stopServiceToken: " + className
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011659 + " " + token + " startId=" + startId);
11660 ServiceRecord r = findServiceLocked(className, token);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011661 if (r != null) {
11662 if (startId >= 0) {
11663 // Asked to only stop if done with all work. Note that
11664 // to avoid leaks, we will take this as dropping all
11665 // start items up to and including this one.
11666 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
11667 if (si != null) {
11668 while (r.deliveredStarts.size() > 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -070011669 ServiceRecord.StartItem cur = r.deliveredStarts.remove(0);
11670 cur.removeUriPermissionsLocked();
11671 if (cur == si) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011672 break;
11673 }
11674 }
11675 }
11676
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011677 if (r.getLastStartId() != startId) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011678 return false;
11679 }
11680
11681 if (r.deliveredStarts.size() > 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011682 Slog.w(TAG, "stopServiceToken startId " + startId
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011683 + " is last, but have " + r.deliveredStarts.size()
11684 + " remaining args");
11685 }
11686 }
11687
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011688 synchronized (r.stats.getBatteryStats()) {
11689 r.stats.stopRunningLocked();
11690 r.startRequested = false;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011691 r.callStart = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011692 }
11693 final long origId = Binder.clearCallingIdentity();
11694 bringDownServiceLocked(r, false);
11695 Binder.restoreCallingIdentity(origId);
11696 return true;
11697 }
11698 }
11699 return false;
11700 }
11701
11702 public void setServiceForeground(ComponentName className, IBinder token,
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011703 int id, Notification notification, boolean removeNotification) {
11704 final long origId = Binder.clearCallingIdentity();
11705 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011706 synchronized(this) {
11707 ServiceRecord r = findServiceLocked(className, token);
11708 if (r != null) {
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011709 if (id != 0) {
11710 if (notification == null) {
11711 throw new IllegalArgumentException("null notification");
11712 }
11713 if (r.foregroundId != id) {
11714 r.cancelNotification();
11715 r.foregroundId = id;
11716 }
11717 notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
11718 r.foregroundNoti = notification;
11719 r.isForeground = true;
11720 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011721 if (r.app != null) {
11722 updateServiceForegroundLocked(r.app, true);
11723 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011724 } else {
11725 if (r.isForeground) {
11726 r.isForeground = false;
11727 if (r.app != null) {
Dianne Hackborn8633e682010-04-22 16:03:41 -070011728 updateLruProcessLocked(r.app, false, true);
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011729 updateServiceForegroundLocked(r.app, true);
11730 }
11731 }
11732 if (removeNotification) {
11733 r.cancelNotification();
11734 r.foregroundId = 0;
11735 r.foregroundNoti = null;
11736 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011737 }
11738 }
11739 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011740 } finally {
11741 Binder.restoreCallingIdentity(origId);
11742 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011743 }
11744
11745 public void updateServiceForegroundLocked(ProcessRecord proc, boolean oomAdj) {
11746 boolean anyForeground = false;
Dianne Hackborn860755f2010-06-03 18:47:52 -070011747 for (ServiceRecord sr : proc.services) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011748 if (sr.isForeground) {
11749 anyForeground = true;
11750 break;
11751 }
11752 }
11753 if (anyForeground != proc.foregroundServices) {
11754 proc.foregroundServices = anyForeground;
11755 if (oomAdj) {
11756 updateOomAdjLocked();
11757 }
11758 }
11759 }
Amith Yamasania4a54e22012-04-16 15:44:19 -070011760
11761 boolean isSingleton(String componentProcessName, ApplicationInfo aInfo) {
11762 boolean result = false;
11763 if (UserId.getAppId(aInfo.uid) >= Process.FIRST_APPLICATION_UID) {
11764 result = false;
11765 } else if (componentProcessName == aInfo.packageName) {
11766 result = (aInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0;
11767 } else if ("system".equals(componentProcessName)) {
11768 result = true;
11769 }
11770 if (DEBUG_MU) {
11771 Slog.v(TAG, "isSingleton(" + componentProcessName + ", " + aInfo + ") = " + result);
11772 }
11773 return result;
11774 }
11775
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011776 public int bindService(IApplicationThread caller, IBinder token,
11777 Intent service, String resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011778 IServiceConnection connection, int flags, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011779 enforceNotIsolatedCaller("bindService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011780 // Refuse possible leaked file descriptors
11781 if (service != null && service.hasFileDescriptors() == true) {
11782 throw new IllegalArgumentException("File descriptors passed in Intent");
11783 }
11784
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011785 checkValidCaller(Binder.getCallingUid(), userId);
11786
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011787 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011788 if (DEBUG_SERVICE) Slog.v(TAG, "bindService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011789 + " type=" + resolvedType + " conn=" + connection.asBinder()
11790 + " flags=0x" + Integer.toHexString(flags));
Amith Yamasani742a6712011-05-04 14:49:28 -070011791 if (DEBUG_MU)
11792 Slog.i(TAG_MU, "bindService uid=" + Binder.getCallingUid() + " origUid="
11793 + Binder.getOrigCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011794 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11795 if (callerApp == null) {
11796 throw new SecurityException(
11797 "Unable to find app for caller " + caller
11798 + " (pid=" + Binder.getCallingPid()
11799 + ") when binding service " + service);
11800 }
11801
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011802 ActivityRecord activity = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011803 if (token != null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070011804 activity = mMainStack.isInStackLocked(token);
11805 if (activity == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011806 Slog.w(TAG, "Binding with unknown activity: " + token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011807 return 0;
11808 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011809 }
11810
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011811 int clientLabel = 0;
11812 PendingIntent clientIntent = null;
11813
11814 if (callerApp.info.uid == Process.SYSTEM_UID) {
11815 // Hacky kind of thing -- allow system stuff to tell us
11816 // what they are, so we can report this elsewhere for
11817 // others to know why certain services are running.
11818 try {
11819 clientIntent = (PendingIntent)service.getParcelableExtra(
11820 Intent.EXTRA_CLIENT_INTENT);
11821 } catch (RuntimeException e) {
11822 }
11823 if (clientIntent != null) {
11824 clientLabel = service.getIntExtra(Intent.EXTRA_CLIENT_LABEL, 0);
11825 if (clientLabel != 0) {
11826 // There are no useful extras in the intent, trash them.
11827 // System code calling with this stuff just needs to know
11828 // this will happen.
11829 service = service.cloneFilter();
11830 }
11831 }
11832 }
11833
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011834 ServiceLookupResult res =
11835 retrieveServiceLocked(service, resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011836 Binder.getCallingPid(), Binder.getCallingUid(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011837 if (res == null) {
11838 return 0;
11839 }
11840 if (res.record == null) {
11841 return -1;
11842 }
Amith Yamasania4a54e22012-04-16 15:44:19 -070011843 if (isSingleton(res.record.processName, res.record.appInfo)) {
11844 userId = 0;
11845 res = retrieveServiceLocked(service, resolvedType, Binder.getCallingPid(),
11846 Binder.getCallingUid(), 0);
11847 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011848 ServiceRecord s = res.record;
11849
11850 final long origId = Binder.clearCallingIdentity();
11851
11852 if (unscheduleServiceRestartLocked(s)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011853 if (DEBUG_SERVICE) Slog.v(TAG, "BIND SERVICE WHILE RESTART PENDING: "
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011854 + s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011855 }
11856
11857 AppBindRecord b = s.retrieveAppBindingLocked(service, callerApp);
11858 ConnectionRecord c = new ConnectionRecord(b, activity,
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011859 connection, flags, clientLabel, clientIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011860
11861 IBinder binder = connection.asBinder();
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011862 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
11863 if (clist == null) {
11864 clist = new ArrayList<ConnectionRecord>();
11865 s.connections.put(binder, clist);
11866 }
11867 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011868 b.connections.add(c);
11869 if (activity != null) {
11870 if (activity.connections == null) {
11871 activity.connections = new HashSet<ConnectionRecord>();
11872 }
11873 activity.connections.add(c);
11874 }
11875 b.client.connections.add(c);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070011876 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
11877 b.client.hasAboveClient = true;
11878 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011879 clist = mServiceConnections.get(binder);
11880 if (clist == null) {
11881 clist = new ArrayList<ConnectionRecord>();
11882 mServiceConnections.put(binder, clist);
11883 }
11884 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011885
11886 if ((flags&Context.BIND_AUTO_CREATE) != 0) {
11887 s.lastActivity = SystemClock.uptimeMillis();
11888 if (!bringUpServiceLocked(s, service.getFlags(), false)) {
11889 return 0;
11890 }
11891 }
11892
11893 if (s.app != null) {
11894 // This could have made the service more important.
11895 updateOomAdjLocked(s.app);
11896 }
11897
Joe Onorato8a9b2202010-02-26 18:56:32 -080011898 if (DEBUG_SERVICE) Slog.v(TAG, "Bind " + s + " with " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011899 + ": received=" + b.intent.received
11900 + " apps=" + b.intent.apps.size()
11901 + " doRebind=" + b.intent.doRebind);
11902
11903 if (s.app != null && b.intent.received) {
11904 // Service is already running, so we can immediately
11905 // publish the connection.
11906 try {
11907 c.conn.connected(s.name, b.intent.binder);
11908 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011909 Slog.w(TAG, "Failure sending service " + s.shortName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011910 + " to connection " + c.conn.asBinder()
11911 + " (in " + c.binding.client.processName + ")", e);
11912 }
11913
11914 // If this is the first app connected back to this binding,
11915 // and the service had previously asked to be told when
11916 // rebound, then do so.
11917 if (b.intent.apps.size() == 1 && b.intent.doRebind) {
11918 requestServiceBindingLocked(s, b.intent, true);
11919 }
11920 } else if (!b.intent.requested) {
11921 requestServiceBindingLocked(s, b.intent, false);
11922 }
11923
11924 Binder.restoreCallingIdentity(origId);
11925 }
11926
11927 return 1;
11928 }
11929
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070011930 void removeConnectionLocked(
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011931 ConnectionRecord c, ProcessRecord skipApp, ActivityRecord skipAct) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011932 IBinder binder = c.conn.asBinder();
11933 AppBindRecord b = c.binding;
11934 ServiceRecord s = b.service;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011935 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
11936 if (clist != null) {
11937 clist.remove(c);
11938 if (clist.size() == 0) {
11939 s.connections.remove(binder);
11940 }
11941 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011942 b.connections.remove(c);
11943 if (c.activity != null && c.activity != skipAct) {
11944 if (c.activity.connections != null) {
11945 c.activity.connections.remove(c);
11946 }
11947 }
11948 if (b.client != skipApp) {
11949 b.client.connections.remove(c);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070011950 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
11951 b.client.updateHasAboveClientLocked();
11952 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011953 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011954 clist = mServiceConnections.get(binder);
11955 if (clist != null) {
11956 clist.remove(c);
11957 if (clist.size() == 0) {
11958 mServiceConnections.remove(binder);
11959 }
11960 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011961
11962 if (b.connections.size() == 0) {
11963 b.intent.apps.remove(b.client);
11964 }
11965
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011966 if (!c.serviceDead) {
11967 if (DEBUG_SERVICE) Slog.v(TAG, "Disconnecting binding " + b.intent
11968 + ": shouldUnbind=" + b.intent.hasBound);
11969 if (s.app != null && s.app.thread != null && b.intent.apps.size() == 0
11970 && b.intent.hasBound) {
11971 try {
11972 bumpServiceExecutingLocked(s, "unbind");
11973 updateOomAdjLocked(s.app);
11974 b.intent.hasBound = false;
11975 // Assume the client doesn't want to know about a rebind;
11976 // we will deal with that later if it asks for one.
11977 b.intent.doRebind = false;
11978 s.app.thread.scheduleUnbindService(s, b.intent.intent.getIntent());
11979 } catch (Exception e) {
11980 Slog.w(TAG, "Exception when unbinding service " + s.shortName, e);
11981 serviceDoneExecutingLocked(s, true);
11982 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011983 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011984
11985 if ((c.flags&Context.BIND_AUTO_CREATE) != 0) {
11986 bringDownServiceLocked(s, false);
11987 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011988 }
11989 }
11990
11991 public boolean unbindService(IServiceConnection connection) {
11992 synchronized (this) {
11993 IBinder binder = connection.asBinder();
Joe Onorato8a9b2202010-02-26 18:56:32 -080011994 if (DEBUG_SERVICE) Slog.v(TAG, "unbindService: conn=" + binder);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011995 ArrayList<ConnectionRecord> clist = mServiceConnections.get(binder);
11996 if (clist == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011997 Slog.w(TAG, "Unbind failed: could not find connection for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011998 + connection.asBinder());
11999 return false;
12000 }
12001
12002 final long origId = Binder.clearCallingIdentity();
12003
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012004 while (clist.size() > 0) {
12005 ConnectionRecord r = clist.get(0);
12006 removeConnectionLocked(r, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012007
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012008 if (r.binding.service.app != null) {
12009 // This could have made the service less important.
12010 updateOomAdjLocked(r.binding.service.app);
12011 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012012 }
12013
12014 Binder.restoreCallingIdentity(origId);
12015 }
12016
12017 return true;
12018 }
12019
12020 public void publishService(IBinder token, Intent intent, IBinder service) {
12021 // Refuse possible leaked file descriptors
12022 if (intent != null && intent.hasFileDescriptors() == true) {
12023 throw new IllegalArgumentException("File descriptors passed in Intent");
12024 }
12025
12026 synchronized(this) {
12027 if (!(token instanceof ServiceRecord)) {
12028 throw new IllegalArgumentException("Invalid service token");
12029 }
12030 ServiceRecord r = (ServiceRecord)token;
12031
12032 final long origId = Binder.clearCallingIdentity();
12033
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012034 if (DEBUG_SERVICE) Slog.v(TAG, "PUBLISHING " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012035 + " " + intent + ": " + service);
12036 if (r != null) {
12037 Intent.FilterComparison filter
12038 = new Intent.FilterComparison(intent);
12039 IntentBindRecord b = r.bindings.get(filter);
12040 if (b != null && !b.received) {
12041 b.binder = service;
12042 b.requested = true;
12043 b.received = true;
12044 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012045 Iterator<ArrayList<ConnectionRecord>> it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012046 = r.connections.values().iterator();
12047 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012048 ArrayList<ConnectionRecord> clist = it.next();
12049 for (int i=0; i<clist.size(); i++) {
12050 ConnectionRecord c = clist.get(i);
12051 if (!filter.equals(c.binding.intent.intent)) {
12052 if (DEBUG_SERVICE) Slog.v(
12053 TAG, "Not publishing to: " + c);
12054 if (DEBUG_SERVICE) Slog.v(
12055 TAG, "Bound intent: " + c.binding.intent.intent);
12056 if (DEBUG_SERVICE) Slog.v(
12057 TAG, "Published intent: " + intent);
12058 continue;
12059 }
12060 if (DEBUG_SERVICE) Slog.v(TAG, "Publishing to: " + c);
12061 try {
12062 c.conn.connected(r.name, service);
12063 } catch (Exception e) {
12064 Slog.w(TAG, "Failure sending service " + r.name +
12065 " to connection " + c.conn.asBinder() +
12066 " (in " + c.binding.client.processName + ")", e);
12067 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012068 }
12069 }
12070 }
12071 }
12072
12073 serviceDoneExecutingLocked(r, mStoppingServices.contains(r));
12074
12075 Binder.restoreCallingIdentity(origId);
12076 }
12077 }
12078 }
12079
12080 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
12081 // Refuse possible leaked file descriptors
12082 if (intent != null && intent.hasFileDescriptors() == true) {
12083 throw new IllegalArgumentException("File descriptors passed in Intent");
12084 }
12085
12086 synchronized(this) {
12087 if (!(token instanceof ServiceRecord)) {
12088 throw new IllegalArgumentException("Invalid service token");
12089 }
12090 ServiceRecord r = (ServiceRecord)token;
12091
12092 final long origId = Binder.clearCallingIdentity();
12093
12094 if (r != null) {
12095 Intent.FilterComparison filter
12096 = new Intent.FilterComparison(intent);
12097 IntentBindRecord b = r.bindings.get(filter);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012098 if (DEBUG_SERVICE) Slog.v(TAG, "unbindFinished in " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012099 + " at " + b + ": apps="
12100 + (b != null ? b.apps.size() : 0));
Per Edelberg78f9fff2010-08-30 20:01:35 +020012101
12102 boolean inStopping = mStoppingServices.contains(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012103 if (b != null) {
Per Edelberg78f9fff2010-08-30 20:01:35 +020012104 if (b.apps.size() > 0 && !inStopping) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012105 // Applications have already bound since the last
12106 // unbind, so just rebind right here.
12107 requestServiceBindingLocked(r, b, true);
12108 } else {
12109 // Note to tell the service the next time there is
12110 // a new client.
12111 b.doRebind = true;
12112 }
12113 }
12114
Per Edelberg78f9fff2010-08-30 20:01:35 +020012115 serviceDoneExecutingLocked(r, inStopping);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012116
12117 Binder.restoreCallingIdentity(origId);
12118 }
12119 }
12120 }
12121
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012122 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012123 synchronized(this) {
12124 if (!(token instanceof ServiceRecord)) {
12125 throw new IllegalArgumentException("Invalid service token");
12126 }
12127 ServiceRecord r = (ServiceRecord)token;
12128 boolean inStopping = mStoppingServices.contains(token);
12129 if (r != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012130 if (r != token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012131 Slog.w(TAG, "Done executing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012132 + " with incorrect token: given " + token
12133 + ", expected " + r);
12134 return;
12135 }
12136
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012137 if (type == 1) {
12138 // This is a call from a service start... take care of
12139 // book-keeping.
12140 r.callStart = true;
12141 switch (res) {
12142 case Service.START_STICKY_COMPATIBILITY:
12143 case Service.START_STICKY: {
12144 // We are done with the associated start arguments.
12145 r.findDeliveredStart(startId, true);
12146 // Don't stop if killed.
12147 r.stopIfKilled = false;
12148 break;
12149 }
12150 case Service.START_NOT_STICKY: {
12151 // We are done with the associated start arguments.
12152 r.findDeliveredStart(startId, true);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070012153 if (r.getLastStartId() == startId) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012154 // There is no more work, and this service
12155 // doesn't want to hang around if killed.
12156 r.stopIfKilled = true;
12157 }
12158 break;
12159 }
12160 case Service.START_REDELIVER_INTENT: {
12161 // We'll keep this item until they explicitly
12162 // call stop for it, but keep track of the fact
12163 // that it was delivered.
12164 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
12165 if (si != null) {
12166 si.deliveryCount = 0;
12167 si.doneExecutingCount++;
12168 // Don't stop if killed.
12169 r.stopIfKilled = true;
12170 }
12171 break;
12172 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070012173 case Service.START_TASK_REMOVED_COMPLETE: {
12174 // Special processing for onTaskRemoved(). Don't
12175 // impact normal onStartCommand() processing.
12176 r.findDeliveredStart(startId, true);
12177 break;
12178 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012179 default:
12180 throw new IllegalArgumentException(
12181 "Unknown service start result: " + res);
12182 }
12183 if (res == Service.START_STICKY_COMPATIBILITY) {
12184 r.callStart = false;
12185 }
12186 }
Amith Yamasani742a6712011-05-04 14:49:28 -070012187 if (DEBUG_MU)
12188 Slog.v(TAG_MU, "before serviceDontExecutingLocked, uid="
12189 + Binder.getOrigCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012190 final long origId = Binder.clearCallingIdentity();
12191 serviceDoneExecutingLocked(r, inStopping);
12192 Binder.restoreCallingIdentity(origId);
12193 } else {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012194 Slog.w(TAG, "Done executing unknown service from pid "
12195 + Binder.getCallingPid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012196 }
12197 }
12198 }
12199
12200 public void serviceDoneExecutingLocked(ServiceRecord r, boolean inStopping) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012201 if (DEBUG_SERVICE) Slog.v(TAG, "<<< DONE EXECUTING " + r
12202 + ": nesting=" + r.executeNesting
12203 + ", inStopping=" + inStopping + ", app=" + r.app);
Dianne Hackborn287952c2010-09-22 22:34:31 -070012204 else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG, "<<< DONE EXECUTING " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012205 r.executeNesting--;
12206 if (r.executeNesting <= 0 && r.app != null) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012207 if (DEBUG_SERVICE) Slog.v(TAG,
12208 "Nesting at 0 of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012209 r.app.executingServices.remove(r);
12210 if (r.app.executingServices.size() == 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012211 if (DEBUG_SERVICE || DEBUG_SERVICE_EXECUTING) Slog.v(TAG,
12212 "No more executingServices of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012213 mHandler.removeMessages(SERVICE_TIMEOUT_MSG, r.app);
12214 }
12215 if (inStopping) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012216 if (DEBUG_SERVICE) Slog.v(TAG,
12217 "doneExecuting remove stopping " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012218 mStoppingServices.remove(r);
Mattias Petersson3996b412010-10-27 09:32:51 +020012219 r.bindings.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012220 }
12221 updateOomAdjLocked(r.app);
12222 }
12223 }
12224
12225 void serviceTimeout(ProcessRecord proc) {
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012226 String anrMessage = null;
12227
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012228 synchronized(this) {
12229 if (proc.executingServices.size() == 0 || proc.thread == null) {
12230 return;
12231 }
12232 long maxTime = SystemClock.uptimeMillis() - SERVICE_TIMEOUT;
12233 Iterator<ServiceRecord> it = proc.executingServices.iterator();
12234 ServiceRecord timeout = null;
12235 long nextTime = 0;
12236 while (it.hasNext()) {
12237 ServiceRecord sr = it.next();
12238 if (sr.executingStart < maxTime) {
12239 timeout = sr;
12240 break;
12241 }
12242 if (sr.executingStart > nextTime) {
12243 nextTime = sr.executingStart;
12244 }
12245 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012246 if (timeout != null && mLruProcesses.contains(proc)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012247 Slog.w(TAG, "Timeout executing service: " + timeout);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012248 anrMessage = "Executing service " + timeout.shortName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012249 } else {
12250 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
12251 msg.obj = proc;
12252 mHandler.sendMessageAtTime(msg, nextTime+SERVICE_TIMEOUT);
12253 }
12254 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012255
12256 if (anrMessage != null) {
12257 appNotResponding(proc, null, null, anrMessage);
12258 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012259 }
12260
12261 // =========================================================
Christopher Tate181fafa2009-05-14 11:12:14 -070012262 // BACKUP AND RESTORE
12263 // =========================================================
12264
12265 // Cause the target app to be launched if necessary and its backup agent
12266 // instantiated. The backup agent will invoke backupAgentCreated() on the
12267 // activity manager to announce its creation.
12268 public boolean bindBackupAgent(ApplicationInfo app, int backupMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012269 if (DEBUG_BACKUP) Slog.v(TAG, "startBackupAgent: app=" + app + " mode=" + backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070012270 enforceCallingPermission("android.permission.BACKUP", "startBackupAgent");
12271
12272 synchronized(this) {
12273 // !!! TODO: currently no check here that we're already bound
12274 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
12275 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
12276 synchronized (stats) {
12277 ss = stats.getServiceStatsLocked(app.uid, app.packageName, app.name);
12278 }
12279
Dianne Hackborne7f97212011-02-24 14:40:20 -080012280 // Backup agent is now in use, its package can't be stopped.
12281 try {
12282 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -070012283 app.packageName, false, UserId.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -080012284 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080012285 } catch (IllegalArgumentException e) {
12286 Slog.w(TAG, "Failed trying to unstop package "
12287 + app.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080012288 }
12289
Christopher Tate181fafa2009-05-14 11:12:14 -070012290 BackupRecord r = new BackupRecord(ss, app, backupMode);
Christopher Tate4a627c72011-04-01 14:43:32 -070012291 ComponentName hostingName = (backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL)
12292 ? new ComponentName(app.packageName, app.backupAgentName)
12293 : new ComponentName("android", "FullBackupAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -070012294 // startProcessLocked() returns existing proc's record if it's already running
12295 ProcessRecord proc = startProcessLocked(app.processName, app,
Dianne Hackborna0c283e2012-02-09 10:47:01 -080012296 false, 0, "backup", hostingName, false, false);
Christopher Tate181fafa2009-05-14 11:12:14 -070012297 if (proc == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012298 Slog.e(TAG, "Unable to start backup agent process " + r);
Christopher Tate181fafa2009-05-14 11:12:14 -070012299 return false;
12300 }
12301
12302 r.app = proc;
12303 mBackupTarget = r;
12304 mBackupAppName = app.packageName;
12305
Christopher Tate6fa95972009-06-05 18:43:55 -070012306 // Try not to kill the process during backup
12307 updateOomAdjLocked(proc);
12308
Christopher Tate181fafa2009-05-14 11:12:14 -070012309 // If the process is already attached, schedule the creation of the backup agent now.
12310 // If it is not yet live, this will be done when it attaches to the framework.
12311 if (proc.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012312 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc already running: " + proc);
Christopher Tate181fafa2009-05-14 11:12:14 -070012313 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040012314 proc.thread.scheduleCreateBackupAgent(app,
12315 compatibilityInfoForPackageLocked(app), backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070012316 } catch (RemoteException e) {
Christopher Tate436344a2009-09-30 16:17:37 -070012317 // Will time out on the backup manager side
Christopher Tate181fafa2009-05-14 11:12:14 -070012318 }
12319 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012320 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc not running, waiting for attach");
Christopher Tate181fafa2009-05-14 11:12:14 -070012321 }
12322 // Invariants: at this point, the target app process exists and the application
12323 // is either already running or in the process of coming up. mBackupTarget and
12324 // mBackupAppName describe the app, so that when it binds back to the AM we
12325 // know that it's scheduled for a backup-agent operation.
12326 }
12327
12328 return true;
12329 }
12330
12331 // A backup agent has just come up
12332 public void backupAgentCreated(String agentPackageName, IBinder agent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012333 if (DEBUG_BACKUP) Slog.v(TAG, "backupAgentCreated: " + agentPackageName
Christopher Tate181fafa2009-05-14 11:12:14 -070012334 + " = " + agent);
12335
12336 synchronized(this) {
12337 if (!agentPackageName.equals(mBackupAppName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012338 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
Christopher Tate181fafa2009-05-14 11:12:14 -070012339 return;
12340 }
Dianne Hackborn06740692010-09-22 22:46:21 -070012341 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012342
Dianne Hackborn06740692010-09-22 22:46:21 -070012343 long oldIdent = Binder.clearCallingIdentity();
12344 try {
12345 IBackupManager bm = IBackupManager.Stub.asInterface(
12346 ServiceManager.getService(Context.BACKUP_SERVICE));
12347 bm.agentConnected(agentPackageName, agent);
12348 } catch (RemoteException e) {
12349 // can't happen; the backup manager service is local
12350 } catch (Exception e) {
12351 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: ");
12352 e.printStackTrace();
12353 } finally {
12354 Binder.restoreCallingIdentity(oldIdent);
Christopher Tate181fafa2009-05-14 11:12:14 -070012355 }
12356 }
12357
12358 // done with this agent
12359 public void unbindBackupAgent(ApplicationInfo appInfo) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012360 if (DEBUG_BACKUP) Slog.v(TAG, "unbindBackupAgent: " + appInfo);
Christopher Tate8a27f922009-06-26 11:49:18 -070012361 if (appInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012362 Slog.w(TAG, "unbind backup agent for null app");
Christopher Tate8a27f922009-06-26 11:49:18 -070012363 return;
12364 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012365
12366 synchronized(this) {
Christopher Tate8a27f922009-06-26 11:49:18 -070012367 if (mBackupAppName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012368 Slog.w(TAG, "Unbinding backup agent with no active backup");
Christopher Tate8a27f922009-06-26 11:49:18 -070012369 return;
12370 }
12371
Christopher Tate181fafa2009-05-14 11:12:14 -070012372 if (!mBackupAppName.equals(appInfo.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012373 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
Christopher Tate181fafa2009-05-14 11:12:14 -070012374 return;
12375 }
12376
Christopher Tate6fa95972009-06-05 18:43:55 -070012377 ProcessRecord proc = mBackupTarget.app;
12378 mBackupTarget = null;
12379 mBackupAppName = null;
12380
12381 // Not backing this app up any more; reset its OOM adjustment
12382 updateOomAdjLocked(proc);
12383
Christopher Tatec7b31e32009-06-10 15:49:30 -070012384 // If the app crashed during backup, 'thread' will be null here
12385 if (proc.thread != null) {
12386 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040012387 proc.thread.scheduleDestroyBackupAgent(appInfo,
12388 compatibilityInfoForPackageLocked(appInfo));
Christopher Tatec7b31e32009-06-10 15:49:30 -070012389 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012390 Slog.e(TAG, "Exception when unbinding backup agent:");
Christopher Tatec7b31e32009-06-10 15:49:30 -070012391 e.printStackTrace();
12392 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012393 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012394 }
12395 }
12396 // =========================================================
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012397 // BROADCASTS
12398 // =========================================================
12399
Josh Bartel7f208742010-02-25 11:01:44 -060012400 private final List getStickiesLocked(String action, IntentFilter filter,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012401 List cur) {
12402 final ContentResolver resolver = mContext.getContentResolver();
12403 final ArrayList<Intent> list = mStickyBroadcasts.get(action);
12404 if (list == null) {
12405 return cur;
12406 }
12407 int N = list.size();
12408 for (int i=0; i<N; i++) {
12409 Intent intent = list.get(i);
12410 if (filter.match(resolver, intent, true, TAG) >= 0) {
12411 if (cur == null) {
12412 cur = new ArrayList<Intent>();
12413 }
12414 cur.add(intent);
12415 }
12416 }
12417 return cur;
12418 }
12419
Christopher Tatef46723b2012-01-26 14:19:24 -080012420 boolean isPendingBroadcastProcessLocked(int pid) {
12421 return mFgBroadcastQueue.isPendingBroadcastProcessLocked(pid)
12422 || mBgBroadcastQueue.isPendingBroadcastProcessLocked(pid);
12423 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012424
Christopher Tatef46723b2012-01-26 14:19:24 -080012425 void skipPendingBroadcastLocked(int pid) {
12426 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
12427 for (BroadcastQueue queue : mBroadcastQueues) {
12428 queue.skipPendingBroadcastLocked(pid);
12429 }
12430 }
12431
12432 // The app just attached; send any pending broadcasts that it should receive
12433 boolean sendPendingBroadcastsLocked(ProcessRecord app) {
12434 boolean didSomething = false;
12435 for (BroadcastQueue queue : mBroadcastQueues) {
12436 didSomething |= queue.sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012437 }
Christopher Tatef46723b2012-01-26 14:19:24 -080012438 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012439 }
12440
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012441 public Intent registerReceiver(IApplicationThread caller, String callerPackage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012442 IIntentReceiver receiver, IntentFilter filter, String permission) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012443 enforceNotIsolatedCaller("registerReceiver");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012444 synchronized(this) {
12445 ProcessRecord callerApp = null;
12446 if (caller != null) {
12447 callerApp = getRecordForAppLocked(caller);
12448 if (callerApp == null) {
12449 throw new SecurityException(
12450 "Unable to find app for caller " + caller
12451 + " (pid=" + Binder.getCallingPid()
12452 + ") when registering receiver " + receiver);
12453 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012454 if (callerApp.info.uid != Process.SYSTEM_UID &&
12455 !callerApp.pkgList.contains(callerPackage)) {
12456 throw new SecurityException("Given caller package " + callerPackage
12457 + " is not running in process " + callerApp);
12458 }
12459 } else {
12460 callerPackage = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012461 }
12462
12463 List allSticky = null;
12464
12465 // Look for any matching sticky broadcasts...
12466 Iterator actions = filter.actionsIterator();
12467 if (actions != null) {
12468 while (actions.hasNext()) {
12469 String action = (String)actions.next();
Josh Bartel7f208742010-02-25 11:01:44 -060012470 allSticky = getStickiesLocked(action, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012471 }
12472 } else {
Josh Bartel7f208742010-02-25 11:01:44 -060012473 allSticky = getStickiesLocked(null, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012474 }
12475
12476 // The first sticky in the list is returned directly back to
12477 // the client.
12478 Intent sticky = allSticky != null ? (Intent)allSticky.get(0) : null;
12479
Joe Onorato8a9b2202010-02-26 18:56:32 -080012480 if (DEBUG_BROADCAST) Slog.v(TAG, "Register receiver " + filter
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012481 + ": " + sticky);
12482
12483 if (receiver == null) {
12484 return sticky;
12485 }
12486
12487 ReceiverList rl
12488 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
12489 if (rl == null) {
12490 rl = new ReceiverList(this, callerApp,
12491 Binder.getCallingPid(),
12492 Binder.getCallingUid(), receiver);
12493 if (rl.app != null) {
12494 rl.app.receivers.add(rl);
12495 } else {
12496 try {
12497 receiver.asBinder().linkToDeath(rl, 0);
12498 } catch (RemoteException e) {
12499 return sticky;
12500 }
12501 rl.linkedToDeath = true;
12502 }
12503 mRegisteredReceivers.put(receiver.asBinder(), rl);
12504 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012505 BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage, permission);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012506 rl.add(bf);
12507 if (!bf.debugCheck()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012508 Slog.w(TAG, "==> For Dynamic broadast");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012509 }
12510 mReceiverResolver.addFilter(bf);
12511
12512 // Enqueue broadcasts for all existing stickies that match
12513 // this filter.
12514 if (allSticky != null) {
12515 ArrayList receivers = new ArrayList();
12516 receivers.add(bf);
12517
12518 int N = allSticky.size();
12519 for (int i=0; i<N; i++) {
12520 Intent intent = (Intent)allSticky.get(i);
Christopher Tatef46723b2012-01-26 14:19:24 -080012521 BroadcastQueue queue = broadcastQueueForIntent(intent);
12522 BroadcastRecord r = new BroadcastRecord(queue, intent, null,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012523 null, -1, -1, null, receivers, null, 0, null, null,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012524 false, true, true);
Christopher Tatef46723b2012-01-26 14:19:24 -080012525 queue.enqueueParallelBroadcastLocked(r);
12526 queue.scheduleBroadcastsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012527 }
12528 }
12529
12530 return sticky;
12531 }
12532 }
12533
12534 public void unregisterReceiver(IIntentReceiver receiver) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012535 if (DEBUG_BROADCAST) Slog.v(TAG, "Unregister receiver: " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012536
Christopher Tatef46723b2012-01-26 14:19:24 -080012537 final long origId = Binder.clearCallingIdentity();
12538 try {
12539 boolean doTrim = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012540
Christopher Tatef46723b2012-01-26 14:19:24 -080012541 synchronized(this) {
12542 ReceiverList rl
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012543 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
Christopher Tatef46723b2012-01-26 14:19:24 -080012544 if (rl != null) {
12545 if (rl.curBroadcast != null) {
12546 BroadcastRecord r = rl.curBroadcast;
12547 final boolean doNext = finishReceiverLocked(
12548 receiver.asBinder(), r.resultCode, r.resultData,
12549 r.resultExtras, r.resultAbort, true);
12550 if (doNext) {
12551 doTrim = true;
12552 r.queue.processNextBroadcast(false);
12553 }
12554 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012555
Christopher Tatef46723b2012-01-26 14:19:24 -080012556 if (rl.app != null) {
12557 rl.app.receivers.remove(rl);
12558 }
12559 removeReceiverLocked(rl);
12560 if (rl.linkedToDeath) {
12561 rl.linkedToDeath = false;
12562 rl.receiver.asBinder().unlinkToDeath(rl, 0);
12563 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012564 }
12565 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012566
Christopher Tatef46723b2012-01-26 14:19:24 -080012567 // If we actually concluded any broadcasts, we might now be able
12568 // to trim the recipients' apps from our working set
12569 if (doTrim) {
12570 trimApplications();
12571 return;
12572 }
12573
12574 } finally {
12575 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012576 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012577 }
12578
12579 void removeReceiverLocked(ReceiverList rl) {
12580 mRegisteredReceivers.remove(rl.receiver.asBinder());
12581 int N = rl.size();
12582 for (int i=0; i<N; i++) {
12583 mReceiverResolver.removeFilter(rl.get(i));
12584 }
12585 }
12586
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012587 private final void sendPackageBroadcastLocked(int cmd, String[] packages) {
12588 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
12589 ProcessRecord r = mLruProcesses.get(i);
12590 if (r.thread != null) {
12591 try {
12592 r.thread.dispatchPackageBroadcast(cmd, packages);
12593 } catch (RemoteException ex) {
12594 }
12595 }
12596 }
12597 }
12598
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012599 private final int broadcastIntentLocked(ProcessRecord callerApp,
12600 String callerPackage, Intent intent, String resolvedType,
12601 IIntentReceiver resultTo, int resultCode, String resultData,
12602 Bundle map, String requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070012603 boolean ordered, boolean sticky, int callingPid, int callingUid,
12604 int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012605 intent = new Intent(intent);
12606
Dianne Hackborne7f97212011-02-24 14:40:20 -080012607 // By default broadcasts do not go to stopped apps.
12608 intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
12609
Joe Onorato8a9b2202010-02-26 18:56:32 -080012610 if (DEBUG_BROADCAST_LIGHT) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012611 TAG, (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
Amith Yamasani13593602012-03-22 16:16:17 -070012612 + " ordered=" + ordered + " userid=" + userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012613 if ((resultTo != null) && !ordered) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012614 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012615 }
12616
12617 // Handle special intents: if this broadcast is from the package
12618 // manager about a package being removed, we need to remove all of
12619 // its activities from the history stack.
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012620 final boolean uidRemoved = Intent.ACTION_UID_REMOVED.equals(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012621 intent.getAction());
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012622 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())
12623 || Intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction())
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080012624 || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012625 || uidRemoved) {
12626 if (checkComponentPermission(
12627 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080012628 callingPid, callingUid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012629 == PackageManager.PERMISSION_GRANTED) {
12630 if (uidRemoved) {
12631 final Bundle intentExtras = intent.getExtras();
12632 final int uid = intentExtras != null
12633 ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
12634 if (uid >= 0) {
12635 BatteryStatsImpl bs = mBatteryStatsService.getActiveStatistics();
12636 synchronized (bs) {
12637 bs.removeUidStatsLocked(uid);
12638 }
12639 }
12640 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012641 // If resources are unvailble just force stop all
12642 // those packages and flush the attribute cache as well.
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080012643 if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012644 String list[] = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
12645 if (list != null && (list.length > 0)) {
12646 for (String pkg : list) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070012647 forceStopPackageLocked(pkg, -1, false, true, true, false, userId);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012648 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012649 sendPackageBroadcastLocked(
12650 IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE, list);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012651 }
12652 } else {
12653 Uri data = intent.getData();
12654 String ssp;
12655 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
12656 if (!intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false)) {
12657 forceStopPackageLocked(ssp,
Amith Yamasani483f3b02012-03-13 16:08:00 -070012658 intent.getIntExtra(Intent.EXTRA_UID, -1), false, true, true,
12659 false, userId);
Dianne Hackbornde7faf62009-06-30 13:27:30 -070012660 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012661 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012662 sendPackageBroadcastLocked(IApplicationThread.PACKAGE_REMOVED,
12663 new String[] {ssp});
12664 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012665 }
12666 }
12667 }
12668 } else {
12669 String msg = "Permission Denial: " + intent.getAction()
12670 + " broadcast from " + callerPackage + " (pid=" + callingPid
12671 + ", uid=" + callingUid + ")"
12672 + " requires "
12673 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012674 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012675 throw new SecurityException(msg);
12676 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012677
12678 // Special case for adding a package: by default turn on compatibility
12679 // mode.
12680 } else if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -070012681 Uri data = intent.getData();
12682 String ssp;
12683 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
12684 mCompatModePackages.handlePackageAddedLocked(ssp,
12685 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false));
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012686 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012687 }
12688
12689 /*
12690 * If this is the time zone changed action, queue up a message that will reset the timezone
12691 * of all currently running processes. This message will get queued up before the broadcast
12692 * happens.
12693 */
12694 if (intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) {
12695 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
12696 }
12697
Robert Greenwalt03595d02010-11-02 14:08:23 -070012698 if (intent.ACTION_CLEAR_DNS_CACHE.equals(intent.getAction())) {
12699 mHandler.sendEmptyMessage(CLEAR_DNS_CACHE);
12700 }
12701
Robert Greenwalt434203a2010-10-11 16:00:27 -070012702 if (Proxy.PROXY_CHANGE_ACTION.equals(intent.getAction())) {
12703 ProxyProperties proxy = intent.getParcelableExtra("proxy");
12704 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY, proxy));
12705 }
12706
Dianne Hackborn854060af2009-07-09 18:14:31 -070012707 /*
12708 * Prevent non-system code (defined here to be non-persistent
12709 * processes) from sending protected broadcasts.
12710 */
12711 if (callingUid == Process.SYSTEM_UID || callingUid == Process.PHONE_UID
12712 || callingUid == Process.SHELL_UID || callingUid == 0) {
12713 // Always okay.
12714 } else if (callerApp == null || !callerApp.persistent) {
12715 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012716 if (AppGlobals.getPackageManager().isProtectedBroadcast(
Dianne Hackborn854060af2009-07-09 18:14:31 -070012717 intent.getAction())) {
12718 String msg = "Permission Denial: not allowed to send broadcast "
12719 + intent.getAction() + " from pid="
12720 + callingPid + ", uid=" + callingUid;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012721 Slog.w(TAG, msg);
Dianne Hackborn854060af2009-07-09 18:14:31 -070012722 throw new SecurityException(msg);
12723 }
12724 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012725 Slog.w(TAG, "Remote exception", e);
Dianne Hackborna4972e92012-03-14 10:38:05 -070012726 return ActivityManager.BROADCAST_SUCCESS;
Dianne Hackborn854060af2009-07-09 18:14:31 -070012727 }
12728 }
12729
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012730 // Add to the sticky list if requested.
12731 if (sticky) {
12732 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
12733 callingPid, callingUid)
12734 != PackageManager.PERMISSION_GRANTED) {
12735 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
12736 + callingPid + ", uid=" + callingUid
12737 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012738 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012739 throw new SecurityException(msg);
12740 }
12741 if (requiredPermission != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012742 Slog.w(TAG, "Can't broadcast sticky intent " + intent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012743 + " and enforce permission " + requiredPermission);
Dianne Hackborna4972e92012-03-14 10:38:05 -070012744 return ActivityManager.BROADCAST_STICKY_CANT_HAVE_PERMISSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012745 }
12746 if (intent.getComponent() != null) {
12747 throw new SecurityException(
12748 "Sticky broadcasts can't target a specific component");
12749 }
12750 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
12751 if (list == null) {
12752 list = new ArrayList<Intent>();
12753 mStickyBroadcasts.put(intent.getAction(), list);
12754 }
12755 int N = list.size();
12756 int i;
12757 for (i=0; i<N; i++) {
12758 if (intent.filterEquals(list.get(i))) {
12759 // This sticky already exists, replace it.
12760 list.set(i, new Intent(intent));
12761 break;
12762 }
12763 }
12764 if (i >= N) {
12765 list.add(new Intent(intent));
12766 }
12767 }
12768
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012769 // Figure out who all will receive this broadcast.
12770 List receivers = null;
12771 List<BroadcastFilter> registeredReceivers = null;
12772 try {
12773 if (intent.getComponent() != null) {
12774 // Broadcast is going to one specific receiver class...
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012775 ActivityInfo ai = AppGlobals.getPackageManager().
Amith Yamasani483f3b02012-03-13 16:08:00 -070012776 getReceiverInfo(intent.getComponent(), STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012777 if (ai != null) {
12778 receivers = new ArrayList();
12779 ResolveInfo ri = new ResolveInfo();
Amith Yamasania4a54e22012-04-16 15:44:19 -070012780 if (isSingleton(ai.processName, ai.applicationInfo)) {
12781 ri.activityInfo = getActivityInfoForUser(ai, 0);
12782 } else {
12783 ri.activityInfo = getActivityInfoForUser(ai, userId);
12784 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012785 receivers.add(ri);
12786 }
12787 } else {
12788 // Need to resolve the intent to interested receivers...
12789 if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
12790 == 0) {
12791 receivers =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012792 AppGlobals.getPackageManager().queryIntentReceivers(
Amith Yamasani483f3b02012-03-13 16:08:00 -070012793 intent, resolvedType, STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012794 }
Amith Yamasani483f3b02012-03-13 16:08:00 -070012795 registeredReceivers = mReceiverResolver.queryIntent(intent, resolvedType, false,
12796 userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012797 }
12798 } catch (RemoteException ex) {
12799 // pm is in same process, this will never happen.
12800 }
12801
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012802 final boolean replacePending =
12803 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
12804
Joe Onorato8a9b2202010-02-26 18:56:32 -080012805 if (DEBUG_BROADCAST) Slog.v(TAG, "Enqueing broadcast: " + intent.getAction()
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012806 + " replacePending=" + replacePending);
12807
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012808 int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
12809 if (!ordered && NR > 0) {
12810 // If we are not serializing this broadcast, then send the
12811 // registered receivers separately so they don't wait for the
12812 // components to be launched.
Christopher Tatef46723b2012-01-26 14:19:24 -080012813 final BroadcastQueue queue = broadcastQueueForIntent(intent);
12814 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012815 callerPackage, callingPid, callingUid, requiredPermission,
12816 registeredReceivers, resultTo, resultCode, resultData, map,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012817 ordered, sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012818 if (DEBUG_BROADCAST) Slog.v(
Christopher Tatef46723b2012-01-26 14:19:24 -080012819 TAG, "Enqueueing parallel broadcast " + r);
12820 final boolean replaced = replacePending && queue.replaceParallelBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012821 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012822 queue.enqueueParallelBroadcastLocked(r);
12823 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012824 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012825 registeredReceivers = null;
12826 NR = 0;
12827 }
12828
12829 // Merge into one list.
12830 int ir = 0;
12831 if (receivers != null) {
12832 // A special case for PACKAGE_ADDED: do not allow the package
12833 // being added to see this broadcast. This prevents them from
12834 // using this as a back door to get run as soon as they are
12835 // installed. Maybe in the future we want to have a special install
12836 // broadcast or such for apps, but we'd like to deliberately make
12837 // this decision.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012838 String skipPackages[] = null;
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012839 if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
12840 || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
12841 || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012842 Uri data = intent.getData();
12843 if (data != null) {
12844 String pkgName = data.getSchemeSpecificPart();
12845 if (pkgName != null) {
12846 skipPackages = new String[] { pkgName };
12847 }
12848 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012849 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012850 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
The Android Open Source Project10592532009-03-18 17:39:46 -070012851 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012852 if (skipPackages != null && (skipPackages.length > 0)) {
12853 for (String skipPackage : skipPackages) {
12854 if (skipPackage != null) {
12855 int NT = receivers.size();
12856 for (int it=0; it<NT; it++) {
12857 ResolveInfo curt = (ResolveInfo)receivers.get(it);
12858 if (curt.activityInfo.packageName.equals(skipPackage)) {
12859 receivers.remove(it);
12860 it--;
12861 NT--;
12862 }
12863 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012864 }
12865 }
12866 }
12867
12868 int NT = receivers != null ? receivers.size() : 0;
12869 int it = 0;
12870 ResolveInfo curt = null;
12871 BroadcastFilter curr = null;
12872 while (it < NT && ir < NR) {
12873 if (curt == null) {
12874 curt = (ResolveInfo)receivers.get(it);
12875 }
12876 if (curr == null) {
12877 curr = registeredReceivers.get(ir);
12878 }
12879 if (curr.getPriority() >= curt.priority) {
12880 // Insert this broadcast record into the final list.
12881 receivers.add(it, curr);
12882 ir++;
12883 curr = null;
12884 it++;
12885 NT++;
12886 } else {
12887 // Skip to the next ResolveInfo in the final list.
12888 it++;
12889 curt = null;
12890 }
12891 }
12892 }
12893 while (ir < NR) {
12894 if (receivers == null) {
12895 receivers = new ArrayList();
12896 }
12897 receivers.add(registeredReceivers.get(ir));
12898 ir++;
12899 }
12900
12901 if ((receivers != null && receivers.size() > 0)
12902 || resultTo != null) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012903 BroadcastQueue queue = broadcastQueueForIntent(intent);
12904 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012905 callerPackage, callingPid, callingUid, requiredPermission,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012906 receivers, resultTo, resultCode, resultData, map, ordered,
12907 sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012908 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012909 TAG, "Enqueueing ordered broadcast " + r
Christopher Tatef46723b2012-01-26 14:19:24 -080012910 + ": prev had " + queue.mOrderedBroadcasts.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012911 if (DEBUG_BROADCAST) {
12912 int seq = r.intent.getIntExtra("seq", -1);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012913 Slog.i(TAG, "Enqueueing broadcast " + r.intent.getAction() + " seq=" + seq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012914 }
Christopher Tatef46723b2012-01-26 14:19:24 -080012915 boolean replaced = replacePending && queue.replaceOrderedBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012916 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012917 queue.enqueueOrderedBroadcastLocked(r);
12918 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012919 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012920 }
12921
Dianne Hackborna4972e92012-03-14 10:38:05 -070012922 return ActivityManager.BROADCAST_SUCCESS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012923 }
12924
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012925 final Intent verifyBroadcastLocked(Intent intent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012926 // Refuse possible leaked file descriptors
12927 if (intent != null && intent.hasFileDescriptors() == true) {
12928 throw new IllegalArgumentException("File descriptors passed in Intent");
12929 }
12930
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012931 int flags = intent.getFlags();
12932
12933 if (!mProcessesReady) {
12934 // if the caller really truly claims to know what they're doing, go
12935 // ahead and allow the broadcast without launching any receivers
12936 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
12937 intent = new Intent(intent);
12938 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
12939 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
12940 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
12941 + " before boot completion");
12942 throw new IllegalStateException("Cannot broadcast before boot completed");
12943 }
12944 }
12945
12946 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
12947 throw new IllegalArgumentException(
12948 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
12949 }
12950
12951 return intent;
12952 }
12953
12954 public final int broadcastIntent(IApplicationThread caller,
12955 Intent intent, String resolvedType, IIntentReceiver resultTo,
12956 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070012957 String requiredPermission, boolean serialized, boolean sticky, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012958 enforceNotIsolatedCaller("broadcastIntent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012959 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012960 intent = verifyBroadcastLocked(intent);
Dianne Hackborn9acc0302009-08-25 00:27:12 -070012961
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012962 final ProcessRecord callerApp = getRecordForAppLocked(caller);
12963 final int callingPid = Binder.getCallingPid();
12964 final int callingUid = Binder.getCallingUid();
12965 final long origId = Binder.clearCallingIdentity();
12966 int res = broadcastIntentLocked(callerApp,
12967 callerApp != null ? callerApp.info.packageName : null,
12968 intent, resolvedType, resultTo,
Amith Yamasani742a6712011-05-04 14:49:28 -070012969 resultCode, resultData, map, requiredPermission, serialized, sticky,
12970 callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012971 Binder.restoreCallingIdentity(origId);
12972 return res;
12973 }
12974 }
12975
12976 int broadcastIntentInPackage(String packageName, int uid,
12977 Intent intent, String resolvedType, IIntentReceiver resultTo,
12978 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070012979 String requiredPermission, boolean serialized, boolean sticky, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012980 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012981 intent = verifyBroadcastLocked(intent);
12982
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012983 final long origId = Binder.clearCallingIdentity();
12984 int res = broadcastIntentLocked(null, packageName, intent, resolvedType,
12985 resultTo, resultCode, resultData, map, requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070012986 serialized, sticky, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012987 Binder.restoreCallingIdentity(origId);
12988 return res;
12989 }
12990 }
12991
Amith Yamasani742a6712011-05-04 14:49:28 -070012992 // TODO: Use the userId; maybe mStickyBroadcasts need to be tied to the user.
12993 public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012994 // Refuse possible leaked file descriptors
12995 if (intent != null && intent.hasFileDescriptors() == true) {
12996 throw new IllegalArgumentException("File descriptors passed in Intent");
12997 }
12998
12999 synchronized(this) {
13000 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
13001 != PackageManager.PERMISSION_GRANTED) {
13002 String msg = "Permission Denial: unbroadcastIntent() from pid="
13003 + Binder.getCallingPid()
13004 + ", uid=" + Binder.getCallingUid()
13005 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080013006 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013007 throw new SecurityException(msg);
13008 }
13009 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
13010 if (list != null) {
13011 int N = list.size();
13012 int i;
13013 for (i=0; i<N; i++) {
13014 if (intent.filterEquals(list.get(i))) {
13015 list.remove(i);
13016 break;
13017 }
13018 }
13019 }
13020 }
13021 }
13022
13023 private final boolean finishReceiverLocked(IBinder receiver, int resultCode,
13024 String resultData, Bundle resultExtras, boolean resultAbort,
13025 boolean explicit) {
Christopher Tatef46723b2012-01-26 14:19:24 -080013026 final BroadcastRecord r = broadcastRecordForReceiverLocked(receiver);
13027 if (r == null) {
13028 Slog.w(TAG, "finishReceiver called but not found on queue");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013029 return false;
13030 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013031
Christopher Tatef46723b2012-01-26 14:19:24 -080013032 return r.queue.finishReceiverLocked(r, resultCode, resultData, resultExtras, resultAbort,
13033 explicit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013034 }
13035
13036 public void finishReceiver(IBinder who, int resultCode, String resultData,
13037 Bundle resultExtras, boolean resultAbort) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013038 if (DEBUG_BROADCAST) Slog.v(TAG, "Finish receiver: " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013039
13040 // Refuse possible leaked file descriptors
13041 if (resultExtras != null && resultExtras.hasFileDescriptors()) {
13042 throw new IllegalArgumentException("File descriptors passed in Bundle");
13043 }
13044
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013045 final long origId = Binder.clearCallingIdentity();
Christopher Tatef46723b2012-01-26 14:19:24 -080013046 try {
13047 boolean doNext = false;
13048 BroadcastRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013049
Christopher Tatef46723b2012-01-26 14:19:24 -080013050 synchronized(this) {
13051 r = broadcastRecordForReceiverLocked(who);
13052 if (r != null) {
13053 doNext = r.queue.finishReceiverLocked(r, resultCode,
13054 resultData, resultExtras, resultAbort, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013055 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013056 }
Jeff Brown4d94a762010-09-23 11:33:28 -070013057
Christopher Tatef46723b2012-01-26 14:19:24 -080013058 if (doNext) {
13059 r.queue.processNextBroadcast(false);
13060 }
13061 trimApplications();
13062 } finally {
13063 Binder.restoreCallingIdentity(origId);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070013064 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013065 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013066
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013067 // =========================================================
13068 // INSTRUMENTATION
13069 // =========================================================
13070
13071 public boolean startInstrumentation(ComponentName className,
13072 String profileFile, int flags, Bundle arguments,
13073 IInstrumentationWatcher watcher) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080013074 enforceNotIsolatedCaller("startInstrumentation");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013075 // Refuse possible leaked file descriptors
13076 if (arguments != null && arguments.hasFileDescriptors()) {
13077 throw new IllegalArgumentException("File descriptors passed in Bundle");
13078 }
13079
13080 synchronized(this) {
13081 InstrumentationInfo ii = null;
13082 ApplicationInfo ai = null;
13083 try {
13084 ii = mContext.getPackageManager().getInstrumentationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070013085 className, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013086 ai = mContext.getPackageManager().getApplicationInfo(
Amith Yamasani483f3b02012-03-13 16:08:00 -070013087 ii.targetPackage, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013088 } catch (PackageManager.NameNotFoundException e) {
13089 }
13090 if (ii == null) {
13091 reportStartInstrumentationFailure(watcher, className,
13092 "Unable to find instrumentation info for: " + className);
13093 return false;
13094 }
13095 if (ai == null) {
13096 reportStartInstrumentationFailure(watcher, className,
13097 "Unable to find instrumentation target package: " + ii.targetPackage);
13098 return false;
13099 }
13100
13101 int match = mContext.getPackageManager().checkSignatures(
13102 ii.targetPackage, ii.packageName);
13103 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
13104 String msg = "Permission Denial: starting instrumentation "
13105 + className + " from pid="
13106 + Binder.getCallingPid()
13107 + ", uid=" + Binder.getCallingPid()
13108 + " not allowed because package " + ii.packageName
13109 + " does not have a signature matching the target "
13110 + ii.targetPackage;
13111 reportStartInstrumentationFailure(watcher, className, msg);
13112 throw new SecurityException(msg);
13113 }
13114
Amith Yamasani483f3b02012-03-13 16:08:00 -070013115 int userId = UserId.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013116 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -070013117 // Instrumentation can kill and relaunch even persistent processes
Amith Yamasani483f3b02012-03-13 16:08:00 -070013118 forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true, userId);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013119 ProcessRecord app = addAppLocked(ai, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013120 app.instrumentationClass = className;
Dianne Hackborn1655be42009-05-08 14:29:01 -070013121 app.instrumentationInfo = ai;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013122 app.instrumentationProfileFile = profileFile;
13123 app.instrumentationArguments = arguments;
13124 app.instrumentationWatcher = watcher;
13125 app.instrumentationResultClass = className;
13126 Binder.restoreCallingIdentity(origId);
13127 }
13128
13129 return true;
13130 }
13131
13132 /**
13133 * Report errors that occur while attempting to start Instrumentation. Always writes the
13134 * error to the logs, but if somebody is watching, send the report there too. This enables
13135 * the "am" command to report errors with more information.
13136 *
13137 * @param watcher The IInstrumentationWatcher. Null if there isn't one.
13138 * @param cn The component name of the instrumentation.
13139 * @param report The error report.
13140 */
13141 private void reportStartInstrumentationFailure(IInstrumentationWatcher watcher,
13142 ComponentName cn, String report) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013143 Slog.w(TAG, report);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013144 try {
13145 if (watcher != null) {
13146 Bundle results = new Bundle();
13147 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
13148 results.putString("Error", report);
13149 watcher.instrumentationStatus(cn, -1, results);
13150 }
13151 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013152 Slog.w(TAG, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013153 }
13154 }
13155
13156 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
13157 if (app.instrumentationWatcher != null) {
13158 try {
13159 // NOTE: IInstrumentationWatcher *must* be oneway here
13160 app.instrumentationWatcher.instrumentationFinished(
13161 app.instrumentationClass,
13162 resultCode,
13163 results);
13164 } catch (RemoteException e) {
13165 }
13166 }
13167 app.instrumentationWatcher = null;
13168 app.instrumentationClass = null;
Dianne Hackborn1655be42009-05-08 14:29:01 -070013169 app.instrumentationInfo = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013170 app.instrumentationProfileFile = null;
13171 app.instrumentationArguments = null;
13172
Amith Yamasani483f3b02012-03-13 16:08:00 -070013173 forceStopPackageLocked(app.processName, -1, false, false, true, true, app.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013174 }
13175
13176 public void finishInstrumentation(IApplicationThread target,
13177 int resultCode, Bundle results) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070013178 int userId = UserId.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013179 // Refuse possible leaked file descriptors
13180 if (results != null && results.hasFileDescriptors()) {
13181 throw new IllegalArgumentException("File descriptors passed in Intent");
13182 }
13183
13184 synchronized(this) {
13185 ProcessRecord app = getRecordForAppLocked(target);
13186 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013187 Slog.w(TAG, "finishInstrumentation: no app for " + target);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013188 return;
13189 }
13190 final long origId = Binder.clearCallingIdentity();
13191 finishInstrumentationLocked(app, resultCode, results);
13192 Binder.restoreCallingIdentity(origId);
13193 }
13194 }
13195
13196 // =========================================================
13197 // CONFIGURATION
13198 // =========================================================
13199
13200 public ConfigurationInfo getDeviceConfigurationInfo() {
13201 ConfigurationInfo config = new ConfigurationInfo();
13202 synchronized (this) {
13203 config.reqTouchScreen = mConfiguration.touchscreen;
13204 config.reqKeyboardType = mConfiguration.keyboard;
13205 config.reqNavigation = mConfiguration.navigation;
Dianne Hackbornfae76f52009-07-16 13:41:23 -070013206 if (mConfiguration.navigation == Configuration.NAVIGATION_DPAD
13207 || mConfiguration.navigation == Configuration.NAVIGATION_TRACKBALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013208 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
13209 }
Dianne Hackbornfae76f52009-07-16 13:41:23 -070013210 if (mConfiguration.keyboard != Configuration.KEYBOARD_UNDEFINED
13211 && mConfiguration.keyboard != Configuration.KEYBOARD_NOKEYS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013212 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
13213 }
Jack Palevichb90d28c2009-07-22 15:35:24 -070013214 config.reqGlEsVersion = GL_ES_VERSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013215 }
13216 return config;
13217 }
13218
13219 public Configuration getConfiguration() {
13220 Configuration ci;
13221 synchronized(this) {
13222 ci = new Configuration(mConfiguration);
13223 }
13224 return ci;
13225 }
13226
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013227 public void updatePersistentConfiguration(Configuration values) {
13228 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
13229 "updateConfiguration()");
13230 enforceCallingPermission(android.Manifest.permission.WRITE_SETTINGS,
13231 "updateConfiguration()");
13232 if (values == null) {
13233 throw new NullPointerException("Configuration must not be null");
13234 }
13235
13236 synchronized(this) {
13237 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn813075a62011-11-14 17:45:19 -080013238 updateConfigurationLocked(values, null, true, false);
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013239 Binder.restoreCallingIdentity(origId);
13240 }
13241 }
13242
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013243 public void updateConfiguration(Configuration values) {
13244 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
13245 "updateConfiguration()");
13246
13247 synchronized(this) {
13248 if (values == null && mWindowManager != null) {
13249 // sentinel: fetch the current configuration from the window manager
13250 values = mWindowManager.computeNewConfiguration();
13251 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013252
13253 if (mWindowManager != null) {
13254 mProcessList.applyDisplaySize(mWindowManager);
13255 }
13256
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013257 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013258 if (values != null) {
13259 Settings.System.clearConfiguration(values);
13260 }
Dianne Hackborn813075a62011-11-14 17:45:19 -080013261 updateConfigurationLocked(values, null, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013262 Binder.restoreCallingIdentity(origId);
13263 }
13264 }
13265
13266 /**
13267 * Do either or both things: (1) change the current configuration, and (2)
13268 * make sure the given activity is running with the (now) current
13269 * configuration. Returns true if the activity has been left running, or
13270 * false if <var>starting</var> is being destroyed to match the new
13271 * configuration.
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013272 * @param persistent TODO
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013273 */
Dianne Hackborna573f6a2012-02-09 16:12:18 -080013274 boolean updateConfigurationLocked(Configuration values,
Dianne Hackborn813075a62011-11-14 17:45:19 -080013275 ActivityRecord starting, boolean persistent, boolean initLocale) {
Mike Lockwood3a74bd32011-08-12 13:55:22 -070013276 // do nothing if we are headless
13277 if (mHeadless) return true;
13278
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013279 int changes = 0;
13280
13281 boolean kept = true;
13282
13283 if (values != null) {
13284 Configuration newConfig = new Configuration(mConfiguration);
13285 changes = newConfig.updateFrom(values);
13286 if (changes != 0) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013287 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013288 Slog.i(TAG, "Updating configuration to: " + values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013289 }
13290
Doug Zongker2bec3d42009-12-04 12:52:44 -080013291 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013292
Dianne Hackborn813075a62011-11-14 17:45:19 -080013293 if (values.locale != null && !initLocale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013294 saveLocaleLocked(values.locale,
13295 !values.locale.equals(mConfiguration.locale),
13296 values.userSetLocale);
13297 }
13298
Dianne Hackborne36d6e22010-02-17 19:46:25 -080013299 mConfigurationSeq++;
13300 if (mConfigurationSeq <= 0) {
13301 mConfigurationSeq = 1;
13302 }
13303 newConfig.seq = mConfigurationSeq;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013304 mConfiguration = newConfig;
Joe Onorato8a9b2202010-02-26 18:56:32 -080013305 Slog.i(TAG, "Config changed: " + newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013306
13307 final Configuration configCopy = new Configuration(mConfiguration);
Joe Onorato54a4a412011-11-02 20:50:08 -070013308
13309 // TODO: If our config changes, should we auto dismiss any currently
13310 // showing dialogs?
13311 mShowDialogs = shouldShowDialogs(newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013312
Dianne Hackborn826d17c2009-11-12 12:55:51 -080013313 AttributeCache ac = AttributeCache.instance();
13314 if (ac != null) {
Dianne Hackborn813075a62011-11-14 17:45:19 -080013315 ac.updateConfiguration(configCopy);
Dianne Hackborn826d17c2009-11-12 12:55:51 -080013316 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013317
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070013318 // Make sure all resources in our process are updated
13319 // right now, so that anyone who is going to retrieve
13320 // resource values after we return will be sure to get
13321 // the new ones. This is especially important during
13322 // boot, where the first config change needs to guarantee
13323 // all resources have that config before following boot
13324 // code is executed.
Dianne Hackborn813075a62011-11-14 17:45:19 -080013325 mSystemThread.applyConfigurationToResources(configCopy);
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070013326
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013327 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080013328 Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013329 msg.obj = new Configuration(configCopy);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080013330 mHandler.sendMessage(msg);
13331 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013332
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013333 for (int i=mLruProcesses.size()-1; i>=0; i--) {
13334 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013335 try {
13336 if (app.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013337 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending to proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013338 + app.processName + " new config " + mConfiguration);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013339 app.thread.scheduleConfigurationChanged(configCopy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013340 }
13341 } catch (Exception e) {
13342 }
13343 }
13344 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080013345 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
13346 | Intent.FLAG_RECEIVER_REPLACE_PENDING);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013347 broadcastIntentLocked(null, null, intent, null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070013348 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080013349 if ((changes&ActivityInfo.CONFIG_LOCALE) != 0) {
13350 broadcastIntentLocked(null, null,
13351 new Intent(Intent.ACTION_LOCALE_CHANGED),
13352 null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070013353 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080013354 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013355 }
13356 }
13357
13358 if (changes != 0 && starting == null) {
13359 // If the configuration changed, and the caller is not already
13360 // in the process of starting an activity, then find the top
13361 // activity to check if its configuration needs to change.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013362 starting = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013363 }
13364
13365 if (starting != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013366 kept = mMainStack.ensureActivityConfigurationLocked(starting, changes);
Dianne Hackborn5f4d6432010-12-21 20:40:11 -080013367 // And we need to make sure at this point that all other activities
13368 // are made visible with the correct configuration.
13369 mMainStack.ensureActivitiesVisibleLocked(starting, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013370 }
13371
Dianne Hackborne36d6e22010-02-17 19:46:25 -080013372 if (values != null && mWindowManager != null) {
13373 mWindowManager.setNewConfiguration(mConfiguration);
13374 }
13375
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013376 return kept;
13377 }
Joe Onorato54a4a412011-11-02 20:50:08 -070013378
13379 /**
13380 * Decide based on the configuration whether we should shouw the ANR,
13381 * crash, etc dialogs. The idea is that if there is no affordnace to
13382 * press the on-screen buttons, we shouldn't show the dialog.
13383 *
13384 * A thought: SystemUI might also want to get told about this, the Power
13385 * dialog / global actions also might want different behaviors.
13386 */
13387 private static final boolean shouldShowDialogs(Configuration config) {
13388 return !(config.keyboard == Configuration.KEYBOARD_NOKEYS
13389 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH);
13390 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013391
13392 /**
13393 * Save the locale. You must be inside a synchronized (this) block.
13394 */
13395 private void saveLocaleLocked(Locale l, boolean isDiff, boolean isPersist) {
13396 if(isDiff) {
13397 SystemProperties.set("user.language", l.getLanguage());
13398 SystemProperties.set("user.region", l.getCountry());
13399 }
13400
13401 if(isPersist) {
13402 SystemProperties.set("persist.sys.language", l.getLanguage());
13403 SystemProperties.set("persist.sys.country", l.getCountry());
13404 SystemProperties.set("persist.sys.localevar", l.getVariant());
13405 }
13406 }
13407
Adam Powelldd8fab22012-03-22 17:47:27 -070013408 @Override
13409 public boolean targetTaskAffinityMatchesActivity(IBinder token, String destAffinity) {
13410 ActivityRecord srec = ActivityRecord.forToken(token);
13411 return srec.task.affinity != null && srec.task.affinity.equals(destAffinity);
13412 }
13413
13414 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
13415 Intent resultData) {
13416 ComponentName dest = destIntent.getComponent();
13417
13418 synchronized (this) {
13419 ActivityRecord srec = ActivityRecord.forToken(token);
13420 ArrayList<ActivityRecord> history = srec.stack.mHistory;
13421 final int start = history.indexOf(srec);
13422 if (start < 0) {
13423 // Current activity is not in history stack; do nothing.
13424 return false;
13425 }
13426 int finishTo = start - 1;
13427 ActivityRecord parent = null;
13428 boolean foundParentInTask = false;
13429 if (dest != null) {
13430 TaskRecord tr = srec.task;
13431 for (int i = start - 1; i >= 0; i--) {
13432 ActivityRecord r = history.get(i);
13433 if (tr != r.task) {
13434 // Couldn't find parent in the same task; stop at the one above this.
13435 // (Root of current task; in-app "home" behavior)
13436 // Always at least finish the current activity.
13437 finishTo = Math.min(start - 1, i + 1);
13438 parent = history.get(finishTo);
13439 break;
13440 } else if (r.info.packageName.equals(dest.getPackageName()) &&
13441 r.info.name.equals(dest.getClassName())) {
13442 finishTo = i;
13443 parent = r;
13444 foundParentInTask = true;
13445 break;
13446 }
13447 }
13448 }
13449
13450 if (mController != null) {
13451 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
13452 if (next != null) {
13453 // ask watcher if this is allowed
13454 boolean resumeOK = true;
13455 try {
13456 resumeOK = mController.activityResuming(next.packageName);
13457 } catch (RemoteException e) {
13458 mController = null;
13459 }
13460
13461 if (!resumeOK) {
13462 return false;
13463 }
13464 }
13465 }
13466 final long origId = Binder.clearCallingIdentity();
13467 for (int i = start; i > finishTo; i--) {
13468 ActivityRecord r = history.get(i);
13469 mMainStack.requestFinishActivityLocked(r.appToken, resultCode, resultData,
13470 "navigate-up");
13471 // Only return the supplied result for the first activity finished
13472 resultCode = Activity.RESULT_CANCELED;
13473 resultData = null;
13474 }
13475
13476 if (parent != null && foundParentInTask) {
13477 final int parentLaunchMode = parent.info.launchMode;
13478 final int destIntentFlags = destIntent.getFlags();
13479 if (parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE ||
13480 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TASK ||
13481 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TOP ||
13482 (destIntentFlags & Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
13483 parent.deliverNewIntentLocked(srec.app.uid, destIntent);
13484 } else {
13485 try {
13486 ActivityInfo aInfo = AppGlobals.getPackageManager().getActivityInfo(
13487 destIntent.getComponent(), 0, UserId.getCallingUserId());
13488 int res = mMainStack.startActivityLocked(srec.app.thread, destIntent,
13489 null, aInfo, parent.appToken, null,
13490 0, -1, parent.launchedFromUid, 0, null, true, null);
13491 foundParentInTask = res == ActivityManager.START_SUCCESS;
13492 } catch (RemoteException e) {
13493 foundParentInTask = false;
13494 }
13495 mMainStack.requestFinishActivityLocked(parent.appToken, resultCode,
13496 resultData, "navigate-up");
13497 }
13498 }
13499 Binder.restoreCallingIdentity(origId);
13500 return foundParentInTask;
13501 }
13502 }
13503
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013504 // =========================================================
13505 // LIFETIME MANAGEMENT
13506 // =========================================================
13507
Christopher Tatef46723b2012-01-26 14:19:24 -080013508 // Returns which broadcast queue the app is the current [or imminent] receiver
13509 // on, or 'null' if the app is not an active broadcast recipient.
13510 private BroadcastQueue isReceivingBroadcast(ProcessRecord app) {
13511 BroadcastRecord r = app.curReceiver;
13512 if (r != null) {
13513 return r.queue;
13514 }
13515
13516 // It's not the current receiver, but it might be starting up to become one
13517 synchronized (this) {
13518 for (BroadcastQueue queue : mBroadcastQueues) {
13519 r = queue.mPendingBroadcast;
13520 if (r != null && r.curApp == app) {
13521 // found it; report which queue it's in
13522 return queue;
13523 }
13524 }
13525 }
13526
13527 return null;
13528 }
13529
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013530 private final int computeOomAdjLocked(ProcessRecord app, int hiddenAdj,
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013531 ProcessRecord TOP_APP, boolean recursed, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013532 if (mAdjSeq == app.adjSeq) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013533 // This adjustment has already been computed. If we are calling
13534 // from the top, we may have already computed our adjustment with
13535 // an earlier hidden adjustment that isn't really for us... if
13536 // so, use the new hidden adjustment.
13537 if (!recursed && app.hidden) {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013538 app.curAdj = app.curRawAdj = app.nonStoppingAdj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013539 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013540 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013541 }
13542
13543 if (app.thread == null) {
13544 app.adjSeq = mAdjSeq;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013545 app.curSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013546 return (app.curAdj=ProcessList.HIDDEN_APP_MAX_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013547 }
13548
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013549 app.adjTypeCode = ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN;
13550 app.adjSource = null;
13551 app.adjTarget = null;
13552 app.empty = false;
13553 app.hidden = false;
13554
13555 final int activitiesSize = app.activities.size();
13556
Dianne Hackborn7d608422011-08-07 16:24:18 -070013557 if (app.maxAdj <= ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013558 // The max adjustment doesn't allow this app to be anything
13559 // below foreground, so it is not worth doing work for it.
13560 app.adjType = "fixed";
13561 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013562 app.curRawAdj = app.nonStoppingAdj = app.maxAdj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013563 app.foregroundActivities = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013564 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013565 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013566 // System process can do UI, and when they do we want to have
13567 // them trim their memory after the user leaves the UI. To
13568 // facilitate this, here we need to determine whether or not it
13569 // is currently showing UI.
13570 app.systemNoUi = true;
13571 if (app == TOP_APP) {
13572 app.systemNoUi = false;
13573 } else if (activitiesSize > 0) {
13574 for (int j = 0; j < activitiesSize; j++) {
13575 final ActivityRecord r = app.activities.get(j);
13576 if (r.visible) {
13577 app.systemNoUi = false;
13578 break;
13579 }
13580 }
13581 }
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013582 return (app.curAdj=app.maxAdj);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013583 }
13584
13585 final boolean hadForegroundActivities = app.foregroundActivities;
13586
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013587 app.foregroundActivities = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013588 app.keeping = false;
13589 app.systemNoUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013590
The Android Open Source Project4df24232009-03-05 14:34:35 -080013591 // Determine the importance of the process, starting with most
13592 // important to least, and assign an appropriate OOM adjustment.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013593 int adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013594 int schedGroup;
Christopher Tatef46723b2012-01-26 14:19:24 -080013595 BroadcastQueue queue;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013596 if (app == TOP_APP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013597 // The last app on the list is the foreground app.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013598 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013599 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013600 app.adjType = "top-activity";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013601 app.foregroundActivities = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013602 } else if (app.instrumentationClass != null) {
13603 // Don't want to kill running instrumentation.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013604 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013605 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013606 app.adjType = "instrumentation";
Christopher Tatef46723b2012-01-26 14:19:24 -080013607 } else if ((queue = isReceivingBroadcast(app)) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013608 // An app that is currently receiving a broadcast also
Christopher Tatef46723b2012-01-26 14:19:24 -080013609 // counts as being in the foreground for OOM killer purposes.
13610 // It's placed in a sched group based on the nature of the
13611 // broadcast as reflected by which queue it's active in.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013612 adj = ProcessList.FOREGROUND_APP_ADJ;
Christopher Tatef46723b2012-01-26 14:19:24 -080013613 schedGroup = (queue == mFgBroadcastQueue)
13614 ? Process.THREAD_GROUP_DEFAULT : Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013615 app.adjType = "broadcast";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013616 } else if (app.executingServices.size() > 0) {
13617 // An app that is currently executing a service callback also
13618 // counts as being in the foreground.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013619 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013620 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013621 app.adjType = "exec-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013622 } else if (activitiesSize > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013623 // This app is in the background with paused activities.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013624 // We inspect activities to potentially upgrade adjustment further below.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013625 adj = hiddenAdj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013626 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013627 app.hidden = true;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013628 app.adjType = "bg-activities";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013629 } else {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013630 // A very not-needed process. If this is lower in the lru list,
13631 // we will push it in to the empty bucket.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013632 adj = hiddenAdj;
13633 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013634 app.hidden = true;
13635 app.empty = true;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013636 app.adjType = "bg-empty";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013637 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013638
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013639 boolean hasStoppingActivities = false;
13640
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013641 // Examine all activities if not already foreground.
13642 if (!app.foregroundActivities && activitiesSize > 0) {
13643 for (int j = 0; j < activitiesSize; j++) {
13644 final ActivityRecord r = app.activities.get(j);
13645 if (r.visible) {
13646 // App has a visible activity; only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013647 if (adj > ProcessList.VISIBLE_APP_ADJ) {
13648 adj = ProcessList.VISIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013649 app.adjType = "visible";
13650 }
13651 schedGroup = Process.THREAD_GROUP_DEFAULT;
13652 app.hidden = false;
13653 app.foregroundActivities = true;
13654 break;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013655 } else if (r.state == ActivityState.PAUSING || r.state == ActivityState.PAUSED) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013656 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13657 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013658 app.adjType = "pausing";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013659 }
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -080013660 app.hidden = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013661 app.foregroundActivities = true;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013662 } else if (r.state == ActivityState.STOPPING) {
13663 // We will apply the actual adjustment later, because
13664 // we want to allow this process to immediately go through
13665 // any memory trimming that is in effect.
13666 app.hidden = false;
13667 app.foregroundActivities = true;
13668 hasStoppingActivities = true;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013669 }
13670 }
13671 }
13672
Dianne Hackborn7d608422011-08-07 16:24:18 -070013673 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013674 if (app.foregroundServices) {
13675 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013676 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013677 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013678 app.adjType = "foreground-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013679 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013680 } else if (app.forcingToForeground != null) {
13681 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013682 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013683 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013684 app.adjType = "force-foreground";
13685 app.adjSource = app.forcingToForeground;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013686 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013687 }
13688 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013689
Dianne Hackborn7d608422011-08-07 16:24:18 -070013690 if (adj > ProcessList.HEAVY_WEIGHT_APP_ADJ && app == mHeavyWeightProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013691 // We don't want to kill the current heavy-weight process.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013692 adj = ProcessList.HEAVY_WEIGHT_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013693 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013694 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013695 app.adjType = "heavy";
13696 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013697
Dianne Hackborn7d608422011-08-07 16:24:18 -070013698 if (adj > ProcessList.HOME_APP_ADJ && app == mHomeProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013699 // This process is hosting what we currently consider to be the
13700 // home app, so we don't want to let it go into the background.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013701 adj = ProcessList.HOME_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013702 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013703 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013704 app.adjType = "home";
13705 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013706
Dianne Hackbornf35fe232011-11-01 19:25:20 -070013707 if (adj > ProcessList.PREVIOUS_APP_ADJ && app == mPreviousProcess
13708 && app.activities.size() > 0) {
13709 // This was the previous process that showed UI to the user.
13710 // We want to try to keep it around more aggressively, to give
13711 // a good experience around switching between two apps.
13712 adj = ProcessList.PREVIOUS_APP_ADJ;
13713 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
13714 app.hidden = false;
13715 app.adjType = "previous";
13716 }
13717
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013718 if (false) Slog.i(TAG, "OOM " + app + ": initial adj=" + adj
13719 + " reason=" + app.adjType);
13720
The Android Open Source Project4df24232009-03-05 14:34:35 -080013721 // By default, we use the computed adjustment. It may be changed if
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013722 // there are applications dependent on our services or providers, but
13723 // this gives us a baseline and makes sure we don't get into an
13724 // infinite recursion.
13725 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013726 app.curRawAdj = app.nonStoppingAdj = adj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013727
Christopher Tate6fa95972009-06-05 18:43:55 -070013728 if (mBackupTarget != null && app == mBackupTarget.app) {
13729 // If possible we want to avoid killing apps while they're being backed up
Dianne Hackborn7d608422011-08-07 16:24:18 -070013730 if (adj > ProcessList.BACKUP_APP_ADJ) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013731 if (DEBUG_BACKUP) Slog.v(TAG, "oom BACKUP_APP_ADJ for " + app);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013732 adj = ProcessList.BACKUP_APP_ADJ;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013733 app.adjType = "backup";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013734 app.hidden = false;
Christopher Tate6fa95972009-06-05 18:43:55 -070013735 }
13736 }
13737
Dianne Hackborn7d608422011-08-07 16:24:18 -070013738 if (app.services.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013739 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013740 final long now = SystemClock.uptimeMillis();
13741 // This process is more important if the top activity is
13742 // bound to the service.
Dianne Hackborn860755f2010-06-03 18:47:52 -070013743 Iterator<ServiceRecord> jt = app.services.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013744 while (jt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013745 ServiceRecord s = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013746 if (s.startRequested) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013747 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013748 // If this process has shown some UI, let it immediately
13749 // go to the LRU list because it may be pretty heavy with
13750 // UI stuff. We'll tag it with a label just to help
13751 // debug and understand what is going on.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013752 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013753 app.adjType = "started-bg-ui-services";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013754 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013755 } else {
13756 if (now < (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
13757 // This service has seen some activity within
13758 // recent memory, so we will keep its process ahead
13759 // of the background processes.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013760 if (adj > ProcessList.SERVICE_ADJ) {
13761 adj = ProcessList.SERVICE_ADJ;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013762 app.adjType = "started-services";
13763 app.hidden = false;
13764 }
13765 }
13766 // If we have let the service slide into the background
13767 // state, still have some text describing what it is doing
13768 // even though the service no longer has an impact.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013769 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013770 app.adjType = "started-bg-services";
13771 }
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080013772 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013773 // Don't kill this process because it is doing work; it
13774 // has said it is doing work.
13775 app.keeping = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013776 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013777 if (s.connections.size() > 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013778 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013779 Iterator<ArrayList<ConnectionRecord>> kt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013780 = s.connections.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013781 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013782 ArrayList<ConnectionRecord> clist = kt.next();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013783 for (int i=0; i<clist.size() && adj > ProcessList.FOREGROUND_APP_ADJ; i++) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013784 // XXX should compute this based on the max of
13785 // all connected clients.
13786 ConnectionRecord cr = clist.get(i);
13787 if (cr.binding.client == app) {
13788 // Binding to ourself is not interesting.
13789 continue;
13790 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013791 if ((cr.flags&Context.BIND_WAIVE_PRIORITY) == 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013792 ProcessRecord client = cr.binding.client;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013793 int clientAdj = adj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013794 int myHiddenAdj = hiddenAdj;
13795 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013796 if (client.hiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013797 myHiddenAdj = client.hiddenAdj;
13798 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013799 myHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013800 }
13801 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013802 clientAdj = computeOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013803 client, myHiddenAdj, TOP_APP, true, doingAll);
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013804 String adjType = null;
13805 if ((cr.flags&Context.BIND_ALLOW_OOM_MANAGEMENT) != 0) {
13806 // Not doing bind OOM management, so treat
13807 // this guy more like a started service.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013808 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013809 // If this process has shown some UI, let it immediately
13810 // go to the LRU list because it may be pretty heavy with
13811 // UI stuff. We'll tag it with a label just to help
13812 // debug and understand what is going on.
13813 if (adj > clientAdj) {
13814 adjType = "bound-bg-ui-services";
13815 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013816 app.hidden = false;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013817 clientAdj = adj;
13818 } else {
13819 if (now >= (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
13820 // This service has not seen activity within
13821 // recent memory, so allow it to drop to the
13822 // LRU list if there is no other reason to keep
13823 // it around. We'll also tag it with a label just
13824 // to help debug and undertand what is going on.
13825 if (adj > clientAdj) {
13826 adjType = "bound-bg-services";
13827 }
13828 clientAdj = adj;
13829 }
13830 }
13831 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013832 if (adj > clientAdj) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013833 // If this process has recently shown UI, and
13834 // the process that is binding to it is less
13835 // important than being visible, then we don't
13836 // care about the binding as much as we care
13837 // about letting this process get into the LRU
13838 // list to be killed and restarted if needed for
13839 // memory.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013840 if (app.hasShownUi && app != mHomeProcess
13841 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013842 adjType = "bound-bg-ui-services";
13843 } else {
13844 if ((cr.flags&(Context.BIND_ABOVE_CLIENT
13845 |Context.BIND_IMPORTANT)) != 0) {
13846 adj = clientAdj;
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070013847 } else if ((cr.flags&Context.BIND_NOT_VISIBLE) != 0
13848 && clientAdj < ProcessList.PERCEPTIBLE_APP_ADJ
13849 && adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13850 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13851 } else if (clientAdj > ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013852 adj = clientAdj;
13853 } else {
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070013854 app.pendingUiClean = true;
13855 if (adj > ProcessList.VISIBLE_APP_ADJ) {
13856 adj = ProcessList.VISIBLE_APP_ADJ;
13857 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013858 }
13859 if (!client.hidden) {
13860 app.hidden = false;
13861 }
13862 if (client.keeping) {
13863 app.keeping = true;
13864 }
13865 adjType = "service";
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013866 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013867 }
13868 if (adjType != null) {
13869 app.adjType = adjType;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013870 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13871 .REASON_SERVICE_IN_USE;
13872 app.adjSource = cr.binding.client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013873 app.adjSourceOom = clientAdj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013874 app.adjTarget = s.name;
13875 }
13876 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
13877 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
13878 schedGroup = Process.THREAD_GROUP_DEFAULT;
13879 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013880 }
13881 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013882 if ((cr.flags&Context.BIND_ADJUST_WITH_ACTIVITY) != 0) {
13883 ActivityRecord a = cr.activity;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013884 if (a != null && adj > ProcessList.FOREGROUND_APP_ADJ &&
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013885 (a.visible || a.state == ActivityState.RESUMED
13886 || a.state == ActivityState.PAUSING)) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013887 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013888 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
13889 schedGroup = Process.THREAD_GROUP_DEFAULT;
13890 }
13891 app.hidden = false;
13892 app.adjType = "service";
13893 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13894 .REASON_SERVICE_IN_USE;
13895 app.adjSource = a;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013896 app.adjSourceOom = adj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013897 app.adjTarget = s.name;
13898 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013899 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013900 }
13901 }
13902 }
13903 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013904
Dianne Hackborn287952c2010-09-22 22:34:31 -070013905 // Finally, if this process has active services running in it, we
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013906 // would like to avoid killing it unless it would prevent the current
13907 // application from running. By default we put the process in
13908 // with the rest of the background processes; as we scan through
13909 // its services we may bump it up from there.
13910 if (adj > hiddenAdj) {
13911 adj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013912 app.hidden = false;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013913 app.adjType = "bg-services";
13914 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013915 }
13916
Dianne Hackborn7d608422011-08-07 16:24:18 -070013917 if (app.pubProviders.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013918 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013919 Iterator<ContentProviderRecord> jt = app.pubProviders.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013920 while (jt.hasNext() && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013921 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013922 ContentProviderRecord cpr = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013923 if (cpr.clients.size() != 0) {
13924 Iterator<ProcessRecord> kt = cpr.clients.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013925 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013926 ProcessRecord client = kt.next();
The Android Open Source Project10592532009-03-18 17:39:46 -070013927 if (client == app) {
13928 // Being our own client is not interesting.
13929 continue;
13930 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013931 int myHiddenAdj = hiddenAdj;
13932 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013933 if (client.hiddenAdj > ProcessList.FOREGROUND_APP_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013934 myHiddenAdj = client.hiddenAdj;
13935 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013936 myHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013937 }
13938 }
13939 int clientAdj = computeOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013940 client, myHiddenAdj, TOP_APP, true, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013941 if (adj > clientAdj) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013942 if (app.hasShownUi && app != mHomeProcess
13943 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013944 app.adjType = "bg-ui-provider";
13945 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013946 adj = clientAdj > ProcessList.FOREGROUND_APP_ADJ
13947 ? clientAdj : ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013948 app.adjType = "provider";
13949 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013950 if (!client.hidden) {
13951 app.hidden = false;
13952 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013953 if (client.keeping) {
13954 app.keeping = true;
13955 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070013956 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13957 .REASON_PROVIDER_IN_USE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013958 app.adjSource = client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013959 app.adjSourceOom = clientAdj;
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070013960 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013961 }
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013962 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
13963 schedGroup = Process.THREAD_GROUP_DEFAULT;
13964 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013965 }
13966 }
13967 // If the provider has external (non-framework) process
13968 // dependencies, ensure that its adjustment is at least
13969 // FOREGROUND_APP_ADJ.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080013970 if (cpr.hasExternalProcessHandles()) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013971 if (adj > ProcessList.FOREGROUND_APP_ADJ) {
13972 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013973 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013974 app.hidden = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013975 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013976 app.adjType = "provider";
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070013977 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013978 }
13979 }
13980 }
13981 }
13982
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013983 if (adj == ProcessList.SERVICE_ADJ) {
13984 if (doingAll) {
13985 app.serviceb = mNewNumServiceProcs > (mNumServiceProcs/3);
13986 mNewNumServiceProcs++;
13987 }
13988 if (app.serviceb) {
13989 adj = ProcessList.SERVICE_B_ADJ;
13990 }
13991 } else {
13992 app.serviceb = false;
13993 }
13994
13995 app.nonStoppingAdj = adj;
13996
13997 if (hasStoppingActivities) {
13998 // Only upgrade adjustment.
13999 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
14000 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
14001 app.adjType = "stopping";
14002 }
14003 }
14004
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014005 app.curRawAdj = adj;
14006
Joe Onorato8a9b2202010-02-26 18:56:32 -080014007 //Slog.i(TAG, "OOM ADJ " + app + ": pid=" + app.pid +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014008 // " adj=" + adj + " curAdj=" + app.curAdj + " maxAdj=" + app.maxAdj);
14009 if (adj > app.maxAdj) {
14010 adj = app.maxAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070014011 if (app.maxAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014012 schedGroup = Process.THREAD_GROUP_DEFAULT;
14013 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014014 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070014015 if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070014016 app.keeping = true;
14017 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014018
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014019 if (app.hasAboveClient) {
14020 // If this process has bound to any services with BIND_ABOVE_CLIENT,
14021 // then we need to drop its adjustment to be lower than the service's
14022 // in order to honor the request. We want to drop it by one adjustment
14023 // level... but there is special meaning applied to various levels so
14024 // we will skip some of them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014025 if (adj < ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014026 // System process will not get dropped, ever
Dianne Hackborn7d608422011-08-07 16:24:18 -070014027 } else if (adj < ProcessList.VISIBLE_APP_ADJ) {
14028 adj = ProcessList.VISIBLE_APP_ADJ;
14029 } else if (adj < ProcessList.PERCEPTIBLE_APP_ADJ) {
14030 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
14031 } else if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
14032 adj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014033 } else if (adj < ProcessList.HIDDEN_APP_MAX_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014034 adj++;
14035 }
14036 }
14037
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014038 app.curAdj = adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014039 app.curSchedGroup = schedGroup;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070014040
14041 if (hadForegroundActivities != app.foregroundActivities) {
Jeff Sharkey287bd832011-05-28 19:36:26 -070014042 mHandler.obtainMessage(DISPATCH_FOREGROUND_ACTIVITIES_CHANGED, app.pid, app.info.uid,
14043 app.foregroundActivities).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070014044 }
14045
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014046 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014047 }
14048
14049 /**
14050 * Ask a given process to GC right now.
14051 */
14052 final void performAppGcLocked(ProcessRecord app) {
14053 try {
14054 app.lastRequestedGc = SystemClock.uptimeMillis();
14055 if (app.thread != null) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014056 if (app.reportLowMemory) {
14057 app.reportLowMemory = false;
14058 app.thread.scheduleLowMemory();
14059 } else {
14060 app.thread.processInBackground();
14061 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014062 }
14063 } catch (Exception e) {
14064 // whatever.
14065 }
14066 }
14067
14068 /**
14069 * Returns true if things are idle enough to perform GCs.
14070 */
Josh Bartel7f208742010-02-25 11:01:44 -060014071 private final boolean canGcNowLocked() {
Christopher Tatef46723b2012-01-26 14:19:24 -080014072 boolean processingBroadcasts = false;
14073 for (BroadcastQueue q : mBroadcastQueues) {
14074 if (q.mParallelBroadcasts.size() != 0 || q.mOrderedBroadcasts.size() != 0) {
14075 processingBroadcasts = true;
14076 }
14077 }
14078 return !processingBroadcasts
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014079 && (mSleeping || (mMainStack.mResumedActivity != null &&
14080 mMainStack.mResumedActivity.idle));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014081 }
14082
14083 /**
14084 * Perform GCs on all processes that are waiting for it, but only
14085 * if things are idle.
14086 */
14087 final void performAppGcsLocked() {
14088 final int N = mProcessesToGc.size();
14089 if (N <= 0) {
14090 return;
14091 }
Josh Bartel7f208742010-02-25 11:01:44 -060014092 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014093 while (mProcessesToGc.size() > 0) {
14094 ProcessRecord proc = mProcessesToGc.remove(0);
Dianne Hackborn7d608422011-08-07 16:24:18 -070014095 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014096 if ((proc.lastRequestedGc+GC_MIN_INTERVAL)
14097 <= SystemClock.uptimeMillis()) {
14098 // To avoid spamming the system, we will GC processes one
14099 // at a time, waiting a few seconds between each.
14100 performAppGcLocked(proc);
14101 scheduleAppGcsLocked();
14102 return;
14103 } else {
14104 // It hasn't been long enough since we last GCed this
14105 // process... put it in the list to wait for its time.
14106 addProcessToGcListLocked(proc);
14107 break;
14108 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014109 }
14110 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014111
14112 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014113 }
14114 }
14115
14116 /**
14117 * If all looks good, perform GCs on all processes waiting for them.
14118 */
14119 final void performAppGcsIfAppropriateLocked() {
Josh Bartel7f208742010-02-25 11:01:44 -060014120 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014121 performAppGcsLocked();
14122 return;
14123 }
14124 // Still not idle, wait some more.
14125 scheduleAppGcsLocked();
14126 }
14127
14128 /**
14129 * Schedule the execution of all pending app GCs.
14130 */
14131 final void scheduleAppGcsLocked() {
14132 mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014133
14134 if (mProcessesToGc.size() > 0) {
14135 // Schedule a GC for the time to the next process.
14136 ProcessRecord proc = mProcessesToGc.get(0);
14137 Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG);
14138
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014139 long when = proc.lastRequestedGc + GC_MIN_INTERVAL;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014140 long now = SystemClock.uptimeMillis();
14141 if (when < (now+GC_TIMEOUT)) {
14142 when = now + GC_TIMEOUT;
14143 }
14144 mHandler.sendMessageAtTime(msg, when);
14145 }
14146 }
14147
14148 /**
14149 * Add a process to the array of processes waiting to be GCed. Keeps the
14150 * list in sorted order by the last GC time. The process can't already be
14151 * on the list.
14152 */
14153 final void addProcessToGcListLocked(ProcessRecord proc) {
14154 boolean added = false;
14155 for (int i=mProcessesToGc.size()-1; i>=0; i--) {
14156 if (mProcessesToGc.get(i).lastRequestedGc <
14157 proc.lastRequestedGc) {
14158 added = true;
14159 mProcessesToGc.add(i+1, proc);
14160 break;
14161 }
14162 }
14163 if (!added) {
14164 mProcessesToGc.add(0, proc);
14165 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014166 }
14167
14168 /**
14169 * Set up to ask a process to GC itself. This will either do it
14170 * immediately, or put it on the list of processes to gc the next
14171 * time things are idle.
14172 */
14173 final void scheduleAppGcLocked(ProcessRecord app) {
14174 long now = SystemClock.uptimeMillis();
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014175 if ((app.lastRequestedGc+GC_MIN_INTERVAL) > now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014176 return;
14177 }
14178 if (!mProcessesToGc.contains(app)) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014179 addProcessToGcListLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014180 scheduleAppGcsLocked();
14181 }
14182 }
14183
Dianne Hackborn287952c2010-09-22 22:34:31 -070014184 final void checkExcessivePowerUsageLocked(boolean doKills) {
14185 updateCpuStatsNow();
14186
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014187 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborn287952c2010-09-22 22:34:31 -070014188 boolean doWakeKills = doKills;
14189 boolean doCpuKills = doKills;
14190 if (mLastPowerCheckRealtime == 0) {
14191 doWakeKills = false;
14192 }
14193 if (mLastPowerCheckUptime == 0) {
14194 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014195 }
14196 if (stats.isScreenOn()) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070014197 doWakeKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014198 }
14199 final long curRealtime = SystemClock.elapsedRealtime();
Dianne Hackborn287952c2010-09-22 22:34:31 -070014200 final long realtimeSince = curRealtime - mLastPowerCheckRealtime;
14201 final long curUptime = SystemClock.uptimeMillis();
14202 final long uptimeSince = curUptime - mLastPowerCheckUptime;
14203 mLastPowerCheckRealtime = curRealtime;
14204 mLastPowerCheckUptime = curUptime;
14205 if (realtimeSince < WAKE_LOCK_MIN_CHECK_DURATION) {
14206 doWakeKills = false;
14207 }
14208 if (uptimeSince < CPU_MIN_CHECK_DURATION) {
14209 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014210 }
14211 int i = mLruProcesses.size();
14212 while (i > 0) {
14213 i--;
14214 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn287952c2010-09-22 22:34:31 -070014215 if (!app.keeping) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014216 long wtime;
14217 synchronized (stats) {
14218 wtime = stats.getProcessWakeTime(app.info.uid,
14219 app.pid, curRealtime);
14220 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070014221 long wtimeUsed = wtime - app.lastWakeTime;
14222 long cputimeUsed = app.curCpuTime - app.lastCpuTime;
14223 if (DEBUG_POWER) {
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014224 StringBuilder sb = new StringBuilder(128);
14225 sb.append("Wake for ");
14226 app.toShortString(sb);
14227 sb.append(": over ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070014228 TimeUtils.formatDuration(realtimeSince, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014229 sb.append(" used ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070014230 TimeUtils.formatDuration(wtimeUsed, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014231 sb.append(" (");
Dianne Hackborn287952c2010-09-22 22:34:31 -070014232 sb.append((wtimeUsed*100)/realtimeSince);
14233 sb.append("%)");
14234 Slog.i(TAG, sb.toString());
14235 sb.setLength(0);
14236 sb.append("CPU for ");
14237 app.toShortString(sb);
14238 sb.append(": over ");
14239 TimeUtils.formatDuration(uptimeSince, sb);
14240 sb.append(" used ");
14241 TimeUtils.formatDuration(cputimeUsed, sb);
14242 sb.append(" (");
14243 sb.append((cputimeUsed*100)/uptimeSince);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014244 sb.append("%)");
14245 Slog.i(TAG, sb.toString());
14246 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014247 // If a process has held a wake lock for more
14248 // than 50% of the time during this period,
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014249 // that sounds bad. Kill!
Dianne Hackborn287952c2010-09-22 22:34:31 -070014250 if (doWakeKills && realtimeSince > 0
14251 && ((wtimeUsed*100)/realtimeSince) >= 50) {
14252 synchronized (stats) {
14253 stats.reportExcessiveWakeLocked(app.info.uid, app.processName,
14254 realtimeSince, wtimeUsed);
14255 }
14256 Slog.w(TAG, "Excessive wake lock in " + app.processName
14257 + " (pid " + app.pid + "): held " + wtimeUsed
14258 + " during " + realtimeSince);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014259 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14260 app.processName, app.setAdj, "excessive wake lock");
14261 Process.killProcessQuiet(app.pid);
Dianne Hackborn287952c2010-09-22 22:34:31 -070014262 } else if (doCpuKills && uptimeSince > 0
14263 && ((cputimeUsed*100)/uptimeSince) >= 50) {
14264 synchronized (stats) {
14265 stats.reportExcessiveCpuLocked(app.info.uid, app.processName,
14266 uptimeSince, cputimeUsed);
14267 }
14268 Slog.w(TAG, "Excessive CPU in " + app.processName
14269 + " (pid " + app.pid + "): used " + cputimeUsed
14270 + " during " + uptimeSince);
14271 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14272 app.processName, app.setAdj, "excessive cpu");
14273 Process.killProcessQuiet(app.pid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014274 } else {
14275 app.lastWakeTime = wtime;
Dianne Hackborn287952c2010-09-22 22:34:31 -070014276 app.lastCpuTime = app.curCpuTime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014277 }
14278 }
14279 }
14280 }
14281
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014282 private final boolean updateOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014283 ProcessRecord app, int hiddenAdj, ProcessRecord TOP_APP, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014284 app.hiddenAdj = hiddenAdj;
14285
14286 if (app.thread == null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014287 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014288 }
14289
Dianne Hackborn287952c2010-09-22 22:34:31 -070014290 final boolean wasKeeping = app.keeping;
14291
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014292 boolean success = true;
14293
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014294 computeOomAdjLocked(app, hiddenAdj, TOP_APP, false, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014295
Jeff Brown10e89712011-07-08 18:52:57 -070014296 if (app.curRawAdj != app.setRawAdj) {
Jeff Brown10e89712011-07-08 18:52:57 -070014297 if (wasKeeping && !app.keeping) {
14298 // This app is no longer something we want to keep. Note
14299 // its current wake lock time to later know to kill it if
14300 // it is not behaving well.
14301 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
14302 synchronized (stats) {
14303 app.lastWakeTime = stats.getProcessWakeTime(app.info.uid,
14304 app.pid, SystemClock.elapsedRealtime());
14305 }
14306 app.lastCpuTime = app.curCpuTime;
14307 }
14308
14309 app.setRawAdj = app.curRawAdj;
14310 }
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014311
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014312 if (app.curAdj != app.setAdj) {
14313 if (Process.setOomAdj(app.pid, app.curAdj)) {
Dianne Hackbornbbb09ac2011-11-30 11:31:29 -080014314 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014315 TAG, "Set " + app.pid + " " + app.processName +
14316 " adj " + app.curAdj + ": " + app.adjType);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014317 app.setAdj = app.curAdj;
Jeff Brown10e89712011-07-08 18:52:57 -070014318 } else {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014319 success = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014320 Slog.w(TAG, "Failed setting oom adj of " + app + " to " + app.curAdj);
Jeff Brown10e89712011-07-08 18:52:57 -070014321 }
14322 }
14323 if (app.setSchedGroup != app.curSchedGroup) {
14324 app.setSchedGroup = app.curSchedGroup;
14325 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
14326 "Setting process group of " + app.processName
14327 + " to " + app.curSchedGroup);
14328 if (app.waitingToKill != null &&
14329 app.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
14330 Slog.i(TAG, "Killing " + app.toShortString() + ": " + app.waitingToKill);
14331 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14332 app.processName, app.setAdj, app.waitingToKill);
14333 Process.killProcessQuiet(app.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014334 success = false;
Jeff Brown10e89712011-07-08 18:52:57 -070014335 } else {
14336 if (true) {
14337 long oldId = Binder.clearCallingIdentity();
14338 try {
14339 Process.setProcessGroup(app.pid, app.curSchedGroup);
14340 } catch (Exception e) {
14341 Slog.w(TAG, "Failed setting process group of " + app.pid
14342 + " to " + app.curSchedGroup);
14343 e.printStackTrace();
14344 } finally {
14345 Binder.restoreCallingIdentity(oldId);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014346 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014347 } else {
Jeff Brown10e89712011-07-08 18:52:57 -070014348 if (app.thread != null) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070014349 try {
Jeff Brown10e89712011-07-08 18:52:57 -070014350 app.thread.setSchedulingGroup(app.curSchedGroup);
14351 } catch (RemoteException e) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070014352 }
14353 }
14354 }
14355 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014356 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014357 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014358 }
14359
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014360 private final ActivityRecord resumedAppLocked() {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014361 ActivityRecord resumedActivity = mMainStack.mResumedActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014362 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -080014363 resumedActivity = mMainStack.mPausingActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014364 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014365 resumedActivity = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014366 }
14367 }
14368 return resumedActivity;
14369 }
14370
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014371 private final boolean updateOomAdjLocked(ProcessRecord app) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014372 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014373 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
14374 int curAdj = app.curAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070014375 final boolean wasHidden = curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
14376 && curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014377
14378 mAdjSeq++;
14379
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014380 boolean success = updateOomAdjLocked(app, app.hiddenAdj, TOP_APP, false);
Dianne Hackborn7d608422011-08-07 16:24:18 -070014381 final boolean nowHidden = app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
14382 && app.curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014383 if (nowHidden != wasHidden) {
14384 // Changed to/from hidden state, so apps after it in the LRU
14385 // list may also be changed.
14386 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014387 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014388 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014389 }
14390
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014391 final void updateOomAdjLocked() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014392 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014393 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
14394
14395 if (false) {
14396 RuntimeException e = new RuntimeException();
14397 e.fillInStackTrace();
Joe Onorato8a9b2202010-02-26 18:56:32 -080014398 Slog.i(TAG, "updateOomAdj: top=" + TOP_ACT, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014399 }
14400
14401 mAdjSeq++;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014402 mNewNumServiceProcs = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014403
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014404 // Let's determine how many processes we have running vs.
14405 // how many slots we have for background processes; we may want
14406 // to put multiple processes in a slot of there are enough of
14407 // them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014408 int numSlots = ProcessList.HIDDEN_APP_MAX_ADJ - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014409 int factor = (mLruProcesses.size()-4)/numSlots;
14410 if (factor < 1) factor = 1;
14411 int step = 0;
Dianne Hackborn8633e682010-04-22 16:03:41 -070014412 int numHidden = 0;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014413 int numTrimming = 0;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014414
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014415 // First update the OOM adjustment for each of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014416 // application processes based on their current state.
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014417 int i = mLruProcesses.size();
Dianne Hackborn7d608422011-08-07 16:24:18 -070014418 int curHiddenAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014419 while (i > 0) {
14420 i--;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014421 ProcessRecord app = mLruProcesses.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080014422 //Slog.i(TAG, "OOM " + app + ": cur hidden=" + curHiddenAdj);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014423 updateOomAdjLocked(app, curHiddenAdj, TOP_APP, true);
14424 if (curHiddenAdj < ProcessList.HIDDEN_APP_MAX_ADJ
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014425 && app.curAdj == curHiddenAdj) {
14426 step++;
14427 if (step >= factor) {
14428 step = 0;
14429 curHiddenAdj++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014430 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014431 }
14432 if (!app.killedBackground) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070014433 if (app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014434 numHidden++;
14435 if (numHidden > mProcessLimit) {
14436 Slog.i(TAG, "No longer want " + app.processName
14437 + " (pid " + app.pid + "): hidden #" + numHidden);
14438 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14439 app.processName, app.setAdj, "too many background");
14440 app.killedBackground = true;
14441 Process.killProcessQuiet(app.pid);
Dianne Hackborn8633e682010-04-22 16:03:41 -070014442 }
14443 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -080014444 if (!app.killedBackground && app.isolated && app.services.size() <= 0) {
14445 // If this is an isolated process, and there are no
14446 // services running in it, then the process is no longer
14447 // needed. We agressively kill these because we can by
14448 // definition not re-use the same process again, and it is
14449 // good to avoid having whatever code was running in them
14450 // left sitting around after no longer needed.
14451 Slog.i(TAG, "Isolated process " + app.processName
14452 + " (pid " + app.pid + ") no longer needed");
14453 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14454 app.processName, app.setAdj, "isolated not needed");
14455 app.killedBackground = true;
14456 Process.killProcessQuiet(app.pid);
14457 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014458 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
14459 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
14460 && !app.killedBackground) {
14461 numTrimming++;
14462 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014463 }
14464 }
14465
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014466 mNumServiceProcs = mNewNumServiceProcs;
14467
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014468 // Now determine the memory trimming level of background processes.
14469 // Unfortunately we need to start at the back of the list to do this
14470 // properly. We only do this if the number of background apps we
14471 // are managing to keep around is less than half the maximum we desire;
14472 // if we are keeping a good number around, we'll let them use whatever
14473 // memory they want.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014474 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/2)) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014475 final int N = mLruProcesses.size();
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014476 factor = numTrimming/3;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080014477 int minFactor = 2;
14478 if (mHomeProcess != null) minFactor++;
14479 if (mPreviousProcess != null) minFactor++;
14480 if (factor < minFactor) factor = minFactor;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014481 step = 0;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014482 int fgTrimLevel;
14483 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/5)) {
14484 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL;
14485 } else if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/3)) {
14486 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW;
14487 } else {
14488 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE;
14489 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014490 int curLevel = ComponentCallbacks2.TRIM_MEMORY_COMPLETE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014491 for (i=0; i<N; i++) {
14492 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014493 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
14494 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080014495 && !app.killedBackground) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014496 if (app.trimMemoryLevel < curLevel && app.thread != null) {
14497 try {
14498 app.thread.scheduleTrimMemory(curLevel);
14499 } catch (RemoteException e) {
14500 }
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080014501 if (false) {
14502 // For now we won't do this; our memory trimming seems
14503 // to be good enough at this point that destroying
14504 // activities causes more harm than good.
14505 if (curLevel >= ComponentCallbacks2.TRIM_MEMORY_COMPLETE
14506 && app != mHomeProcess && app != mPreviousProcess) {
14507 // For these apps we will also finish their activities
14508 // to help them free memory.
14509 mMainStack.destroyActivitiesLocked(app, false, "trim");
14510 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014511 }
14512 }
14513 app.trimMemoryLevel = curLevel;
14514 step++;
14515 if (step >= factor) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014516 step = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014517 switch (curLevel) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014518 case ComponentCallbacks2.TRIM_MEMORY_COMPLETE:
14519 curLevel = ComponentCallbacks2.TRIM_MEMORY_MODERATE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014520 break;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014521 case ComponentCallbacks2.TRIM_MEMORY_MODERATE:
14522 curLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014523 break;
14524 }
14525 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014526 } else if (app.nonStoppingAdj == ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014527 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014528 && app.thread != null) {
14529 try {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014530 app.thread.scheduleTrimMemory(
14531 ComponentCallbacks2.TRIM_MEMORY_BACKGROUND);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014532 } catch (RemoteException e) {
14533 }
14534 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014535 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014536 } else {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014537 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014538 && app.pendingUiClean) {
14539 // If this application is now in the background and it
14540 // had done UI, then give it the special trim level to
14541 // have it free UI resources.
14542 final int level = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
14543 if (app.trimMemoryLevel < level && app.thread != null) {
14544 try {
14545 app.thread.scheduleTrimMemory(level);
14546 } catch (RemoteException e) {
14547 }
14548 }
14549 app.pendingUiClean = false;
14550 }
14551 if (app.trimMemoryLevel < fgTrimLevel && app.thread != null) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014552 try {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014553 app.thread.scheduleTrimMemory(fgTrimLevel);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014554 } catch (RemoteException e) {
14555 }
14556 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014557 app.trimMemoryLevel = fgTrimLevel;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014558 }
14559 }
14560 } else {
14561 final int N = mLruProcesses.size();
14562 for (i=0; i<N; i++) {
14563 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014564 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014565 && app.pendingUiClean) {
14566 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
14567 && app.thread != null) {
14568 try {
14569 app.thread.scheduleTrimMemory(
14570 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
14571 } catch (RemoteException e) {
14572 }
14573 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014574 app.pendingUiClean = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014575 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014576 app.trimMemoryLevel = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014577 }
14578 }
14579
14580 if (mAlwaysFinishActivities) {
Dianne Hackborn28695e02011-11-02 21:59:51 -070014581 mMainStack.destroyActivitiesLocked(null, false, "always-finish");
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014582 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014583 }
14584
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014585 final void trimApplications() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014586 synchronized (this) {
14587 int i;
14588
14589 // First remove any unused application processes whose package
14590 // has been removed.
14591 for (i=mRemovedProcesses.size()-1; i>=0; i--) {
14592 final ProcessRecord app = mRemovedProcesses.get(i);
14593 if (app.activities.size() == 0
14594 && app.curReceiver == null && app.services.size() == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080014595 Slog.i(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014596 TAG, "Exiting empty application process "
14597 + app.processName + " ("
14598 + (app.thread != null ? app.thread.asBinder() : null)
14599 + ")\n");
14600 if (app.pid > 0 && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070014601 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14602 app.processName, app.setAdj, "empty");
14603 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014604 } else {
14605 try {
14606 app.thread.scheduleExit();
14607 } catch (Exception e) {
14608 // Ignore exceptions.
14609 }
14610 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070014611 cleanUpApplicationRecordLocked(app, false, true, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014612 mRemovedProcesses.remove(i);
14613
14614 if (app.persistent) {
14615 if (app.persistent) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080014616 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014617 }
14618 }
14619 }
14620 }
14621
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014622 // Now update the oom adj for all processes.
14623 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014624 }
14625 }
14626
14627 /** This method sends the specified signal to each of the persistent apps */
14628 public void signalPersistentProcesses(int sig) throws RemoteException {
14629 if (sig != Process.SIGNAL_USR1) {
14630 throw new SecurityException("Only SIGNAL_USR1 is allowed");
14631 }
14632
14633 synchronized (this) {
14634 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
14635 != PackageManager.PERMISSION_GRANTED) {
14636 throw new SecurityException("Requires permission "
14637 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
14638 }
14639
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014640 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
14641 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014642 if (r.thread != null && r.persistent) {
14643 Process.sendSignal(r.pid, sig);
14644 }
14645 }
14646 }
14647 }
14648
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014649 private void stopProfilerLocked(ProcessRecord proc, String path, int profileType) {
14650 if (proc == null || proc == mProfileProc) {
14651 proc = mProfileProc;
14652 path = mProfileFile;
14653 profileType = mProfileType;
14654 clearProfilerLocked();
14655 }
14656 if (proc == null) {
14657 return;
14658 }
14659 try {
14660 proc.thread.profilerControl(false, path, null, profileType);
14661 } catch (RemoteException e) {
14662 throw new IllegalStateException("Process disappeared");
14663 }
14664 }
14665
14666 private void clearProfilerLocked() {
14667 if (mProfileFd != null) {
14668 try {
14669 mProfileFd.close();
14670 } catch (IOException e) {
14671 }
14672 }
14673 mProfileApp = null;
14674 mProfileProc = null;
14675 mProfileFile = null;
14676 mProfileType = 0;
14677 mAutoStopProfiler = false;
14678 }
14679
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014680 public boolean profileControl(String process, boolean start,
Romain Guy7eabe552011-07-21 14:56:34 -070014681 String path, ParcelFileDescriptor fd, int profileType) throws RemoteException {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014682
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014683 try {
14684 synchronized (this) {
14685 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14686 // its own permission.
14687 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14688 != PackageManager.PERMISSION_GRANTED) {
14689 throw new SecurityException("Requires permission "
14690 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014691 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014692
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014693 if (start && fd == null) {
14694 throw new IllegalArgumentException("null fd");
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014695 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014696
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014697 ProcessRecord proc = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014698 if (process != null) {
14699 try {
14700 int pid = Integer.parseInt(process);
14701 synchronized (mPidsSelfLocked) {
14702 proc = mPidsSelfLocked.get(pid);
14703 }
14704 } catch (NumberFormatException e) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014705 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014706
14707 if (proc == null) {
14708 HashMap<String, SparseArray<ProcessRecord>> all
14709 = mProcessNames.getMap();
14710 SparseArray<ProcessRecord> procs = all.get(process);
14711 if (procs != null && procs.size() > 0) {
14712 proc = procs.valueAt(0);
14713 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014714 }
14715 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014716
14717 if (start && (proc == null || proc.thread == null)) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014718 throw new IllegalArgumentException("Unknown process: " + process);
14719 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014720
14721 if (start) {
14722 stopProfilerLocked(null, null, 0);
14723 setProfileApp(proc.info, proc.processName, path, fd, false);
14724 mProfileProc = proc;
14725 mProfileType = profileType;
14726 try {
14727 fd = fd.dup();
14728 } catch (IOException e) {
14729 fd = null;
14730 }
14731 proc.thread.profilerControl(start, path, fd, profileType);
14732 fd = null;
14733 mProfileFd = null;
14734 } else {
14735 stopProfilerLocked(proc, path, profileType);
14736 if (fd != null) {
14737 try {
14738 fd.close();
14739 } catch (IOException e) {
14740 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014741 }
14742 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014743
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014744 return true;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014745 }
14746 } catch (RemoteException e) {
14747 throw new IllegalStateException("Process disappeared");
14748 } finally {
14749 if (fd != null) {
14750 try {
14751 fd.close();
14752 } catch (IOException e) {
14753 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014754 }
14755 }
14756 }
Andy McFadden824c5102010-07-09 16:26:57 -070014757
14758 public boolean dumpHeap(String process, boolean managed,
14759 String path, ParcelFileDescriptor fd) throws RemoteException {
14760
14761 try {
14762 synchronized (this) {
14763 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14764 // its own permission (same as profileControl).
14765 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14766 != PackageManager.PERMISSION_GRANTED) {
14767 throw new SecurityException("Requires permission "
14768 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
14769 }
14770
14771 if (fd == null) {
14772 throw new IllegalArgumentException("null fd");
14773 }
14774
14775 ProcessRecord proc = null;
14776 try {
14777 int pid = Integer.parseInt(process);
14778 synchronized (mPidsSelfLocked) {
14779 proc = mPidsSelfLocked.get(pid);
14780 }
14781 } catch (NumberFormatException e) {
14782 }
14783
14784 if (proc == null) {
14785 HashMap<String, SparseArray<ProcessRecord>> all
14786 = mProcessNames.getMap();
14787 SparseArray<ProcessRecord> procs = all.get(process);
14788 if (procs != null && procs.size() > 0) {
14789 proc = procs.valueAt(0);
14790 }
14791 }
14792
14793 if (proc == null || proc.thread == null) {
14794 throw new IllegalArgumentException("Unknown process: " + process);
14795 }
14796
Dianne Hackbornf02e57b2011-03-01 22:21:04 -080014797 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
14798 if (!isDebuggable) {
Andy McFadden824c5102010-07-09 16:26:57 -070014799 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
14800 throw new SecurityException("Process not debuggable: " + proc);
14801 }
14802 }
14803
14804 proc.thread.dumpHeap(managed, path, fd);
14805 fd = null;
14806 return true;
14807 }
14808 } catch (RemoteException e) {
14809 throw new IllegalStateException("Process disappeared");
14810 } finally {
14811 if (fd != null) {
14812 try {
14813 fd.close();
14814 } catch (IOException e) {
14815 }
14816 }
14817 }
14818 }
14819
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014820 /** In this method we try to acquire our lock to make sure that we have not deadlocked */
14821 public void monitor() {
14822 synchronized (this) { }
14823 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014824
Dianne Hackborna573f6a2012-02-09 16:12:18 -080014825 void onCoreSettingsChange(Bundle settings) {
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014826 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
14827 ProcessRecord processRecord = mLruProcesses.get(i);
14828 try {
14829 if (processRecord.thread != null) {
14830 processRecord.thread.setCoreSettings(settings);
14831 }
14832 } catch (RemoteException re) {
14833 /* ignore */
14834 }
14835 }
14836 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014837
14838 // Multi-user methods
14839
Amith Yamasani742a6712011-05-04 14:49:28 -070014840 private int mCurrentUserId;
14841 private SparseIntArray mLoggedInUsers = new SparseIntArray(5);
14842
14843 public boolean switchUser(int userId) {
14844 final int callingUid = Binder.getCallingUid();
14845 if (callingUid != 0 && callingUid != Process.myUid()) {
14846 Slog.e(TAG, "Trying to switch user from unauthorized app");
14847 return false;
14848 }
14849 if (mCurrentUserId == userId)
14850 return true;
14851
14852 synchronized (this) {
14853 // Check if user is already logged in, otherwise check if user exists first before
14854 // adding to the list of logged in users.
14855 if (mLoggedInUsers.indexOfKey(userId) < 0) {
14856 if (!userExists(userId)) {
14857 return false;
14858 }
14859 mLoggedInUsers.append(userId, userId);
14860 }
14861
14862 mCurrentUserId = userId;
14863 boolean haveActivities = mMainStack.switchUser(userId);
14864 if (!haveActivities) {
14865 startHomeActivityLocked(userId);
14866 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014867
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014868 }
Amith Yamasani13593602012-03-22 16:16:17 -070014869
14870 // Inform of user switch
14871 Intent addedIntent = new Intent(Intent.ACTION_USER_SWITCHED);
14872 addedIntent.putExtra(Intent.EXTRA_USERID, userId);
14873 mContext.sendBroadcast(addedIntent, android.Manifest.permission.MANAGE_ACCOUNTS);
14874
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014875 return true;
14876 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014877
Amith Yamasani52f1d752012-03-28 18:19:29 -070014878 @Override
14879 public UserInfo getCurrentUser() throws RemoteException {
14880 final int callingUid = Binder.getCallingUid();
14881 if (callingUid != 0 && callingUid != Process.myUid()) {
14882 Slog.e(TAG, "Trying to get user from unauthorized app");
14883 return null;
14884 }
14885 return AppGlobals.getPackageManager().getUser(mCurrentUserId);
14886 }
14887
Amith Yamasani13593602012-03-22 16:16:17 -070014888 private void onUserRemoved(Intent intent) {
14889 int extraUserId = intent.getIntExtra(Intent.EXTRA_USERID, -1);
14890 if (extraUserId < 1) return;
14891
14892 // Kill all the processes for the user
14893 ArrayList<Pair<String, Integer>> pkgAndUids = new ArrayList<Pair<String,Integer>>();
14894 synchronized (this) {
14895 HashMap<String,SparseArray<ProcessRecord>> map = mProcessNames.getMap();
14896 for (Entry<String, SparseArray<ProcessRecord>> uidMap : map.entrySet()) {
14897 SparseArray<ProcessRecord> uids = uidMap.getValue();
14898 for (int i = 0; i < uids.size(); i++) {
14899 if (UserId.getUserId(uids.keyAt(i)) == extraUserId) {
14900 pkgAndUids.add(new Pair<String,Integer>(uidMap.getKey(), uids.keyAt(i)));
14901 }
14902 }
14903 }
14904
14905 for (Pair<String,Integer> pkgAndUid : pkgAndUids) {
14906 forceStopPackageLocked(pkgAndUid.first, pkgAndUid.second,
14907 false, false, true, true, extraUserId);
14908 }
14909 }
14910 }
14911
Amith Yamasani742a6712011-05-04 14:49:28 -070014912 private boolean userExists(int userId) {
14913 try {
Amith Yamasani13593602012-03-22 16:16:17 -070014914 UserInfo user = AppGlobals.getPackageManager().getUser(userId);
14915 return user != null;
Amith Yamasani742a6712011-05-04 14:49:28 -070014916 } catch (RemoteException re) {
14917 // Won't happen, in same process
14918 }
14919
14920 return false;
14921 }
14922
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014923 private void checkValidCaller(int uid, int userId) {
14924 if (UserId.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) return;
14925
14926 throw new SecurityException("Caller uid=" + uid
14927 + " is not privileged to communicate with user=" + userId);
14928 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014929
14930 private int applyUserId(int uid, int userId) {
14931 return UserId.getUid(userId, uid);
14932 }
14933
14934 private ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080014935 if (info == null) return null;
Amith Yamasani742a6712011-05-04 14:49:28 -070014936 ApplicationInfo newInfo = new ApplicationInfo(info);
14937 newInfo.uid = applyUserId(info.uid, userId);
Amith Yamasania4a54e22012-04-16 15:44:19 -070014938 newInfo.dataDir = USER_DATA_DIR + userId + "/"
14939 + info.packageName;
Amith Yamasani742a6712011-05-04 14:49:28 -070014940 return newInfo;
14941 }
14942
14943 ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) {
Amith Yamasania4a54e22012-04-16 15:44:19 -070014944 if (aInfo == null
14945 || (userId < 1 && aInfo.applicationInfo.uid < UserId.PER_USER_RANGE)) {
Amith Yamasani742a6712011-05-04 14:49:28 -070014946 return aInfo;
14947 }
14948
14949 ActivityInfo info = new ActivityInfo(aInfo);
14950 info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId);
14951 return info;
14952 }
14953
14954 static class ServiceMap {
14955
14956 private final SparseArray<HashMap<ComponentName, ServiceRecord>> mServicesByNamePerUser
14957 = new SparseArray<HashMap<ComponentName, ServiceRecord>>();
14958 private final SparseArray<HashMap<Intent.FilterComparison, ServiceRecord>>
14959 mServicesByIntentPerUser = new SparseArray<
14960 HashMap<Intent.FilterComparison, ServiceRecord>>();
14961
14962 ServiceRecord getServiceByName(ComponentName name, int callingUser) {
14963 // TODO: Deal with global services
14964 if (DEBUG_MU)
14965 Slog.v(TAG_MU, "getServiceByName(" + name + "), callingUser = " + callingUser);
14966 return getServices(callingUser).get(name);
14967 }
14968
14969 ServiceRecord getServiceByName(ComponentName name) {
14970 return getServiceByName(name, -1);
14971 }
14972
14973 ServiceRecord getServiceByIntent(Intent.FilterComparison filter, int callingUser) {
14974 // TODO: Deal with global services
14975 if (DEBUG_MU)
14976 Slog.v(TAG_MU, "getServiceByIntent(" + filter + "), callingUser = " + callingUser);
14977 return getServicesByIntent(callingUser).get(filter);
14978 }
14979
14980 ServiceRecord getServiceByIntent(Intent.FilterComparison filter) {
14981 return getServiceByIntent(filter, -1);
14982 }
14983
14984 void putServiceByName(ComponentName name, int callingUser, ServiceRecord value) {
14985 // TODO: Deal with global services
14986 getServices(callingUser).put(name, value);
14987 }
14988
14989 void putServiceByIntent(Intent.FilterComparison filter, int callingUser,
14990 ServiceRecord value) {
14991 // TODO: Deal with global services
14992 getServicesByIntent(callingUser).put(filter, value);
14993 }
14994
14995 void removeServiceByName(ComponentName name, int callingUser) {
14996 // TODO: Deal with global services
14997 ServiceRecord removed = getServices(callingUser).remove(name);
14998 if (DEBUG_MU)
14999 Slog.v(TAG, "removeServiceByName user=" + callingUser + " name=" + name
15000 + " removed=" + removed);
15001 }
15002
15003 void removeServiceByIntent(Intent.FilterComparison filter, int callingUser) {
15004 // TODO: Deal with global services
15005 ServiceRecord removed = getServicesByIntent(callingUser).remove(filter);
15006 if (DEBUG_MU)
15007 Slog.v(TAG_MU, "removeServiceByIntent user=" + callingUser + " intent=" + filter
15008 + " removed=" + removed);
15009 }
15010
15011 Collection<ServiceRecord> getAllServices(int callingUser) {
15012 // TODO: Deal with global services
15013 return getServices(callingUser).values();
15014 }
15015
15016 private HashMap<ComponentName, ServiceRecord> getServices(int callingUser) {
15017 HashMap map = mServicesByNamePerUser.get(callingUser);
15018 if (map == null) {
15019 map = new HashMap<ComponentName, ServiceRecord>();
15020 mServicesByNamePerUser.put(callingUser, map);
15021 }
15022 return map;
15023 }
15024
15025 private HashMap<Intent.FilterComparison, ServiceRecord> getServicesByIntent(
15026 int callingUser) {
15027 HashMap map = mServicesByIntentPerUser.get(callingUser);
15028 if (map == null) {
15029 map = new HashMap<Intent.FilterComparison, ServiceRecord>();
15030 mServicesByIntentPerUser.put(callingUser, map);
15031 }
15032 return map;
15033 }
15034 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015035}