blob: 42c42c92ccc84bcceccffae303b66a76dc36db73 [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 Hackborn55280a92009-05-07 15:53:46 -0700700 * Set if we are shutting down the system, similar to sleeping.
701 */
702 boolean mShuttingDown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800703
704 /**
705 * Task identifier that activities are currently being started
706 * in. Incremented each time a new task is created.
707 * todo: Replace this with a TokenSpace class that generates non-repeating
708 * integers that won't wrap.
709 */
710 int mCurTask = 1;
711
712 /**
713 * Current sequence id for oom_adj computation traversal.
714 */
715 int mAdjSeq = 0;
716
717 /**
Dianne Hackborn906497c2010-05-10 15:57:38 -0700718 * Current sequence id for process LRU updating.
719 */
720 int mLruSeq = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800721
722 /**
Dianne Hackborne02c88a2011-10-28 13:58:15 -0700723 * Keep track of the number of service processes we last found, to
724 * determine on the next iteration which should be B services.
725 */
726 int mNumServiceProcs = 0;
727 int mNewNumServiceProcs = 0;
728
729 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800730 * System monitoring: number of processes that died since the last
731 * N procs were started.
732 */
733 int[] mProcDeaths = new int[20];
734
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700735 /**
736 * This is set if we had to do a delayed dexopt of an app before launching
737 * it, to increasing the ANR timeouts in that case.
738 */
739 boolean mDidDexOpt;
740
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800741 String mDebugApp = null;
742 boolean mWaitForDebugger = false;
743 boolean mDebugTransient = false;
744 String mOrigDebugApp = null;
745 boolean mOrigWaitForDebugger = false;
746 boolean mAlwaysFinishActivities = false;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700747 IActivityController mController = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700748 String mProfileApp = null;
749 ProcessRecord mProfileProc = null;
750 String mProfileFile;
751 ParcelFileDescriptor mProfileFd;
752 int mProfileType = 0;
753 boolean mAutoStopProfiler = false;
Siva Velusamy92a8b222012-03-09 16:24:04 -0800754 String mOpenGlTraceApp = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800755
Jeff Sharkeya4620792011-05-20 15:29:23 -0700756 final RemoteCallbackList<IProcessObserver> mProcessObservers
757 = new RemoteCallbackList<IProcessObserver>();
758
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800759 /**
760 * Callback of last caller to {@link #requestPss}.
761 */
762 Runnable mRequestPssCallback;
763
764 /**
765 * Remaining processes for which we are waiting results from the last
766 * call to {@link #requestPss}.
767 */
768 final ArrayList<ProcessRecord> mRequestPssList
769 = new ArrayList<ProcessRecord>();
770
771 /**
772 * Runtime statistics collection thread. This object's lock is used to
773 * protect all related state.
774 */
775 final Thread mProcessStatsThread;
776
777 /**
778 * Used to collect process stats when showing not responding dialog.
779 * Protected by mProcessStatsThread.
780 */
781 final ProcessStats mProcessStats = new ProcessStats(
782 MONITOR_THREAD_CPU_USAGE);
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700783 final AtomicLong mLastCpuTime = new AtomicLong(0);
784 final AtomicBoolean mProcessStatsMutexFree = new AtomicBoolean(true);
785
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800786 long mLastWriteTime = 0;
787
788 /**
789 * Set to true after the system has finished booting.
790 */
791 boolean mBooted = false;
792
Dianne Hackborn7d608422011-08-07 16:24:18 -0700793 int mProcessLimit = ProcessList.MAX_HIDDEN_APPS;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700794 int mProcessLimitOverride = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800795
796 WindowManagerService mWindowManager;
797
798 static ActivityManagerService mSelf;
799 static ActivityThread mSystemThread;
800
801 private final class AppDeathRecipient implements IBinder.DeathRecipient {
802 final ProcessRecord mApp;
803 final int mPid;
804 final IApplicationThread mAppThread;
805
806 AppDeathRecipient(ProcessRecord app, int pid,
807 IApplicationThread thread) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800808 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800809 TAG, "New death recipient " + this
810 + " for thread " + thread.asBinder());
811 mApp = app;
812 mPid = pid;
813 mAppThread = thread;
814 }
815
816 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800817 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800818 TAG, "Death received in " + this
819 + " for thread " + mAppThread.asBinder());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800820 synchronized(ActivityManagerService.this) {
821 appDiedLocked(mApp, mPid, mAppThread);
822 }
823 }
824 }
825
826 static final int SHOW_ERROR_MSG = 1;
827 static final int SHOW_NOT_RESPONDING_MSG = 2;
828 static final int SHOW_FACTORY_ERROR_MSG = 3;
829 static final int UPDATE_CONFIGURATION_MSG = 4;
830 static final int GC_BACKGROUND_PROCESSES_MSG = 5;
831 static final int WAIT_FOR_DEBUGGER_MSG = 6;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800832 static final int SERVICE_TIMEOUT_MSG = 12;
833 static final int UPDATE_TIME_ZONE = 13;
834 static final int SHOW_UID_ERROR_MSG = 14;
835 static final int IM_FEELING_LUCKY_MSG = 15;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800836 static final int PROC_START_TIMEOUT_MSG = 20;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700837 static final int DO_PENDING_ACTIVITY_LAUNCHES_MSG = 21;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -0700838 static final int KILL_APPLICATION_MSG = 22;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800839 static final int FINALIZE_PENDING_INTENT_MSG = 23;
Dianne Hackborn860755f2010-06-03 18:47:52 -0700840 static final int POST_HEAVY_NOTIFICATION_MSG = 24;
841 static final int CANCEL_HEAVY_NOTIFICATION_MSG = 25;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700842 static final int SHOW_STRICT_MODE_VIOLATION_MSG = 26;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700843 static final int CHECK_EXCESSIVE_WAKE_LOCKS_MSG = 27;
Robert Greenwalt03595d02010-11-02 14:08:23 -0700844 static final int CLEAR_DNS_CACHE = 28;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700845 static final int UPDATE_HTTP_PROXY = 29;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700846 static final int SHOW_COMPAT_MODE_DIALOG_MSG = 30;
Dianne Hackborn36f80f32011-05-31 18:26:45 -0700847 static final int DISPATCH_FOREGROUND_ACTIVITIES_CHANGED = 31;
848 static final int DISPATCH_PROCESS_DIED = 32;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700849 static final int REPORT_MEM_USAGE = 33;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800850
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800851 static final int FIRST_ACTIVITY_STACK_MSG = 100;
852 static final int FIRST_BROADCAST_QUEUE_MSG = 200;
853 static final int FIRST_COMPAT_MODE_MSG = 300;
854
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800855 AlertDialog mUidAlert;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700856 CompatModeDialog mCompatModeDialog;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700857 long mLastMemUsageReportTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800858
859 final Handler mHandler = new Handler() {
860 //public Handler() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800861 // if (localLOGV) Slog.v(TAG, "Handler started!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800862 //}
863
864 public void handleMessage(Message msg) {
865 switch (msg.what) {
866 case SHOW_ERROR_MSG: {
867 HashMap data = (HashMap) msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800868 synchronized (ActivityManagerService.this) {
869 ProcessRecord proc = (ProcessRecord)data.get("app");
870 if (proc != null && proc.crashDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800871 Slog.e(TAG, "App already has crash dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800872 return;
873 }
874 AppErrorResult res = (AppErrorResult) data.get("result");
Joe Onorato54a4a412011-11-02 20:50:08 -0700875 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Dan Egnorb7f03672009-12-09 16:22:32 -0800876 Dialog d = new AppErrorDialog(mContext, res, proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800877 d.show();
878 proc.crashDialog = d;
879 } else {
880 // The device is asleep, so just pretend that the user
881 // saw a crash dialog and hit "force quit".
882 res.set(0);
883 }
884 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700885
886 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800887 } break;
888 case SHOW_NOT_RESPONDING_MSG: {
889 synchronized (ActivityManagerService.this) {
890 HashMap data = (HashMap) msg.obj;
891 ProcessRecord proc = (ProcessRecord)data.get("app");
892 if (proc != null && proc.anrDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800893 Slog.e(TAG, "App already has anr dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800894 return;
895 }
The Android Open Source Project4df24232009-03-05 14:34:35 -0800896
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700897 Intent intent = new Intent("android.intent.action.ANR");
898 if (!mProcessesReady) {
Christopher Tatef46723b2012-01-26 14:19:24 -0800899 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
900 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700901 }
902 broadcastIntentLocked(null, null, intent,
The Android Open Source Project4df24232009-03-05 14:34:35 -0800903 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -0700904 false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
The Android Open Source Project4df24232009-03-05 14:34:35 -0800905
Justin Kohbc52ca22012-03-29 15:11:44 -0700906 if (mShowDialogs) {
907 Dialog d = new AppNotRespondingDialog(ActivityManagerService.this,
Mike Lockwood69ccdbd2012-04-03 11:53:47 -0700908 mContext, proc, (ActivityRecord)data.get("activity"));
Justin Kohbc52ca22012-03-29 15:11:44 -0700909 d.show();
910 proc.anrDialog = d;
911 } else {
912 // Just kill the app if there is no dialog to be shown.
913 killAppAtUsersRequest(proc, null);
914 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800915 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700916
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700917 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800918 } break;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700919 case SHOW_STRICT_MODE_VIOLATION_MSG: {
920 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj;
921 synchronized (ActivityManagerService.this) {
922 ProcessRecord proc = (ProcessRecord) data.get("app");
923 if (proc == null) {
924 Slog.e(TAG, "App not found when showing strict mode dialog.");
925 break;
926 }
927 if (proc.crashDialog != null) {
928 Slog.e(TAG, "App already has strict mode dialog: " + proc);
929 return;
930 }
931 AppErrorResult res = (AppErrorResult) data.get("result");
Joe Onorato54a4a412011-11-02 20:50:08 -0700932 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700933 Dialog d = new StrictModeViolationDialog(mContext, res, proc);
934 d.show();
935 proc.crashDialog = d;
936 } else {
937 // The device is asleep, so just pretend that the user
938 // saw a crash dialog and hit "force quit".
939 res.set(0);
940 }
941 }
942 ensureBootCompleted();
943 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800944 case SHOW_FACTORY_ERROR_MSG: {
945 Dialog d = new FactoryErrorDialog(
946 mContext, msg.getData().getCharSequence("msg"));
947 d.show();
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700948 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800949 } break;
950 case UPDATE_CONFIGURATION_MSG: {
951 final ContentResolver resolver = mContext.getContentResolver();
952 Settings.System.putConfiguration(resolver, (Configuration)msg.obj);
953 } break;
954 case GC_BACKGROUND_PROCESSES_MSG: {
955 synchronized (ActivityManagerService.this) {
956 performAppGcsIfAppropriateLocked();
957 }
958 } break;
959 case WAIT_FOR_DEBUGGER_MSG: {
960 synchronized (ActivityManagerService.this) {
961 ProcessRecord app = (ProcessRecord)msg.obj;
962 if (msg.arg1 != 0) {
963 if (!app.waitedForDebugger) {
964 Dialog d = new AppWaitingForDebuggerDialog(
965 ActivityManagerService.this,
966 mContext, app);
967 app.waitDialog = d;
968 app.waitedForDebugger = true;
969 d.show();
970 }
971 } else {
972 if (app.waitDialog != null) {
973 app.waitDialog.dismiss();
974 app.waitDialog = null;
975 }
976 }
977 }
978 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800979 case SERVICE_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700980 if (mDidDexOpt) {
981 mDidDexOpt = false;
982 Message nmsg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
983 nmsg.obj = msg.obj;
984 mHandler.sendMessageDelayed(nmsg, SERVICE_TIMEOUT);
985 return;
986 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800987 serviceTimeout((ProcessRecord)msg.obj);
988 } break;
989 case UPDATE_TIME_ZONE: {
990 synchronized (ActivityManagerService.this) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800991 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
992 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800993 if (r.thread != null) {
994 try {
995 r.thread.updateTimeZone();
996 } catch (RemoteException ex) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800997 Slog.w(TAG, "Failed to update time zone for: " + r.info.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800998 }
999 }
1000 }
1001 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001002 } break;
Robert Greenwalt03595d02010-11-02 14:08:23 -07001003 case CLEAR_DNS_CACHE: {
1004 synchronized (ActivityManagerService.this) {
1005 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1006 ProcessRecord r = mLruProcesses.get(i);
1007 if (r.thread != null) {
1008 try {
1009 r.thread.clearDnsCache();
1010 } catch (RemoteException ex) {
1011 Slog.w(TAG, "Failed to clear dns cache for: " + r.info.processName);
1012 }
1013 }
1014 }
1015 }
1016 } break;
Robert Greenwalt434203a2010-10-11 16:00:27 -07001017 case UPDATE_HTTP_PROXY: {
1018 ProxyProperties proxy = (ProxyProperties)msg.obj;
1019 String host = "";
1020 String port = "";
1021 String exclList = "";
1022 if (proxy != null) {
1023 host = proxy.getHost();
1024 port = Integer.toString(proxy.getPort());
1025 exclList = proxy.getExclusionList();
1026 }
1027 synchronized (ActivityManagerService.this) {
1028 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1029 ProcessRecord r = mLruProcesses.get(i);
1030 if (r.thread != null) {
1031 try {
1032 r.thread.setHttpProxy(host, port, exclList);
1033 } catch (RemoteException ex) {
1034 Slog.w(TAG, "Failed to update http proxy for: " +
1035 r.info.processName);
1036 }
1037 }
1038 }
1039 }
1040 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001041 case SHOW_UID_ERROR_MSG: {
Joe Onorato54a4a412011-11-02 20:50:08 -07001042 String title = "System UIDs Inconsistent";
1043 String text = "UIDs on the system are inconsistent, you need to wipe your"
1044 + " data partition or your device will be unstable.";
1045 Log.e(TAG, title + ": " + text);
1046 if (mShowDialogs) {
1047 // XXX This is a temporary dialog, no need to localize.
1048 AlertDialog d = new BaseErrorDialog(mContext);
1049 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
1050 d.setCancelable(false);
1051 d.setTitle(title);
1052 d.setMessage(text);
1053 d.setButton(DialogInterface.BUTTON_POSITIVE, "I'm Feeling Lucky",
1054 mHandler.obtainMessage(IM_FEELING_LUCKY_MSG));
1055 mUidAlert = d;
1056 d.show();
1057 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001058 } break;
1059 case IM_FEELING_LUCKY_MSG: {
1060 if (mUidAlert != null) {
1061 mUidAlert.dismiss();
1062 mUidAlert = null;
1063 }
1064 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001065 case PROC_START_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001066 if (mDidDexOpt) {
1067 mDidDexOpt = false;
1068 Message nmsg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
1069 nmsg.obj = msg.obj;
1070 mHandler.sendMessageDelayed(nmsg, PROC_START_TIMEOUT);
1071 return;
1072 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001073 ProcessRecord app = (ProcessRecord)msg.obj;
1074 synchronized (ActivityManagerService.this) {
1075 processStartTimedOutLocked(app);
1076 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001077 } break;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07001078 case DO_PENDING_ACTIVITY_LAUNCHES_MSG: {
1079 synchronized (ActivityManagerService.this) {
1080 doPendingActivityLaunchesLocked(true);
1081 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001082 } break;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001083 case KILL_APPLICATION_MSG: {
1084 synchronized (ActivityManagerService.this) {
1085 int uid = msg.arg1;
1086 boolean restart = (msg.arg2 == 1);
1087 String pkg = (String) msg.obj;
Amith Yamasani483f3b02012-03-13 16:08:00 -07001088 forceStopPackageLocked(pkg, uid, restart, false, true, false,
1089 UserId.getUserId(uid));
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001090 }
1091 } break;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001092 case FINALIZE_PENDING_INTENT_MSG: {
1093 ((PendingIntentRecord)msg.obj).completeFinalize();
1094 } break;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001095 case POST_HEAVY_NOTIFICATION_MSG: {
1096 INotificationManager inm = NotificationManager.getService();
1097 if (inm == null) {
1098 return;
1099 }
1100
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001101 ActivityRecord root = (ActivityRecord)msg.obj;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001102 ProcessRecord process = root.app;
1103 if (process == null) {
1104 return;
1105 }
1106
1107 try {
1108 Context context = mContext.createPackageContext(process.info.packageName, 0);
1109 String text = mContext.getString(R.string.heavy_weight_notification,
1110 context.getApplicationInfo().loadLabel(context.getPackageManager()));
1111 Notification notification = new Notification();
1112 notification.icon = com.android.internal.R.drawable.stat_sys_adb; //context.getApplicationInfo().icon;
1113 notification.when = 0;
1114 notification.flags = Notification.FLAG_ONGOING_EVENT;
1115 notification.tickerText = text;
1116 notification.defaults = 0; // please be quiet
1117 notification.sound = null;
1118 notification.vibrate = null;
1119 notification.setLatestEventInfo(context, text,
1120 mContext.getText(R.string.heavy_weight_notification_detail),
1121 PendingIntent.getActivity(mContext, 0, root.intent,
1122 PendingIntent.FLAG_CANCEL_CURRENT));
1123
1124 try {
1125 int[] outId = new int[1];
1126 inm.enqueueNotification("android", R.string.heavy_weight_notification,
1127 notification, outId);
1128 } catch (RuntimeException e) {
1129 Slog.w(ActivityManagerService.TAG,
1130 "Error showing notification for heavy-weight app", e);
1131 } catch (RemoteException e) {
1132 }
1133 } catch (NameNotFoundException e) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07001134 Slog.w(TAG, "Unable to create context for heavy notification", e);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001135 }
1136 } break;
1137 case CANCEL_HEAVY_NOTIFICATION_MSG: {
1138 INotificationManager inm = NotificationManager.getService();
1139 if (inm == null) {
1140 return;
1141 }
1142 try {
1143 inm.cancelNotification("android",
1144 R.string.heavy_weight_notification);
1145 } catch (RuntimeException e) {
1146 Slog.w(ActivityManagerService.TAG,
1147 "Error canceling notification for service", e);
1148 } catch (RemoteException e) {
1149 }
1150 } break;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001151 case CHECK_EXCESSIVE_WAKE_LOCKS_MSG: {
1152 synchronized (ActivityManagerService.this) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001153 checkExcessivePowerUsageLocked(true);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07001154 removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001155 Message nmsg = obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
1156 sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001157 }
1158 } break;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001159 case SHOW_COMPAT_MODE_DIALOG_MSG: {
1160 synchronized (ActivityManagerService.this) {
1161 ActivityRecord ar = (ActivityRecord)msg.obj;
1162 if (mCompatModeDialog != null) {
1163 if (mCompatModeDialog.mAppInfo.packageName.equals(
1164 ar.info.applicationInfo.packageName)) {
1165 return;
1166 }
1167 mCompatModeDialog.dismiss();
1168 mCompatModeDialog = null;
1169 }
Dianne Hackborn29478262011-06-07 15:44:22 -07001170 if (ar != null && false) {
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001171 if (mCompatModePackages.getPackageAskCompatModeLocked(
1172 ar.packageName)) {
1173 int mode = mCompatModePackages.computeCompatModeLocked(
1174 ar.info.applicationInfo);
1175 if (mode == ActivityManager.COMPAT_MODE_DISABLED
1176 || mode == ActivityManager.COMPAT_MODE_ENABLED) {
1177 mCompatModeDialog = new CompatModeDialog(
1178 ActivityManagerService.this, mContext,
1179 ar.info.applicationInfo);
1180 mCompatModeDialog.show();
1181 }
1182 }
1183 }
1184 }
Dianne Hackborn36f80f32011-05-31 18:26:45 -07001185 break;
1186 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001187 case DISPATCH_FOREGROUND_ACTIVITIES_CHANGED: {
Jeff Sharkey287bd832011-05-28 19:36:26 -07001188 final int pid = msg.arg1;
1189 final int uid = msg.arg2;
1190 final boolean foregroundActivities = (Boolean) msg.obj;
1191 dispatchForegroundActivitiesChanged(pid, uid, foregroundActivities);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001192 break;
1193 }
1194 case DISPATCH_PROCESS_DIED: {
Jeff Sharkey287bd832011-05-28 19:36:26 -07001195 final int pid = msg.arg1;
1196 final int uid = msg.arg2;
1197 dispatchProcessDied(pid, uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001198 break;
1199 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001200 case REPORT_MEM_USAGE: {
1201 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
1202 if (!isDebuggable) {
1203 return;
1204 }
1205 synchronized (ActivityManagerService.this) {
1206 long now = SystemClock.uptimeMillis();
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001207 if (now < (mLastMemUsageReportTime+5*60*1000)) {
1208 // Don't report more than every 5 minutes to somewhat
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001209 // avoid spamming.
1210 return;
1211 }
1212 mLastMemUsageReportTime = now;
1213 }
1214 Thread thread = new Thread() {
1215 @Override public void run() {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001216 StringBuilder dropBuilder = new StringBuilder(1024);
1217 StringBuilder logBuilder = new StringBuilder(1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -08001218 StringWriter oomSw = new StringWriter();
1219 PrintWriter oomPw = new PrintWriter(oomSw);
1220 StringWriter catSw = new StringWriter();
1221 PrintWriter catPw = new PrintWriter(catSw);
1222 String[] emptyArgs = new String[] { };
1223 StringBuilder tag = new StringBuilder(128);
1224 StringBuilder stack = new StringBuilder(128);
1225 tag.append("Low on memory -- ");
1226 dumpApplicationMemoryUsage(null, oomPw, " ", emptyArgs, true, catPw,
1227 tag, stack);
1228 dropBuilder.append(stack);
1229 dropBuilder.append('\n');
1230 dropBuilder.append('\n');
1231 String oomString = oomSw.toString();
1232 dropBuilder.append(oomString);
1233 dropBuilder.append('\n');
1234 logBuilder.append(oomString);
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001235 try {
1236 java.lang.Process proc = Runtime.getRuntime().exec(new String[] {
1237 "procrank", });
1238 final InputStreamReader converter = new InputStreamReader(
1239 proc.getInputStream());
1240 BufferedReader in = new BufferedReader(converter);
1241 String line;
1242 while (true) {
1243 line = in.readLine();
1244 if (line == null) {
1245 break;
1246 }
1247 if (line.length() > 0) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001248 logBuilder.append(line);
1249 logBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001250 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001251 dropBuilder.append(line);
1252 dropBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001253 }
1254 converter.close();
1255 } catch (IOException e) {
1256 }
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001257 synchronized (ActivityManagerService.this) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08001258 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001259 dumpProcessesLocked(null, catPw, emptyArgs, 0, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001260 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001261 dumpServicesLocked(null, catPw, emptyArgs, 0, false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001262 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001263 dumpActivitiesLocked(null, catPw, emptyArgs, 0, false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001264 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001265 dropBuilder.append(catSw.toString());
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001266 addErrorToDropBox("lowmem", null, "system_server", null,
1267 null, tag.toString(), dropBuilder.toString(), null, null);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001268 Slog.i(TAG, logBuilder.toString());
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001269 synchronized (ActivityManagerService.this) {
1270 long now = SystemClock.uptimeMillis();
1271 if (mLastMemUsageReportTime < now) {
1272 mLastMemUsageReportTime = now;
1273 }
1274 }
1275 }
1276 };
1277 thread.start();
1278 break;
1279 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001280 }
1281 }
1282 };
1283
1284 public static void setSystemProcess() {
1285 try {
1286 ActivityManagerService m = mSelf;
1287
Dianne Hackborna573f6a2012-02-09 16:12:18 -08001288 ServiceManager.addService("activity", m, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001289 ServiceManager.addService("meminfo", new MemBinder(m));
Chet Haase9c1e23b2011-03-24 10:51:31 -07001290 ServiceManager.addService("gfxinfo", new GraphicsBinder(m));
Jeff Brown6754ba22011-12-14 20:20:01 -08001291 ServiceManager.addService("dbinfo", new DbBinder(m));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001292 if (MONITOR_CPU_USAGE) {
1293 ServiceManager.addService("cpuinfo", new CpuBinder(m));
1294 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001295 ServiceManager.addService("permission", new PermissionController(m));
1296
1297 ApplicationInfo info =
1298 mSelf.mContext.getPackageManager().getApplicationInfo(
Amith Yamasani483f3b02012-03-13 16:08:00 -07001299 "android", STOCK_PM_FLAGS);
Mike Cleron432b7132009-09-24 15:28:29 -07001300 mSystemThread.installSystemApplicationInfo(info);
1301
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001302 synchronized (mSelf) {
1303 ProcessRecord app = mSelf.newProcessRecordLocked(
1304 mSystemThread.getApplicationThread(), info,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001305 info.processName, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001306 app.persistent = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08001307 app.pid = MY_PID;
Dianne Hackborn7d608422011-08-07 16:24:18 -07001308 app.maxAdj = ProcessList.SYSTEM_ADJ;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001309 mSelf.mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001310 synchronized (mSelf.mPidsSelfLocked) {
1311 mSelf.mPidsSelfLocked.put(app.pid, app);
1312 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001313 mSelf.updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001314 }
1315 } catch (PackageManager.NameNotFoundException e) {
1316 throw new RuntimeException(
1317 "Unable to find android system package", e);
1318 }
1319 }
1320
1321 public void setWindowManager(WindowManagerService wm) {
1322 mWindowManager = wm;
1323 }
1324
1325 public static final Context main(int factoryTest) {
1326 AThread thr = new AThread();
1327 thr.start();
1328
1329 synchronized (thr) {
1330 while (thr.mService == null) {
1331 try {
1332 thr.wait();
1333 } catch (InterruptedException e) {
1334 }
1335 }
1336 }
1337
1338 ActivityManagerService m = thr.mService;
1339 mSelf = m;
1340 ActivityThread at = ActivityThread.systemMain();
1341 mSystemThread = at;
1342 Context context = at.getSystemContext();
Dianne Hackborn247fe742011-01-08 17:25:57 -08001343 context.setTheme(android.R.style.Theme_Holo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001344 m.mContext = context;
1345 m.mFactoryTest = factoryTest;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001346 m.mMainStack = new ActivityStack(m, context, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001347
1348 m.mBatteryStatsService.publish(context);
1349 m.mUsageStatsService.publish(context);
1350
1351 synchronized (thr) {
1352 thr.mReady = true;
1353 thr.notifyAll();
1354 }
1355
1356 m.startRunning(null, null, null, null);
1357
1358 return context;
1359 }
1360
1361 public static ActivityManagerService self() {
1362 return mSelf;
1363 }
1364
1365 static class AThread extends Thread {
1366 ActivityManagerService mService;
1367 boolean mReady = false;
1368
1369 public AThread() {
1370 super("ActivityManager");
1371 }
1372
1373 public void run() {
1374 Looper.prepare();
1375
1376 android.os.Process.setThreadPriority(
1377 android.os.Process.THREAD_PRIORITY_FOREGROUND);
Christopher Tate160edb32010-06-30 17:46:30 -07001378 android.os.Process.setCanSelfBackground(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001379
1380 ActivityManagerService m = new ActivityManagerService();
1381
1382 synchronized (this) {
1383 mService = m;
1384 notifyAll();
1385 }
1386
1387 synchronized (this) {
1388 while (!mReady) {
1389 try {
1390 wait();
1391 } catch (InterruptedException e) {
1392 }
1393 }
1394 }
1395
Brad Fitzpatrickec062f62010-11-03 09:56:54 -07001396 // For debug builds, log event loop stalls to dropbox for analysis.
1397 if (StrictMode.conditionallyEnableDebugLogging()) {
1398 Slog.i(TAG, "Enabled StrictMode logging for AThread's Looper");
1399 }
1400
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001401 Looper.loop();
1402 }
1403 }
1404
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001405 static class MemBinder extends Binder {
1406 ActivityManagerService mActivityManagerService;
1407 MemBinder(ActivityManagerService activityManagerService) {
1408 mActivityManagerService = activityManagerService;
1409 }
1410
1411 @Override
1412 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001413 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1414 != PackageManager.PERMISSION_GRANTED) {
1415 pw.println("Permission Denial: can't dump meminfo from from pid="
1416 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1417 + " without permission " + android.Manifest.permission.DUMP);
1418 return;
1419 }
1420
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001421 mActivityManagerService.dumpApplicationMemoryUsage(fd, pw, " ", args,
Dianne Hackborn672342c2011-11-29 11:29:02 -08001422 false, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001423 }
1424 }
1425
Chet Haase9c1e23b2011-03-24 10:51:31 -07001426 static class GraphicsBinder extends Binder {
1427 ActivityManagerService mActivityManagerService;
1428 GraphicsBinder(ActivityManagerService activityManagerService) {
1429 mActivityManagerService = activityManagerService;
1430 }
1431
1432 @Override
1433 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001434 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1435 != PackageManager.PERMISSION_GRANTED) {
1436 pw.println("Permission Denial: can't dump gfxinfo from from pid="
1437 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1438 + " without permission " + android.Manifest.permission.DUMP);
1439 return;
1440 }
1441
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001442 mActivityManagerService.dumpGraphicsHardwareUsage(fd, pw, args);
Chet Haase9c1e23b2011-03-24 10:51:31 -07001443 }
1444 }
1445
Jeff Brown6754ba22011-12-14 20:20:01 -08001446 static class DbBinder extends Binder {
1447 ActivityManagerService mActivityManagerService;
1448 DbBinder(ActivityManagerService activityManagerService) {
1449 mActivityManagerService = activityManagerService;
1450 }
1451
1452 @Override
1453 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1454 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1455 != PackageManager.PERMISSION_GRANTED) {
1456 pw.println("Permission Denial: can't dump dbinfo from from pid="
1457 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1458 + " without permission " + android.Manifest.permission.DUMP);
1459 return;
1460 }
1461
1462 mActivityManagerService.dumpDbInfo(fd, pw, args);
1463 }
1464 }
1465
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001466 static class CpuBinder extends Binder {
1467 ActivityManagerService mActivityManagerService;
1468 CpuBinder(ActivityManagerService activityManagerService) {
1469 mActivityManagerService = activityManagerService;
1470 }
1471
1472 @Override
1473 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001474 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1475 != PackageManager.PERMISSION_GRANTED) {
1476 pw.println("Permission Denial: can't dump cpuinfo from from pid="
1477 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1478 + " without permission " + android.Manifest.permission.DUMP);
1479 return;
1480 }
1481
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001482 synchronized (mActivityManagerService.mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07001483 pw.print(mActivityManagerService.mProcessStats.printCurrentLoad());
1484 pw.print(mActivityManagerService.mProcessStats.printCurrentState(
1485 SystemClock.uptimeMillis()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001486 }
1487 }
1488 }
1489
1490 private ActivityManagerService() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001491 Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
Dianne Hackborn2c6c5e62009-10-08 17:55:49 -07001492
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001493 mFgBroadcastQueue = new BroadcastQueue(this, "foreground", BROADCAST_FG_TIMEOUT);
1494 mBgBroadcastQueue = new BroadcastQueue(this, "background", BROADCAST_BG_TIMEOUT);
1495 mBroadcastQueues[0] = mFgBroadcastQueue;
1496 mBroadcastQueues[1] = mBgBroadcastQueue;
1497
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001498 File dataDir = Environment.getDataDirectory();
1499 File systemDir = new File(dataDir, "system");
1500 systemDir.mkdirs();
1501 mBatteryStatsService = new BatteryStatsService(new File(
1502 systemDir, "batterystats.bin").toString());
1503 mBatteryStatsService.getActiveStatistics().readLocked();
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001504 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
Dianne Hackborn287952c2010-09-22 22:34:31 -07001505 mOnBattery = DEBUG_POWER ? true
1506 : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001507 mBatteryStatsService.getActiveStatistics().setCallback(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001508
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001509 mUsageStatsService = new UsageStatsService(new File(
Dianne Hackborn6447ca32009-04-07 19:50:08 -07001510 systemDir, "usagestats").toString());
Mike Lockwood3a74bd32011-08-12 13:55:22 -07001511 mHeadless = "1".equals(SystemProperties.get("ro.config.headless", "0"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001512
Jack Palevichb90d28c2009-07-22 15:35:24 -07001513 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",
1514 ConfigurationInfo.GL_ES_VERSION_UNDEFINED);
1515
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001516 mConfiguration.setToDefaults();
1517 mConfiguration.locale = Locale.getDefault();
Dianne Hackborn813075a62011-11-14 17:45:19 -08001518 mConfigurationSeq = mConfiguration.seq = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001519 mProcessStats.init();
1520
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07001521 mCompatModePackages = new CompatModePackages(this, systemDir);
1522
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001523 // Add ourself to the Watchdog monitors.
1524 Watchdog.getInstance().addMonitor(this);
1525
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001526 mProcessStatsThread = new Thread("ProcessStats") {
1527 public void run() {
1528 while (true) {
1529 try {
1530 try {
1531 synchronized(this) {
1532 final long now = SystemClock.uptimeMillis();
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001533 long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001534 long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001535 //Slog.i(TAG, "Cpu delay=" + nextCpuDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001536 // + ", write delay=" + nextWriteDelay);
1537 if (nextWriteDelay < nextCpuDelay) {
1538 nextCpuDelay = nextWriteDelay;
1539 }
1540 if (nextCpuDelay > 0) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001541 mProcessStatsMutexFree.set(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001542 this.wait(nextCpuDelay);
1543 }
1544 }
1545 } catch (InterruptedException e) {
1546 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001547 updateCpuStatsNow();
1548 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001549 Slog.e(TAG, "Unexpected exception collecting process stats", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001550 }
1551 }
1552 }
1553 };
1554 mProcessStatsThread.start();
1555 }
1556
1557 @Override
1558 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1559 throws RemoteException {
1560 try {
1561 return super.onTransact(code, data, reply, flags);
1562 } catch (RuntimeException e) {
1563 // The activity manager only throws security exceptions, so let's
1564 // log all others.
1565 if (!(e instanceof SecurityException)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001566 Slog.e(TAG, "Activity Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001567 }
1568 throw e;
1569 }
1570 }
1571
1572 void updateCpuStats() {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001573 final long now = SystemClock.uptimeMillis();
1574 if (mLastCpuTime.get() >= now - MONITOR_CPU_MIN_TIME) {
1575 return;
1576 }
1577 if (mProcessStatsMutexFree.compareAndSet(true, false)) {
1578 synchronized (mProcessStatsThread) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001579 mProcessStatsThread.notify();
1580 }
1581 }
1582 }
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001583
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001584 void updateCpuStatsNow() {
1585 synchronized (mProcessStatsThread) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001586 mProcessStatsMutexFree.set(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001587 final long now = SystemClock.uptimeMillis();
1588 boolean haveNewCpuStats = false;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07001589
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001590 if (MONITOR_CPU_USAGE &&
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001591 mLastCpuTime.get() < (now-MONITOR_CPU_MIN_TIME)) {
1592 mLastCpuTime.set(now);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001593 haveNewCpuStats = true;
1594 mProcessStats.update();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001595 //Slog.i(TAG, mProcessStats.printCurrentState());
1596 //Slog.i(TAG, "Total CPU usage: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001597 // + mProcessStats.getTotalCpuPercent() + "%");
1598
Joe Onorato8a9b2202010-02-26 18:56:32 -08001599 // Slog the cpu usage if the property is set.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001600 if ("true".equals(SystemProperties.get("events.cpu"))) {
1601 int user = mProcessStats.getLastUserTime();
1602 int system = mProcessStats.getLastSystemTime();
1603 int iowait = mProcessStats.getLastIoWaitTime();
1604 int irq = mProcessStats.getLastIrqTime();
1605 int softIrq = mProcessStats.getLastSoftIrqTime();
1606 int idle = mProcessStats.getLastIdleTime();
1607
1608 int total = user + system + iowait + irq + softIrq + idle;
1609 if (total == 0) total = 1;
1610
Doug Zongker2bec3d42009-12-04 12:52:44 -08001611 EventLog.writeEvent(EventLogTags.CPU,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001612 ((user+system+iowait+irq+softIrq) * 100) / total,
1613 (user * 100) / total,
1614 (system * 100) / total,
1615 (iowait * 100) / total,
1616 (irq * 100) / total,
1617 (softIrq * 100) / total);
1618 }
1619 }
1620
Amith Yamasanie43530a2009-08-21 13:11:37 -07001621 long[] cpuSpeedTimes = mProcessStats.getLastCpuSpeedTimes();
Amith Yamasani819f9282009-06-24 23:18:15 -07001622 final BatteryStatsImpl bstats = mBatteryStatsService.getActiveStatistics();
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001623 synchronized(bstats) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001624 synchronized(mPidsSelfLocked) {
1625 if (haveNewCpuStats) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001626 if (mOnBattery) {
1627 int perc = bstats.startAddingCpuLocked();
1628 int totalUTime = 0;
1629 int totalSTime = 0;
Dianne Hackborn287952c2010-09-22 22:34:31 -07001630 final int N = mProcessStats.countStats();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001631 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001632 ProcessStats.Stats st = mProcessStats.getStats(i);
1633 if (!st.working) {
1634 continue;
1635 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001636 ProcessRecord pr = mPidsSelfLocked.get(st.pid);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001637 int otherUTime = (st.rel_utime*perc)/100;
1638 int otherSTime = (st.rel_stime*perc)/100;
1639 totalUTime += otherUTime;
1640 totalSTime += otherSTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001641 if (pr != null) {
1642 BatteryStatsImpl.Uid.Proc ps = pr.batteryStats;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001643 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1644 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001645 ps.addSpeedStepTimes(cpuSpeedTimes);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001646 pr.curCpuTime += (st.rel_utime+st.rel_stime) * 10;
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001647 } else {
1648 BatteryStatsImpl.Uid.Proc ps =
Amith Yamasani819f9282009-06-24 23:18:15 -07001649 bstats.getProcessStatsLocked(st.name, st.pid);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001650 if (ps != null) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001651 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1652 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001653 ps.addSpeedStepTimes(cpuSpeedTimes);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001654 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001655 }
1656 }
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001657 bstats.finishAddingCpuLocked(perc, totalUTime,
1658 totalSTime, cpuSpeedTimes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001659 }
1660 }
1661 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001662
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001663 if (mLastWriteTime < (now-BATTERY_STATS_TIME)) {
1664 mLastWriteTime = now;
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001665 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001666 }
1667 }
1668 }
1669 }
1670
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001671 @Override
1672 public void batteryNeedsCpuUpdate() {
1673 updateCpuStatsNow();
1674 }
1675
1676 @Override
1677 public void batteryPowerChanged(boolean onBattery) {
1678 // When plugging in, update the CPU stats first before changing
1679 // the plug state.
1680 updateCpuStatsNow();
1681 synchronized (this) {
1682 synchronized(mPidsSelfLocked) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001683 mOnBattery = DEBUG_POWER ? true : onBattery;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001684 }
1685 }
1686 }
1687
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001688 /**
1689 * Initialize the application bind args. These are passed to each
1690 * process when the bindApplication() IPC is sent to the process. They're
1691 * lazily setup to make sure the services are running when they're asked for.
1692 */
1693 private HashMap<String, IBinder> getCommonServicesLocked() {
1694 if (mAppBindArgs == null) {
1695 mAppBindArgs = new HashMap<String, IBinder>();
1696
1697 // Setup the application init args
1698 mAppBindArgs.put("package", ServiceManager.getService("package"));
1699 mAppBindArgs.put("window", ServiceManager.getService("window"));
1700 mAppBindArgs.put(Context.ALARM_SERVICE,
1701 ServiceManager.getService(Context.ALARM_SERVICE));
1702 }
1703 return mAppBindArgs;
1704 }
1705
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001706 final void setFocusedActivityLocked(ActivityRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001707 if (mFocusedActivity != r) {
1708 mFocusedActivity = r;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001709 if (r != null) {
1710 mWindowManager.setFocusedApp(r.appToken, true);
1711 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001712 }
1713 }
1714
Dianne Hackborn906497c2010-05-10 15:57:38 -07001715 private final void updateLruProcessInternalLocked(ProcessRecord app,
1716 boolean oomAdj, boolean updateActivityTime, int bestPos) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001717 // put it on the LRU to keep track of when it should be exited.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001718 int lrui = mLruProcesses.indexOf(app);
1719 if (lrui >= 0) mLruProcesses.remove(lrui);
1720
1721 int i = mLruProcesses.size()-1;
1722 int skipTop = 0;
1723
Dianne Hackborn906497c2010-05-10 15:57:38 -07001724 app.lruSeq = mLruSeq;
1725
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001726 // compute the new weight for this process.
1727 if (updateActivityTime) {
1728 app.lastActivityTime = SystemClock.uptimeMillis();
1729 }
1730 if (app.activities.size() > 0) {
1731 // If this process has activities, we more strongly want to keep
1732 // it around.
1733 app.lruWeight = app.lastActivityTime;
1734 } else if (app.pubProviders.size() > 0) {
1735 // If this process contains content providers, we want to keep
1736 // it a little more strongly.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001737 app.lruWeight = app.lastActivityTime - ProcessList.CONTENT_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001738 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001739 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001740 } else {
1741 // If this process doesn't have activities, we less strongly
1742 // want to keep it around, and generally want to avoid getting
1743 // in front of any very recently used activities.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001744 app.lruWeight = app.lastActivityTime - ProcessList.EMPTY_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001745 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001746 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001747 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001748
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001749 while (i >= 0) {
1750 ProcessRecord p = mLruProcesses.get(i);
1751 // If this app shouldn't be in front of the first N background
1752 // apps, then skip over that many that are currently hidden.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001753 if (skipTop > 0 && p.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001754 skipTop--;
1755 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001756 if (p.lruWeight <= app.lruWeight || i < bestPos) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001757 mLruProcesses.add(i+1, app);
1758 break;
1759 }
1760 i--;
1761 }
1762 if (i < 0) {
1763 mLruProcesses.add(0, app);
1764 }
1765
Dianne Hackborn906497c2010-05-10 15:57:38 -07001766 // If the app is currently using a content provider or service,
1767 // bump those processes as well.
1768 if (app.connections.size() > 0) {
1769 for (ConnectionRecord cr : app.connections) {
1770 if (cr.binding != null && cr.binding.service != null
1771 && cr.binding.service.app != null
1772 && cr.binding.service.app.lruSeq != mLruSeq) {
1773 updateLruProcessInternalLocked(cr.binding.service.app, oomAdj,
1774 updateActivityTime, i+1);
1775 }
1776 }
1777 }
1778 if (app.conProviders.size() > 0) {
1779 for (ContentProviderRecord cpr : app.conProviders.keySet()) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07001780 if (cpr.proc != null && cpr.proc.lruSeq != mLruSeq) {
1781 updateLruProcessInternalLocked(cpr.proc, oomAdj,
Dianne Hackborn906497c2010-05-10 15:57:38 -07001782 updateActivityTime, i+1);
1783 }
1784 }
1785 }
1786
Joe Onorato8a9b2202010-02-26 18:56:32 -08001787 //Slog.i(TAG, "Putting proc to front: " + app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001788 if (oomAdj) {
1789 updateOomAdjLocked();
1790 }
1791 }
1792
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001793 final void updateLruProcessLocked(ProcessRecord app,
Dianne Hackborn906497c2010-05-10 15:57:38 -07001794 boolean oomAdj, boolean updateActivityTime) {
1795 mLruSeq++;
1796 updateLruProcessInternalLocked(app, oomAdj, updateActivityTime, 0);
1797 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001798
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001799 final ProcessRecord getProcessRecordLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001800 String processName, int uid) {
Amith Yamasani0184ce92012-03-28 22:41:41 -07001801 // Temporary hack to make Settings run per user
1802 if (uid == Process.SYSTEM_UID && !processName.equals("com.android.settings")) {
1803 // The system gets to run in any process. If there are multiple
1804 // processes with the same uid, just pick the first (this
1805 // should never happen).
1806 SparseArray<ProcessRecord> procs = mProcessNames.getMap().get(
1807 processName);
1808 return procs != null ? procs.valueAt(0) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001809 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001810 // uid = applyUserId(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001811 ProcessRecord proc = mProcessNames.get(processName, uid);
1812 return proc;
1813 }
1814
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001815 void ensurePackageDexOpt(String packageName) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001816 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001817 try {
1818 if (pm.performDexOpt(packageName)) {
1819 mDidDexOpt = true;
1820 }
1821 } catch (RemoteException e) {
1822 }
1823 }
1824
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001825 boolean isNextTransitionForward() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001826 int transit = mWindowManager.getPendingAppTransition();
1827 return transit == WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
1828 || transit == WindowManagerPolicy.TRANSIT_TASK_OPEN
1829 || transit == WindowManagerPolicy.TRANSIT_TASK_TO_FRONT;
1830 }
1831
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001832 final ProcessRecord startProcessLocked(String processName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001833 ApplicationInfo info, boolean knownToBeDead, int intentFlags,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001834 String hostingType, ComponentName hostingName, boolean allowWhileBooting,
1835 boolean isolated) {
1836 ProcessRecord app;
1837 if (!isolated) {
1838 app = getProcessRecordLocked(processName, info.uid);
1839 } else {
1840 // If this is an isolated process, it can't re-use an existing process.
1841 app = null;
1842 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001843 // We don't have to do anything more if:
1844 // (1) There is an existing application record; and
1845 // (2) The caller doesn't think it is dead, OR there is no thread
1846 // object attached to it so we know it couldn't have crashed; and
1847 // (3) There is a pid assigned to it, so it is either starting or
1848 // already running.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001849 if (DEBUG_PROCESSES) Slog.v(TAG, "startProcess: name=" + processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001850 + " app=" + app + " knownToBeDead=" + knownToBeDead
1851 + " thread=" + (app != null ? app.thread : null)
1852 + " pid=" + (app != null ? app.pid : -1));
Magnus Edlund7bb25812010-02-24 15:45:06 +01001853 if (app != null && app.pid > 0) {
1854 if (!knownToBeDead || app.thread == null) {
Dianne Hackborn20cb56e2010-03-04 00:58:29 -08001855 // We already have the app running, or are waiting for it to
1856 // come up (we have a pid but not yet its thread), so keep it.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001857 if (DEBUG_PROCESSES) Slog.v(TAG, "App already running: " + app);
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001858 // If this is a new package in the process, add the package to the list
1859 app.addPackage(info.packageName);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001860 return app;
1861 } else {
1862 // An application record is attached to a previous process,
1863 // clean it up now.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001864 if (DEBUG_PROCESSES) Slog.v(TAG, "App died: " + app);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07001865 handleAppDiedLocked(app, true, true);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001866 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001867 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01001868
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001869 String hostingNameStr = hostingName != null
1870 ? hostingName.flattenToShortString() : null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001871
1872 if (!isolated) {
1873 if ((intentFlags&Intent.FLAG_FROM_BACKGROUND) != 0) {
1874 // If we are in the background, then check to see if this process
1875 // is bad. If so, we will just silently fail.
1876 if (mBadProcesses.get(info.processName, info.uid) != null) {
1877 if (DEBUG_PROCESSES) Slog.v(TAG, "Bad process: " + info.uid
1878 + "/" + info.processName);
1879 return null;
1880 }
1881 } else {
1882 // When the user is explicitly starting a process, then clear its
1883 // crash count so that we won't make it bad until they see at
1884 // least one crash dialog again, and make the process good again
1885 // if it had been bad.
1886 if (DEBUG_PROCESSES) Slog.v(TAG, "Clearing bad process: " + info.uid
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001887 + "/" + info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001888 mProcessCrashTimes.remove(info.processName, info.uid);
1889 if (mBadProcesses.get(info.processName, info.uid) != null) {
1890 EventLog.writeEvent(EventLogTags.AM_PROC_GOOD, info.uid,
1891 info.processName);
1892 mBadProcesses.remove(info.processName, info.uid);
1893 if (app != null) {
1894 app.bad = false;
1895 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001896 }
1897 }
1898 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001899
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001900 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001901 app = newProcessRecordLocked(null, info, processName, isolated);
1902 if (app == null) {
1903 Slog.w(TAG, "Failed making new process record for "
1904 + processName + "/" + info.uid + " isolated=" + isolated);
1905 return null;
1906 }
1907 mProcessNames.put(processName, app.uid, app);
1908 if (isolated) {
1909 mIsolatedProcesses.put(app.uid, app);
1910 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001911 } else {
1912 // If this is a new package in the process, add the package to the list
1913 app.addPackage(info.packageName);
1914 }
1915
1916 // If the system is not ready yet, then hold off on starting this
1917 // process until it is.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001918 if (!mProcessesReady
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001919 && !isAllowedWhileBooting(info)
1920 && !allowWhileBooting) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001921 if (!mProcessesOnHold.contains(app)) {
1922 mProcessesOnHold.add(app);
1923 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001924 if (DEBUG_PROCESSES) Slog.v(TAG, "System not ready, putting on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001925 return app;
1926 }
1927
1928 startProcessLocked(app, hostingType, hostingNameStr);
1929 return (app.pid != 0) ? app : null;
1930 }
1931
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001932 boolean isAllowedWhileBooting(ApplicationInfo ai) {
1933 return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0;
1934 }
1935
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001936 private final void startProcessLocked(ProcessRecord app,
1937 String hostingType, String hostingNameStr) {
1938 if (app.pid > 0 && app.pid != MY_PID) {
1939 synchronized (mPidsSelfLocked) {
1940 mPidsSelfLocked.remove(app.pid);
1941 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
1942 }
1943 app.pid = 0;
1944 }
1945
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001946 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
1947 "startProcessLocked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001948 mProcessesOnHold.remove(app);
1949
1950 updateCpuStats();
1951
1952 System.arraycopy(mProcDeaths, 0, mProcDeaths, 1, mProcDeaths.length-1);
1953 mProcDeaths[0] = 0;
1954
1955 try {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001956 int uid = app.uid;
Amith Yamasani742a6712011-05-04 14:49:28 -07001957
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001958 int[] gids = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001959 if (!app.isolated) {
1960 try {
1961 gids = mContext.getPackageManager().getPackageGids(
1962 app.info.packageName);
1963 } catch (PackageManager.NameNotFoundException e) {
1964 Slog.w(TAG, "Unable to retrieve gids", e);
1965 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001966 }
1967 if (mFactoryTest != SystemServer.FACTORY_TEST_OFF) {
1968 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
1969 && mTopComponent != null
1970 && app.processName.equals(mTopComponent.getPackageName())) {
1971 uid = 0;
1972 }
1973 if (mFactoryTest == SystemServer.FACTORY_TEST_HIGH_LEVEL
1974 && (app.info.flags&ApplicationInfo.FLAG_FACTORY_TEST) != 0) {
1975 uid = 0;
1976 }
1977 }
1978 int debugFlags = 0;
1979 if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
1980 debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;
Elliott Hughesfa36aee2011-06-17 14:39:41 -07001981 // Also turn on CheckJNI for debuggable apps. It's quite
1982 // awkward to turn on otherwise.
1983 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001984 }
Ben Cheng6c0afff2010-02-14 16:18:56 -08001985 // Run the app in safe mode if its manifest requests so or the
1986 // system is booted in safe mode.
1987 if ((app.info.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0 ||
1988 Zygote.systemInSafeMode == true) {
Ben Cheng23085b72010-02-08 16:06:32 -08001989 debugFlags |= Zygote.DEBUG_ENABLE_SAFEMODE;
1990 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001991 if ("1".equals(SystemProperties.get("debug.checkjni"))) {
1992 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
1993 }
Elliott Hughesae07ecf2011-07-06 17:33:27 -07001994 if ("1".equals(SystemProperties.get("debug.jni.logging"))) {
1995 debugFlags |= Zygote.DEBUG_ENABLE_JNI_LOGGING;
1996 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001997 if ("1".equals(SystemProperties.get("debug.assert"))) {
1998 debugFlags |= Zygote.DEBUG_ENABLE_ASSERT;
1999 }
Jeff Brown3f9dd282011-07-08 20:02:19 -07002000
2001 // Start the process. It will either succeed and return a result containing
2002 // the PID of the new process, or else throw a RuntimeException.
2003 Process.ProcessStartResult startResult = Process.start("android.app.ActivityThread",
Elliott Hughese1dfcb72011-07-08 11:08:07 -07002004 app.processName, uid, uid, gids, debugFlags,
2005 app.info.targetSdkVersion, null);
Jeff Brown3f9dd282011-07-08 20:02:19 -07002006
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002007 BatteryStatsImpl bs = app.batteryStats.getBatteryStats();
2008 synchronized (bs) {
2009 if (bs.isOnBattery()) {
2010 app.batteryStats.incStartsLocked();
2011 }
2012 }
2013
Jeff Brown3f9dd282011-07-08 20:02:19 -07002014 EventLog.writeEvent(EventLogTags.AM_PROC_START, startResult.pid, uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002015 app.processName, hostingType,
2016 hostingNameStr != null ? hostingNameStr : "");
2017
2018 if (app.persistent) {
Jeff Brown3f9dd282011-07-08 20:02:19 -07002019 Watchdog.getInstance().processStarted(app.processName, startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002020 }
2021
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07002022 StringBuilder buf = mStringBuilder;
2023 buf.setLength(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002024 buf.append("Start proc ");
2025 buf.append(app.processName);
2026 buf.append(" for ");
2027 buf.append(hostingType);
2028 if (hostingNameStr != null) {
2029 buf.append(" ");
2030 buf.append(hostingNameStr);
2031 }
2032 buf.append(": pid=");
Jeff Brown3f9dd282011-07-08 20:02:19 -07002033 buf.append(startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002034 buf.append(" uid=");
2035 buf.append(uid);
2036 buf.append(" gids={");
2037 if (gids != null) {
2038 for (int gi=0; gi<gids.length; gi++) {
2039 if (gi != 0) buf.append(", ");
2040 buf.append(gids[gi]);
2041
2042 }
2043 }
2044 buf.append("}");
Joe Onorato8a9b2202010-02-26 18:56:32 -08002045 Slog.i(TAG, buf.toString());
Jeff Brown3f9dd282011-07-08 20:02:19 -07002046 app.pid = startResult.pid;
2047 app.usingWrapper = startResult.usingWrapper;
2048 app.removed = false;
2049 synchronized (mPidsSelfLocked) {
2050 this.mPidsSelfLocked.put(startResult.pid, app);
2051 Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
2052 msg.obj = app;
2053 mHandler.sendMessageDelayed(msg, startResult.usingWrapper
2054 ? PROC_START_TIMEOUT_WITH_WRAPPER : PROC_START_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002055 }
2056 } catch (RuntimeException e) {
2057 // XXX do better error recovery.
2058 app.pid = 0;
Joe Onorato8a9b2202010-02-26 18:56:32 -08002059 Slog.e(TAG, "Failure starting process " + app.processName, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002060 }
2061 }
2062
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002063 void updateUsageStats(ActivityRecord resumedComponent, boolean resumed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002064 if (resumed) {
2065 mUsageStatsService.noteResumeComponent(resumedComponent.realActivity);
2066 } else {
2067 mUsageStatsService.notePauseComponent(resumedComponent.realActivity);
2068 }
2069 }
2070
Amith Yamasani742a6712011-05-04 14:49:28 -07002071 boolean startHomeActivityLocked(int userId) {
Mike Lockwooda8f767a2011-08-31 14:32:37 -04002072 if (mHeadless) {
2073 // Added because none of the other calls to ensureBootCompleted seem to fire
2074 // when running headless.
2075 ensureBootCompleted();
2076 return false;
2077 }
2078
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002079 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2080 && mTopAction == null) {
2081 // We are running in factory test mode, but unable to find
2082 // the factory test app, so just sit around displaying the
2083 // error message and don't try to start anything.
2084 return false;
2085 }
2086 Intent intent = new Intent(
2087 mTopAction,
2088 mTopData != null ? Uri.parse(mTopData) : null);
2089 intent.setComponent(mTopComponent);
2090 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
2091 intent.addCategory(Intent.CATEGORY_HOME);
2092 }
2093 ActivityInfo aInfo =
2094 intent.resolveActivityInfo(mContext.getPackageManager(),
2095 STOCK_PM_FLAGS);
2096 if (aInfo != null) {
2097 intent.setComponent(new ComponentName(
2098 aInfo.applicationInfo.packageName, aInfo.name));
2099 // Don't do this if the home app is currently being
2100 // instrumented.
Amith Yamasani742a6712011-05-04 14:49:28 -07002101 aInfo = new ActivityInfo(aInfo);
2102 aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002103 ProcessRecord app = getProcessRecordLocked(aInfo.processName,
2104 aInfo.applicationInfo.uid);
2105 if (app == null || app.instrumentationClass == null) {
2106 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002107 mMainStack.startActivityLocked(null, intent, null, aInfo,
2108 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002109 }
2110 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002111
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002112 return true;
2113 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002114
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002115 /**
2116 * Starts the "new version setup screen" if appropriate.
2117 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002118 void startSetupActivityLocked() {
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002119 // Only do this once per boot.
2120 if (mCheckedForSetup) {
2121 return;
2122 }
2123
2124 // We will show this screen if the current one is a different
2125 // version than the last one shown, and we are not running in
2126 // low-level factory test mode.
2127 final ContentResolver resolver = mContext.getContentResolver();
2128 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL &&
2129 Settings.Secure.getInt(resolver,
2130 Settings.Secure.DEVICE_PROVISIONED, 0) != 0) {
2131 mCheckedForSetup = true;
2132
2133 // See if we should be showing the platform update setup UI.
2134 Intent intent = new Intent(Intent.ACTION_UPGRADE_SETUP);
2135 List<ResolveInfo> ris = mSelf.mContext.getPackageManager()
2136 .queryIntentActivities(intent, PackageManager.GET_META_DATA);
2137
2138 // We don't allow third party apps to replace this.
2139 ResolveInfo ri = null;
2140 for (int i=0; ris != null && i<ris.size(); i++) {
2141 if ((ris.get(i).activityInfo.applicationInfo.flags
2142 & ApplicationInfo.FLAG_SYSTEM) != 0) {
2143 ri = ris.get(i);
2144 break;
2145 }
2146 }
2147
2148 if (ri != null) {
2149 String vers = ri.activityInfo.metaData != null
2150 ? ri.activityInfo.metaData.getString(Intent.METADATA_SETUP_VERSION)
2151 : null;
2152 if (vers == null && ri.activityInfo.applicationInfo.metaData != null) {
2153 vers = ri.activityInfo.applicationInfo.metaData.getString(
2154 Intent.METADATA_SETUP_VERSION);
2155 }
2156 String lastVers = Settings.Secure.getString(
2157 resolver, Settings.Secure.LAST_SETUP_SHOWN);
2158 if (vers != null && !vers.equals(lastVers)) {
2159 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2160 intent.setComponent(new ComponentName(
2161 ri.activityInfo.packageName, ri.activityInfo.name));
Dianne Hackborna4972e92012-03-14 10:38:05 -07002162 mMainStack.startActivityLocked(null, intent, null, ri.activityInfo,
2163 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002164 }
2165 }
2166 }
2167 }
2168
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002169 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002170 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002171 }
2172
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002173 void enforceNotIsolatedCaller(String caller) {
2174 if (UserId.isIsolated(Binder.getCallingUid())) {
2175 throw new SecurityException("Isolated process not allowed to call " + caller);
2176 }
2177 }
2178
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002179 public int getFrontActivityScreenCompatMode() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002180 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002181 synchronized (this) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002182 return mCompatModePackages.getFrontActivityScreenCompatModeLocked();
2183 }
2184 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002185
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002186 public void setFrontActivityScreenCompatMode(int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002187 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2188 "setFrontActivityScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002189 synchronized (this) {
2190 mCompatModePackages.setFrontActivityScreenCompatModeLocked(mode);
2191 }
2192 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002193
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002194 public int getPackageScreenCompatMode(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002195 enforceNotIsolatedCaller("getPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002196 synchronized (this) {
2197 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
2198 }
2199 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002200
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002201 public void setPackageScreenCompatMode(String packageName, int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002202 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2203 "setPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002204 synchronized (this) {
2205 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002206 }
2207 }
2208
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002209 public boolean getPackageAskScreenCompat(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002210 enforceNotIsolatedCaller("getPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002211 synchronized (this) {
2212 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
2213 }
2214 }
2215
2216 public void setPackageAskScreenCompat(String packageName, boolean ask) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002217 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2218 "setPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002219 synchronized (this) {
2220 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
2221 }
2222 }
2223
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002224 void reportResumedActivityLocked(ActivityRecord r) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002225 //Slog.i(TAG, "**** REPORT RESUME: " + r);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002226
2227 final int identHash = System.identityHashCode(r);
2228 updateUsageStats(r, true);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002229 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002230
Jeff Sharkeya4620792011-05-20 15:29:23 -07002231 private void dispatchForegroundActivitiesChanged(int pid, int uid, boolean foregroundActivities) {
2232 int i = mProcessObservers.beginBroadcast();
2233 while (i > 0) {
2234 i--;
2235 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2236 if (observer != null) {
2237 try {
2238 observer.onForegroundActivitiesChanged(pid, uid, foregroundActivities);
2239 } catch (RemoteException e) {
2240 }
2241 }
2242 }
2243 mProcessObservers.finishBroadcast();
2244 }
2245
2246 private void dispatchProcessDied(int pid, int uid) {
2247 int i = mProcessObservers.beginBroadcast();
2248 while (i > 0) {
2249 i--;
2250 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2251 if (observer != null) {
2252 try {
2253 observer.onProcessDied(pid, uid);
2254 } catch (RemoteException e) {
2255 }
2256 }
2257 }
2258 mProcessObservers.finishBroadcast();
2259 }
2260
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002261 final void doPendingActivityLaunchesLocked(boolean doResume) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002262 final int N = mPendingActivityLaunches.size();
2263 if (N <= 0) {
2264 return;
2265 }
2266 for (int i=0; i<N; i++) {
2267 PendingActivityLaunch pal = mPendingActivityLaunches.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002268 mMainStack.startActivityUncheckedLocked(pal.r, pal.sourceRecord,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002269 pal.startFlags, doResume && i == (N-1), null);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002270 }
2271 mPendingActivityLaunches.clear();
2272 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002273
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002274 public final int startActivity(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002275 Intent intent, String resolvedType, IBinder resultTo,
2276 String resultWho, int requestCode, int startFlags,
2277 String profileFile, ParcelFileDescriptor profileFd, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002278 enforceNotIsolatedCaller("startActivity");
Amith Yamasani742a6712011-05-04 14:49:28 -07002279 int userId = 0;
2280 if (intent.getCategories() != null && intent.getCategories().contains(Intent.CATEGORY_HOME)) {
2281 // Requesting home, set the identity to the current user
2282 // HACK!
2283 userId = mCurrentUserId;
2284 } else {
2285 // TODO: Fix this in a better way - calls coming from SystemUI should probably carry
2286 // the current user's userId
2287 if (Binder.getCallingUid() < Process.FIRST_APPLICATION_UID) {
2288 userId = 0;
2289 } else {
2290 userId = Binder.getOrigCallingUser();
2291 }
2292 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002293 return mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002294 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
2295 null, null, options, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002296 }
2297
2298 public final WaitResult startActivityAndWait(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002299 Intent intent, String resolvedType, IBinder resultTo,
2300 String resultWho, int requestCode, int startFlags, String profileFile,
2301 ParcelFileDescriptor profileFd, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002302 enforceNotIsolatedCaller("startActivityAndWait");
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002303 WaitResult res = new WaitResult();
Amith Yamasani742a6712011-05-04 14:49:28 -07002304 int userId = Binder.getOrigCallingUser();
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002305 mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002306 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
2307 res, null, options, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002308 return res;
2309 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08002310
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002311 public final int startActivityWithConfig(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002312 Intent intent, String resolvedType, IBinder resultTo,
2313 String resultWho, int requestCode, int startFlags, Configuration config,
2314 Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002315 enforceNotIsolatedCaller("startActivityWithConfig");
Amith Yamasani742a6712011-05-04 14:49:28 -07002316 int ret = mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002317 resultTo, resultWho, requestCode, startFlags,
2318 null, null, null, config, options, Binder.getOrigCallingUser());
Amith Yamasani742a6712011-05-04 14:49:28 -07002319 return ret;
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002320 }
2321
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002322 public int startActivityIntentSender(IApplicationThread caller,
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002323 IntentSender intent, Intent fillInIntent, String resolvedType,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002324 IBinder resultTo, String resultWho, int requestCode,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002325 int flagsMask, int flagsValues, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002326 enforceNotIsolatedCaller("startActivityIntentSender");
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002327 // Refuse possible leaked file descriptors
2328 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
2329 throw new IllegalArgumentException("File descriptors passed in Intent");
2330 }
2331
2332 IIntentSender sender = intent.getTarget();
2333 if (!(sender instanceof PendingIntentRecord)) {
2334 throw new IllegalArgumentException("Bad PendingIntent object");
2335 }
2336
2337 PendingIntentRecord pir = (PendingIntentRecord)sender;
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002338
2339 synchronized (this) {
2340 // If this is coming from the currently resumed activity, it is
2341 // effectively saying that app switches are allowed at this point.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002342 if (mMainStack.mResumedActivity != null
2343 && mMainStack.mResumedActivity.info.applicationInfo.uid ==
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002344 Binder.getCallingUid()) {
2345 mAppSwitchesAllowedTime = 0;
2346 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002347 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002348 int ret = pir.sendInner(0, fillInIntent, resolvedType, null, null,
2349 resultTo, resultWho, requestCode, flagsMask, flagsValues, options);
Amith Yamasani742a6712011-05-04 14:49:28 -07002350 return ret;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002351 }
2352
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002353 public boolean startNextMatchingActivity(IBinder callingActivity,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002354 Intent intent, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002355 // Refuse possible leaked file descriptors
2356 if (intent != null && intent.hasFileDescriptors() == true) {
2357 throw new IllegalArgumentException("File descriptors passed in Intent");
2358 }
2359
2360 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002361 ActivityRecord r = mMainStack.isInStackLocked(callingActivity);
2362 if (r == null) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002363 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002364 return false;
2365 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002366 if (r.app == null || r.app.thread == null) {
2367 // The caller is not running... d'oh!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002368 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002369 return false;
2370 }
2371 intent = new Intent(intent);
2372 // The caller is not allowed to change the data.
2373 intent.setDataAndType(r.intent.getData(), r.intent.getType());
2374 // And we are resetting to find the next component...
2375 intent.setComponent(null);
2376
2377 ActivityInfo aInfo = null;
2378 try {
2379 List<ResolveInfo> resolves =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002380 AppGlobals.getPackageManager().queryIntentActivities(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002381 intent, r.resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002382 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
2383 UserId.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002384
2385 // Look for the original activity in the list...
2386 final int N = resolves != null ? resolves.size() : 0;
2387 for (int i=0; i<N; i++) {
2388 ResolveInfo rInfo = resolves.get(i);
2389 if (rInfo.activityInfo.packageName.equals(r.packageName)
2390 && rInfo.activityInfo.name.equals(r.info.name)) {
2391 // We found the current one... the next matching is
2392 // after it.
2393 i++;
2394 if (i<N) {
2395 aInfo = resolves.get(i).activityInfo;
2396 }
2397 break;
2398 }
2399 }
2400 } catch (RemoteException e) {
2401 }
2402
2403 if (aInfo == null) {
2404 // Nobody who is next!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002405 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002406 return false;
2407 }
2408
2409 intent.setComponent(new ComponentName(
2410 aInfo.applicationInfo.packageName, aInfo.name));
2411 intent.setFlags(intent.getFlags()&~(
2412 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
2413 Intent.FLAG_ACTIVITY_CLEAR_TOP|
2414 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
2415 Intent.FLAG_ACTIVITY_NEW_TASK));
2416
2417 // Okay now we need to start the new activity, replacing the
2418 // currently running activity. This is a little tricky because
2419 // we want to start the new one as if the current one is finished,
2420 // but not finish the current one first so that there is no flicker.
2421 // And thus...
2422 final boolean wasFinishing = r.finishing;
2423 r.finishing = true;
2424
2425 // Propagate reply information over to the new activity.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002426 final ActivityRecord resultTo = r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002427 final String resultWho = r.resultWho;
2428 final int requestCode = r.requestCode;
2429 r.resultTo = null;
2430 if (resultTo != null) {
2431 resultTo.removeResultsLocked(r, resultWho, requestCode);
2432 }
2433
2434 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002435 int res = mMainStack.startActivityLocked(r.app.thread, intent,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002436 r.resolvedType, aInfo, resultTo != null ? resultTo.appToken : null,
2437 resultWho, requestCode, -1, r.launchedFromUid, 0,
2438 options, false, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002439 Binder.restoreCallingIdentity(origId);
2440
2441 r.finishing = wasFinishing;
Dianne Hackborna4972e92012-03-14 10:38:05 -07002442 if (res != ActivityManager.START_SUCCESS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002443 return false;
2444 }
2445 return true;
2446 }
2447 }
2448
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002449 public final int startActivityInPackage(int uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002450 Intent intent, String resolvedType, IBinder resultTo,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002451 String resultWho, int requestCode, int startFlags, Bundle options) {
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002452
2453 // This is so super not safe, that only the system (or okay root)
2454 // can do it.
Amith Yamasani742a6712011-05-04 14:49:28 -07002455 int userId = Binder.getOrigCallingUser();
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002456 final int callingUid = Binder.getCallingUid();
2457 if (callingUid != 0 && callingUid != Process.myUid()) {
2458 throw new SecurityException(
2459 "startActivityInPackage only available to the system");
2460 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002461
Amith Yamasani742a6712011-05-04 14:49:28 -07002462 int ret = mMainStack.startActivityMayWait(null, uid, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002463 resultTo, resultWho, requestCode, startFlags,
2464 null, null, null, null, options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002465 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002466 }
2467
2468 public final int startActivities(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002469 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002470 enforceNotIsolatedCaller("startActivities");
Amith Yamasani742a6712011-05-04 14:49:28 -07002471 int ret = mMainStack.startActivities(caller, -1, intents, resolvedTypes, resultTo,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002472 options, Binder.getOrigCallingUser());
Amith Yamasani742a6712011-05-04 14:49:28 -07002473 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002474 }
2475
2476 public final int startActivitiesInPackage(int uid,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002477 Intent[] intents, String[] resolvedTypes, IBinder resultTo,
2478 Bundle options) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002479
2480 // This is so super not safe, that only the system (or okay root)
2481 // can do it.
2482 final int callingUid = Binder.getCallingUid();
2483 if (callingUid != 0 && callingUid != Process.myUid()) {
2484 throw new SecurityException(
2485 "startActivityInPackage only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002486 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002487 int ret = mMainStack.startActivities(null, uid, intents, resolvedTypes, resultTo,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002488 options, UserId.getUserId(uid));
Amith Yamasani742a6712011-05-04 14:49:28 -07002489 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002490 }
2491
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002492 final void addRecentTaskLocked(TaskRecord task) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002493 int N = mRecentTasks.size();
Dianne Hackborn7c0e75e2010-12-21 19:15:40 -08002494 // Quick case: check if the top-most recent task is the same.
2495 if (N > 0 && mRecentTasks.get(0) == task) {
2496 return;
2497 }
2498 // Remove any existing entries that are the same kind of task.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002499 for (int i=0; i<N; i++) {
2500 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07002501 if (task.userId == tr.userId
2502 && ((task.affinity != null && task.affinity.equals(tr.affinity))
2503 || (task.intent != null && task.intent.filterEquals(tr.intent)))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002504 mRecentTasks.remove(i);
2505 i--;
2506 N--;
2507 if (task.intent == null) {
2508 // If the new recent task we are adding is not fully
2509 // specified, then replace it with the existing recent task.
2510 task = tr;
2511 }
2512 }
2513 }
2514 if (N >= MAX_RECENT_TASKS) {
2515 mRecentTasks.remove(N-1);
2516 }
2517 mRecentTasks.add(0, task);
2518 }
2519
2520 public void setRequestedOrientation(IBinder token,
2521 int requestedOrientation) {
2522 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002523 ActivityRecord r = mMainStack.isInStackLocked(token);
2524 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002525 return;
2526 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002527 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornbe707852011-11-11 14:32:10 -08002528 mWindowManager.setAppOrientation(r.appToken, requestedOrientation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002529 Configuration config = mWindowManager.updateOrientationFromAppTokens(
The Android Open Source Project10592532009-03-18 17:39:46 -07002530 mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -08002531 r.mayFreezeScreenLocked(r.app) ? r.appToken : null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002532 if (config != null) {
2533 r.frozenBeforeDestroy = true;
Dianne Hackborn813075a62011-11-14 17:45:19 -08002534 if (!updateConfigurationLocked(config, r, false, false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002535 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002536 }
2537 }
2538 Binder.restoreCallingIdentity(origId);
2539 }
2540 }
2541
2542 public int getRequestedOrientation(IBinder token) {
2543 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002544 ActivityRecord r = mMainStack.isInStackLocked(token);
2545 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002546 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
2547 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08002548 return mWindowManager.getAppOrientation(r.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002549 }
2550 }
2551
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002552 /**
2553 * This is the internal entry point for handling Activity.finish().
2554 *
2555 * @param token The Binder token referencing the Activity we want to finish.
2556 * @param resultCode Result code, if any, from this Activity.
2557 * @param resultData Result data (Intent), if any, from this Activity.
2558 *
Alexey Tarasov83bad3d2009-08-12 15:05:43 +11002559 * @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 -08002560 */
2561 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData) {
2562 // Refuse possible leaked file descriptors
2563 if (resultData != null && resultData.hasFileDescriptors() == true) {
2564 throw new IllegalArgumentException("File descriptors passed in Intent");
2565 }
2566
2567 synchronized(this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002568 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002569 // Find the first activity that is not finishing.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002570 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002571 if (next != null) {
2572 // ask watcher if this is allowed
2573 boolean resumeOK = true;
2574 try {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002575 resumeOK = mController.activityResuming(next.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002576 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002577 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002578 }
2579
2580 if (!resumeOK) {
2581 return false;
2582 }
2583 }
2584 }
2585 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002586 boolean res = mMainStack.requestFinishActivityLocked(token, resultCode,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002587 resultData, "app-request");
2588 Binder.restoreCallingIdentity(origId);
2589 return res;
2590 }
2591 }
2592
Dianne Hackborn860755f2010-06-03 18:47:52 -07002593 public final void finishHeavyWeightApp() {
2594 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2595 != PackageManager.PERMISSION_GRANTED) {
2596 String msg = "Permission Denial: finishHeavyWeightApp() from pid="
2597 + Binder.getCallingPid()
2598 + ", uid=" + Binder.getCallingUid()
2599 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2600 Slog.w(TAG, msg);
2601 throw new SecurityException(msg);
2602 }
2603
2604 synchronized(this) {
2605 if (mHeavyWeightProcess == null) {
2606 return;
2607 }
2608
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002609 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>(
Dianne Hackborn860755f2010-06-03 18:47:52 -07002610 mHeavyWeightProcess.activities);
2611 for (int i=0; i<activities.size(); i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002612 ActivityRecord r = activities.get(i);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002613 if (!r.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002614 int index = mMainStack.indexOfTokenLocked(r.appToken);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002615 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002616 mMainStack.finishActivityLocked(r, index, Activity.RESULT_CANCELED,
Dianne Hackborn860755f2010-06-03 18:47:52 -07002617 null, "finish-heavy");
2618 }
2619 }
2620 }
2621
2622 mHeavyWeightProcess = null;
2623 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
2624 }
2625 }
2626
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002627 public void crashApplication(int uid, int initialPid, String packageName,
2628 String message) {
2629 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2630 != PackageManager.PERMISSION_GRANTED) {
2631 String msg = "Permission Denial: crashApplication() from pid="
2632 + Binder.getCallingPid()
2633 + ", uid=" + Binder.getCallingUid()
2634 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2635 Slog.w(TAG, msg);
2636 throw new SecurityException(msg);
2637 }
2638
2639 synchronized(this) {
2640 ProcessRecord proc = null;
2641
2642 // Figure out which process to kill. We don't trust that initialPid
2643 // still has any relation to current pids, so must scan through the
2644 // list.
2645 synchronized (mPidsSelfLocked) {
2646 for (int i=0; i<mPidsSelfLocked.size(); i++) {
2647 ProcessRecord p = mPidsSelfLocked.valueAt(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002648 if (p.uid != uid) {
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002649 continue;
2650 }
2651 if (p.pid == initialPid) {
2652 proc = p;
2653 break;
2654 }
2655 for (String str : p.pkgList) {
2656 if (str.equals(packageName)) {
2657 proc = p;
2658 }
2659 }
2660 }
2661 }
2662
2663 if (proc == null) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07002664 Slog.w(TAG, "crashApplication: nothing for uid=" + uid
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002665 + " initialPid=" + initialPid
2666 + " packageName=" + packageName);
2667 return;
2668 }
2669
2670 if (proc.thread != null) {
Dianne Hackborn9f531192010-08-04 17:48:03 -07002671 if (proc.pid == Process.myPid()) {
2672 Log.w(TAG, "crashApplication: trying to crash self!");
2673 return;
2674 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002675 long ident = Binder.clearCallingIdentity();
2676 try {
2677 proc.thread.scheduleCrash(message);
2678 } catch (RemoteException e) {
2679 }
2680 Binder.restoreCallingIdentity(ident);
2681 }
2682 }
2683 }
2684
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002685 public final void finishSubActivity(IBinder token, String resultWho,
2686 int requestCode) {
2687 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002688 ActivityRecord self = mMainStack.isInStackLocked(token);
2689 if (self == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002690 return;
2691 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002692
2693 final long origId = Binder.clearCallingIdentity();
2694
2695 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002696 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2697 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002698 if (r.resultTo == self && r.requestCode == requestCode) {
2699 if ((r.resultWho == null && resultWho == null) ||
2700 (r.resultWho != null && r.resultWho.equals(resultWho))) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002701 mMainStack.finishActivityLocked(r, i,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002702 Activity.RESULT_CANCELED, null, "request-sub");
2703 }
2704 }
2705 }
2706
2707 Binder.restoreCallingIdentity(origId);
2708 }
2709 }
2710
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002711 public boolean willActivityBeVisible(IBinder token) {
2712 synchronized(this) {
2713 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002714 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2715 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08002716 if (r.appToken == token) {
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002717 return true;
2718 }
2719 if (r.fullscreen && !r.finishing) {
2720 return false;
2721 }
2722 }
2723 return true;
2724 }
2725 }
2726
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002727 public void overridePendingTransition(IBinder token, String packageName,
2728 int enterAnim, int exitAnim) {
2729 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002730 ActivityRecord self = mMainStack.isInStackLocked(token);
2731 if (self == null) {
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002732 return;
2733 }
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002734
2735 final long origId = Binder.clearCallingIdentity();
2736
2737 if (self.state == ActivityState.RESUMED
2738 || self.state == ActivityState.PAUSING) {
2739 mWindowManager.overridePendingAppTransition(packageName,
2740 enterAnim, exitAnim);
2741 }
2742
2743 Binder.restoreCallingIdentity(origId);
2744 }
2745 }
2746
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002747 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002748 * Main function for removing an existing process from the activity manager
2749 * as a result of that process going away. Clears out all connections
2750 * to the process.
2751 */
2752 private final void handleAppDiedLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002753 boolean restarting, boolean allowRestart) {
2754 cleanUpApplicationRecordLocked(app, restarting, allowRestart, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002755 if (!restarting) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002756 mLruProcesses.remove(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002757 }
2758
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002759 if (mProfileProc == app) {
2760 clearProfilerLocked();
2761 }
2762
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002763 // Just in case...
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002764 if (mMainStack.mPausingActivity != null && mMainStack.mPausingActivity.app == app) {
2765 if (DEBUG_PAUSE) Slog.v(TAG, "App died while pausing: " +mMainStack.mPausingActivity);
2766 mMainStack.mPausingActivity = null;
2767 }
2768 if (mMainStack.mLastPausedActivity != null && mMainStack.mLastPausedActivity.app == app) {
2769 mMainStack.mLastPausedActivity = null;
2770 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002771
2772 // Remove this application's activities from active lists.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002773 mMainStack.removeHistoryRecordsForAppLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002774
2775 boolean atTop = true;
2776 boolean hasVisibleActivities = false;
2777
2778 // Clean out the history list.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002779 int i = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08002780 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002781 TAG, "Removing app " + app + " from history with " + i + " entries");
2782 while (i > 0) {
2783 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002784 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002785 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002786 TAG, "Record #" + i + " " + r + ": app=" + r.app);
2787 if (r.app == app) {
2788 if ((!r.haveState && !r.stateNotNeeded) || r.finishing) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002789 if (ActivityStack.DEBUG_ADD_REMOVE) {
2790 RuntimeException here = new RuntimeException("here");
2791 here.fillInStackTrace();
2792 Slog.i(TAG, "Removing activity " + r + " from stack at " + i
2793 + ": haveState=" + r.haveState
2794 + " stateNotNeeded=" + r.stateNotNeeded
2795 + " finishing=" + r.finishing
2796 + " state=" + r.state, here);
2797 }
2798 if (!r.finishing) {
2799 Slog.w(TAG, "Force removing " + r + ": app died, no saved state");
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -08002800 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
2801 System.identityHashCode(r),
2802 r.task.taskId, r.shortComponentName,
2803 "proc died without state saved");
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002804 }
Dianne Hackborn5c607432012-02-28 14:44:19 -08002805 mMainStack.removeActivityFromHistoryLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002806
2807 } else {
2808 // We have the current state for this activity, so
2809 // it can be restarted later when needed.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002810 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002811 TAG, "Keeping entry, setting app to null");
2812 if (r.visible) {
2813 hasVisibleActivities = true;
2814 }
2815 r.app = null;
2816 r.nowVisible = false;
2817 if (!r.haveState) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002818 if (ActivityStack.DEBUG_SAVED_STATE) Slog.i(TAG,
2819 "App died, clearing saved state of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002820 r.icicle = null;
2821 }
2822 }
2823
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002824 r.stack.cleanUpActivityLocked(r, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002825 }
2826 atTop = false;
2827 }
2828
2829 app.activities.clear();
2830
2831 if (app.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002832 Slog.w(TAG, "Crash of app " + app.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002833 + " running instrumentation " + app.instrumentationClass);
2834 Bundle info = new Bundle();
2835 info.putString("shortMsg", "Process crashed.");
2836 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
2837 }
2838
2839 if (!restarting) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002840 if (!mMainStack.resumeTopActivityLocked(null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002841 // If there was nothing to resume, and we are not already
2842 // restarting this process, but there is a visible activity that
2843 // is hosted by the process... then make sure all visible
2844 // activities are running, taking care of restarting this
2845 // process.
2846 if (hasVisibleActivities) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002847 mMainStack.ensureActivitiesVisibleLocked(null, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002848 }
2849 }
2850 }
2851 }
2852
2853 private final int getLRURecordIndexForAppLocked(IApplicationThread thread) {
2854 IBinder threadBinder = thread.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002855 // Find the application record.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002856 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2857 ProcessRecord rec = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002858 if (rec.thread != null && rec.thread.asBinder() == threadBinder) {
2859 return i;
2860 }
2861 }
2862 return -1;
2863 }
2864
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002865 final ProcessRecord getRecordForAppLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002866 IApplicationThread thread) {
2867 if (thread == null) {
2868 return null;
2869 }
2870
2871 int appIndex = getLRURecordIndexForAppLocked(thread);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002872 return appIndex >= 0 ? mLruProcesses.get(appIndex) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002873 }
2874
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002875 final void appDiedLocked(ProcessRecord app, int pid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002876 IApplicationThread thread) {
2877
2878 mProcDeaths[0]++;
2879
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002880 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
2881 synchronized (stats) {
2882 stats.noteProcessDiedLocked(app.info.uid, pid);
2883 }
2884
Magnus Edlund7bb25812010-02-24 15:45:06 +01002885 // Clean up already done if the process has been re-started.
2886 if (app.pid == pid && app.thread != null &&
2887 app.thread.asBinder() == thread.asBinder()) {
Dianne Hackborn906497c2010-05-10 15:57:38 -07002888 if (!app.killedBackground) {
2889 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
2890 + ") has died.");
2891 }
Doug Zongker2bec3d42009-12-04 12:52:44 -08002892 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002893 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002894 TAG, "Dying app: " + app + ", pid: " + pid
2895 + ", thread: " + thread.asBinder());
2896 boolean doLowMem = app.instrumentationClass == null;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002897 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002898
2899 if (doLowMem) {
2900 // If there are no longer any background processes running,
2901 // and the app that died was not running instrumentation,
2902 // then tell everyone we are now low on memory.
2903 boolean haveBg = false;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002904 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2905 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -07002906 if (rec.thread != null && rec.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002907 haveBg = true;
2908 break;
2909 }
2910 }
2911
2912 if (!haveBg) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002913 EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mLruProcesses.size());
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002914 long now = SystemClock.uptimeMillis();
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002915 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2916 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn36124872009-10-08 16:22:03 -07002917 if (rec != app && rec.thread != null &&
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002918 (rec.lastLowMemory+GC_MIN_INTERVAL) <= now) {
2919 // The low memory report is overriding any current
2920 // state for a GC request. Make sure to do
Dianne Hackborn32907cf2010-06-10 17:50:20 -07002921 // heavy/important/visible/foreground processes first.
Dianne Hackborn7d608422011-08-07 16:24:18 -07002922 if (rec.setAdj <= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002923 rec.lastRequestedGc = 0;
2924 } else {
2925 rec.lastRequestedGc = rec.lastLowMemory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002926 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002927 rec.reportLowMemory = true;
2928 rec.lastLowMemory = now;
2929 mProcessesToGc.remove(rec);
2930 addProcessToGcListLocked(rec);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002931 }
2932 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07002933 mHandler.sendEmptyMessage(REPORT_MEM_USAGE);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002934 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002935 }
2936 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01002937 } else if (app.pid != pid) {
2938 // A new process has already been started.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002939 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
Magnus Edlund7bb25812010-02-24 15:45:06 +01002940 + ") has died and restarted (pid " + app.pid + ").");
Dianne Hackborn28a8c2b2010-03-01 11:30:02 -08002941 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08002942 } else if (DEBUG_PROCESSES) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002943 Slog.d(TAG, "Received spurious death notification for thread "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002944 + thread.asBinder());
2945 }
2946 }
2947
Dan Egnor42471dd2010-01-07 17:25:22 -08002948 /**
2949 * If a stack trace dump file is configured, dump process stack traces.
Christopher Tate6ee412d2010-05-28 12:01:56 -07002950 * @param clearTraces causes the dump file to be erased prior to the new
2951 * traces being written, if true; when false, the new traces will be
2952 * appended to any existing file content.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002953 * @param firstPids of dalvik VM processes to dump stack traces for first
2954 * @param lastPids of dalvik VM processes to dump stack traces for last
Dan Egnor42471dd2010-01-07 17:25:22 -08002955 * @return file containing stack traces, or null if no dump file is configured
2956 */
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002957 public static File dumpStackTraces(boolean clearTraces, ArrayList<Integer> firstPids,
2958 ProcessStats processStats, SparseArray<Boolean> lastPids) {
Dan Egnor42471dd2010-01-07 17:25:22 -08002959 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
2960 if (tracesPath == null || tracesPath.length() == 0) {
2961 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002962 }
Dan Egnor42471dd2010-01-07 17:25:22 -08002963
2964 File tracesFile = new File(tracesPath);
2965 try {
2966 File tracesDir = tracesFile.getParentFile();
2967 if (!tracesDir.exists()) tracesFile.mkdirs();
2968 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
2969
Christopher Tate6ee412d2010-05-28 12:01:56 -07002970 if (clearTraces && tracesFile.exists()) tracesFile.delete();
Dan Egnor42471dd2010-01-07 17:25:22 -08002971 tracesFile.createNewFile();
2972 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
2973 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002974 Slog.w(TAG, "Unable to prepare ANR traces file: " + tracesPath, e);
Dan Egnor42471dd2010-01-07 17:25:22 -08002975 return null;
2976 }
2977
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07002978 dumpStackTraces(tracesPath, firstPids, processStats, lastPids);
2979 return tracesFile;
2980 }
2981
2982 private static void dumpStackTraces(String tracesPath, ArrayList<Integer> firstPids,
2983 ProcessStats processStats, SparseArray<Boolean> lastPids) {
Dan Egnor42471dd2010-01-07 17:25:22 -08002984 // Use a FileObserver to detect when traces finish writing.
2985 // The order of traces is considered important to maintain for legibility.
2986 FileObserver observer = new FileObserver(tracesPath, FileObserver.CLOSE_WRITE) {
2987 public synchronized void onEvent(int event, String path) { notify(); }
2988 };
2989
2990 try {
2991 observer.startWatching();
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002992
2993 // First collect all of the stacks of the most important pids.
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07002994 if (firstPids != null) {
2995 try {
2996 int num = firstPids.size();
2997 for (int i = 0; i < num; i++) {
2998 synchronized (observer) {
2999 Process.sendSignal(firstPids.get(i), Process.SIGNAL_QUIT);
3000 observer.wait(200); // Wait for write-close, give up after 200msec
3001 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003002 }
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003003 } catch (InterruptedException e) {
3004 Log.wtf(TAG, e);
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003005 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003006 }
3007
3008 // Next measure CPU usage.
3009 if (processStats != null) {
3010 processStats.init();
3011 System.gc();
3012 processStats.update();
3013 try {
3014 synchronized (processStats) {
3015 processStats.wait(500); // measure over 1/2 second.
3016 }
3017 } catch (InterruptedException e) {
3018 }
3019 processStats.update();
3020
3021 // We'll take the stack crawls of just the top apps using CPU.
3022 final int N = processStats.countWorkingStats();
3023 int numProcs = 0;
3024 for (int i=0; i<N && numProcs<5; i++) {
3025 ProcessStats.Stats stats = processStats.getWorkingStats(i);
3026 if (lastPids.indexOfKey(stats.pid) >= 0) {
3027 numProcs++;
3028 try {
3029 synchronized (observer) {
3030 Process.sendSignal(stats.pid, Process.SIGNAL_QUIT);
3031 observer.wait(200); // Wait for write-close, give up after 200msec
3032 }
3033 } catch (InterruptedException e) {
3034 Log.wtf(TAG, e);
3035 }
3036
3037 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003038 }
3039 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003040
Dan Egnor42471dd2010-01-07 17:25:22 -08003041 } finally {
3042 observer.stopWatching();
3043 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003044 }
3045
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003046 final void logAppTooSlow(ProcessRecord app, long startTime, String msg) {
Dianne Hackborn69dc66e2012-03-26 10:50:54 -07003047 if (true || IS_USER_BUILD) {
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003048 return;
3049 }
3050 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
3051 if (tracesPath == null || tracesPath.length() == 0) {
3052 return;
3053 }
3054
3055 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
3056 StrictMode.allowThreadDiskWrites();
3057 try {
3058 final File tracesFile = new File(tracesPath);
3059 final File tracesDir = tracesFile.getParentFile();
3060 final File tracesTmp = new File(tracesDir, "__tmp__");
3061 try {
3062 if (!tracesDir.exists()) tracesFile.mkdirs();
3063 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
3064
3065 if (tracesFile.exists()) {
3066 tracesTmp.delete();
3067 tracesFile.renameTo(tracesTmp);
3068 }
3069 StringBuilder sb = new StringBuilder();
3070 Time tobj = new Time();
3071 tobj.set(System.currentTimeMillis());
3072 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
3073 sb.append(": ");
3074 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
3075 sb.append(" since ");
3076 sb.append(msg);
3077 FileOutputStream fos = new FileOutputStream(tracesFile);
3078 fos.write(sb.toString().getBytes());
3079 if (app == null) {
3080 fos.write("\n*** No application process!".getBytes());
3081 }
3082 fos.close();
3083 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
3084 } catch (IOException e) {
3085 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesPath, e);
3086 return;
3087 }
3088
3089 if (app != null) {
3090 ArrayList<Integer> firstPids = new ArrayList<Integer>();
3091 firstPids.add(app.pid);
3092 dumpStackTraces(tracesPath, firstPids, null, null);
3093 }
3094
3095 File lastTracesFile = null;
3096 File curTracesFile = null;
3097 for (int i=9; i>=0; i--) {
3098 String name = String.format("slow%02d.txt", i);
3099 curTracesFile = new File(tracesDir, name);
3100 if (curTracesFile.exists()) {
3101 if (lastTracesFile != null) {
3102 curTracesFile.renameTo(lastTracesFile);
3103 } else {
3104 curTracesFile.delete();
3105 }
3106 }
3107 lastTracesFile = curTracesFile;
3108 }
3109 tracesFile.renameTo(curTracesFile);
3110 if (tracesTmp.exists()) {
3111 tracesTmp.renameTo(tracesFile);
3112 }
3113 } finally {
3114 StrictMode.setThreadPolicy(oldPolicy);
3115 }
3116 }
3117
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003118 final void appNotResponding(ProcessRecord app, ActivityRecord activity,
3119 ActivityRecord parent, final String annotation) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003120 ArrayList<Integer> firstPids = new ArrayList<Integer>(5);
3121 SparseArray<Boolean> lastPids = new SparseArray<Boolean>(20);
3122
Dianne Hackborn287952c2010-09-22 22:34:31 -07003123 if (mController != null) {
3124 try {
3125 // 0 == continue, -1 = kill process immediately
3126 int res = mController.appEarlyNotResponding(app.processName, app.pid, annotation);
3127 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3128 } catch (RemoteException e) {
3129 mController = null;
3130 }
3131 }
3132
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003133 long anrTime = SystemClock.uptimeMillis();
3134 if (MONITOR_CPU_USAGE) {
3135 updateCpuStatsNow();
3136 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003137
3138 synchronized (this) {
3139 // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down.
3140 if (mShuttingDown) {
3141 Slog.i(TAG, "During shutdown skipping ANR: " + app + " " + annotation);
3142 return;
3143 } else if (app.notResponding) {
3144 Slog.i(TAG, "Skipping duplicate ANR: " + app + " " + annotation);
3145 return;
3146 } else if (app.crashing) {
3147 Slog.i(TAG, "Crashing app skipping ANR: " + app + " " + annotation);
3148 return;
3149 }
3150
3151 // In case we come through here for the same app before completing
3152 // this one, mark as anring now so we will bail out.
3153 app.notResponding = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08003154
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003155 // Log the ANR to the event log.
3156 EventLog.writeEvent(EventLogTags.AM_ANR, app.pid, app.processName, app.info.flags,
3157 annotation);
Dan Egnor42471dd2010-01-07 17:25:22 -08003158
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003159 // Dump thread traces as quickly as we can, starting with "interesting" processes.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003160 firstPids.add(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003161
3162 int parentPid = app.pid;
3163 if (parent != null && parent.app != null && parent.app.pid > 0) parentPid = parent.app.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003164 if (parentPid != app.pid) firstPids.add(parentPid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003165
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003166 if (MY_PID != app.pid && MY_PID != parentPid) firstPids.add(MY_PID);
Dan Egnor42471dd2010-01-07 17:25:22 -08003167
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003168 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
3169 ProcessRecord r = mLruProcesses.get(i);
3170 if (r != null && r.thread != null) {
3171 int pid = r.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003172 if (pid > 0 && pid != app.pid && pid != parentPid && pid != MY_PID) {
3173 if (r.persistent) {
3174 firstPids.add(pid);
3175 } else {
3176 lastPids.put(pid, Boolean.TRUE);
3177 }
3178 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003179 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003180 }
3181 }
3182
Dan Egnor42471dd2010-01-07 17:25:22 -08003183 // Log the ANR to the main log.
Jeff Browndeb6ed82012-04-10 14:26:26 -07003184 StringBuilder info = new StringBuilder();
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07003185 info.setLength(0);
Dan Egnor42471dd2010-01-07 17:25:22 -08003186 info.append("ANR in ").append(app.processName);
3187 if (activity != null && activity.shortComponentName != null) {
3188 info.append(" (").append(activity.shortComponentName).append(")");
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07003189 }
Eric Rowe6f4f6192010-02-17 18:29:04 -08003190 info.append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003191 if (annotation != null) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003192 info.append("Reason: ").append(annotation).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003193 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003194 if (parent != null && parent != activity) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003195 info.append("Parent: ").append(parent.shortComponentName).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003196 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003197
Dianne Hackborn287952c2010-09-22 22:34:31 -07003198 final ProcessStats processStats = new ProcessStats(true);
3199
3200 File tracesFile = dumpStackTraces(true, firstPids, processStats, lastPids);
3201
Dan Egnor42471dd2010-01-07 17:25:22 -08003202 String cpuInfo = null;
3203 if (MONITOR_CPU_USAGE) {
3204 updateCpuStatsNow();
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003205 synchronized (mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003206 cpuInfo = mProcessStats.printCurrentState(anrTime);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003207 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003208 info.append(processStats.printCurrentLoad());
Dan Egnor42471dd2010-01-07 17:25:22 -08003209 info.append(cpuInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003210 }
3211
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003212 info.append(processStats.printCurrentState(anrTime));
3213
Joe Onorato8a9b2202010-02-26 18:56:32 -08003214 Slog.e(TAG, info.toString());
Dan Egnor42471dd2010-01-07 17:25:22 -08003215 if (tracesFile == null) {
3216 // There is no trace file, so dump (only) the alleged culprit's threads to the log
3217 Process.sendSignal(app.pid, Process.SIGNAL_QUIT);
3218 }
3219
Jeff Sharkeya353d262011-10-28 11:12:06 -07003220 addErrorToDropBox("anr", app, app.processName, activity, parent, annotation,
3221 cpuInfo, tracesFile, null);
Dan Egnor42471dd2010-01-07 17:25:22 -08003222
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003223 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003224 try {
Dan Egnor42471dd2010-01-07 17:25:22 -08003225 // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately
3226 int res = mController.appNotResponding(app.processName, app.pid, info.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003227 if (res != 0) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003228 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3229 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003230 }
3231 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003232 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003233 }
3234 }
3235
Dan Egnor42471dd2010-01-07 17:25:22 -08003236 // Unless configured otherwise, swallow ANRs in background processes & kill the process.
3237 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
3238 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003239
3240 synchronized (this) {
3241 if (!showBackground && !app.isInterestingToUserLocked() && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003242 Slog.w(TAG, "Killing " + app + ": background ANR");
3243 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
3244 app.processName, app.setAdj, "background ANR");
3245 Process.killProcessQuiet(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003246 return;
3247 }
3248
3249 // Set the app's notResponding state, and look up the errorReportReceiver
3250 makeAppNotRespondingLocked(app,
3251 activity != null ? activity.shortComponentName : null,
3252 annotation != null ? "ANR " + annotation : "ANR",
3253 info.toString());
3254
3255 // Bring up the infamous App Not Responding dialog
3256 Message msg = Message.obtain();
3257 HashMap map = new HashMap();
3258 msg.what = SHOW_NOT_RESPONDING_MSG;
3259 msg.obj = map;
3260 map.put("app", app);
3261 if (activity != null) {
3262 map.put("activity", activity);
3263 }
3264
3265 mHandler.sendMessage(msg);
Dan Egnor42471dd2010-01-07 17:25:22 -08003266 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003267 }
3268
Dianne Hackborn0dad3642010-09-09 21:25:35 -07003269 final void showLaunchWarningLocked(final ActivityRecord cur, final ActivityRecord next) {
3270 if (!mLaunchWarningShown) {
3271 mLaunchWarningShown = true;
3272 mHandler.post(new Runnable() {
3273 @Override
3274 public void run() {
3275 synchronized (ActivityManagerService.this) {
3276 final Dialog d = new LaunchWarningWindow(mContext, cur, next);
3277 d.show();
3278 mHandler.postDelayed(new Runnable() {
3279 @Override
3280 public void run() {
3281 synchronized (ActivityManagerService.this) {
3282 d.dismiss();
3283 mLaunchWarningShown = false;
3284 }
3285 }
3286 }, 4000);
3287 }
3288 }
3289 });
3290 }
3291 }
3292
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003293 public boolean clearApplicationUserData(final String packageName,
Amith Yamasani742a6712011-05-04 14:49:28 -07003294 final IPackageDataObserver observer, final int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003295 enforceNotIsolatedCaller("clearApplicationUserData");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003296 int uid = Binder.getCallingUid();
3297 int pid = Binder.getCallingPid();
3298 long callingId = Binder.clearCallingIdentity();
3299 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003300 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003301 int pkgUid = -1;
3302 synchronized(this) {
3303 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003304 pkgUid = pm.getPackageUid(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003305 } catch (RemoteException e) {
3306 }
3307 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003308 Slog.w(TAG, "Invalid packageName:" + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003309 return false;
3310 }
3311 if (uid == pkgUid || checkComponentPermission(
3312 android.Manifest.permission.CLEAR_APP_USER_DATA,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08003313 pid, uid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003314 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003315 forceStopPackageLocked(packageName, pkgUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003316 } else {
3317 throw new SecurityException(pid+" does not have permission:"+
3318 android.Manifest.permission.CLEAR_APP_USER_DATA+" to clear data" +
3319 "for process:"+packageName);
3320 }
3321 }
3322
3323 try {
3324 //clear application user data
Amith Yamasani483f3b02012-03-13 16:08:00 -07003325 pm.clearApplicationUserData(packageName, observer, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003326 Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED,
3327 Uri.fromParts("package", packageName, null));
3328 intent.putExtra(Intent.EXTRA_UID, pkgUid);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003329 broadcastIntentInPackage("android", Process.SYSTEM_UID, intent,
Amith Yamasani742a6712011-05-04 14:49:28 -07003330 null, null, 0, null, null, null, false, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003331 } catch (RemoteException e) {
3332 }
3333 } finally {
3334 Binder.restoreCallingIdentity(callingId);
3335 }
3336 return true;
3337 }
3338
Dianne Hackborn03abb812010-01-04 18:43:19 -08003339 public void killBackgroundProcesses(final String packageName) {
3340 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3341 != PackageManager.PERMISSION_GRANTED &&
3342 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES)
3343 != PackageManager.PERMISSION_GRANTED) {
3344 String msg = "Permission Denial: killBackgroundProcesses() from pid="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003345 + Binder.getCallingPid()
3346 + ", uid=" + Binder.getCallingUid()
Dianne Hackborn03abb812010-01-04 18:43:19 -08003347 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003348 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003349 throw new SecurityException(msg);
3350 }
3351
Amith Yamasani483f3b02012-03-13 16:08:00 -07003352 int userId = UserId.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003353 long callingId = Binder.clearCallingIdentity();
3354 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003355 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003356 int pkgUid = -1;
3357 synchronized(this) {
3358 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003359 pkgUid = pm.getPackageUid(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003360 } catch (RemoteException e) {
3361 }
3362 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003363 Slog.w(TAG, "Invalid packageName: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003364 return;
3365 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003366 killPackageProcessesLocked(packageName, pkgUid,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003367 ProcessList.SERVICE_ADJ, false, true, true, false, "kill background");
3368 }
3369 } finally {
3370 Binder.restoreCallingIdentity(callingId);
3371 }
3372 }
3373
3374 public void killAllBackgroundProcesses() {
3375 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3376 != PackageManager.PERMISSION_GRANTED) {
3377 String msg = "Permission Denial: killAllBackgroundProcesses() from pid="
3378 + Binder.getCallingPid()
3379 + ", uid=" + Binder.getCallingUid()
3380 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
3381 Slog.w(TAG, msg);
3382 throw new SecurityException(msg);
3383 }
3384
3385 long callingId = Binder.clearCallingIdentity();
3386 try {
3387 synchronized(this) {
3388 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
3389 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3390 final int NA = apps.size();
3391 for (int ia=0; ia<NA; ia++) {
3392 ProcessRecord app = apps.valueAt(ia);
3393 if (app.persistent) {
3394 // we don't kill persistent processes
3395 continue;
3396 }
3397 if (app.removed) {
3398 procs.add(app);
3399 } else if (app.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
3400 app.removed = true;
3401 procs.add(app);
3402 }
3403 }
3404 }
3405
3406 int N = procs.size();
3407 for (int i=0; i<N; i++) {
3408 removeProcessLocked(procs.get(i), false, true, "kill all background");
3409 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003410 }
3411 } finally {
3412 Binder.restoreCallingIdentity(callingId);
3413 }
3414 }
3415
3416 public void forceStopPackage(final String packageName) {
3417 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3418 != PackageManager.PERMISSION_GRANTED) {
3419 String msg = "Permission Denial: forceStopPackage() from pid="
3420 + Binder.getCallingPid()
3421 + ", uid=" + Binder.getCallingUid()
3422 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003423 Slog.w(TAG, msg);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003424 throw new SecurityException(msg);
3425 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07003426 final int userId = UserId.getCallingUserId();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003427 long callingId = Binder.clearCallingIdentity();
3428 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003429 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003430 int pkgUid = -1;
3431 synchronized(this) {
3432 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003433 pkgUid = pm.getPackageUid(packageName, userId);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003434 } catch (RemoteException e) {
3435 }
3436 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003437 Slog.w(TAG, "Invalid packageName: " + packageName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003438 return;
3439 }
3440 forceStopPackageLocked(packageName, pkgUid);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003441 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003442 pm.setPackageStoppedState(packageName, true, userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003443 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08003444 } catch (IllegalArgumentException e) {
3445 Slog.w(TAG, "Failed trying to unstop package "
3446 + packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003447 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003448 }
3449 } finally {
3450 Binder.restoreCallingIdentity(callingId);
3451 }
3452 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003453
3454 /*
3455 * The pkg name and uid have to be specified.
3456 * @see android.app.IActivityManager#killApplicationWithUid(java.lang.String, int)
3457 */
3458 public void killApplicationWithUid(String pkg, int uid) {
3459 if (pkg == null) {
3460 return;
3461 }
3462 // Make sure the uid is valid.
3463 if (uid < 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003464 Slog.w(TAG, "Invalid uid specified for pkg : " + pkg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003465 return;
3466 }
3467 int callerUid = Binder.getCallingUid();
3468 // Only the system server can kill an application
3469 if (callerUid == Process.SYSTEM_UID) {
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07003470 // Post an aysnc message to kill the application
3471 Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG);
3472 msg.arg1 = uid;
3473 msg.arg2 = 0;
3474 msg.obj = pkg;
Suchi Amalapurapud50066f2009-08-18 16:57:41 -07003475 mHandler.sendMessage(msg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003476 } else {
3477 throw new SecurityException(callerUid + " cannot kill pkg: " +
3478 pkg);
3479 }
3480 }
3481
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003482 public void closeSystemDialogs(String reason) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003483 enforceNotIsolatedCaller("closeSystemDialogs");
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003484 Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003485 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003486 if (reason != null) {
3487 intent.putExtra("reason", reason);
3488 }
3489
3490 final int uid = Binder.getCallingUid();
3491 final long origId = Binder.clearCallingIdentity();
3492 synchronized (this) {
Dianne Hackbornffa42482009-09-23 22:20:11 -07003493 mWindowManager.closeSystemDialogs(reason);
3494
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08003495 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003496 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornffa42482009-09-23 22:20:11 -07003497 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003498 r.stack.finishActivityLocked(r, i,
Dianne Hackbornffa42482009-09-23 22:20:11 -07003499 Activity.RESULT_CANCELED, null, "close-sys");
3500 }
3501 }
3502
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003503 broadcastIntentLocked(null, null, intent, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07003504 null, 0, null, null, null, false, false, -1, uid, 0 /* TODO: Verify */);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003505 }
3506 Binder.restoreCallingIdentity(origId);
3507 }
3508
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003509 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids)
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003510 throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003511 enforceNotIsolatedCaller("getProcessMemoryInfo");
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003512 Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length];
3513 for (int i=pids.length-1; i>=0; i--) {
3514 infos[i] = new Debug.MemoryInfo();
3515 Debug.getMemoryInfo(pids[i], infos[i]);
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003516 }
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003517 return infos;
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003518 }
Christopher Tate5e1ab332009-09-01 20:32:49 -07003519
Dianne Hackbornb437e092011-08-05 17:50:29 -07003520 public long[] getProcessPss(int[] pids) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003521 enforceNotIsolatedCaller("getProcessPss");
Dianne Hackbornb437e092011-08-05 17:50:29 -07003522 long[] pss = new long[pids.length];
3523 for (int i=pids.length-1; i>=0; i--) {
3524 pss[i] = Debug.getPss(pids[i]);
3525 }
3526 return pss;
3527 }
3528
Christopher Tate5e1ab332009-09-01 20:32:49 -07003529 public void killApplicationProcess(String processName, int uid) {
3530 if (processName == null) {
3531 return;
3532 }
3533
3534 int callerUid = Binder.getCallingUid();
3535 // Only the system server can kill an application
3536 if (callerUid == Process.SYSTEM_UID) {
3537 synchronized (this) {
3538 ProcessRecord app = getProcessRecordLocked(processName, uid);
Christopher Tate4a627c72011-04-01 14:43:32 -07003539 if (app != null && app.thread != null) {
Christopher Tate5e1ab332009-09-01 20:32:49 -07003540 try {
3541 app.thread.scheduleSuicide();
3542 } catch (RemoteException e) {
3543 // If the other end already died, then our work here is done.
3544 }
3545 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003546 Slog.w(TAG, "Process/uid not found attempting kill of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07003547 + processName + " / " + uid);
3548 }
3549 }
3550 } else {
3551 throw new SecurityException(callerUid + " cannot kill app process: " +
3552 processName);
3553 }
3554 }
3555
Dianne Hackborn03abb812010-01-04 18:43:19 -08003556 private void forceStopPackageLocked(final String packageName, int uid) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003557 forceStopPackageLocked(packageName, uid, false, false, true, false, UserId.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003558 Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED,
3559 Uri.fromParts("package", packageName, null));
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003560 if (!mProcessesReady) {
3561 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3562 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003563 intent.putExtra(Intent.EXTRA_UID, uid);
3564 broadcastIntentLocked(null, null, intent,
3565 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07003566 false, false,
3567 MY_PID, Process.SYSTEM_UID, UserId.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003568 }
3569
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003570 private final boolean killPackageProcessesLocked(String packageName, int uid,
Christopher Tate3dacd842011-08-19 14:56:15 -07003571 int minOomAdj, boolean callerWillRestart, boolean allowRestart, boolean doit,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003572 boolean evenPersistent, String reason) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003573 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003574
Dianne Hackborn03abb812010-01-04 18:43:19 -08003575 // Remove all processes this package may have touched: all with the
3576 // same UID (except for the system or root user), and all whose name
3577 // matches the package name.
3578 final String procNamePrefix = packageName + ":";
3579 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3580 final int NA = apps.size();
3581 for (int ia=0; ia<NA; ia++) {
3582 ProcessRecord app = apps.valueAt(ia);
Christopher Tate3dacd842011-08-19 14:56:15 -07003583 if (app.persistent && !evenPersistent) {
Christopher Tate064d8422011-07-26 15:38:07 -07003584 // we don't kill persistent processes
3585 continue;
3586 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003587 if (app.removed) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003588 if (doit) {
3589 procs.add(app);
3590 }
Amith Yamasani13593602012-03-22 16:16:17 -07003591 // If uid is specified and the uid and process name match
3592 // Or, the uid is not specified and the process name matches
3593 } else if (((uid > 0 && uid != Process.SYSTEM_UID && app.info.uid == uid)
Amith Yamasani34db3d62012-04-02 16:35:19 -07003594 || ((app.processName.equals(packageName)
3595 || app.processName.startsWith(procNamePrefix))
3596 && uid < 0))) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003597 if (app.setAdj >= minOomAdj) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003598 if (!doit) {
3599 return true;
3600 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003601 app.removed = true;
3602 procs.add(app);
3603 }
3604 }
3605 }
3606 }
3607
3608 int N = procs.size();
3609 for (int i=0; i<N; i++) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003610 removeProcessLocked(procs.get(i), callerWillRestart, allowRestart, reason);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003611 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003612 return N > 0;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003613 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003614
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003615 private final boolean forceStopPackageLocked(String name, int uid,
Christopher Tate3dacd842011-08-19 14:56:15 -07003616 boolean callerWillRestart, boolean purgeCache, boolean doit,
Amith Yamasani483f3b02012-03-13 16:08:00 -07003617 boolean evenPersistent, int userId) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003618 int i;
3619 int N;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003620
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003621 if (uid < 0) {
3622 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003623 uid = AppGlobals.getPackageManager().getPackageUid(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003624 } catch (RemoteException e) {
3625 }
3626 }
3627
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003628 if (doit) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003629 Slog.i(TAG, "Force stopping package " + name + " uid=" + uid);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003630
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003631 Iterator<SparseArray<Long>> badApps = mProcessCrashTimes.getMap().values().iterator();
3632 while (badApps.hasNext()) {
3633 SparseArray<Long> ba = badApps.next();
3634 if (ba.get(uid) != null) {
3635 badApps.remove();
3636 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003637 }
3638 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003639
3640 boolean didSomething = killPackageProcessesLocked(name, uid, -100,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003641 callerWillRestart, false, doit, evenPersistent, "force stop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003642
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003643 TaskRecord lastTask = null;
3644 for (i=0; i<mMainStack.mHistory.size(); i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003645 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003646 final boolean samePackage = r.packageName.equals(name);
Amith Yamasani13593602012-03-22 16:16:17 -07003647 if (r.userId == userId
3648 && (samePackage || r.task == lastTask)
Christopher Tate3dacd842011-08-19 14:56:15 -07003649 && (r.app == null || evenPersistent || !r.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003650 if (!doit) {
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003651 if (r.finishing) {
3652 // If this activity is just finishing, then it is not
3653 // interesting as far as something to stop.
3654 continue;
3655 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003656 return true;
3657 }
3658 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003659 Slog.i(TAG, " Force finishing activity " + r);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003660 if (samePackage) {
3661 if (r.app != null) {
3662 r.app.removed = true;
3663 }
3664 r.app = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003665 }
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003666 lastTask = r.task;
3667 if (r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003668 null, "force-stop", true)) {
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003669 i--;
3670 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003671 }
3672 }
3673
3674 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
Amith Yamasani742a6712011-05-04 14:49:28 -07003675 for (ServiceRecord service : mServiceMap.getAllServices(userId)) {
Christopher Tate064d8422011-07-26 15:38:07 -07003676 if (service.packageName.equals(name)
Christopher Tate3dacd842011-08-19 14:56:15 -07003677 && (service.app == null || evenPersistent || !service.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003678 if (!doit) {
3679 return true;
3680 }
3681 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003682 Slog.i(TAG, " Force stopping service " + service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003683 if (service.app != null) {
3684 service.app.removed = true;
3685 }
3686 service.app = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003687 service.isolatedProc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003688 services.add(service);
3689 }
3690 }
3691
3692 N = services.size();
3693 for (i=0; i<N; i++) {
3694 bringDownServiceLocked(services.get(i), true);
3695 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003696
3697 ArrayList<ContentProviderRecord> providers = new ArrayList<ContentProviderRecord>();
Amith Yamasani13593602012-03-22 16:16:17 -07003698 for (ContentProviderRecord provider : mProviderMap.getProvidersByClass(userId).values()) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003699 if (provider.info.packageName.equals(name)
3700 && (provider.proc == null || evenPersistent || !provider.proc.persistent)) {
3701 if (!doit) {
3702 return true;
3703 }
3704 didSomething = true;
3705 providers.add(provider);
3706 }
3707 }
3708
3709 N = providers.size();
3710 for (i=0; i<N; i++) {
3711 removeDyingProviderLocked(null, providers.get(i));
3712 }
3713
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003714 if (doit) {
3715 if (purgeCache) {
3716 AttributeCache ac = AttributeCache.instance();
3717 if (ac != null) {
3718 ac.removePackage(name);
3719 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003720 }
Dianne Hackborn38cc8962011-10-13 11:33:55 -07003721 if (mBooted) {
3722 mMainStack.resumeTopActivityLocked(null);
3723 mMainStack.scheduleIdleLocked();
3724 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003725 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003726
3727 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003728 }
3729
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003730 private final boolean removeProcessLocked(ProcessRecord app,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003731 boolean callerWillRestart, boolean allowRestart, String reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003732 final String name = app.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003733 final int uid = app.uid;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003734 if (DEBUG_PROCESSES) Slog.d(
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003735 TAG, "Force removing proc " + app.toShortString() + " (" + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003736 + "/" + uid + ")");
3737
3738 mProcessNames.remove(name, uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003739 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003740 if (mHeavyWeightProcess == app) {
3741 mHeavyWeightProcess = null;
3742 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3743 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003744 boolean needRestart = false;
3745 if (app.pid > 0 && app.pid != MY_PID) {
3746 int pid = app.pid;
3747 synchronized (mPidsSelfLocked) {
3748 mPidsSelfLocked.remove(pid);
3749 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3750 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003751 Slog.i(TAG, "Killing proc " + app.toShortString() + ": " + reason);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003752 handleAppDiedLocked(app, true, allowRestart);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003753 mLruProcesses.remove(app);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003754 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003755
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003756 if (app.persistent && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003757 if (!callerWillRestart) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003758 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003759 } else {
3760 needRestart = true;
3761 }
3762 }
3763 } else {
3764 mRemovedProcesses.add(app);
3765 }
3766
3767 return needRestart;
3768 }
3769
3770 private final void processStartTimedOutLocked(ProcessRecord app) {
3771 final int pid = app.pid;
3772 boolean gone = false;
3773 synchronized (mPidsSelfLocked) {
3774 ProcessRecord knownApp = mPidsSelfLocked.get(pid);
3775 if (knownApp != null && knownApp.thread == null) {
3776 mPidsSelfLocked.remove(pid);
3777 gone = true;
3778 }
3779 }
3780
3781 if (gone) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003782 Slog.w(TAG, "Process " + app + " failed to attach");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003783 EventLog.writeEvent(EventLogTags.AM_PROCESS_START_TIMEOUT, pid, app.uid,
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003784 app.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003785 mProcessNames.remove(app.processName, app.uid);
3786 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003787 if (mHeavyWeightProcess == app) {
3788 mHeavyWeightProcess = null;
3789 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3790 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003791 // Take care of any launching providers waiting for this process.
3792 checkAppInLaunchingProvidersLocked(app, true);
3793 // Take care of any services that are waiting for the process.
3794 for (int i=0; i<mPendingServices.size(); i++) {
3795 ServiceRecord sr = mPendingServices.get(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003796 if ((app.uid == sr.appInfo.uid
3797 && app.processName.equals(sr.processName))
3798 || sr.isolatedProc == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003799 Slog.w(TAG, "Forcing bringing down service: " + sr);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003800 sr.isolatedProc = null;
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003801 mPendingServices.remove(i);
3802 i--;
3803 bringDownServiceLocked(sr, true);
3804 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003805 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003806 EventLog.writeEvent(EventLogTags.AM_KILL, pid,
3807 app.processName, app.setAdj, "start timeout");
3808 Process.killProcessQuiet(pid);
Christopher Tate181fafa2009-05-14 11:12:14 -07003809 if (mBackupTarget != null && mBackupTarget.app.pid == pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003810 Slog.w(TAG, "Unattached app died before backup, skipping");
Christopher Tate181fafa2009-05-14 11:12:14 -07003811 try {
3812 IBackupManager bm = IBackupManager.Stub.asInterface(
3813 ServiceManager.getService(Context.BACKUP_SERVICE));
3814 bm.agentDisconnected(app.info.packageName);
3815 } catch (RemoteException e) {
3816 // Can't happen; the backup manager is local
3817 }
3818 }
Christopher Tatef46723b2012-01-26 14:19:24 -08003819 if (isPendingBroadcastProcessLocked(pid)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003820 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
Christopher Tatef46723b2012-01-26 14:19:24 -08003821 skipPendingBroadcastLocked(pid);
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003822 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003823 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003824 Slog.w(TAG, "Spurious process start timeout - pid not known for " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003825 }
3826 }
3827
3828 private final boolean attachApplicationLocked(IApplicationThread thread,
3829 int pid) {
3830
3831 // Find the application record that is being attached... either via
3832 // the pid if we are running in multiple processes, or just pull the
3833 // next app record if we are emulating process with anonymous threads.
3834 ProcessRecord app;
3835 if (pid != MY_PID && pid >= 0) {
3836 synchronized (mPidsSelfLocked) {
3837 app = mPidsSelfLocked.get(pid);
3838 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003839 } else {
3840 app = null;
3841 }
3842
3843 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003844 Slog.w(TAG, "No pending application record for pid " + pid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003845 + " (IApplicationThread " + thread + "); dropping process");
Doug Zongker2bec3d42009-12-04 12:52:44 -08003846 EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003847 if (pid > 0 && pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003848 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003849 } else {
3850 try {
3851 thread.scheduleExit();
3852 } catch (Exception e) {
3853 // Ignore exceptions.
3854 }
3855 }
3856 return false;
3857 }
3858
3859 // If this application record is still attached to a previous
3860 // process, clean it up now.
3861 if (app.thread != null) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003862 handleAppDiedLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003863 }
3864
3865 // Tell the process all about itself.
3866
Joe Onorato8a9b2202010-02-26 18:56:32 -08003867 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003868 TAG, "Binding process pid " + pid + " to record " + app);
3869
3870 String processName = app.processName;
3871 try {
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07003872 AppDeathRecipient adr = new AppDeathRecipient(
3873 app, pid, thread);
3874 thread.asBinder().linkToDeath(adr, 0);
3875 app.deathRecipient = adr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003876 } catch (RemoteException e) {
3877 app.resetPackageList();
3878 startProcessLocked(app, "link fail", processName);
3879 return false;
3880 }
3881
Doug Zongker2bec3d42009-12-04 12:52:44 -08003882 EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.pid, app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003883
3884 app.thread = thread;
3885 app.curAdj = app.setAdj = -100;
Dianne Hackborn09c916b2009-12-08 14:50:51 -08003886 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
3887 app.setSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003888 app.forcingToForeground = null;
3889 app.foregroundServices = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07003890 app.hasShownUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003891 app.debugging = false;
3892
3893 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3894
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003895 boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003896 List providers = normalMode ? generateApplicationProvidersLocked(app) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003897
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003898 if (!normalMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003899 Slog.i(TAG, "Launching preboot mode app: " + app);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003900 }
3901
Joe Onorato8a9b2202010-02-26 18:56:32 -08003902 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003903 TAG, "New app record " + app
3904 + " thread=" + thread.asBinder() + " pid=" + pid);
3905 try {
3906 int testMode = IApplicationThread.DEBUG_OFF;
3907 if (mDebugApp != null && mDebugApp.equals(processName)) {
3908 testMode = mWaitForDebugger
3909 ? IApplicationThread.DEBUG_WAIT
3910 : IApplicationThread.DEBUG_ON;
3911 app.debugging = true;
3912 if (mDebugTransient) {
3913 mDebugApp = mOrigDebugApp;
3914 mWaitForDebugger = mOrigWaitForDebugger;
3915 }
3916 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003917 String profileFile = app.instrumentationProfileFile;
3918 ParcelFileDescriptor profileFd = null;
3919 boolean profileAutoStop = false;
3920 if (mProfileApp != null && mProfileApp.equals(processName)) {
3921 mProfileProc = app;
3922 profileFile = mProfileFile;
3923 profileFd = mProfileFd;
3924 profileAutoStop = mAutoStopProfiler;
3925 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08003926 boolean enableOpenGlTrace = false;
3927 if (mOpenGlTraceApp != null && mOpenGlTraceApp.equals(processName)) {
3928 enableOpenGlTrace = true;
3929 mOpenGlTraceApp = null;
3930 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003931
Christopher Tate181fafa2009-05-14 11:12:14 -07003932 // If the app is being launched for restore or full backup, set it up specially
3933 boolean isRestrictedBackupMode = false;
3934 if (mBackupTarget != null && mBackupAppName.equals(processName)) {
3935 isRestrictedBackupMode = (mBackupTarget.backupMode == BackupRecord.RESTORE)
Christopher Tate75a99702011-05-18 16:28:19 -07003936 || (mBackupTarget.backupMode == BackupRecord.RESTORE_FULL)
Christopher Tate181fafa2009-05-14 11:12:14 -07003937 || (mBackupTarget.backupMode == BackupRecord.BACKUP_FULL);
3938 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003939
Dianne Hackbornd7f6daa2009-06-22 17:06:35 -07003940 ensurePackageDexOpt(app.instrumentationInfo != null
3941 ? app.instrumentationInfo.packageName
3942 : app.info.packageName);
3943 if (app.instrumentationClass != null) {
3944 ensurePackageDexOpt(app.instrumentationClass.getPackageName());
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003945 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08003946 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Binding proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003947 + processName + " with config " + mConfiguration);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003948 ApplicationInfo appInfo = app.instrumentationInfo != null
3949 ? app.instrumentationInfo : app.info;
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -07003950 app.compat = compatibilityInfoForPackageLocked(appInfo);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003951 if (profileFd != null) {
3952 profileFd = profileFd.dup();
3953 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003954 thread.bindApplication(processName, appInfo, providers,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003955 app.instrumentationClass, profileFile, profileFd, profileAutoStop,
Siva Velusamy92a8b222012-03-09 16:24:04 -08003956 app.instrumentationArguments, app.instrumentationWatcher, testMode,
3957 enableOpenGlTrace, isRestrictedBackupMode || !normalMode, app.persistent,
Dianne Hackborn813075a62011-11-14 17:45:19 -08003958 new Configuration(mConfiguration), app.compat, getCommonServicesLocked(),
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08003959 mCoreSettingsObserver.getCoreSettingsLocked());
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003960 updateLruProcessLocked(app, false, true);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003961 app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003962 } catch (Exception e) {
3963 // todo: Yikes! What should we do? For now we will try to
3964 // start another process, but that could easily get us in
3965 // an infinite loop of restarting processes...
Joe Onorato8a9b2202010-02-26 18:56:32 -08003966 Slog.w(TAG, "Exception thrown during bind!", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003967
3968 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07003969 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003970 startProcessLocked(app, "bind fail", processName);
3971 return false;
3972 }
3973
3974 // Remove this record from the list of starting applications.
3975 mPersistentStartingProcesses.remove(app);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003976 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
3977 "Attach application locked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003978 mProcessesOnHold.remove(app);
3979
3980 boolean badApp = false;
3981 boolean didSomething = false;
3982
3983 // See if the top visible activity is waiting to run in this process...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003984 ActivityRecord hr = mMainStack.topRunningActivityLocked(null);
Christopher Tate04c0af82010-06-07 18:35:20 -07003985 if (hr != null && normalMode) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003986 if (hr.app == null && app.uid == hr.info.applicationInfo.uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003987 && processName.equals(hr.processName)) {
3988 try {
Mike Lockwood3a74bd32011-08-12 13:55:22 -07003989 if (mHeadless) {
3990 Slog.e(TAG, "Starting activities not supported on headless device: " + hr);
3991 } else if (mMainStack.realStartActivityLocked(hr, app, true, true)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003992 didSomething = true;
3993 }
3994 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003995 Slog.w(TAG, "Exception in new application when starting activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003996 + hr.intent.getComponent().flattenToShortString(), e);
3997 badApp = true;
3998 }
3999 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004000 mMainStack.ensureActivitiesVisibleLocked(hr, null, processName, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004001 }
4002 }
4003
4004 // Find any services that should be running in this process...
4005 if (!badApp && mPendingServices.size() > 0) {
4006 ServiceRecord sr = null;
4007 try {
4008 for (int i=0; i<mPendingServices.size(); i++) {
4009 sr = mPendingServices.get(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004010 if (app != sr.isolatedProc && (app.uid != sr.appInfo.uid
4011 || !processName.equals(sr.processName))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004012 continue;
4013 }
4014
4015 mPendingServices.remove(i);
4016 i--;
4017 realStartServiceLocked(sr, app);
4018 didSomething = true;
4019 }
4020 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004021 Slog.w(TAG, "Exception in new application when starting service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004022 + sr.shortName, e);
4023 badApp = true;
4024 }
4025 }
4026
Christopher Tatef46723b2012-01-26 14:19:24 -08004027 // Check if a next-broadcast receiver is in this process...
4028 if (!badApp && isPendingBroadcastProcessLocked(pid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004029 try {
Christopher Tatef46723b2012-01-26 14:19:24 -08004030 didSomething = sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004031 } catch (Exception e) {
Christopher Tatef46723b2012-01-26 14:19:24 -08004032 // If the app died trying to launch the receiver we declare it 'bad'
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004033 badApp = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004034 }
4035 }
4036
Christopher Tate181fafa2009-05-14 11:12:14 -07004037 // Check whether the next backup agent is in this process...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004038 if (!badApp && mBackupTarget != null && mBackupTarget.appInfo.uid == app.uid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004039 if (DEBUG_BACKUP) Slog.v(TAG, "New app is backup target, launching agent for " + app);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004040 ensurePackageDexOpt(mBackupTarget.appInfo.packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07004041 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004042 thread.scheduleCreateBackupAgent(mBackupTarget.appInfo,
4043 compatibilityInfoForPackageLocked(mBackupTarget.appInfo),
4044 mBackupTarget.backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -07004045 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004046 Slog.w(TAG, "Exception scheduling backup agent creation: ");
Christopher Tate181fafa2009-05-14 11:12:14 -07004047 e.printStackTrace();
4048 }
4049 }
4050
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004051 if (badApp) {
4052 // todo: Also need to kill application to deal with all
4053 // kinds of exceptions.
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004054 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004055 return false;
4056 }
4057
4058 if (!didSomething) {
4059 updateOomAdjLocked();
4060 }
4061
4062 return true;
4063 }
4064
4065 public final void attachApplication(IApplicationThread thread) {
4066 synchronized (this) {
4067 int callingPid = Binder.getCallingPid();
4068 final long origId = Binder.clearCallingIdentity();
4069 attachApplicationLocked(thread, callingPid);
4070 Binder.restoreCallingIdentity(origId);
4071 }
4072 }
4073
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004074 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004075 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004076 ActivityRecord r = mMainStack.activityIdleInternal(token, false, config);
4077 if (stopProfiling) {
4078 synchronized (this) {
4079 if (mProfileProc == r.app) {
4080 if (mProfileFd != null) {
4081 try {
4082 mProfileFd.close();
4083 } catch (IOException e) {
4084 }
4085 clearProfilerLocked();
4086 }
4087 }
4088 }
4089 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004090 Binder.restoreCallingIdentity(origId);
4091 }
4092
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004093 void enableScreenAfterBoot() {
Doug Zongker2bec3d42009-12-04 12:52:44 -08004094 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004095 SystemClock.uptimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004096 mWindowManager.enableScreenAfterBoot();
4097 }
4098
Dianne Hackborn661cd522011-08-22 00:26:20 -07004099 public void showBootMessage(final CharSequence msg, final boolean always) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004100 enforceNotIsolatedCaller("showBootMessage");
Dianne Hackborn661cd522011-08-22 00:26:20 -07004101 mWindowManager.showBootMessage(msg, always);
4102 }
4103
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004104 public void dismissKeyguardOnNextActivity() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004105 enforceNotIsolatedCaller("dismissKeyguardOnNextActivity");
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004106 synchronized (this) {
4107 mMainStack.dismissKeyguardOnNextActivityLocked();
4108 }
4109 }
4110
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004111 final void finishBooting() {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004112 IntentFilter pkgFilter = new IntentFilter();
4113 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
4114 pkgFilter.addDataScheme("package");
4115 mContext.registerReceiver(new BroadcastReceiver() {
4116 @Override
4117 public void onReceive(Context context, Intent intent) {
4118 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
4119 if (pkgs != null) {
4120 for (String pkg : pkgs) {
Vairavan Srinivasan61f07652010-07-22 13:36:40 -07004121 synchronized (ActivityManagerService.this) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07004122 if (forceStopPackageLocked(pkg, -1, false, false, false, false, 0)) {
4123 setResultCode(Activity.RESULT_OK);
4124 return;
4125 }
4126 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004127 }
4128 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004129 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004130 }, pkgFilter);
Amith Yamasani13593602012-03-22 16:16:17 -07004131
4132 IntentFilter userFilter = new IntentFilter();
4133 userFilter.addAction(Intent.ACTION_USER_REMOVED);
4134 mContext.registerReceiver(new BroadcastReceiver() {
4135 @Override
4136 public void onReceive(Context context, Intent intent) {
4137 onUserRemoved(intent);
4138 }
4139 }, userFilter);
4140
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004141 synchronized (this) {
4142 // Ensure that any processes we had put on hold are now started
4143 // up.
4144 final int NP = mProcessesOnHold.size();
4145 if (NP > 0) {
4146 ArrayList<ProcessRecord> procs =
4147 new ArrayList<ProcessRecord>(mProcessesOnHold);
4148 for (int ip=0; ip<NP; ip++) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004149 if (DEBUG_PROCESSES) Slog.v(TAG, "Starting process on hold: "
4150 + procs.get(ip));
4151 startProcessLocked(procs.get(ip), "on-hold", null);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004152 }
4153 }
4154
4155 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004156 // Start looking for apps that are abusing wake locks.
4157 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07004158 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004159 // Tell anyone interested that we are done booting!
Dianne Hackbornf4c454b2010-08-11 12:47:41 -07004160 SystemProperties.set("sys.boot_completed", "1");
Guang Zhu191713a2012-01-12 12:02:22 -08004161 SystemProperties.set("dev.bootcomplete", "1");
Amith Yamasani742a6712011-05-04 14:49:28 -07004162 /* TODO: Send this to all users that are to be logged in on startup */
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004163 broadcastIntentLocked(null, null,
4164 new Intent(Intent.ACTION_BOOT_COMPLETED, null),
4165 null, null, 0, null, null,
4166 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
Amith Yamasani742a6712011-05-04 14:49:28 -07004167 false, false, MY_PID, Process.SYSTEM_UID, Binder.getOrigCallingUser());
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004168 }
4169 }
4170 }
4171
4172 final void ensureBootCompleted() {
4173 boolean booting;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004174 boolean enableScreen;
4175 synchronized (this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004176 booting = mBooting;
4177 mBooting = false;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004178 enableScreen = !mBooted;
4179 mBooted = true;
4180 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004181
4182 if (booting) {
4183 finishBooting();
4184 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004185
4186 if (enableScreen) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004187 enableScreenAfterBoot();
4188 }
4189 }
4190
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004191 public final void activityPaused(IBinder token) {
4192 final long origId = Binder.clearCallingIdentity();
4193 mMainStack.activityPaused(token, false);
4194 Binder.restoreCallingIdentity(origId);
4195 }
4196
4197 public final void activityStopped(IBinder token, Bundle icicle, Bitmap thumbnail,
4198 CharSequence description) {
4199 if (localLOGV) Slog.v(
4200 TAG, "Activity stopped: token=" + token);
4201
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004202 // Refuse possible leaked file descriptors
4203 if (icicle != null && icicle.hasFileDescriptors()) {
4204 throw new IllegalArgumentException("File descriptors passed in Bundle");
4205 }
4206
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004207 ActivityRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004208
4209 final long origId = Binder.clearCallingIdentity();
4210
4211 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004212 r = mMainStack.isInStackLocked(token);
4213 if (r != null) {
4214 r.stack.activityStoppedLocked(r, icicle, thumbnail, description);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004215 }
4216 }
4217
4218 if (r != null) {
4219 sendPendingThumbnail(r, null, null, null, false);
4220 }
4221
4222 trimApplications();
4223
4224 Binder.restoreCallingIdentity(origId);
4225 }
4226
4227 public final void activityDestroyed(IBinder token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004228 if (DEBUG_SWITCH) Slog.v(TAG, "ACTIVITY DESTROYED: " + token);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004229 mMainStack.activityDestroyed(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004230 }
4231
4232 public String getCallingPackage(IBinder token) {
4233 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004234 ActivityRecord r = getCallingRecordLocked(token);
Dianne Hackborn9bbcb912009-10-20 15:42:38 -07004235 return r != null && r.app != null ? r.info.packageName : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004236 }
4237 }
4238
4239 public ComponentName getCallingActivity(IBinder token) {
4240 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004241 ActivityRecord r = getCallingRecordLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004242 return r != null ? r.intent.getComponent() : null;
4243 }
4244 }
4245
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004246 private ActivityRecord getCallingRecordLocked(IBinder token) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004247 ActivityRecord r = mMainStack.isInStackLocked(token);
4248 if (r == null) {
4249 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004250 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004251 return r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004252 }
4253
4254 public ComponentName getActivityClassForToken(IBinder token) {
4255 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004256 ActivityRecord r = mMainStack.isInStackLocked(token);
4257 if (r == null) {
4258 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004259 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004260 return r.intent.getComponent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004261 }
4262 }
4263
4264 public String getPackageForToken(IBinder token) {
4265 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004266 ActivityRecord r = mMainStack.isInStackLocked(token);
4267 if (r == null) {
4268 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004269 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004270 return r.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004271 }
4272 }
4273
4274 public IIntentSender getIntentSender(int type,
4275 String packageName, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004276 int requestCode, Intent[] intents, String[] resolvedTypes,
4277 int flags, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004278 enforceNotIsolatedCaller("getIntentSender");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004279 // Refuse possible leaked file descriptors
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004280 if (intents != null) {
4281 if (intents.length < 1) {
4282 throw new IllegalArgumentException("Intents array length must be >= 1");
4283 }
4284 for (int i=0; i<intents.length; i++) {
4285 Intent intent = intents[i];
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004286 if (intent != null) {
4287 if (intent.hasFileDescriptors()) {
4288 throw new IllegalArgumentException("File descriptors passed in Intent");
4289 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07004290 if (type == ActivityManager.INTENT_SENDER_BROADCAST &&
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004291 (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
4292 throw new IllegalArgumentException(
4293 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
4294 }
4295 intents[i] = new Intent(intent);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004296 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004297 }
4298 if (resolvedTypes != null && resolvedTypes.length != intents.length) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004299 throw new IllegalArgumentException(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004300 "Intent array length does not match resolvedTypes length");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004301 }
4302 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004303 if (options != null) {
4304 if (options.hasFileDescriptors()) {
4305 throw new IllegalArgumentException("File descriptors passed in options");
4306 }
4307 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004308
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004309 synchronized(this) {
4310 int callingUid = Binder.getCallingUid();
4311 try {
Jeff Brown10e89712011-07-08 18:52:57 -07004312 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004313 int uid = AppGlobals.getPackageManager()
Amith Yamasani483f3b02012-03-13 16:08:00 -07004314 .getPackageUid(packageName, UserId.getUserId(callingUid));
4315 if (!UserId.isSameApp(callingUid, uid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004316 String msg = "Permission Denial: getIntentSender() from pid="
4317 + Binder.getCallingPid()
4318 + ", uid=" + Binder.getCallingUid()
4319 + ", (need uid=" + uid + ")"
4320 + " is not allowed to send as package " + packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004321 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004322 throw new SecurityException(msg);
4323 }
4324 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004325
Amith Yamasani742a6712011-05-04 14:49:28 -07004326 if (DEBUG_MU)
4327 Slog.i(TAG_MU, "Getting intent sender for origCallingUid="
4328 + Binder.getOrigCallingUid());
4329 return getIntentSenderLocked(type, packageName, Binder.getOrigCallingUid(),
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004330 token, resultWho, requestCode, intents, resolvedTypes, flags, options);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004331
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004332 } catch (RemoteException e) {
4333 throw new SecurityException(e);
4334 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004335 }
4336 }
4337
4338 IIntentSender getIntentSenderLocked(int type,
4339 String packageName, int callingUid, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004340 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
4341 Bundle options) {
Amith Yamasani742a6712011-05-04 14:49:28 -07004342 if (DEBUG_MU)
4343 Slog.v(TAG_MU, "getIntentSenderLocked(): uid=" + callingUid);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004344 ActivityRecord activity = null;
Dianne Hackborna4972e92012-03-14 10:38:05 -07004345 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004346 activity = mMainStack.isInStackLocked(token);
4347 if (activity == null) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004348 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004349 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004350 if (activity.finishing) {
4351 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004352 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004353 }
4354
4355 final boolean noCreate = (flags&PendingIntent.FLAG_NO_CREATE) != 0;
4356 final boolean cancelCurrent = (flags&PendingIntent.FLAG_CANCEL_CURRENT) != 0;
4357 final boolean updateCurrent = (flags&PendingIntent.FLAG_UPDATE_CURRENT) != 0;
4358 flags &= ~(PendingIntent.FLAG_NO_CREATE|PendingIntent.FLAG_CANCEL_CURRENT
4359 |PendingIntent.FLAG_UPDATE_CURRENT);
4360
4361 PendingIntentRecord.Key key = new PendingIntentRecord.Key(
4362 type, packageName, activity, resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004363 requestCode, intents, resolvedTypes, flags, options);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004364 WeakReference<PendingIntentRecord> ref;
4365 ref = mIntentSenderRecords.get(key);
4366 PendingIntentRecord rec = ref != null ? ref.get() : null;
4367 if (rec != null) {
4368 if (!cancelCurrent) {
4369 if (updateCurrent) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004370 if (rec.key.requestIntent != null) {
4371 rec.key.requestIntent.replaceExtras(intents != null ? intents[0] : null);
4372 }
4373 if (intents != null) {
4374 intents[intents.length-1] = rec.key.requestIntent;
4375 rec.key.allIntents = intents;
4376 rec.key.allResolvedTypes = resolvedTypes;
4377 } else {
4378 rec.key.allIntents = null;
4379 rec.key.allResolvedTypes = null;
4380 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004381 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004382 return rec;
4383 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004384 rec.canceled = true;
4385 mIntentSenderRecords.remove(key);
4386 }
4387 if (noCreate) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004388 return rec;
4389 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004390 rec = new PendingIntentRecord(this, key, callingUid);
4391 mIntentSenderRecords.put(key, rec.ref);
Dianne Hackborna4972e92012-03-14 10:38:05 -07004392 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004393 if (activity.pendingResults == null) {
4394 activity.pendingResults
4395 = new HashSet<WeakReference<PendingIntentRecord>>();
4396 }
4397 activity.pendingResults.add(rec.ref);
4398 }
4399 return rec;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004400 }
4401
4402 public void cancelIntentSender(IIntentSender sender) {
4403 if (!(sender instanceof PendingIntentRecord)) {
4404 return;
4405 }
4406 synchronized(this) {
4407 PendingIntentRecord rec = (PendingIntentRecord)sender;
4408 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004409 int uid = AppGlobals.getPackageManager()
Amith Yamasani483f3b02012-03-13 16:08:00 -07004410 .getPackageUid(rec.key.packageName, UserId.getCallingUserId());
Amith Yamasani04e0d262012-02-14 11:50:53 -08004411 if (!UserId.isSameApp(uid, Binder.getCallingUid())) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004412 String msg = "Permission Denial: cancelIntentSender() from pid="
4413 + Binder.getCallingPid()
4414 + ", uid=" + Binder.getCallingUid()
4415 + " is not allowed to cancel packges "
4416 + rec.key.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004417 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004418 throw new SecurityException(msg);
4419 }
4420 } catch (RemoteException e) {
4421 throw new SecurityException(e);
4422 }
4423 cancelIntentSenderLocked(rec, true);
4424 }
4425 }
4426
4427 void cancelIntentSenderLocked(PendingIntentRecord rec, boolean cleanActivity) {
4428 rec.canceled = true;
4429 mIntentSenderRecords.remove(rec.key);
4430 if (cleanActivity && rec.key.activity != null) {
4431 rec.key.activity.pendingResults.remove(rec.ref);
4432 }
4433 }
4434
4435 public String getPackageForIntentSender(IIntentSender pendingResult) {
4436 if (!(pendingResult instanceof PendingIntentRecord)) {
4437 return null;
4438 }
Brad Fitzpatrickb213d102010-04-19 11:58:52 -07004439 try {
4440 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4441 return res.key.packageName;
4442 } catch (ClassCastException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004443 }
4444 return null;
4445 }
4446
Christopher Tatec4a07d12012-04-06 14:19:13 -07004447 public int getUidForIntentSender(IIntentSender sender) {
4448 if (sender instanceof PendingIntentRecord) {
4449 try {
4450 PendingIntentRecord res = (PendingIntentRecord)sender;
4451 return res.uid;
4452 } catch (ClassCastException e) {
4453 }
4454 }
4455 return -1;
4456 }
4457
Dianne Hackborn6c418d52011-06-29 14:05:33 -07004458 public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) {
4459 if (!(pendingResult instanceof PendingIntentRecord)) {
4460 return false;
4461 }
4462 try {
4463 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4464 if (res.key.allIntents == null) {
4465 return false;
4466 }
4467 for (int i=0; i<res.key.allIntents.length; i++) {
4468 Intent intent = res.key.allIntents[i];
4469 if (intent.getPackage() != null && intent.getComponent() != null) {
4470 return false;
4471 }
4472 }
4473 return true;
4474 } catch (ClassCastException e) {
4475 }
4476 return false;
4477 }
4478
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004479 public void setProcessLimit(int max) {
4480 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4481 "setProcessLimit()");
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004482 synchronized (this) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07004483 mProcessLimit = max < 0 ? ProcessList.MAX_HIDDEN_APPS : max;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004484 mProcessLimitOverride = max;
4485 }
4486 trimApplications();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004487 }
4488
4489 public int getProcessLimit() {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004490 synchronized (this) {
4491 return mProcessLimitOverride;
4492 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004493 }
4494
4495 void foregroundTokenDied(ForegroundToken token) {
4496 synchronized (ActivityManagerService.this) {
4497 synchronized (mPidsSelfLocked) {
4498 ForegroundToken cur
4499 = mForegroundProcesses.get(token.pid);
4500 if (cur != token) {
4501 return;
4502 }
4503 mForegroundProcesses.remove(token.pid);
4504 ProcessRecord pr = mPidsSelfLocked.get(token.pid);
4505 if (pr == null) {
4506 return;
4507 }
4508 pr.forcingToForeground = null;
4509 pr.foregroundServices = false;
4510 }
4511 updateOomAdjLocked();
4512 }
4513 }
4514
4515 public void setProcessForeground(IBinder token, int pid, boolean isForeground) {
4516 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4517 "setProcessForeground()");
4518 synchronized(this) {
4519 boolean changed = false;
4520
4521 synchronized (mPidsSelfLocked) {
4522 ProcessRecord pr = mPidsSelfLocked.get(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004523 if (pr == null && isForeground) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004524 Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004525 return;
4526 }
4527 ForegroundToken oldToken = mForegroundProcesses.get(pid);
4528 if (oldToken != null) {
4529 oldToken.token.unlinkToDeath(oldToken, 0);
4530 mForegroundProcesses.remove(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004531 if (pr != null) {
4532 pr.forcingToForeground = null;
4533 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004534 changed = true;
4535 }
4536 if (isForeground && token != null) {
4537 ForegroundToken newToken = new ForegroundToken() {
4538 public void binderDied() {
4539 foregroundTokenDied(this);
4540 }
4541 };
4542 newToken.pid = pid;
4543 newToken.token = token;
4544 try {
4545 token.linkToDeath(newToken, 0);
4546 mForegroundProcesses.put(pid, newToken);
4547 pr.forcingToForeground = token;
4548 changed = true;
4549 } catch (RemoteException e) {
4550 // If the process died while doing this, we will later
4551 // do the cleanup with the process death link.
4552 }
4553 }
4554 }
4555
4556 if (changed) {
4557 updateOomAdjLocked();
4558 }
4559 }
4560 }
4561
4562 // =========================================================
4563 // PERMISSIONS
4564 // =========================================================
4565
4566 static class PermissionController extends IPermissionController.Stub {
4567 ActivityManagerService mActivityManagerService;
4568 PermissionController(ActivityManagerService activityManagerService) {
4569 mActivityManagerService = activityManagerService;
4570 }
4571
4572 public boolean checkPermission(String permission, int pid, int uid) {
4573 return mActivityManagerService.checkPermission(permission, pid,
4574 uid) == PackageManager.PERMISSION_GRANTED;
4575 }
4576 }
4577
4578 /**
4579 * This can be called with or without the global lock held.
4580 */
4581 int checkComponentPermission(String permission, int pid, int uid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004582 int owningUid, boolean exported) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004583 // We might be performing an operation on behalf of an indirect binder
4584 // invocation, e.g. via {@link #openContentUri}. Check and adjust the
4585 // client identity accordingly before proceeding.
4586 Identity tlsIdentity = sCallerIdentity.get();
4587 if (tlsIdentity != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004588 Slog.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004589 + tlsIdentity.pid + "," + tlsIdentity.uid + "}");
4590 uid = tlsIdentity.uid;
4591 pid = tlsIdentity.pid;
4592 }
4593
4594 // Root, system server and our own process get to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07004595 if (uid == 0 || uid == Process.SYSTEM_UID || pid == MY_PID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004596 return PackageManager.PERMISSION_GRANTED;
4597 }
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004598 // Isolated processes don't get any permissions.
4599 if (UserId.isIsolated(uid)) {
4600 return PackageManager.PERMISSION_DENIED;
4601 }
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004602 // If there is a uid that owns whatever is being accessed, it has
4603 // blanket access to it regardless of the permissions it requires.
Amith Yamasani742a6712011-05-04 14:49:28 -07004604 if (owningUid >= 0 && UserId.isSameApp(uid, owningUid)) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004605 return PackageManager.PERMISSION_GRANTED;
4606 }
4607 // If the target is not exported, then nobody else can get to it.
4608 if (!exported) {
4609 Slog.w(TAG, "Permission denied: checkComponentPermission() owningUid=" + owningUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004610 return PackageManager.PERMISSION_DENIED;
4611 }
4612 if (permission == null) {
4613 return PackageManager.PERMISSION_GRANTED;
4614 }
4615 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004616 return AppGlobals.getPackageManager()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004617 .checkUidPermission(permission, uid);
4618 } catch (RemoteException e) {
4619 // Should never happen, but if it does... deny!
Joe Onorato8a9b2202010-02-26 18:56:32 -08004620 Slog.e(TAG, "PackageManager is dead?!?", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004621 }
4622 return PackageManager.PERMISSION_DENIED;
4623 }
4624
4625 /**
4626 * As the only public entry point for permissions checking, this method
4627 * can enforce the semantic that requesting a check on a null global
4628 * permission is automatically denied. (Internally a null permission
4629 * string is used when calling {@link #checkComponentPermission} in cases
4630 * when only uid-based security is needed.)
4631 *
4632 * This can be called with or without the global lock held.
4633 */
4634 public int checkPermission(String permission, int pid, int uid) {
4635 if (permission == null) {
4636 return PackageManager.PERMISSION_DENIED;
4637 }
Amith Yamasani742a6712011-05-04 14:49:28 -07004638 return checkComponentPermission(permission, pid, UserId.getAppId(uid), -1, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004639 }
4640
4641 /**
4642 * Binder IPC calls go through the public entry point.
4643 * This can be called with or without the global lock held.
4644 */
4645 int checkCallingPermission(String permission) {
4646 return checkPermission(permission,
4647 Binder.getCallingPid(),
Amith Yamasani742a6712011-05-04 14:49:28 -07004648 UserId.getAppId(Binder.getCallingUid()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004649 }
4650
4651 /**
4652 * This can be called with or without the global lock held.
4653 */
4654 void enforceCallingPermission(String permission, String func) {
4655 if (checkCallingPermission(permission)
4656 == PackageManager.PERMISSION_GRANTED) {
4657 return;
4658 }
4659
4660 String msg = "Permission Denial: " + func + " from pid="
4661 + Binder.getCallingPid()
4662 + ", uid=" + Binder.getCallingUid()
4663 + " requires " + permission;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004664 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004665 throw new SecurityException(msg);
4666 }
4667
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004668 /**
4669 * Determine if UID is holding permissions required to access {@link Uri} in
4670 * the given {@link ProviderInfo}. Final permission checking is always done
4671 * in {@link ContentProvider}.
4672 */
4673 private final boolean checkHoldingPermissionsLocked(
4674 IPackageManager pm, ProviderInfo pi, Uri uri, int uid, int modeFlags) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004675 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4676 "checkHoldingPermissionsLocked: uri=" + uri + " uid=" + uid);
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004677
4678 if (pi.applicationInfo.uid == uid) {
4679 return true;
4680 } else if (!pi.exported) {
4681 return false;
4682 }
4683
4684 boolean readMet = (modeFlags & Intent.FLAG_GRANT_READ_URI_PERMISSION) == 0;
4685 boolean writeMet = (modeFlags & Intent.FLAG_GRANT_WRITE_URI_PERMISSION) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004686 try {
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004687 // check if target holds top-level <provider> permissions
4688 if (!readMet && pi.readPermission != null
4689 && (pm.checkUidPermission(pi.readPermission, uid) == PERMISSION_GRANTED)) {
4690 readMet = true;
4691 }
4692 if (!writeMet && pi.writePermission != null
4693 && (pm.checkUidPermission(pi.writePermission, uid) == PERMISSION_GRANTED)) {
4694 writeMet = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004695 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004696
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004697 // track if unprotected read/write is allowed; any denied
4698 // <path-permission> below removes this ability
4699 boolean allowDefaultRead = pi.readPermission == null;
4700 boolean allowDefaultWrite = pi.writePermission == null;
Dianne Hackborn48058e82010-09-27 16:53:23 -07004701
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004702 // check if target holds any <path-permission> that match uri
4703 final PathPermission[] pps = pi.pathPermissions;
4704 if (pps != null) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004705 final String path = uri.getPath();
4706 int i = pps.length;
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004707 while (i > 0 && (!readMet || !writeMet)) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004708 i--;
4709 PathPermission pp = pps[i];
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004710 if (pp.match(path)) {
4711 if (!readMet) {
4712 final String pprperm = pp.getReadPermission();
4713 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking read perm for "
4714 + pprperm + " for " + pp.getPath()
4715 + ": match=" + pp.match(path)
4716 + " check=" + pm.checkUidPermission(pprperm, uid));
4717 if (pprperm != null) {
4718 if (pm.checkUidPermission(pprperm, uid) == PERMISSION_GRANTED) {
4719 readMet = true;
4720 } else {
4721 allowDefaultRead = false;
4722 }
4723 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004724 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004725 if (!writeMet) {
4726 final String ppwperm = pp.getWritePermission();
4727 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking write perm "
4728 + ppwperm + " for " + pp.getPath()
4729 + ": match=" + pp.match(path)
4730 + " check=" + pm.checkUidPermission(ppwperm, uid));
4731 if (ppwperm != null) {
4732 if (pm.checkUidPermission(ppwperm, uid) == PERMISSION_GRANTED) {
4733 writeMet = true;
4734 } else {
4735 allowDefaultWrite = false;
4736 }
4737 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004738 }
4739 }
4740 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07004741 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004742
4743 // grant unprotected <provider> read/write, if not blocked by
4744 // <path-permission> above
4745 if (allowDefaultRead) readMet = true;
4746 if (allowDefaultWrite) writeMet = true;
4747
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004748 } catch (RemoteException e) {
4749 return false;
4750 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004751
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004752 return readMet && writeMet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004753 }
4754
4755 private final boolean checkUriPermissionLocked(Uri uri, int uid,
4756 int modeFlags) {
4757 // Root gets to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07004758 if (uid == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004759 return true;
4760 }
4761 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(uid);
4762 if (perms == null) return false;
4763 UriPermission perm = perms.get(uri);
4764 if (perm == null) return false;
4765 return (modeFlags&perm.modeFlags) == modeFlags;
4766 }
4767
4768 public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004769 enforceNotIsolatedCaller("checkUriPermission");
4770
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004771 // Another redirected-binder-call permissions check as in
4772 // {@link checkComponentPermission}.
4773 Identity tlsIdentity = sCallerIdentity.get();
4774 if (tlsIdentity != null) {
4775 uid = tlsIdentity.uid;
4776 pid = tlsIdentity.pid;
4777 }
4778
Amith Yamasani742a6712011-05-04 14:49:28 -07004779 uid = UserId.getAppId(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004780 // Our own process gets to do everything.
4781 if (pid == MY_PID) {
4782 return PackageManager.PERMISSION_GRANTED;
4783 }
4784 synchronized(this) {
4785 return checkUriPermissionLocked(uri, uid, modeFlags)
4786 ? PackageManager.PERMISSION_GRANTED
4787 : PackageManager.PERMISSION_DENIED;
4788 }
4789 }
4790
Dianne Hackborn39792d22010-08-19 18:01:52 -07004791 /**
4792 * Check if the targetPkg can be granted permission to access uri by
4793 * the callingUid using the given modeFlags. Throws a security exception
4794 * if callingUid is not allowed to do this. Returns the uid of the target
4795 * if the URI permission grant should be performed; returns -1 if it is not
4796 * needed (for example targetPkg already has permission to access the URI).
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004797 * If you already know the uid of the target, you can supply it in
4798 * lastTargetUid else set that to -1.
Dianne Hackborn39792d22010-08-19 18:01:52 -07004799 */
4800 int checkGrantUriPermissionLocked(int callingUid, String targetPkg,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004801 Uri uri, int modeFlags, int lastTargetUid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004802 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4803 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4804 if (modeFlags == 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004805 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004806 }
4807
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004808 if (targetPkg != null) {
4809 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4810 "Checking grant " + targetPkg + " permission to " + uri);
4811 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004812
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004813 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004814
4815 // If this is not a content: uri, we can't do anything with it.
4816 if (!ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004817 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004818 "Can't grant URI permission for non-content URI: " + uri);
Dianne Hackborn39792d22010-08-19 18:01:52 -07004819 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004820 }
4821
4822 String name = uri.getAuthority();
4823 ProviderInfo pi = null;
Amith Yamasani742a6712011-05-04 14:49:28 -07004824 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
4825 UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004826 if (cpr != null) {
4827 pi = cpr.info;
4828 } else {
4829 try {
4830 pi = pm.resolveContentProvider(name,
Amith Yamasani483f3b02012-03-13 16:08:00 -07004831 PackageManager.GET_URI_PERMISSION_PATTERNS, UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004832 } catch (RemoteException ex) {
4833 }
4834 }
4835 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07004836 Slog.w(TAG, "No content provider found for permission check: " + uri.toSafeString());
Dianne Hackborn39792d22010-08-19 18:01:52 -07004837 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004838 }
4839
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004840 int targetUid = lastTargetUid;
4841 if (targetUid < 0 && targetPkg != null) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004842 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07004843 targetUid = pm.getPackageUid(targetPkg, UserId.getUserId(callingUid));
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004844 if (targetUid < 0) {
4845 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4846 "Can't grant URI permission no uid for: " + targetPkg);
4847 return -1;
4848 }
4849 } catch (RemoteException ex) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004850 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004851 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004852 }
4853
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004854 if (targetUid >= 0) {
4855 // First... does the target actually need this permission?
4856 if (checkHoldingPermissionsLocked(pm, pi, uri, targetUid, modeFlags)) {
4857 // No need to grant the target this permission.
4858 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4859 "Target " + targetPkg + " already has full permission to " + uri);
4860 return -1;
4861 }
4862 } else {
4863 // First... there is no target package, so can anyone access it?
4864 boolean allowed = pi.exported;
4865 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
4866 if (pi.readPermission != null) {
4867 allowed = false;
4868 }
4869 }
4870 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
4871 if (pi.writePermission != null) {
4872 allowed = false;
4873 }
4874 }
4875 if (allowed) {
4876 return -1;
4877 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004878 }
4879
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004880 // Second... is the provider allowing granting of URI permissions?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004881 if (!pi.grantUriPermissions) {
4882 throw new SecurityException("Provider " + pi.packageName
4883 + "/" + pi.name
4884 + " does not allow granting of Uri permissions (uri "
4885 + uri + ")");
4886 }
4887 if (pi.uriPermissionPatterns != null) {
4888 final int N = pi.uriPermissionPatterns.length;
4889 boolean allowed = false;
4890 for (int i=0; i<N; i++) {
4891 if (pi.uriPermissionPatterns[i] != null
4892 && pi.uriPermissionPatterns[i].match(uri.getPath())) {
4893 allowed = true;
4894 break;
4895 }
4896 }
4897 if (!allowed) {
4898 throw new SecurityException("Provider " + pi.packageName
4899 + "/" + pi.name
4900 + " does not allow granting of permission to path of Uri "
4901 + uri);
4902 }
4903 }
4904
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004905 // Third... does the caller itself have permission to access
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004906 // this uri?
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004907 if (callingUid != Process.myUid()) {
4908 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
4909 if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
4910 throw new SecurityException("Uid " + callingUid
4911 + " does not have permission to uri " + uri);
4912 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004913 }
4914 }
4915
Dianne Hackborn39792d22010-08-19 18:01:52 -07004916 return targetUid;
4917 }
4918
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004919 public int checkGrantUriPermission(int callingUid, String targetPkg,
4920 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004921 enforceNotIsolatedCaller("checkGrantUriPermission");
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004922 synchronized(this) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004923 return checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004924 }
4925 }
4926
Dianne Hackborn39792d22010-08-19 18:01:52 -07004927 void grantUriPermissionUncheckedLocked(int targetUid, String targetPkg,
4928 Uri uri, int modeFlags, UriPermissionOwner owner) {
4929 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4930 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4931 if (modeFlags == 0) {
4932 return;
4933 }
4934
4935 // So here we are: the caller has the assumed permission
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004936 // to the uri, and the target doesn't. Let's now give this to
4937 // the target.
4938
Joe Onorato8a9b2202010-02-26 18:56:32 -08004939 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn39792d22010-08-19 18:01:52 -07004940 "Granting " + targetPkg + "/" + targetUid + " permission to " + uri);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004941
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004942 HashMap<Uri, UriPermission> targetUris
4943 = mGrantedUriPermissions.get(targetUid);
4944 if (targetUris == null) {
4945 targetUris = new HashMap<Uri, UriPermission>();
4946 mGrantedUriPermissions.put(targetUid, targetUris);
4947 }
4948
4949 UriPermission perm = targetUris.get(uri);
4950 if (perm == null) {
4951 perm = new UriPermission(targetUid, uri);
4952 targetUris.put(uri, perm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004953 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07004954
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004955 perm.modeFlags |= modeFlags;
Dianne Hackborn39792d22010-08-19 18:01:52 -07004956 if (owner == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004957 perm.globalModeFlags |= modeFlags;
Vairavan Srinivasan91c12c22011-01-21 18:26:06 -08004958 } else {
4959 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
4960 perm.readOwners.add(owner);
4961 owner.addReadPermission(perm);
4962 }
4963 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
4964 perm.writeOwners.add(owner);
4965 owner.addWritePermission(perm);
4966 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004967 }
4968 }
4969
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004970 void grantUriPermissionLocked(int callingUid, String targetPkg, Uri uri,
4971 int modeFlags, UriPermissionOwner owner) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004972 if (targetPkg == null) {
4973 throw new NullPointerException("targetPkg");
4974 }
4975
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004976 int targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn39792d22010-08-19 18:01:52 -07004977 if (targetUid < 0) {
4978 return;
4979 }
4980
4981 grantUriPermissionUncheckedLocked(targetUid, targetPkg, uri, modeFlags, owner);
4982 }
4983
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004984 static class NeededUriGrants extends ArrayList<Uri> {
4985 final String targetPkg;
4986 final int targetUid;
4987 final int flags;
4988
4989 NeededUriGrants(String _targetPkg, int _targetUid, int _flags) {
4990 targetPkg = _targetPkg;
4991 targetUid = _targetUid;
4992 flags = _flags;
4993 }
4994 }
4995
Dianne Hackborn39792d22010-08-19 18:01:52 -07004996 /**
4997 * Like checkGrantUriPermissionLocked, but takes an Intent.
4998 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004999 NeededUriGrants checkGrantUriPermissionFromIntentLocked(int callingUid,
5000 String targetPkg, Intent intent, int mode, NeededUriGrants needed) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07005001 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005002 "Checking URI perm to data=" + (intent != null ? intent.getData() : null)
5003 + " clip=" + (intent != null ? intent.getClipData() : null)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005004 + " from " + intent + "; flags=0x"
5005 + Integer.toHexString(intent != null ? intent.getFlags() : 0));
5006
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005007 if (targetPkg == null) {
5008 throw new NullPointerException("targetPkg");
5009 }
5010
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005011 if (intent == null) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005012 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005013 }
5014 Uri data = intent.getData();
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005015 ClipData clip = intent.getClipData();
5016 if (data == null && clip == null) {
5017 return null;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005018 }
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005019 if (data != null) {
5020 int target = checkGrantUriPermissionLocked(callingUid, targetPkg, data,
5021 mode, needed != null ? needed.targetUid : -1);
5022 if (target > 0) {
5023 if (needed == null) {
5024 needed = new NeededUriGrants(targetPkg, target, mode);
5025 }
5026 needed.add(data);
5027 }
5028 }
5029 if (clip != null) {
5030 for (int i=0; i<clip.getItemCount(); i++) {
5031 Uri uri = clip.getItemAt(i).getUri();
5032 if (uri != null) {
5033 int target = -1;
5034 target = checkGrantUriPermissionLocked(callingUid, targetPkg, uri,
5035 mode, needed != null ? needed.targetUid : -1);
5036 if (target > 0) {
5037 if (needed == null) {
5038 needed = new NeededUriGrants(targetPkg, target, mode);
5039 }
5040 needed.add(uri);
5041 }
5042 } else {
5043 Intent clipIntent = clip.getItemAt(i).getIntent();
5044 if (clipIntent != null) {
5045 NeededUriGrants newNeeded = checkGrantUriPermissionFromIntentLocked(
5046 callingUid, targetPkg, clipIntent, mode, needed);
5047 if (newNeeded != null) {
5048 needed = newNeeded;
5049 }
5050 }
5051 }
5052 }
5053 }
5054
5055 return needed;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005056 }
5057
5058 /**
5059 * Like grantUriPermissionUncheckedLocked, but takes an Intent.
5060 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005061 void grantUriPermissionUncheckedFromIntentLocked(NeededUriGrants needed,
5062 UriPermissionOwner owner) {
5063 if (needed != null) {
5064 for (int i=0; i<needed.size(); i++) {
5065 grantUriPermissionUncheckedLocked(needed.targetUid, needed.targetPkg,
5066 needed.get(i), needed.flags, owner);
5067 }
5068 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005069 }
5070
5071 void grantUriPermissionFromIntentLocked(int callingUid,
5072 String targetPkg, Intent intent, UriPermissionOwner owner) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005073 NeededUriGrants needed = checkGrantUriPermissionFromIntentLocked(callingUid, targetPkg,
Dianne Hackbornd9781fe2012-03-08 18:04:18 -08005074 intent, intent != null ? intent.getFlags() : 0, null);
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005075 if (needed == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005076 return;
5077 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005078
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005079 grantUriPermissionUncheckedFromIntentLocked(needed, owner);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005080 }
5081
5082 public void grantUriPermission(IApplicationThread caller, String targetPkg,
5083 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005084 enforceNotIsolatedCaller("grantUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005085 synchronized(this) {
5086 final ProcessRecord r = getRecordForAppLocked(caller);
5087 if (r == null) {
5088 throw new SecurityException("Unable to find app for caller "
5089 + caller
5090 + " when granting permission to uri " + uri);
5091 }
5092 if (targetPkg == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005093 throw new IllegalArgumentException("null target");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005094 }
5095 if (uri == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005096 throw new IllegalArgumentException("null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005097 }
5098
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005099 grantUriPermissionLocked(r.uid, targetPkg, uri, modeFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005100 null);
5101 }
5102 }
5103
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005104 void removeUriPermissionIfNeededLocked(UriPermission perm) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005105 if ((perm.modeFlags&(Intent.FLAG_GRANT_READ_URI_PERMISSION
5106 |Intent.FLAG_GRANT_WRITE_URI_PERMISSION)) == 0) {
5107 HashMap<Uri, UriPermission> perms
5108 = mGrantedUriPermissions.get(perm.uid);
5109 if (perms != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005110 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005111 "Removing " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005112 perms.remove(perm.uri);
5113 if (perms.size() == 0) {
5114 mGrantedUriPermissions.remove(perm.uid);
5115 }
5116 }
5117 }
5118 }
5119
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005120 private void revokeUriPermissionLocked(int callingUid, Uri uri,
5121 int modeFlags) {
5122 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5123 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5124 if (modeFlags == 0) {
5125 return;
5126 }
5127
Joe Onorato8a9b2202010-02-26 18:56:32 -08005128 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005129 "Revoking all granted permissions to " + uri);
5130
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005131 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005132
5133 final String authority = uri.getAuthority();
5134 ProviderInfo pi = null;
Amith Yamasani483f3b02012-03-13 16:08:00 -07005135 int userId = UserId.getUserId(callingUid);
5136 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005137 if (cpr != null) {
5138 pi = cpr.info;
5139 } else {
5140 try {
5141 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005142 PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005143 } catch (RemoteException ex) {
5144 }
5145 }
5146 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005147 Slog.w(TAG, "No content provider found for permission revoke: " + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005148 return;
5149 }
5150
5151 // Does the caller have this permission on the URI?
Dianne Hackborn48058e82010-09-27 16:53:23 -07005152 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005153 // Right now, if you are not the original owner of the permission,
5154 // you are not allowed to revoke it.
5155 //if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5156 throw new SecurityException("Uid " + callingUid
5157 + " does not have permission to uri " + uri);
5158 //}
5159 }
5160
5161 // Go through all of the permissions and remove any that match.
5162 final List<String> SEGMENTS = uri.getPathSegments();
5163 if (SEGMENTS != null) {
5164 final int NS = SEGMENTS.size();
5165 int N = mGrantedUriPermissions.size();
5166 for (int i=0; i<N; i++) {
5167 HashMap<Uri, UriPermission> perms
5168 = mGrantedUriPermissions.valueAt(i);
5169 Iterator<UriPermission> it = perms.values().iterator();
5170 toploop:
5171 while (it.hasNext()) {
5172 UriPermission perm = it.next();
5173 Uri targetUri = perm.uri;
5174 if (!authority.equals(targetUri.getAuthority())) {
5175 continue;
5176 }
5177 List<String> targetSegments = targetUri.getPathSegments();
5178 if (targetSegments == null) {
5179 continue;
5180 }
5181 if (targetSegments.size() < NS) {
5182 continue;
5183 }
5184 for (int j=0; j<NS; j++) {
5185 if (!SEGMENTS.get(j).equals(targetSegments.get(j))) {
5186 continue toploop;
5187 }
5188 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08005189 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005190 "Revoking " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005191 perm.clearModes(modeFlags);
5192 if (perm.modeFlags == 0) {
5193 it.remove();
5194 }
5195 }
5196 if (perms.size() == 0) {
5197 mGrantedUriPermissions.remove(
5198 mGrantedUriPermissions.keyAt(i));
5199 N--;
5200 i--;
5201 }
5202 }
5203 }
5204 }
5205
5206 public void revokeUriPermission(IApplicationThread caller, Uri uri,
5207 int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005208 enforceNotIsolatedCaller("revokeUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005209 synchronized(this) {
5210 final ProcessRecord r = getRecordForAppLocked(caller);
5211 if (r == null) {
5212 throw new SecurityException("Unable to find app for caller "
5213 + caller
5214 + " when revoking permission to uri " + uri);
5215 }
5216 if (uri == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005217 Slog.w(TAG, "revokeUriPermission: null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005218 return;
5219 }
5220
5221 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5222 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5223 if (modeFlags == 0) {
5224 return;
5225 }
5226
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005227 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005228
5229 final String authority = uri.getAuthority();
5230 ProviderInfo pi = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005231 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005232 if (cpr != null) {
5233 pi = cpr.info;
5234 } else {
5235 try {
5236 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005237 PackageManager.GET_URI_PERMISSION_PATTERNS, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005238 } catch (RemoteException ex) {
5239 }
5240 }
5241 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005242 Slog.w(TAG, "No content provider found for permission revoke: "
5243 + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005244 return;
5245 }
5246
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005247 revokeUriPermissionLocked(r.uid, uri, modeFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005248 }
5249 }
5250
Dianne Hackborn7e269642010-08-25 19:50:20 -07005251 @Override
5252 public IBinder newUriPermissionOwner(String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005253 enforceNotIsolatedCaller("newUriPermissionOwner");
Dianne Hackborn7e269642010-08-25 19:50:20 -07005254 synchronized(this) {
5255 UriPermissionOwner owner = new UriPermissionOwner(this, name);
5256 return owner.getExternalTokenLocked();
5257 }
5258 }
5259
5260 @Override
5261 public void grantUriPermissionFromOwner(IBinder token, int fromUid, String targetPkg,
5262 Uri uri, int modeFlags) {
5263 synchronized(this) {
5264 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5265 if (owner == null) {
5266 throw new IllegalArgumentException("Unknown owner: " + token);
5267 }
5268 if (fromUid != Binder.getCallingUid()) {
5269 if (Binder.getCallingUid() != Process.myUid()) {
5270 // Only system code can grant URI permissions on behalf
5271 // of other users.
5272 throw new SecurityException("nice try");
5273 }
5274 }
5275 if (targetPkg == null) {
5276 throw new IllegalArgumentException("null target");
5277 }
5278 if (uri == null) {
5279 throw new IllegalArgumentException("null uri");
5280 }
5281
5282 grantUriPermissionLocked(fromUid, targetPkg, uri, modeFlags, owner);
5283 }
5284 }
5285
5286 @Override
5287 public void revokeUriPermissionFromOwner(IBinder token, Uri uri, int mode) {
5288 synchronized(this) {
5289 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5290 if (owner == null) {
5291 throw new IllegalArgumentException("Unknown owner: " + token);
5292 }
5293
5294 if (uri == null) {
5295 owner.removeUriPermissionsLocked(mode);
5296 } else {
5297 owner.removeUriPermissionLocked(uri, mode);
5298 }
5299 }
5300 }
5301
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005302 public void showWaitingForDebugger(IApplicationThread who, boolean waiting) {
5303 synchronized (this) {
5304 ProcessRecord app =
5305 who != null ? getRecordForAppLocked(who) : null;
5306 if (app == null) return;
5307
5308 Message msg = Message.obtain();
5309 msg.what = WAIT_FOR_DEBUGGER_MSG;
5310 msg.obj = app;
5311 msg.arg1 = waiting ? 1 : 0;
5312 mHandler.sendMessage(msg);
5313 }
5314 }
5315
5316 public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07005317 final long homeAppMem = mProcessList.getMemLevel(ProcessList.HOME_APP_ADJ);
5318 final long hiddenAppMem = mProcessList.getMemLevel(ProcessList.HIDDEN_APP_MIN_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005319 outInfo.availMem = Process.getFreeMemory();
Dianne Hackborn7d608422011-08-07 16:24:18 -07005320 outInfo.threshold = homeAppMem;
5321 outInfo.lowMemory = outInfo.availMem < (homeAppMem + ((hiddenAppMem-homeAppMem)/2));
5322 outInfo.hiddenAppThreshold = hiddenAppMem;
5323 outInfo.secondaryServerThreshold = mProcessList.getMemLevel(
Dianne Hackborne02c88a2011-10-28 13:58:15 -07005324 ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07005325 outInfo.visibleAppThreshold = mProcessList.getMemLevel(
5326 ProcessList.VISIBLE_APP_ADJ);
5327 outInfo.foregroundAppThreshold = mProcessList.getMemLevel(
5328 ProcessList.FOREGROUND_APP_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005329 }
5330
5331 // =========================================================
5332 // TASK MANAGEMENT
5333 // =========================================================
5334
5335 public List getTasks(int maxNum, int flags,
5336 IThumbnailReceiver receiver) {
5337 ArrayList list = new ArrayList();
5338
5339 PendingThumbnailsRecord pending = null;
5340 IApplicationThread topThumbnail = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005341 ActivityRecord topRecord = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005342
5343 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005344 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005345 TAG, "getTasks: max=" + maxNum + ", flags=" + flags
5346 + ", receiver=" + receiver);
5347
5348 if (checkCallingPermission(android.Manifest.permission.GET_TASKS)
5349 != PackageManager.PERMISSION_GRANTED) {
5350 if (receiver != null) {
5351 // If the caller wants to wait for pending thumbnails,
5352 // it ain't gonna get them.
5353 try {
5354 receiver.finished();
5355 } catch (RemoteException ex) {
5356 }
5357 }
5358 String msg = "Permission Denial: getTasks() from pid="
5359 + Binder.getCallingPid()
5360 + ", uid=" + Binder.getCallingUid()
5361 + " requires " + android.Manifest.permission.GET_TASKS;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005362 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005363 throw new SecurityException(msg);
5364 }
5365
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005366 int pos = mMainStack.mHistory.size()-1;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005367 ActivityRecord next =
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005368 pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005369 ActivityRecord top = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005370 TaskRecord curTask = null;
5371 int numActivities = 0;
5372 int numRunning = 0;
5373 while (pos >= 0 && maxNum > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005374 final ActivityRecord r = next;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005375 pos--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005376 next = pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005377
5378 // Initialize state for next task if needed.
5379 if (top == null ||
5380 (top.state == ActivityState.INITIALIZING
5381 && top.task == r.task)) {
5382 top = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005383 curTask = r.task;
5384 numActivities = numRunning = 0;
5385 }
5386
5387 // Add 'r' into the current task.
5388 numActivities++;
5389 if (r.app != null && r.app.thread != null) {
5390 numRunning++;
5391 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005392
Joe Onorato8a9b2202010-02-26 18:56:32 -08005393 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005394 TAG, r.intent.getComponent().flattenToShortString()
5395 + ": task=" + r.task);
5396
5397 // If the next one is a different task, generate a new
5398 // TaskInfo entry for what we have.
5399 if (next == null || next.task != curTask) {
5400 ActivityManager.RunningTaskInfo ci
5401 = new ActivityManager.RunningTaskInfo();
5402 ci.id = curTask.taskId;
5403 ci.baseActivity = r.intent.getComponent();
5404 ci.topActivity = top.intent.getComponent();
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005405 if (top.thumbHolder != null) {
5406 ci.description = top.thumbHolder.lastDescription;
5407 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005408 ci.numActivities = numActivities;
5409 ci.numRunning = numRunning;
5410 //System.out.println(
5411 // "#" + maxNum + ": " + " descr=" + ci.description);
5412 if (ci.thumbnail == null && receiver != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005413 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005414 TAG, "State=" + top.state + "Idle=" + top.idle
5415 + " app=" + top.app
5416 + " thr=" + (top.app != null ? top.app.thread : null));
5417 if (top.state == ActivityState.RESUMED
5418 || top.state == ActivityState.PAUSING) {
5419 if (top.idle && top.app != null
5420 && top.app.thread != null) {
5421 topRecord = top;
5422 topThumbnail = top.app.thread;
5423 } else {
5424 top.thumbnailNeeded = true;
5425 }
5426 }
5427 if (pending == null) {
5428 pending = new PendingThumbnailsRecord(receiver);
5429 }
5430 pending.pendingRecords.add(top);
5431 }
5432 list.add(ci);
5433 maxNum--;
5434 top = null;
5435 }
5436 }
5437
5438 if (pending != null) {
5439 mPendingThumbnails.add(pending);
5440 }
5441 }
5442
Joe Onorato8a9b2202010-02-26 18:56:32 -08005443 if (localLOGV) Slog.v(TAG, "We have pending thumbnails: " + pending);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005444
5445 if (topThumbnail != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005446 if (localLOGV) Slog.v(TAG, "Requesting top thumbnail");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005447 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08005448 topThumbnail.requestThumbnail(topRecord.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005449 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005450 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005451 sendPendingThumbnail(null, topRecord.appToken, null, null, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005452 }
5453 }
5454
5455 if (pending == null && receiver != null) {
5456 // In this case all thumbnails were available and the client
5457 // is being asked to be told when the remaining ones come in...
5458 // which is unusually, since the top-most currently running
5459 // activity should never have a canned thumbnail! Oh well.
5460 try {
5461 receiver.finished();
5462 } catch (RemoteException ex) {
5463 }
5464 }
5465
5466 return list;
5467 }
5468
5469 public List<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum,
5470 int flags) {
Amith Yamasani742a6712011-05-04 14:49:28 -07005471 final int callingUid = Binder.getCallingUid();
5472 // If it's the system uid asking, then use the current user id.
5473 // TODO: Make sure that there aren't any other legitimate calls from the system uid that
5474 // require the entire list.
5475 final int callingUserId = callingUid == Process.SYSTEM_UID
5476 ? mCurrentUserId : UserId.getUserId(callingUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005477 synchronized (this) {
5478 enforceCallingPermission(android.Manifest.permission.GET_TASKS,
5479 "getRecentTasks()");
5480
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005481 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005482
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005483 final int N = mRecentTasks.size();
5484 ArrayList<ActivityManager.RecentTaskInfo> res
5485 = new ArrayList<ActivityManager.RecentTaskInfo>(
5486 maxNum < N ? maxNum : N);
5487 for (int i=0; i<N && maxNum > 0; i++) {
5488 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005489 // Only add calling user's recent tasks
5490 if (tr.userId != callingUserId) continue;
Dianne Hackborn905577f2011-09-07 18:31:28 -07005491 // Return the entry if desired by the caller. We always return
5492 // the first entry, because callers always expect this to be the
Amith Yamasani742a6712011-05-04 14:49:28 -07005493 // foreground app. We may filter others if the caller has
Dianne Hackborn905577f2011-09-07 18:31:28 -07005494 // not supplied RECENT_WITH_EXCLUDED and there is some reason
5495 // we should exclude the entry.
Amith Yamasani742a6712011-05-04 14:49:28 -07005496
Dianne Hackborn905577f2011-09-07 18:31:28 -07005497 if (i == 0
5498 || ((flags&ActivityManager.RECENT_WITH_EXCLUDED) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005499 || (tr.intent == null)
5500 || ((tr.intent.getFlags()
5501 &Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) == 0)) {
5502 ActivityManager.RecentTaskInfo rti
5503 = new ActivityManager.RecentTaskInfo();
5504 rti.id = tr.numActivities > 0 ? tr.taskId : -1;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005505 rti.persistentId = tr.taskId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005506 rti.baseIntent = new Intent(
5507 tr.intent != null ? tr.intent : tr.affinityIntent);
5508 rti.origActivity = tr.origActivity;
Dianne Hackbornd2835932010-12-13 16:28:46 -08005509 rti.description = tr.lastDescription;
5510
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005511 if ((flags&ActivityManager.RECENT_IGNORE_UNAVAILABLE) != 0) {
5512 // Check whether this activity is currently available.
5513 try {
5514 if (rti.origActivity != null) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07005515 if (pm.getActivityInfo(rti.origActivity, 0, callingUserId)
5516 == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005517 continue;
5518 }
5519 } else if (rti.baseIntent != null) {
5520 if (pm.queryIntentActivities(rti.baseIntent,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005521 null, 0, callingUserId) == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005522 continue;
5523 }
5524 }
5525 } catch (RemoteException e) {
5526 // Will never happen.
5527 }
5528 }
5529
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005530 res.add(rti);
5531 maxNum--;
5532 }
5533 }
5534 return res;
5535 }
5536 }
5537
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005538 private TaskRecord taskForIdLocked(int id) {
5539 final int N = mRecentTasks.size();
5540 for (int i=0; i<N; i++) {
5541 TaskRecord tr = mRecentTasks.get(i);
5542 if (tr.taskId == id) {
5543 return tr;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005544 }
5545 }
5546 return null;
5547 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005548
5549 public ActivityManager.TaskThumbnails getTaskThumbnails(int id) {
5550 synchronized (this) {
5551 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
5552 "getTaskThumbnails()");
5553 TaskRecord tr = taskForIdLocked(id);
5554 if (tr != null) {
5555 return mMainStack.getTaskThumbnailsLocked(tr);
5556 }
5557 }
5558 return null;
5559 }
5560
5561 public boolean removeSubTask(int taskId, int subTaskIndex) {
5562 synchronized (this) {
5563 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5564 "removeSubTask()");
5565 long ident = Binder.clearCallingIdentity();
5566 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005567 return mMainStack.removeTaskActivitiesLocked(taskId, subTaskIndex,
5568 true) != null;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005569 } finally {
5570 Binder.restoreCallingIdentity(ident);
5571 }
5572 }
5573 }
5574
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005575 private void cleanUpRemovedTaskLocked(TaskRecord tr, int flags) {
5576 final boolean killProcesses = (flags&ActivityManager.REMOVE_TASK_KILL_PROCESS) != 0;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005577 Intent baseIntent = new Intent(
5578 tr.intent != null ? tr.intent : tr.affinityIntent);
5579 ComponentName component = baseIntent.getComponent();
5580 if (component == null) {
5581 Slog.w(TAG, "Now component for base intent of task: " + tr);
5582 return;
5583 }
5584
5585 // Find any running services associated with this app.
5586 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005587 for (ServiceRecord sr : mServiceMap.getAllServices(tr.userId)) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005588 if (sr.packageName.equals(component.getPackageName())) {
5589 services.add(sr);
5590 }
5591 }
5592
5593 // Take care of any running services associated with the app.
5594 for (int i=0; i<services.size(); i++) {
5595 ServiceRecord sr = services.get(i);
5596 if (sr.startRequested) {
5597 if ((sr.serviceInfo.flags&ServiceInfo.FLAG_STOP_WITH_TASK) != 0) {
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005598 Slog.i(TAG, "Stopping service " + sr.shortName + ": remove task");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005599 stopServiceLocked(sr);
5600 } else {
5601 sr.pendingStarts.add(new ServiceRecord.StartItem(sr, true,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005602 sr.makeNextStartId(), baseIntent, null));
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005603 if (sr.app != null && sr.app.thread != null) {
5604 sendServiceArgsLocked(sr, false);
5605 }
5606 }
5607 }
5608 }
5609
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005610 if (killProcesses) {
5611 // Find any running processes associated with this app.
5612 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
5613 SparseArray<ProcessRecord> appProcs
5614 = mProcessNames.getMap().get(component.getPackageName());
5615 if (appProcs != null) {
5616 for (int i=0; i<appProcs.size(); i++) {
5617 procs.add(appProcs.valueAt(i));
5618 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005619 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005620
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005621 // Kill the running processes.
5622 for (int i=0; i<procs.size(); i++) {
5623 ProcessRecord pr = procs.get(i);
5624 if (pr.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
5625 Slog.i(TAG, "Killing " + pr.toShortString() + ": remove task");
5626 EventLog.writeEvent(EventLogTags.AM_KILL, pr.pid,
5627 pr.processName, pr.setAdj, "remove task");
5628 Process.killProcessQuiet(pr.pid);
5629 } else {
5630 pr.waitingToKill = "remove task";
5631 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005632 }
5633 }
5634 }
5635
5636 public boolean removeTask(int taskId, int flags) {
5637 synchronized (this) {
5638 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5639 "removeTask()");
5640 long ident = Binder.clearCallingIdentity();
5641 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005642 ActivityRecord r = mMainStack.removeTaskActivitiesLocked(taskId, -1,
5643 false);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005644 if (r != null) {
5645 mRecentTasks.remove(r.task);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005646 cleanUpRemovedTaskLocked(r.task, flags);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005647 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005648 } else {
5649 TaskRecord tr = null;
5650 int i=0;
5651 while (i < mRecentTasks.size()) {
5652 TaskRecord t = mRecentTasks.get(i);
5653 if (t.taskId == taskId) {
5654 tr = t;
5655 break;
5656 }
5657 i++;
5658 }
5659 if (tr != null) {
5660 if (tr.numActivities <= 0) {
5661 // Caller is just removing a recent task that is
5662 // not actively running. That is easy!
5663 mRecentTasks.remove(i);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005664 cleanUpRemovedTaskLocked(tr, flags);
5665 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005666 } else {
5667 Slog.w(TAG, "removeTask: task " + taskId
5668 + " does not have activities to remove, "
5669 + " but numActivities=" + tr.numActivities
5670 + ": " + tr);
5671 }
5672 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005673 }
5674 } finally {
5675 Binder.restoreCallingIdentity(ident);
5676 }
5677 }
5678 return false;
5679 }
Dianne Hackbornd94df452011-02-16 18:53:31 -08005680
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005681 private final int findAffinityTaskTopLocked(int startIndex, String affinity) {
5682 int j;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005683 TaskRecord startTask = ((ActivityRecord)mMainStack.mHistory.get(startIndex)).task;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005684 TaskRecord jt = startTask;
5685
5686 // First look backwards
5687 for (j=startIndex-1; j>=0; j--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005688 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005689 if (r.task != jt) {
5690 jt = r.task;
5691 if (affinity.equals(jt.affinity)) {
5692 return j;
5693 }
5694 }
5695 }
5696
5697 // Now look forwards
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005698 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005699 jt = startTask;
5700 for (j=startIndex+1; j<N; j++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005701 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005702 if (r.task != jt) {
5703 if (affinity.equals(jt.affinity)) {
5704 return j;
5705 }
5706 jt = r.task;
5707 }
5708 }
5709
5710 // Might it be at the top?
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005711 if (affinity.equals(((ActivityRecord)mMainStack.mHistory.get(N-1)).task.affinity)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005712 return N-1;
5713 }
5714
5715 return -1;
5716 }
5717
5718 /**
Dianne Hackbornb06ea702009-07-13 13:07:51 -07005719 * TODO: Add mController hook
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005720 */
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005721 public void moveTaskToFront(int task, int flags, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005722 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5723 "moveTaskToFront()");
5724
5725 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005726 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5727 Binder.getCallingUid(), "Task to front")) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005728 ActivityOptions.abort(options);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005729 return;
5730 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005731 final long origId = Binder.clearCallingIdentity();
5732 try {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005733 TaskRecord tr = taskForIdLocked(task);
5734 if (tr != null) {
5735 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5736 mMainStack.mUserLeaving = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005737 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005738 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5739 // Caller wants the home activity moved with it. To accomplish this,
5740 // we'll just move the home task to the top first.
5741 mMainStack.moveHomeToFrontLocked();
5742 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005743 mMainStack.moveTaskToFrontLocked(tr, null, options);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005744 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005745 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005746 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
5747 ActivityRecord hr = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005748 if (hr.task.taskId == task) {
Dianne Hackbornd94df452011-02-16 18:53:31 -08005749 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5750 mMainStack.mUserLeaving = true;
5751 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005752 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5753 // Caller wants the home activity moved with it. To accomplish this,
5754 // we'll just move the home task to the top first.
5755 mMainStack.moveHomeToFrontLocked();
5756 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005757 mMainStack.moveTaskToFrontLocked(hr.task, null, options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005758 return;
5759 }
5760 }
5761 } finally {
5762 Binder.restoreCallingIdentity(origId);
5763 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005764 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005765 }
5766 }
5767
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005768 public void moveTaskToBack(int task) {
5769 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5770 "moveTaskToBack()");
5771
5772 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005773 if (mMainStack.mResumedActivity != null
5774 && mMainStack.mResumedActivity.task.taskId == task) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005775 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5776 Binder.getCallingUid(), "Task to back")) {
5777 return;
5778 }
5779 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005780 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005781 mMainStack.moveTaskToBackLocked(task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005782 Binder.restoreCallingIdentity(origId);
5783 }
5784 }
5785
5786 /**
5787 * Moves an activity, and all of the other activities within the same task, to the bottom
5788 * of the history stack. The activity's order within the task is unchanged.
5789 *
5790 * @param token A reference to the activity we wish to move
5791 * @param nonRoot If false then this only works if the activity is the root
5792 * of a task; if true it will work for any activity in a task.
5793 * @return Returns true if the move completed, false if not.
5794 */
5795 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005796 enforceNotIsolatedCaller("moveActivityTaskToBack");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005797 synchronized(this) {
5798 final long origId = Binder.clearCallingIdentity();
5799 int taskId = getTaskForActivityLocked(token, !nonRoot);
5800 if (taskId >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005801 return mMainStack.moveTaskToBackLocked(taskId, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005802 }
5803 Binder.restoreCallingIdentity(origId);
5804 }
5805 return false;
5806 }
5807
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005808 public void moveTaskBackwards(int task) {
5809 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5810 "moveTaskBackwards()");
5811
5812 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005813 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5814 Binder.getCallingUid(), "Task backwards")) {
5815 return;
5816 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005817 final long origId = Binder.clearCallingIdentity();
5818 moveTaskBackwardsLocked(task);
5819 Binder.restoreCallingIdentity(origId);
5820 }
5821 }
5822
5823 private final void moveTaskBackwardsLocked(int task) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005824 Slog.e(TAG, "moveTaskBackwards not yet implemented!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005825 }
5826
5827 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
5828 synchronized(this) {
5829 return getTaskForActivityLocked(token, onlyRoot);
5830 }
5831 }
5832
5833 int getTaskForActivityLocked(IBinder token, boolean onlyRoot) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005834 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005835 TaskRecord lastTask = null;
5836 for (int i=0; i<N; i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005837 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005838 if (r.appToken == token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005839 if (!onlyRoot || lastTask != r.task) {
5840 return r.task.taskId;
5841 }
5842 return -1;
5843 }
5844 lastTask = r.task;
5845 }
5846
5847 return -1;
5848 }
5849
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005850 // =========================================================
5851 // THUMBNAILS
5852 // =========================================================
5853
5854 public void reportThumbnail(IBinder token,
5855 Bitmap thumbnail, CharSequence description) {
5856 //System.out.println("Report thumbnail for " + token + ": " + thumbnail);
5857 final long origId = Binder.clearCallingIdentity();
5858 sendPendingThumbnail(null, token, thumbnail, description, true);
5859 Binder.restoreCallingIdentity(origId);
5860 }
5861
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005862 final void sendPendingThumbnail(ActivityRecord r, IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005863 Bitmap thumbnail, CharSequence description, boolean always) {
5864 TaskRecord task = null;
5865 ArrayList receivers = null;
5866
5867 //System.out.println("Send pending thumbnail: " + r);
5868
5869 synchronized(this) {
5870 if (r == null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07005871 r = mMainStack.isInStackLocked(token);
5872 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005873 return;
5874 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005875 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005876 if (thumbnail == null && r.thumbHolder != null) {
5877 thumbnail = r.thumbHolder.lastThumbnail;
5878 description = r.thumbHolder.lastDescription;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005879 }
5880 if (thumbnail == null && !always) {
5881 // If there is no thumbnail, and this entry is not actually
5882 // going away, then abort for now and pick up the next
5883 // thumbnail we get.
5884 return;
5885 }
5886 task = r.task;
5887
5888 int N = mPendingThumbnails.size();
5889 int i=0;
5890 while (i<N) {
5891 PendingThumbnailsRecord pr =
5892 (PendingThumbnailsRecord)mPendingThumbnails.get(i);
5893 //System.out.println("Looking in " + pr.pendingRecords);
5894 if (pr.pendingRecords.remove(r)) {
5895 if (receivers == null) {
5896 receivers = new ArrayList();
5897 }
5898 receivers.add(pr);
5899 if (pr.pendingRecords.size() == 0) {
5900 pr.finished = true;
5901 mPendingThumbnails.remove(i);
5902 N--;
5903 continue;
5904 }
5905 }
5906 i++;
5907 }
5908 }
5909
5910 if (receivers != null) {
5911 final int N = receivers.size();
5912 for (int i=0; i<N; i++) {
5913 try {
5914 PendingThumbnailsRecord pr =
5915 (PendingThumbnailsRecord)receivers.get(i);
5916 pr.receiver.newThumbnail(
5917 task != null ? task.taskId : -1, thumbnail, description);
5918 if (pr.finished) {
5919 pr.receiver.finished();
5920 }
5921 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005922 Slog.w(TAG, "Exception thrown when sending thumbnail", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005923 }
5924 }
5925 }
5926 }
5927
5928 // =========================================================
5929 // CONTENT PROVIDERS
5930 // =========================================================
5931
Jeff Brown10e89712011-07-08 18:52:57 -07005932 private final List<ProviderInfo> generateApplicationProvidersLocked(ProcessRecord app) {
5933 List<ProviderInfo> providers = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005934 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005935 providers = AppGlobals.getPackageManager().
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005936 queryContentProviders(app.processName, app.uid,
Dianne Hackborn1655be42009-05-08 14:29:01 -07005937 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005938 } catch (RemoteException ex) {
5939 }
Amith Yamasani742a6712011-05-04 14:49:28 -07005940 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005941 Slog.v(TAG_MU, "generateApplicationProvidersLocked, app.info.uid = " + app.uid);
5942 int userId = app.userId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005943 if (providers != null) {
5944 final int N = providers.size();
5945 for (int i=0; i<N; i++) {
5946 ProviderInfo cpi =
5947 (ProviderInfo)providers.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005948
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07005949 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07005950 ContentProviderRecord cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005951 if (cpr == null) {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08005952 cpr = new ContentProviderRecord(this, cpi, app.info, comp);
Amith Yamasani742a6712011-05-04 14:49:28 -07005953 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005954 }
Amith Yamasani742a6712011-05-04 14:49:28 -07005955 if (DEBUG_MU)
5956 Slog.v(TAG_MU, "generateApplicationProvidersLocked, cpi.uid = " + cpr.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005957 app.pubProviders.put(cpi.name, cpr);
5958 app.addPackage(cpi.applicationInfo.packageName);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07005959 ensurePackageDexOpt(cpi.applicationInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005960 }
5961 }
5962 return providers;
5963 }
5964
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005965 /**
5966 * Check if {@link ProcessRecord} has a possible chance at accessing the
5967 * given {@link ProviderInfo}. Final permission checking is always done
5968 * in {@link ContentProvider}.
5969 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005970 private final String checkContentProviderPermissionLocked(
Dianne Hackbornb424b632010-08-18 15:59:05 -07005971 ProviderInfo cpi, ProcessRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005972 final int callingPid = (r != null) ? r.pid : Binder.getCallingPid();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005973 final int callingUid = (r != null) ? r.uid : Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005974 if (checkComponentPermission(cpi.readPermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005975 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005976 == PackageManager.PERMISSION_GRANTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005977 return null;
5978 }
5979 if (checkComponentPermission(cpi.writePermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005980 cpi.applicationInfo.uid, cpi.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005981 == PackageManager.PERMISSION_GRANTED) {
5982 return null;
5983 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07005984
5985 PathPermission[] pps = cpi.pathPermissions;
5986 if (pps != null) {
5987 int i = pps.length;
5988 while (i > 0) {
5989 i--;
5990 PathPermission pp = pps[i];
5991 if (checkComponentPermission(pp.getReadPermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005992 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005993 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07005994 return null;
5995 }
5996 if (checkComponentPermission(pp.getWritePermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005997 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackborn2af632f2009-07-08 14:56:37 -07005998 == PackageManager.PERMISSION_GRANTED) {
5999 return null;
6000 }
6001 }
6002 }
6003
Dianne Hackbornb424b632010-08-18 15:59:05 -07006004 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(callingUid);
6005 if (perms != null) {
6006 for (Map.Entry<Uri, UriPermission> uri : perms.entrySet()) {
6007 if (uri.getKey().getAuthority().equals(cpi.authority)) {
6008 return null;
6009 }
6010 }
6011 }
6012
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006013 String msg;
6014 if (!cpi.exported) {
6015 msg = "Permission Denial: opening provider " + cpi.name
6016 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6017 + ", uid=" + callingUid + ") that is not exported from uid "
6018 + cpi.applicationInfo.uid;
6019 } else {
6020 msg = "Permission Denial: opening provider " + cpi.name
6021 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6022 + ", uid=" + callingUid + ") requires "
6023 + cpi.readPermission + " or " + cpi.writePermission;
6024 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08006025 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006026 return msg;
6027 }
6028
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006029 boolean incProviderCount(ProcessRecord r, final ContentProviderRecord cpr,
6030 IBinder externalProcessToken) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006031 if (r != null) {
6032 Integer cnt = r.conProviders.get(cpr);
6033 if (DEBUG_PROVIDER) Slog.v(TAG,
6034 "Adding provider requested by "
6035 + r.processName + " from process "
6036 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
6037 + " cnt=" + (cnt == null ? 1 : cnt));
6038 if (cnt == null) {
6039 cpr.clients.add(r);
6040 r.conProviders.put(cpr, new Integer(1));
6041 return true;
6042 } else {
6043 r.conProviders.put(cpr, new Integer(cnt.intValue()+1));
6044 }
6045 } else {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006046 cpr.addExternalProcessHandleLocked(externalProcessToken);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006047 }
6048 return false;
6049 }
6050
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006051 boolean decProviderCount(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 "Removing provider requested by "
6057 + r.processName + " from process "
6058 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
6059 + " cnt=" + cnt);
6060 if (cnt == null || cnt.intValue() <= 1) {
6061 cpr.clients.remove(r);
6062 r.conProviders.remove(cpr);
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.removeExternalProcessHandleLocked(externalProcessToken);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006069 }
6070 return false;
6071 }
6072
Amith Yamasani742a6712011-05-04 14:49:28 -07006073 private final ContentProviderHolder getContentProviderImpl(IApplicationThread caller,
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006074 String name, IBinder token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006075 ContentProviderRecord cpr;
6076 ProviderInfo cpi = null;
6077
6078 synchronized(this) {
6079 ProcessRecord r = null;
6080 if (caller != null) {
6081 r = getRecordForAppLocked(caller);
6082 if (r == null) {
6083 throw new SecurityException(
6084 "Unable to find app for caller " + caller
6085 + " (pid=" + Binder.getCallingPid()
6086 + ") when getting content provider " + name);
6087 }
6088 }
6089
6090 // First check if this content provider has been published...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006091 int userId = UserId.getUserId(r != null ? r.uid : Binder.getCallingUid());
Amith Yamasani742a6712011-05-04 14:49:28 -07006092 cpr = mProviderMap.getProviderByName(name, userId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006093 boolean providerRunning = cpr != null;
6094 if (providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006095 cpi = cpr.info;
Dianne Hackbornb424b632010-08-18 15:59:05 -07006096 String msg;
6097 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6098 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006099 }
6100
6101 if (r != null && cpr.canRunHere(r)) {
6102 // This provider has been published or is in the process
6103 // of being published... but it is also allowed to run
6104 // in the caller's process, so don't make a connection
6105 // and just let the caller instantiate its own instance.
6106 if (cpr.provider != null) {
6107 // don't give caller the provider object, it needs
6108 // to make its own.
6109 cpr = new ContentProviderRecord(cpr);
6110 }
6111 return cpr;
6112 }
6113
6114 final long origId = Binder.clearCallingIdentity();
6115
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006116 // In this case the provider instance already exists, so we can
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006117 // return it right away.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006118 final boolean countChanged = incProviderCount(r, cpr, token);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006119 if (countChanged) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006120 if (cpr.proc != null && r.setAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006121 // If this is a perceptible app accessing the provider,
Dianne Hackborn906497c2010-05-10 15:57:38 -07006122 // make sure to count it as being accessed and thus
6123 // back up on the LRU list. This is good because
6124 // content providers are often expensive to start.
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006125 updateLruProcessLocked(cpr.proc, false, true);
Dianne Hackborn906497c2010-05-10 15:57:38 -07006126 }
Dianne Hackborn6f86c0e2010-05-11 14:20:52 -07006127 }
6128
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006129 if (cpr.proc != null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006130 if (false) {
6131 if (cpr.name.flattenToShortString().equals(
6132 "com.android.providers.calendar/.CalendarProvider2")) {
6133 Slog.v(TAG, "****************** KILLING "
6134 + cpr.name.flattenToShortString());
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006135 Process.killProcess(cpr.proc.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006136 }
6137 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006138 boolean success = updateOomAdjLocked(cpr.proc);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006139 if (DEBUG_PROVIDER) Slog.i(TAG, "Adjust success: " + success);
6140 // NOTE: there is still a race here where a signal could be
6141 // pending on the process even though we managed to update its
6142 // adj level. Not sure what to do about this, but at least
6143 // the race is now smaller.
6144 if (!success) {
6145 // Uh oh... it looks like the provider's process
6146 // has been killed on us. We need to wait for a new
6147 // process to be started, and make sure its death
6148 // doesn't kill our process.
6149 Slog.i(TAG,
6150 "Existing provider " + cpr.name.flattenToShortString()
6151 + " is crashing; detaching " + r);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006152 boolean lastRef = decProviderCount(r, cpr, token);
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006153 appDiedLocked(cpr.proc, cpr.proc.pid, cpr.proc.thread);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006154 if (!lastRef) {
6155 // This wasn't the last ref our process had on
6156 // the provider... we have now been killed, bail.
6157 return null;
6158 }
6159 providerRunning = false;
6160 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006161 }
6162
6163 Binder.restoreCallingIdentity(origId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006164 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006165
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006166 if (!providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006167 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006168 cpi = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07006169 resolveContentProvider(name,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006170 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006171 } catch (RemoteException ex) {
6172 }
6173 if (cpi == null) {
6174 return null;
6175 }
6176
Amith Yamasani483f3b02012-03-13 16:08:00 -07006177 cpi.applicationInfo = getAppInfoForUser(cpi.applicationInfo, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07006178
Dianne Hackbornb424b632010-08-18 15:59:05 -07006179 String msg;
6180 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6181 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006182 }
6183
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07006184 if (!mProcessesReady && !mDidUpdate && !mWaitingUpdate
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006185 && !cpi.processName.equals("system")) {
6186 // If this content provider does not run in the system
6187 // process, and the system is not yet ready to run other
6188 // processes, then fail fast instead of hanging.
6189 throw new IllegalArgumentException(
6190 "Attempt to launch content provider before system ready");
6191 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006192
6193 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani483f3b02012-03-13 16:08:00 -07006194 cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006195 final boolean firstClass = cpr == null;
6196 if (firstClass) {
6197 try {
6198 ApplicationInfo ai =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006199 AppGlobals.getPackageManager().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006200 getApplicationInfo(
6201 cpi.applicationInfo.packageName,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006202 STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006203 if (ai == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006204 Slog.w(TAG, "No package info for content provider "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006205 + cpi.name);
6206 return null;
6207 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006208 ai = getAppInfoForUser(ai, userId);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006209 cpr = new ContentProviderRecord(this, cpi, ai, comp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006210 } catch (RemoteException ex) {
6211 // pm is in same process, this will never happen.
6212 }
6213 }
6214
6215 if (r != null && cpr.canRunHere(r)) {
6216 // If this is a multiprocess provider, then just return its
6217 // info and allow the caller to instantiate it. Only do
6218 // this if the provider is the same user as the caller's
6219 // process, or can run as root (so can be in any process).
6220 return cpr;
6221 }
6222
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006223 if (DEBUG_PROVIDER) {
6224 RuntimeException e = new RuntimeException("here");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006225 Slog.w(TAG, "LAUNCHING REMOTE PROVIDER (myuid " + r.uid
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006226 + " pruid " + cpr.appInfo.uid + "): " + cpr.info.name, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006227 }
6228
6229 // This is single process, and our app is now connecting to it.
6230 // See if we are already in the process of launching this
6231 // provider.
6232 final int N = mLaunchingProviders.size();
6233 int i;
6234 for (i=0; i<N; i++) {
6235 if (mLaunchingProviders.get(i) == cpr) {
6236 break;
6237 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006238 }
6239
6240 // If the provider is not already being launched, then get it
6241 // started.
6242 if (i >= N) {
6243 final long origId = Binder.clearCallingIdentity();
Dianne Hackborne7f97212011-02-24 14:40:20 -08006244
6245 try {
6246 // Content provider is now in use, its package can't be stopped.
6247 try {
6248 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07006249 cpr.appInfo.packageName, false, userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006250 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006251 } catch (IllegalArgumentException e) {
6252 Slog.w(TAG, "Failed trying to unstop package "
6253 + cpr.appInfo.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006254 }
6255
6256 ProcessRecord proc = startProcessLocked(cpi.processName,
6257 cpr.appInfo, false, 0, "content provider",
6258 new ComponentName(cpi.applicationInfo.packageName,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006259 cpi.name), false, false);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006260 if (proc == null) {
6261 Slog.w(TAG, "Unable to launch app "
6262 + cpi.applicationInfo.packageName + "/"
6263 + cpi.applicationInfo.uid + " for provider "
6264 + name + ": process is bad");
6265 return null;
6266 }
6267 cpr.launchingApp = proc;
6268 mLaunchingProviders.add(cpr);
6269 } finally {
6270 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006271 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006272 }
6273
6274 // Make sure the provider is published (the same provider class
6275 // may be published under multiple names).
6276 if (firstClass) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006277 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006278 }
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006279
Amith Yamasani742a6712011-05-04 14:49:28 -07006280 mProviderMap.putProviderByName(name, cpr);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006281 incProviderCount(r, cpr, token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006282 }
6283 }
6284
6285 // Wait for the provider to be published...
6286 synchronized (cpr) {
6287 while (cpr.provider == null) {
6288 if (cpr.launchingApp == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006289 Slog.w(TAG, "Unable to launch app "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006290 + cpi.applicationInfo.packageName + "/"
6291 + cpi.applicationInfo.uid + " for provider "
6292 + name + ": launching app became null");
Doug Zongker2bec3d42009-12-04 12:52:44 -08006293 EventLog.writeEvent(EventLogTags.AM_PROVIDER_LOST_PROCESS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006294 cpi.applicationInfo.packageName,
6295 cpi.applicationInfo.uid, name);
6296 return null;
6297 }
6298 try {
Amith Yamasani742a6712011-05-04 14:49:28 -07006299 if (DEBUG_MU) {
6300 Slog.v(TAG_MU, "Waiting to start provider " + cpr + " launchingApp="
6301 + cpr.launchingApp);
6302 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006303 cpr.wait();
6304 } catch (InterruptedException ex) {
6305 }
6306 }
6307 }
6308 return cpr;
6309 }
6310
6311 public final ContentProviderHolder getContentProvider(
6312 IApplicationThread caller, String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006313 enforceNotIsolatedCaller("getContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006314 if (caller == null) {
6315 String msg = "null IApplicationThread when getting content provider "
6316 + name;
Joe Onorato8a9b2202010-02-26 18:56:32 -08006317 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006318 throw new SecurityException(msg);
6319 }
6320
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006321 return getContentProviderImpl(caller, name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006322 }
6323
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006324 public ContentProviderHolder getContentProviderExternal(String name, IBinder token) {
6325 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6326 "Do not have permission in call getContentProviderExternal()");
6327 return getContentProviderExternalUnchecked(name, token);
6328 }
6329
6330 private ContentProviderHolder getContentProviderExternalUnchecked(String name,IBinder token) {
6331 return getContentProviderImpl(null, name, token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006332 }
6333
6334 /**
6335 * Drop a content provider from a ProcessRecord's bookkeeping
6336 * @param cpr
6337 */
6338 public void removeContentProvider(IApplicationThread caller, String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006339 enforceNotIsolatedCaller("removeContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006340 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006341 int userId = UserId.getUserId(Binder.getCallingUid());
6342 ContentProviderRecord cpr = mProviderMap.getProviderByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006343 if(cpr == null) {
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006344 // remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006345 if (DEBUG_PROVIDER) Slog.v(TAG, name +
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006346 " provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006347 return;
6348 }
6349 final ProcessRecord r = getRecordForAppLocked(caller);
6350 if (r == null) {
6351 throw new SecurityException(
6352 "Unable to find app for caller " + caller +
6353 " when removing content provider " + name);
6354 }
6355 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006356 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006357 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp, userId);
6358 if (DEBUG_PROVIDER) Slog.v(TAG, "Removing provider requested by "
6359 + r.info.processName + " from process "
6360 + localCpr.appInfo.processName);
6361 if (localCpr.launchingApp == r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006362 //should not happen. taken care of as a local provider
Joe Onorato8a9b2202010-02-26 18:56:32 -08006363 Slog.w(TAG, "removeContentProvider called on local provider: "
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006364 + cpr.info.name + " in process " + r.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006365 return;
6366 } else {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006367 if (decProviderCount(r, localCpr, null)) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006368 updateOomAdjLocked();
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07006369 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006370 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006371 }
6372 }
6373
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006374 public void removeContentProviderExternal(String name, IBinder token) {
6375 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6376 "Do not have permission in call removeContentProviderExternal()");
6377 removeContentProviderExternalUnchecked(name, token);
6378 }
6379
6380 private void removeContentProviderExternalUnchecked(String name, IBinder token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006381 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006382 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
6383 Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006384 if(cpr == null) {
6385 //remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006386 if(localLOGV) Slog.v(TAG, name+" content provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006387 return;
6388 }
6389
6390 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006391 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006392 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp,
6393 Binder.getOrigCallingUser());
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006394 if (localCpr.hasExternalProcessHandles()) {
6395 if (localCpr.removeExternalProcessHandleLocked(token)) {
6396 updateOomAdjLocked();
6397 } else {
6398 Slog.e(TAG, "Attmpt to remove content provider " + localCpr
6399 + " with no external reference for token: "
6400 + token + ".");
6401 }
6402 } else {
6403 Slog.e(TAG, "Attmpt to remove content provider: " + localCpr
6404 + " with no external references.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006405 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006406 }
6407 }
6408
6409 public final void publishContentProviders(IApplicationThread caller,
6410 List<ContentProviderHolder> providers) {
6411 if (providers == null) {
6412 return;
6413 }
6414
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006415 enforceNotIsolatedCaller("publishContentProviders");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006416 synchronized(this) {
6417 final ProcessRecord r = getRecordForAppLocked(caller);
Amith Yamasani742a6712011-05-04 14:49:28 -07006418 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006419 Slog.v(TAG_MU, "ProcessRecord uid = " + r.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006420 if (r == null) {
6421 throw new SecurityException(
6422 "Unable to find app for caller " + caller
6423 + " (pid=" + Binder.getCallingPid()
6424 + ") when publishing content providers");
6425 }
6426
6427 final long origId = Binder.clearCallingIdentity();
6428
6429 final int N = providers.size();
6430 for (int i=0; i<N; i++) {
6431 ContentProviderHolder src = providers.get(i);
6432 if (src == null || src.info == null || src.provider == null) {
6433 continue;
6434 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07006435 ContentProviderRecord dst = r.pubProviders.get(src.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006436 if (DEBUG_MU)
6437 Slog.v(TAG_MU, "ContentProviderRecord uid = " + dst.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006438 if (dst != null) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006439 ComponentName comp = new ComponentName(dst.info.packageName, dst.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006440 mProviderMap.putProviderByClass(comp, dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006441 String names[] = dst.info.authority.split(";");
6442 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006443 mProviderMap.putProviderByName(names[j], dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006444 }
6445
6446 int NL = mLaunchingProviders.size();
6447 int j;
6448 for (j=0; j<NL; j++) {
6449 if (mLaunchingProviders.get(j) == dst) {
6450 mLaunchingProviders.remove(j);
6451 j--;
6452 NL--;
6453 }
6454 }
6455 synchronized (dst) {
6456 dst.provider = src.provider;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006457 dst.proc = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006458 dst.notifyAll();
6459 }
6460 updateOomAdjLocked(r);
6461 }
6462 }
6463
6464 Binder.restoreCallingIdentity(origId);
6465 }
6466 }
6467
6468 public static final void installSystemProviders() {
Jeff Brown10e89712011-07-08 18:52:57 -07006469 List<ProviderInfo> providers;
Josh Bartel2ecce342010-02-25 10:55:48 -06006470 synchronized (mSelf) {
6471 ProcessRecord app = mSelf.mProcessNames.get("system", Process.SYSTEM_UID);
6472 providers = mSelf.generateApplicationProvidersLocked(app);
Dianne Hackborn5c83a5f2010-03-12 16:46:46 -08006473 if (providers != null) {
6474 for (int i=providers.size()-1; i>=0; i--) {
6475 ProviderInfo pi = (ProviderInfo)providers.get(i);
6476 if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6477 Slog.w(TAG, "Not installing system proc provider " + pi.name
6478 + ": not system .apk");
6479 providers.remove(i);
6480 }
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006481 }
6482 }
6483 }
Josh Bartel2ecce342010-02-25 10:55:48 -06006484 if (providers != null) {
6485 mSystemThread.installSystemProviders(providers);
6486 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08006487
6488 mSelf.mCoreSettingsObserver = new CoreSettingsObserver(mSelf);
Mark Brophyc6350272011-08-05 16:16:39 +01006489
6490 mSelf.mUsageStatsService.monitorPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006491 }
6492
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006493 /**
6494 * Allows app to retrieve the MIME type of a URI without having permission
6495 * to access its content provider.
6496 *
6497 * CTS tests for this functionality can be run with "runtest cts-appsecurity".
6498 *
6499 * Test cases are at cts/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/
6500 * src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java
6501 */
6502 public String getProviderMimeType(Uri uri) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006503 enforceNotIsolatedCaller("getProviderMimeType");
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006504 final String name = uri.getAuthority();
6505 final long ident = Binder.clearCallingIdentity();
6506 ContentProviderHolder holder = null;
6507
6508 try {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006509 holder = getContentProviderExternalUnchecked(name, null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006510 if (holder != null) {
6511 return holder.provider.getType(uri);
6512 }
6513 } catch (RemoteException e) {
6514 Log.w(TAG, "Content provider dead retrieving " + uri, e);
6515 return null;
6516 } finally {
6517 if (holder != null) {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006518 removeContentProviderExternalUnchecked(name, null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006519 }
6520 Binder.restoreCallingIdentity(ident);
6521 }
6522
6523 return null;
6524 }
6525
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006526 // =========================================================
6527 // GLOBAL MANAGEMENT
6528 // =========================================================
6529
6530 final ProcessRecord newProcessRecordLocked(IApplicationThread thread,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006531 ApplicationInfo info, String customProcess, boolean isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006532 String proc = customProcess != null ? customProcess : info.processName;
6533 BatteryStatsImpl.Uid.Proc ps = null;
6534 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006535 int uid = info.uid;
6536 if (isolated) {
6537 int userId = UserId.getUserId(uid);
6538 int stepsLeft = Process.LAST_ISOLATED_UID - Process.FIRST_ISOLATED_UID + 1;
6539 uid = 0;
6540 while (true) {
6541 if (mNextIsolatedProcessUid < Process.FIRST_ISOLATED_UID
6542 || mNextIsolatedProcessUid > Process.LAST_ISOLATED_UID) {
6543 mNextIsolatedProcessUid = Process.FIRST_ISOLATED_UID;
6544 }
6545 uid = UserId.getUid(userId, mNextIsolatedProcessUid);
6546 mNextIsolatedProcessUid++;
6547 if (mIsolatedProcesses.indexOfKey(uid) < 0) {
6548 // No process for this uid, use it.
6549 break;
6550 }
6551 stepsLeft--;
6552 if (stepsLeft <= 0) {
6553 return null;
6554 }
6555 }
6556 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006557 synchronized (stats) {
6558 ps = stats.getProcessStatsLocked(info.uid, proc);
6559 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006560 return new ProcessRecord(ps, thread, info, proc, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006561 }
6562
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006563 final ProcessRecord addAppLocked(ApplicationInfo info, boolean isolated) {
6564 ProcessRecord app;
6565 if (!isolated) {
6566 app = getProcessRecordLocked(info.processName, info.uid);
6567 } else {
6568 app = null;
6569 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006570
6571 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006572 app = newProcessRecordLocked(null, info, null, isolated);
6573 mProcessNames.put(info.processName, app.uid, app);
6574 if (isolated) {
6575 mIsolatedProcesses.put(app.uid, app);
6576 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08006577 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006578 }
6579
Dianne Hackborne7f97212011-02-24 14:40:20 -08006580 // This package really, really can not be stopped.
6581 try {
6582 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07006583 info.packageName, false, UserId.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -08006584 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006585 } catch (IllegalArgumentException e) {
6586 Slog.w(TAG, "Failed trying to unstop package "
6587 + info.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006588 }
6589
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006590 if ((info.flags&(ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT))
6591 == (ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT)) {
6592 app.persistent = true;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07006593 app.maxAdj = ProcessList.PERSISTENT_PROC_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006594 }
6595 if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) {
6596 mPersistentStartingProcesses.add(app);
6597 startProcessLocked(app, "added application", app.processName);
6598 }
6599
6600 return app;
6601 }
6602
6603 public void unhandledBack() {
6604 enforceCallingPermission(android.Manifest.permission.FORCE_BACK,
6605 "unhandledBack()");
6606
6607 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006608 int count = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08006609 if (DEBUG_SWITCH) Slog.d(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006610 TAG, "Performing unhandledBack(): stack size = " + count);
6611 if (count > 1) {
6612 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006613 mMainStack.finishActivityLocked((ActivityRecord)mMainStack.mHistory.get(count-1),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006614 count-1, Activity.RESULT_CANCELED, null, "unhandled-back");
6615 Binder.restoreCallingIdentity(origId);
6616 }
6617 }
6618 }
6619
6620 public ParcelFileDescriptor openContentUri(Uri uri) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006621 enforceNotIsolatedCaller("openContentUri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006622 String name = uri.getAuthority();
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006623 ContentProviderHolder cph = getContentProviderExternalUnchecked(name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006624 ParcelFileDescriptor pfd = null;
6625 if (cph != null) {
6626 // We record the binder invoker's uid in thread-local storage before
6627 // going to the content provider to open the file. Later, in the code
6628 // that handles all permissions checks, we look for this uid and use
6629 // that rather than the Activity Manager's own uid. The effect is that
6630 // we do the check against the caller's permissions even though it looks
6631 // to the content provider like the Activity Manager itself is making
6632 // the request.
6633 sCallerIdentity.set(new Identity(
6634 Binder.getCallingPid(), Binder.getCallingUid()));
6635 try {
6636 pfd = cph.provider.openFile(uri, "r");
6637 } catch (FileNotFoundException e) {
6638 // do nothing; pfd will be returned null
6639 } finally {
6640 // Ensure that whatever happens, we clean up the identity state
6641 sCallerIdentity.remove();
6642 }
6643
6644 // We've got the fd now, so we're done with the provider.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006645 removeContentProviderExternalUnchecked(name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006646 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006647 Slog.d(TAG, "Failed to get provider for authority '" + name + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006648 }
6649 return pfd;
6650 }
6651
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006652 // Actually is sleeping or shutting down or whatever else in the future
6653 // is an inactive state.
6654 public boolean isSleeping() {
6655 return mSleeping || mShuttingDown;
6656 }
6657
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006658 public void goingToSleep() {
6659 synchronized(this) {
6660 mSleeping = true;
6661 mWindowManager.setEventDispatching(false);
6662
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006663 mMainStack.stopIfSleepingLocked();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006664
6665 // Initialize the wake times of all processes.
Dianne Hackborn287952c2010-09-22 22:34:31 -07006666 checkExcessivePowerUsageLocked(false);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006667 mHandler.removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
6668 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07006669 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006670 }
6671 }
6672
Dianne Hackborn55280a92009-05-07 15:53:46 -07006673 public boolean shutdown(int timeout) {
6674 if (checkCallingPermission(android.Manifest.permission.SHUTDOWN)
6675 != PackageManager.PERMISSION_GRANTED) {
6676 throw new SecurityException("Requires permission "
6677 + android.Manifest.permission.SHUTDOWN);
6678 }
6679
6680 boolean timedout = false;
6681
6682 synchronized(this) {
6683 mShuttingDown = true;
6684 mWindowManager.setEventDispatching(false);
6685
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006686 if (mMainStack.mResumedActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006687 mMainStack.stopIfSleepingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07006688 final long endTime = System.currentTimeMillis() + timeout;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006689 while (mMainStack.mResumedActivity != null
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08006690 || mMainStack.mPausingActivity != null) {
Dianne Hackborn55280a92009-05-07 15:53:46 -07006691 long delay = endTime - System.currentTimeMillis();
6692 if (delay <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006693 Slog.w(TAG, "Activity manager shutdown timed out");
Dianne Hackborn55280a92009-05-07 15:53:46 -07006694 timedout = true;
6695 break;
6696 }
6697 try {
6698 this.wait();
6699 } catch (InterruptedException e) {
6700 }
6701 }
6702 }
6703 }
6704
6705 mUsageStatsService.shutdown();
6706 mBatteryStatsService.shutdown();
6707
6708 return timedout;
6709 }
6710
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006711 public final void activitySlept(IBinder token) {
6712 if (localLOGV) Slog.v(
6713 TAG, "Activity slept: token=" + token);
6714
6715 ActivityRecord r = null;
6716
6717 final long origId = Binder.clearCallingIdentity();
6718
6719 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006720 r = mMainStack.isInStackLocked(token);
6721 if (r != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006722 mMainStack.activitySleptLocked(r);
6723 }
6724 }
6725
6726 Binder.restoreCallingIdentity(origId);
6727 }
6728
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006729 public void wakingUp() {
6730 synchronized(this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006731 mWindowManager.setEventDispatching(true);
6732 mSleeping = false;
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006733 mMainStack.awakeFromSleepingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006734 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006735 }
6736 }
6737
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006738 public void stopAppSwitches() {
6739 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
6740 != PackageManager.PERMISSION_GRANTED) {
6741 throw new SecurityException("Requires permission "
6742 + android.Manifest.permission.STOP_APP_SWITCHES);
6743 }
6744
6745 synchronized(this) {
6746 mAppSwitchesAllowedTime = SystemClock.uptimeMillis()
6747 + APP_SWITCH_DELAY_TIME;
6748 mDidAppSwitch = false;
6749 mHandler.removeMessages(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
6750 Message msg = mHandler.obtainMessage(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
6751 mHandler.sendMessageDelayed(msg, APP_SWITCH_DELAY_TIME);
6752 }
6753 }
6754
6755 public void resumeAppSwitches() {
6756 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
6757 != PackageManager.PERMISSION_GRANTED) {
6758 throw new SecurityException("Requires permission "
6759 + android.Manifest.permission.STOP_APP_SWITCHES);
6760 }
6761
6762 synchronized(this) {
6763 // Note that we don't execute any pending app switches... we will
6764 // let those wait until either the timeout, or the next start
6765 // activity request.
6766 mAppSwitchesAllowedTime = 0;
6767 }
6768 }
6769
6770 boolean checkAppSwitchAllowedLocked(int callingPid, int callingUid,
6771 String name) {
6772 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
6773 return true;
6774 }
6775
6776 final int perm = checkComponentPermission(
6777 android.Manifest.permission.STOP_APP_SWITCHES, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006778 callingUid, -1, true);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006779 if (perm == PackageManager.PERMISSION_GRANTED) {
6780 return true;
6781 }
6782
Joe Onorato8a9b2202010-02-26 18:56:32 -08006783 Slog.w(TAG, name + " request from " + callingUid + " stopped");
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006784 return false;
6785 }
6786
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006787 public void setDebugApp(String packageName, boolean waitForDebugger,
6788 boolean persistent) {
6789 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
6790 "setDebugApp()");
6791
6792 // Note that this is not really thread safe if there are multiple
6793 // callers into it at the same time, but that's not a situation we
6794 // care about.
6795 if (persistent) {
6796 final ContentResolver resolver = mContext.getContentResolver();
6797 Settings.System.putString(
6798 resolver, Settings.System.DEBUG_APP,
6799 packageName);
6800 Settings.System.putInt(
6801 resolver, Settings.System.WAIT_FOR_DEBUGGER,
6802 waitForDebugger ? 1 : 0);
6803 }
6804
6805 synchronized (this) {
6806 if (!persistent) {
6807 mOrigDebugApp = mDebugApp;
6808 mOrigWaitForDebugger = mWaitForDebugger;
6809 }
6810 mDebugApp = packageName;
6811 mWaitForDebugger = waitForDebugger;
6812 mDebugTransient = !persistent;
6813 if (packageName != null) {
6814 final long origId = Binder.clearCallingIdentity();
Amith Yamasani483f3b02012-03-13 16:08:00 -07006815 forceStopPackageLocked(packageName, -1, false, false, true, true, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006816 Binder.restoreCallingIdentity(origId);
6817 }
6818 }
6819 }
6820
Siva Velusamy92a8b222012-03-09 16:24:04 -08006821 void setOpenGlTraceApp(ApplicationInfo app, String processName) {
6822 synchronized (this) {
6823 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
6824 if (!isDebuggable) {
6825 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
6826 throw new SecurityException("Process not debuggable: " + app.packageName);
6827 }
6828 }
6829
6830 mOpenGlTraceApp = processName;
6831 }
6832 }
6833
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07006834 void setProfileApp(ApplicationInfo app, String processName, String profileFile,
6835 ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
6836 synchronized (this) {
6837 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
6838 if (!isDebuggable) {
6839 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
6840 throw new SecurityException("Process not debuggable: " + app.packageName);
6841 }
6842 }
6843 mProfileApp = processName;
6844 mProfileFile = profileFile;
6845 if (mProfileFd != null) {
6846 try {
6847 mProfileFd.close();
6848 } catch (IOException e) {
6849 }
6850 mProfileFd = null;
6851 }
6852 mProfileFd = profileFd;
6853 mProfileType = 0;
6854 mAutoStopProfiler = autoStopProfiler;
6855 }
6856 }
6857
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006858 public void setAlwaysFinish(boolean enabled) {
6859 enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH,
6860 "setAlwaysFinish()");
6861
6862 Settings.System.putInt(
6863 mContext.getContentResolver(),
6864 Settings.System.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0);
6865
6866 synchronized (this) {
6867 mAlwaysFinishActivities = enabled;
6868 }
6869 }
6870
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006871 public void setActivityController(IActivityController controller) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006872 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006873 "setActivityController()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006874 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006875 mController = controller;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006876 }
6877 }
6878
Dianne Hackborn9327f4f2010-01-29 10:38:29 -08006879 public boolean isUserAMonkey() {
6880 // For now the fact that there is a controller implies
6881 // we have a monkey.
6882 synchronized (this) {
6883 return mController != null;
6884 }
6885 }
6886
Jeff Sharkeya4620792011-05-20 15:29:23 -07006887 public void registerProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08006888 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
6889 "registerProcessObserver()");
6890 synchronized (this) {
6891 mProcessObservers.register(observer);
6892 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07006893 }
6894
6895 public void unregisterProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08006896 synchronized (this) {
6897 mProcessObservers.unregister(observer);
6898 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07006899 }
6900
Daniel Sandler69a48172010-06-23 16:29:36 -04006901 public void setImmersive(IBinder token, boolean immersive) {
6902 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006903 ActivityRecord r = mMainStack.isInStackLocked(token);
6904 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04006905 throw new IllegalArgumentException();
6906 }
Daniel Sandler69a48172010-06-23 16:29:36 -04006907 r.immersive = immersive;
6908 }
6909 }
6910
6911 public boolean isImmersive(IBinder token) {
6912 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006913 ActivityRecord r = mMainStack.isInStackLocked(token);
6914 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04006915 throw new IllegalArgumentException();
6916 }
Daniel Sandler69a48172010-06-23 16:29:36 -04006917 return r.immersive;
6918 }
6919 }
6920
6921 public boolean isTopActivityImmersive() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006922 enforceNotIsolatedCaller("startActivity");
Daniel Sandler69a48172010-06-23 16:29:36 -04006923 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006924 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Daniel Sandler69a48172010-06-23 16:29:36 -04006925 return (r != null) ? r.immersive : false;
6926 }
6927 }
6928
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006929 public final void enterSafeMode() {
6930 synchronized(this) {
6931 // It only makes sense to do this before the system is ready
6932 // and started launching other packages.
6933 if (!mSystemReady) {
6934 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006935 AppGlobals.getPackageManager().enterSafeMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006936 } catch (RemoteException e) {
6937 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006938 }
6939 }
6940 }
6941
Jeff Brownb09abc12011-01-13 21:08:27 -08006942 public final void showSafeModeOverlay() {
6943 View v = LayoutInflater.from(mContext).inflate(
6944 com.android.internal.R.layout.safe_mode, null);
6945 WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
6946 lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
6947 lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
6948 lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
6949 lp.gravity = Gravity.BOTTOM | Gravity.LEFT;
6950 lp.format = v.getBackground().getOpacity();
6951 lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
6952 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
6953 ((WindowManager)mContext.getSystemService(
6954 Context.WINDOW_SERVICE)).addView(v, lp);
6955 }
6956
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006957 public void noteWakeupAlarm(IIntentSender sender) {
6958 if (!(sender instanceof PendingIntentRecord)) {
6959 return;
6960 }
6961 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
6962 synchronized (stats) {
6963 if (mBatteryStatsService.isOnBattery()) {
6964 mBatteryStatsService.enforceCallingPermission();
6965 PendingIntentRecord rec = (PendingIntentRecord)sender;
6966 int MY_UID = Binder.getCallingUid();
6967 int uid = rec.uid == MY_UID ? Process.SYSTEM_UID : rec.uid;
6968 BatteryStatsImpl.Uid.Pkg pkg =
6969 stats.getPackageStatsLocked(uid, rec.key.packageName);
6970 pkg.incWakeupsLocked();
6971 }
6972 }
6973 }
6974
Dianne Hackborn64825172011-03-02 21:32:58 -08006975 public boolean killPids(int[] pids, String pReason, boolean secure) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006976 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006977 throw new SecurityException("killPids only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006978 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006979 String reason = (pReason == null) ? "Unknown" : pReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006980 // XXX Note: don't acquire main activity lock here, because the window
6981 // manager calls in with its locks held.
6982
6983 boolean killed = false;
6984 synchronized (mPidsSelfLocked) {
6985 int[] types = new int[pids.length];
6986 int worstType = 0;
6987 for (int i=0; i<pids.length; i++) {
6988 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
6989 if (proc != null) {
6990 int type = proc.setAdj;
6991 types[i] = type;
6992 if (type > worstType) {
6993 worstType = type;
6994 }
6995 }
6996 }
6997
Dianne Hackborn64825172011-03-02 21:32:58 -08006998 // If the worst oom_adj is somewhere in the hidden proc LRU range,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006999 // then constrain it so we will kill all hidden procs.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007000 if (worstType < ProcessList.HIDDEN_APP_MAX_ADJ
7001 && worstType > ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07007002 worstType = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007003 }
Dianne Hackborn64825172011-03-02 21:32:58 -08007004
7005 // If this is not a secure call, don't let it kill processes that
7006 // are important.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007007 if (!secure && worstType < ProcessList.SERVICE_ADJ) {
7008 worstType = ProcessList.SERVICE_ADJ;
Dianne Hackborn64825172011-03-02 21:32:58 -08007009 }
7010
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007011 Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007012 for (int i=0; i<pids.length; i++) {
7013 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7014 if (proc == null) {
7015 continue;
7016 }
7017 int adj = proc.setAdj;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007018 if (adj >= worstType && !proc.killedBackground) {
Dianne Hackborn8633e682010-04-22 16:03:41 -07007019 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007020 EventLog.writeEvent(EventLogTags.AM_KILL, proc.pid,
7021 proc.processName, adj, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007022 killed = true;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007023 proc.killedBackground = true;
7024 Process.killProcessQuiet(pids[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007025 }
7026 }
7027 }
7028 return killed;
7029 }
Jeff Sharkeyb9a07012012-03-22 17:00:04 -07007030
7031 @Override
7032 public boolean killProcessesBelowForeground(String reason) {
7033 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7034 throw new SecurityException("killProcessesBelowForeground() only available to system");
7035 }
7036
7037 return killProcessesBelowAdj(ProcessList.FOREGROUND_APP_ADJ, reason);
7038 }
7039
7040 private boolean killProcessesBelowAdj(int belowAdj, String reason) {
7041 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7042 throw new SecurityException("killProcessesBelowAdj() only available to system");
7043 }
7044
7045 boolean killed = false;
7046 synchronized (mPidsSelfLocked) {
7047 final int size = mPidsSelfLocked.size();
7048 for (int i = 0; i < size; i++) {
7049 final int pid = mPidsSelfLocked.keyAt(i);
7050 final ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7051 if (proc == null) continue;
7052
7053 final int adj = proc.setAdj;
7054 if (adj > belowAdj && !proc.killedBackground) {
7055 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
7056 EventLog.writeEvent(
7057 EventLogTags.AM_KILL, proc.pid, proc.processName, adj, reason);
7058 killed = true;
7059 proc.killedBackground = true;
7060 Process.killProcessQuiet(pid);
7061 }
7062 }
7063 }
7064 return killed;
7065 }
7066
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007067 public final void startRunning(String pkg, String cls, String action,
7068 String data) {
7069 synchronized(this) {
7070 if (mStartRunning) {
7071 return;
7072 }
7073 mStartRunning = true;
7074 mTopComponent = pkg != null && cls != null
7075 ? new ComponentName(pkg, cls) : null;
7076 mTopAction = action != null ? action : Intent.ACTION_MAIN;
7077 mTopData = data;
7078 if (!mSystemReady) {
7079 return;
7080 }
7081 }
7082
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007083 systemReady(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007084 }
7085
7086 private void retrieveSettings() {
7087 final ContentResolver resolver = mContext.getContentResolver();
7088 String debugApp = Settings.System.getString(
7089 resolver, Settings.System.DEBUG_APP);
7090 boolean waitForDebugger = Settings.System.getInt(
7091 resolver, Settings.System.WAIT_FOR_DEBUGGER, 0) != 0;
7092 boolean alwaysFinishActivities = Settings.System.getInt(
7093 resolver, Settings.System.ALWAYS_FINISH_ACTIVITIES, 0) != 0;
7094
7095 Configuration configuration = new Configuration();
7096 Settings.System.getConfiguration(resolver, configuration);
7097
7098 synchronized (this) {
7099 mDebugApp = mOrigDebugApp = debugApp;
7100 mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger;
7101 mAlwaysFinishActivities = alwaysFinishActivities;
7102 // This happens before any activities are started, so we can
7103 // change mConfiguration in-place.
Dianne Hackborn813075a62011-11-14 17:45:19 -08007104 updateConfigurationLocked(configuration, null, false, true);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007105 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Initial config: " + mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007106 }
7107 }
7108
7109 public boolean testIsSystemReady() {
7110 // no need to synchronize(this) just to read & return the value
7111 return mSystemReady;
7112 }
7113
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007114 private static File getCalledPreBootReceiversFile() {
7115 File dataDir = Environment.getDataDirectory();
7116 File systemDir = new File(dataDir, "system");
7117 File fname = new File(systemDir, "called_pre_boots.dat");
7118 return fname;
7119 }
Dianne Hackborn661cd522011-08-22 00:26:20 -07007120
7121 static final int LAST_DONE_VERSION = 10000;
7122
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007123 private static ArrayList<ComponentName> readLastDonePreBootReceivers() {
7124 ArrayList<ComponentName> lastDoneReceivers = new ArrayList<ComponentName>();
7125 File file = getCalledPreBootReceiversFile();
7126 FileInputStream fis = null;
7127 try {
7128 fis = new FileInputStream(file);
7129 DataInputStream dis = new DataInputStream(new BufferedInputStream(fis, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007130 int fvers = dis.readInt();
7131 if (fvers == LAST_DONE_VERSION) {
7132 String vers = dis.readUTF();
7133 String codename = dis.readUTF();
7134 String build = dis.readUTF();
7135 if (android.os.Build.VERSION.RELEASE.equals(vers)
7136 && android.os.Build.VERSION.CODENAME.equals(codename)
7137 && android.os.Build.VERSION.INCREMENTAL.equals(build)) {
7138 int num = dis.readInt();
7139 while (num > 0) {
7140 num--;
7141 String pkg = dis.readUTF();
7142 String cls = dis.readUTF();
7143 lastDoneReceivers.add(new ComponentName(pkg, cls));
7144 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007145 }
7146 }
7147 } catch (FileNotFoundException e) {
7148 } catch (IOException e) {
7149 Slog.w(TAG, "Failure reading last done pre-boot receivers", e);
7150 } finally {
7151 if (fis != null) {
7152 try {
7153 fis.close();
7154 } catch (IOException e) {
7155 }
7156 }
7157 }
7158 return lastDoneReceivers;
7159 }
7160
7161 private static void writeLastDonePreBootReceivers(ArrayList<ComponentName> list) {
7162 File file = getCalledPreBootReceiversFile();
7163 FileOutputStream fos = null;
7164 DataOutputStream dos = null;
7165 try {
7166 Slog.i(TAG, "Writing new set of last done pre-boot receivers...");
7167 fos = new FileOutputStream(file);
7168 dos = new DataOutputStream(new BufferedOutputStream(fos, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007169 dos.writeInt(LAST_DONE_VERSION);
7170 dos.writeUTF(android.os.Build.VERSION.RELEASE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007171 dos.writeUTF(android.os.Build.VERSION.CODENAME);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007172 dos.writeUTF(android.os.Build.VERSION.INCREMENTAL);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007173 dos.writeInt(list.size());
7174 for (int i=0; i<list.size(); i++) {
7175 dos.writeUTF(list.get(i).getPackageName());
7176 dos.writeUTF(list.get(i).getClassName());
7177 }
7178 } catch (IOException e) {
7179 Slog.w(TAG, "Failure writing last done pre-boot receivers", e);
7180 file.delete();
7181 } finally {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07007182 FileUtils.sync(fos);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007183 if (dos != null) {
7184 try {
7185 dos.close();
7186 } catch (IOException e) {
7187 // TODO Auto-generated catch block
7188 e.printStackTrace();
7189 }
7190 }
7191 }
7192 }
7193
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007194 public void systemReady(final Runnable goingCallback) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007195 synchronized(this) {
7196 if (mSystemReady) {
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007197 if (goingCallback != null) goingCallback.run();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007198 return;
7199 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007200
7201 // Check to see if there are any update receivers to run.
7202 if (!mDidUpdate) {
7203 if (mWaitingUpdate) {
7204 return;
7205 }
7206 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
7207 List<ResolveInfo> ris = null;
7208 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007209 ris = AppGlobals.getPackageManager().queryIntentReceivers(
Amith Yamasani483f3b02012-03-13 16:08:00 -07007210 intent, null, 0, 0);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007211 } catch (RemoteException e) {
7212 }
7213 if (ris != null) {
7214 for (int i=ris.size()-1; i>=0; i--) {
7215 if ((ris.get(i).activityInfo.applicationInfo.flags
7216 &ApplicationInfo.FLAG_SYSTEM) == 0) {
7217 ris.remove(i);
7218 }
7219 }
7220 intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007221
7222 ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers();
7223
7224 final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007225 for (int i=0; i<ris.size(); i++) {
7226 ActivityInfo ai = ris.get(i).activityInfo;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007227 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7228 if (lastDoneReceivers.contains(comp)) {
7229 ris.remove(i);
7230 i--;
7231 }
7232 }
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07007233
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007234 for (int i=0; i<ris.size(); i++) {
7235 ActivityInfo ai = ris.get(i).activityInfo;
7236 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7237 doneReceivers.add(comp);
7238 intent.setComponent(comp);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007239 IIntentReceiver finisher = null;
Dianne Hackbornd6847842010-01-12 18:14:19 -08007240 if (i == ris.size()-1) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007241 finisher = new IIntentReceiver.Stub() {
7242 public void performReceive(Intent intent, int resultCode,
Dianne Hackborn68d881c2009-10-05 13:58:17 -07007243 String data, Bundle extras, boolean ordered,
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007244 boolean sticky) {
7245 // The raw IIntentReceiver interface is called
7246 // with the AM lock held, so redispatch to
7247 // execute our code without the lock.
7248 mHandler.post(new Runnable() {
7249 public void run() {
7250 synchronized (ActivityManagerService.this) {
7251 mDidUpdate = true;
7252 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007253 writeLastDonePreBootReceivers(doneReceivers);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007254 showBootMessage(mContext.getText(
7255 R.string.android_upgrading_complete),
7256 false);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007257 systemReady(goingCallback);
7258 }
7259 });
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007260 }
7261 };
7262 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08007263 Slog.i(TAG, "Sending system update to: " + intent.getComponent());
Amith Yamasani742a6712011-05-04 14:49:28 -07007264 /* TODO: Send this to all users */
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007265 broadcastIntentLocked(null, null, intent, null, finisher,
Amith Yamasani742a6712011-05-04 14:49:28 -07007266 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID,
Amith Yamasanic600e21f2012-02-14 16:08:07 -08007267 0 /* UserId zero */);
Dianne Hackbornd6847842010-01-12 18:14:19 -08007268 if (finisher != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007269 mWaitingUpdate = true;
7270 }
7271 }
7272 }
7273 if (mWaitingUpdate) {
7274 return;
7275 }
7276 mDidUpdate = true;
7277 }
7278
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007279 mSystemReady = true;
7280 if (!mStartRunning) {
7281 return;
7282 }
7283 }
7284
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007285 ArrayList<ProcessRecord> procsToKill = null;
7286 synchronized(mPidsSelfLocked) {
7287 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
7288 ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7289 if (!isAllowedWhileBooting(proc.info)){
7290 if (procsToKill == null) {
7291 procsToKill = new ArrayList<ProcessRecord>();
7292 }
7293 procsToKill.add(proc);
7294 }
7295 }
7296 }
7297
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007298 synchronized(this) {
7299 if (procsToKill != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007300 for (int i=procsToKill.size()-1; i>=0; i--) {
7301 ProcessRecord proc = procsToKill.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007302 Slog.i(TAG, "Removing system update proc: " + proc);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007303 removeProcessLocked(proc, true, false, "system update done");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007304 }
7305 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007306
7307 // Now that we have cleaned up any update processes, we
7308 // are ready to start launching real processes and know that
7309 // we won't trample on them any more.
7310 mProcessesReady = true;
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007311 }
7312
Joe Onorato8a9b2202010-02-26 18:56:32 -08007313 Slog.i(TAG, "System now ready");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007314 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007315 SystemClock.uptimeMillis());
7316
7317 synchronized(this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007318 // Make sure we have no pre-ready processes sitting around.
7319
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007320 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
7321 ResolveInfo ri = mContext.getPackageManager()
7322 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST),
Dianne Hackborn1655be42009-05-08 14:29:01 -07007323 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007324 CharSequence errorMsg = null;
7325 if (ri != null) {
7326 ActivityInfo ai = ri.activityInfo;
7327 ApplicationInfo app = ai.applicationInfo;
7328 if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7329 mTopAction = Intent.ACTION_FACTORY_TEST;
7330 mTopData = null;
7331 mTopComponent = new ComponentName(app.packageName,
7332 ai.name);
7333 } else {
7334 errorMsg = mContext.getResources().getText(
7335 com.android.internal.R.string.factorytest_not_system);
7336 }
7337 } else {
7338 errorMsg = mContext.getResources().getText(
7339 com.android.internal.R.string.factorytest_no_action);
7340 }
7341 if (errorMsg != null) {
7342 mTopAction = null;
7343 mTopData = null;
7344 mTopComponent = null;
7345 Message msg = Message.obtain();
7346 msg.what = SHOW_FACTORY_ERROR_MSG;
7347 msg.getData().putCharSequence("msg", errorMsg);
7348 mHandler.sendMessage(msg);
7349 }
7350 }
7351 }
7352
7353 retrieveSettings();
7354
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007355 if (goingCallback != null) goingCallback.run();
7356
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007357 synchronized (this) {
7358 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
7359 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007360 List apps = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07007361 getPersistentApplications(STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007362 if (apps != null) {
7363 int N = apps.size();
7364 int i;
7365 for (i=0; i<N; i++) {
7366 ApplicationInfo info
7367 = (ApplicationInfo)apps.get(i);
7368 if (info != null &&
7369 !info.packageName.equals("android")) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007370 addAppLocked(info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007371 }
7372 }
7373 }
7374 } catch (RemoteException ex) {
7375 // pm is in same process, this will never happen.
7376 }
7377 }
7378
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007379 // Start up initial activity.
7380 mBooting = true;
7381
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007382 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007383 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007384 Message msg = Message.obtain();
7385 msg.what = SHOW_UID_ERROR_MSG;
7386 mHandler.sendMessage(msg);
7387 }
7388 } catch (RemoteException e) {
7389 }
7390
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007391 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007392 }
7393 }
7394
Dan Egnorb7f03672009-12-09 16:22:32 -08007395 private boolean makeAppCrashingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007396 String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007397 app.crashing = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007398 app.crashingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007399 ActivityManager.ProcessErrorStateInfo.CRASHED, null, shortMsg, longMsg, stackTrace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007400 startAppProblemLocked(app);
7401 app.stopFreezingAllLocked();
7402 return handleAppCrashLocked(app);
7403 }
7404
Dan Egnorb7f03672009-12-09 16:22:32 -08007405 private void makeAppNotRespondingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007406 String activity, String shortMsg, String longMsg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007407 app.notResponding = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007408 app.notRespondingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007409 ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING,
7410 activity, shortMsg, longMsg, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007411 startAppProblemLocked(app);
7412 app.stopFreezingAllLocked();
7413 }
7414
7415 /**
7416 * Generate a process error record, suitable for attachment to a ProcessRecord.
7417 *
7418 * @param app The ProcessRecord in which the error occurred.
7419 * @param condition Crashing, Application Not Responding, etc. Values are defined in
7420 * ActivityManager.AppErrorStateInfo
Dan Egnor60d87622009-12-16 16:32:58 -08007421 * @param activity The activity associated with the crash, if known.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007422 * @param shortMsg Short message describing the crash.
7423 * @param longMsg Long message describing the crash.
Dan Egnorb7f03672009-12-09 16:22:32 -08007424 * @param stackTrace Full crash stack trace, may be null.
7425 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007426 * @return Returns a fully-formed AppErrorStateInfo record.
7427 */
7428 private ActivityManager.ProcessErrorStateInfo generateProcessError(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007429 int condition, String activity, String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007430 ActivityManager.ProcessErrorStateInfo report = new ActivityManager.ProcessErrorStateInfo();
Dan Egnorb7f03672009-12-09 16:22:32 -08007431
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007432 report.condition = condition;
7433 report.processName = app.processName;
7434 report.pid = app.pid;
7435 report.uid = app.info.uid;
Dan Egnor60d87622009-12-16 16:32:58 -08007436 report.tag = activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007437 report.shortMsg = shortMsg;
7438 report.longMsg = longMsg;
Dan Egnorb7f03672009-12-09 16:22:32 -08007439 report.stackTrace = stackTrace;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007440
7441 return report;
7442 }
7443
Dan Egnor42471dd2010-01-07 17:25:22 -08007444 void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007445 synchronized (this) {
7446 app.crashing = false;
7447 app.crashingReport = null;
7448 app.notResponding = false;
7449 app.notRespondingReport = null;
7450 if (app.anrDialog == fromDialog) {
7451 app.anrDialog = null;
7452 }
7453 if (app.waitDialog == fromDialog) {
7454 app.waitDialog = null;
7455 }
7456 if (app.pid > 0 && app.pid != MY_PID) {
Dan Egnor42471dd2010-01-07 17:25:22 -08007457 handleAppCrashLocked(app);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007458 Slog.i(ActivityManagerService.TAG, "Killing " + app + ": user's request");
Dianne Hackborn8633e682010-04-22 16:03:41 -07007459 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
7460 app.processName, app.setAdj, "user's request after error");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007461 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007462 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007463 }
7464 }
Dan Egnor42471dd2010-01-07 17:25:22 -08007465
Dan Egnorb7f03672009-12-09 16:22:32 -08007466 private boolean handleAppCrashLocked(ProcessRecord app) {
Mike Lockwood86548c42011-09-13 17:21:46 -04007467 if (mHeadless) {
7468 Log.e(TAG, "handleAppCrashLocked: " + app.processName);
7469 return false;
7470 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007471 long now = SystemClock.uptimeMillis();
7472
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007473 Long crashTime;
7474 if (!app.isolated) {
7475 crashTime = mProcessCrashTimes.get(app.info.processName, app.uid);
7476 } else {
7477 crashTime = null;
7478 }
Dianne Hackborn7d608422011-08-07 16:24:18 -07007479 if (crashTime != null && now < crashTime+ProcessList.MIN_CRASH_INTERVAL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007480 // This process loses!
Joe Onorato8a9b2202010-02-26 18:56:32 -08007481 Slog.w(TAG, "Process " + app.info.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007482 + " has crashed too many times: killing!");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007483 EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007484 app.info.processName, app.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007485 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
7486 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007487 if (r.app == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007488 Slog.w(TAG, " Force finishing activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007489 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007490 r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED, null, "crashed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007491 }
7492 }
7493 if (!app.persistent) {
7494 // We don't want to start this process again until the user
7495 // explicitly does so... but for persistent process, we really
7496 // need to keep it running. If a persistent process is actually
7497 // repeatedly crashing, then badness for everyone.
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007498 EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007499 app.info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007500 if (!app.isolated) {
7501 // XXX We don't have a way to mark isolated processes
7502 // as bad, since they don't have a peristent identity.
7503 mBadProcesses.put(app.info.processName, app.uid, now);
7504 mProcessCrashTimes.remove(app.info.processName, app.uid);
7505 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007506 app.bad = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007507 app.removed = true;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07007508 // Don't let services in this process be restarted and potentially
7509 // annoy the user repeatedly. Unless it is persistent, since those
7510 // processes run critical code.
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007511 removeProcessLocked(app, false, false, "crash");
Dianne Hackborncb44d962011-03-10 17:02:27 -08007512 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007513 return false;
7514 }
Dianne Hackborncb44d962011-03-10 17:02:27 -08007515 mMainStack.resumeTopActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007516 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007517 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Kevin Hester-Chowd87a9be2012-03-05 08:01:00 -08007518 if (r != null && r.app == app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007519 // If the top running activity is from this crashing
7520 // process, then terminate it to avoid getting in a loop.
7521 Slog.w(TAG, " Force finishing activity "
7522 + r.intent.getComponent().flattenToShortString());
Dianne Hackbornbe707852011-11-11 14:32:10 -08007523 int index = mMainStack.indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007524 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007525 Activity.RESULT_CANCELED, null, "crashed");
Dianne Hackborn070783f2010-12-29 16:46:28 -08007526 // Also terminate any activities below it that aren't yet
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007527 // stopped, to avoid a situation where one will get
7528 // re-start our crashing activity once it gets resumed again.
7529 index--;
7530 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007531 r = (ActivityRecord)mMainStack.mHistory.get(index);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007532 if (r.state == ActivityState.RESUMED
7533 || r.state == ActivityState.PAUSING
7534 || r.state == ActivityState.PAUSED) {
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08007535 if (!r.isHomeActivity || mHomeProcess != r.app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007536 Slog.w(TAG, " Force finishing activity "
7537 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007538 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007539 Activity.RESULT_CANCELED, null, "crashed");
7540 }
7541 }
7542 }
7543 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007544 }
7545
7546 // Bump up the crash count of any services currently running in the proc.
7547 if (app.services.size() != 0) {
7548 // Any services running in the application need to be placed
7549 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -07007550 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007551 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07007552 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007553 sr.crashCount++;
7554 }
7555 }
Mattias Larssona4fd0072010-06-22 22:37:03 +02007556
7557 // If the crashing process is what we consider to be the "home process" and it has been
7558 // replaced by a third-party app, clear the package preferred activities from packages
7559 // with a home activity running in the process to prevent a repeatedly crashing app
7560 // from blocking the user to manually clear the list.
7561 if (app == mHomeProcess && mHomeProcess.activities.size() > 0
7562 && (mHomeProcess.info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
7563 Iterator it = mHomeProcess.activities.iterator();
7564 while (it.hasNext()) {
Jean-Baptiste Queru5ea89f72010-07-30 09:30:31 -07007565 ActivityRecord r = (ActivityRecord)it.next();
Mattias Larssona4fd0072010-06-22 22:37:03 +02007566 if (r.isHomeActivity) {
7567 Log.i(TAG, "Clearing package preferred activities from " + r.packageName);
7568 try {
7569 ActivityThread.getPackageManager()
7570 .clearPackagePreferredActivities(r.packageName);
7571 } catch (RemoteException c) {
7572 // pm is in same process, this will never happen.
7573 }
7574 }
7575 }
7576 }
7577
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007578 if (!app.isolated) {
7579 // XXX Can't keep track of crash times for isolated processes,
7580 // because they don't have a perisistent identity.
7581 mProcessCrashTimes.put(app.info.processName, app.uid, now);
7582 }
7583
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007584 return true;
7585 }
7586
7587 void startAppProblemLocked(ProcessRecord app) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08007588 app.errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver(
7589 mContext, app.info.packageName, app.info.flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007590 skipCurrentReceiverLocked(app);
7591 }
7592
7593 void skipCurrentReceiverLocked(ProcessRecord app) {
Christopher Tatef46723b2012-01-26 14:19:24 -08007594 for (BroadcastQueue queue : mBroadcastQueues) {
7595 queue.skipCurrentReceiverLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007596 }
7597 }
7598
Dan Egnor60d87622009-12-16 16:32:58 -08007599 /**
7600 * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes.
7601 * The application process will exit immediately after this call returns.
7602 * @param app object of the crashing app, null for the system server
7603 * @param crashInfo describing the exception
7604 */
7605 public void handleApplicationCrash(IBinder app, ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007606 ProcessRecord r = findAppProcess(app, "Crash");
Jeff Sharkeya353d262011-10-28 11:12:06 -07007607 final String processName = app == null ? "system_server"
7608 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08007609
7610 EventLog.writeEvent(EventLogTags.AM_CRASH, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07007611 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08007612 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08007613 crashInfo.exceptionClassName,
7614 crashInfo.exceptionMessage,
7615 crashInfo.throwFileName,
7616 crashInfo.throwLineNumber);
7617
Jeff Sharkeya353d262011-10-28 11:12:06 -07007618 addErrorToDropBox("crash", r, processName, null, null, null, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08007619
7620 crashApplication(r, crashInfo);
7621 }
7622
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007623 public void handleApplicationStrictModeViolation(
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007624 IBinder app,
7625 int violationMask,
7626 StrictMode.ViolationInfo info) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007627 ProcessRecord r = findAppProcess(app, "StrictMode");
7628 if (r == null) {
7629 return;
7630 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007631
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007632 if ((violationMask & StrictMode.PENALTY_DROPBOX) != 0) {
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08007633 Integer stackFingerprint = info.hashCode();
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007634 boolean logIt = true;
7635 synchronized (mAlreadyLoggedViolatedStacks) {
7636 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) {
7637 logIt = false;
7638 // TODO: sub-sample into EventLog for these, with
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007639 // the info.durationMillis? Then we'd get
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007640 // the relative pain numbers, without logging all
7641 // the stack traces repeatedly. We'd want to do
7642 // likewise in the client code, which also does
7643 // dup suppression, before the Binder call.
7644 } else {
7645 if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) {
7646 mAlreadyLoggedViolatedStacks.clear();
7647 }
7648 mAlreadyLoggedViolatedStacks.add(stackFingerprint);
7649 }
7650 }
7651 if (logIt) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007652 logStrictModeViolationToDropBox(r, info);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007653 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007654 }
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007655
7656 if ((violationMask & StrictMode.PENALTY_DIALOG) != 0) {
7657 AppErrorResult result = new AppErrorResult();
7658 synchronized (this) {
7659 final long origId = Binder.clearCallingIdentity();
7660
7661 Message msg = Message.obtain();
7662 msg.what = SHOW_STRICT_MODE_VIOLATION_MSG;
7663 HashMap<String, Object> data = new HashMap<String, Object>();
7664 data.put("result", result);
7665 data.put("app", r);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007666 data.put("violationMask", violationMask);
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007667 data.put("info", info);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007668 msg.obj = data;
7669 mHandler.sendMessage(msg);
7670
7671 Binder.restoreCallingIdentity(origId);
7672 }
7673 int res = result.get();
Dianne Hackbornb424b632010-08-18 15:59:05 -07007674 Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007675 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007676 }
7677
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007678 // Depending on the policy in effect, there could be a bunch of
7679 // these in quick succession so we try to batch these together to
7680 // minimize disk writes, number of dropbox entries, and maximize
7681 // compression, by having more fewer, larger records.
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007682 private void logStrictModeViolationToDropBox(
7683 ProcessRecord process,
7684 StrictMode.ViolationInfo info) {
7685 if (info == null) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007686 return;
7687 }
7688 final boolean isSystemApp = process == null ||
7689 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM |
7690 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07007691 final String processName = process == null ? "unknown" : process.processName;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007692 final String dropboxTag = isSystemApp ? "system_app_strictmode" : "data_app_strictmode";
7693 final DropBoxManager dbox = (DropBoxManager)
7694 mContext.getSystemService(Context.DROPBOX_SERVICE);
7695
7696 // Exit early if the dropbox isn't configured to accept this report type.
7697 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
7698
7699 boolean bufferWasEmpty;
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007700 boolean needsFlush;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007701 final StringBuilder sb = isSystemApp ? mStrictModeBuffer : new StringBuilder(1024);
7702 synchronized (sb) {
7703 bufferWasEmpty = sb.length() == 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07007704 appendDropBoxProcessHeaders(process, processName, sb);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007705 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
7706 sb.append("System-App: ").append(isSystemApp).append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007707 sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n");
7708 if (info.violationNumThisLoop != 0) {
7709 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n");
7710 }
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07007711 if (info.numAnimationsRunning != 0) {
7712 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n");
7713 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07007714 if (info.broadcastIntentAction != null) {
7715 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n");
7716 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08007717 if (info.durationMillis != -1) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007718 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n");
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007719 }
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08007720 if (info.numInstances != -1) {
7721 sb.append("Instance-Count: ").append(info.numInstances).append("\n");
7722 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08007723 if (info.tags != null) {
7724 for (String tag : info.tags) {
7725 sb.append("Span-Tag: ").append(tag).append("\n");
7726 }
7727 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007728 sb.append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007729 if (info.crashInfo != null && info.crashInfo.stackTrace != null) {
7730 sb.append(info.crashInfo.stackTrace);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007731 }
7732 sb.append("\n");
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007733
7734 // Only buffer up to ~64k. Various logging bits truncate
7735 // things at 128k.
7736 needsFlush = (sb.length() > 64 * 1024);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007737 }
7738
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007739 // Flush immediately if the buffer's grown too large, or this
7740 // is a non-system app. Non-system apps are isolated with a
7741 // different tag & policy and not batched.
7742 //
7743 // Batching is useful during internal testing with
7744 // StrictMode settings turned up high. Without batching,
7745 // thousands of separate files could be created on boot.
7746 if (!isSystemApp || needsFlush) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007747 new Thread("Error dump: " + dropboxTag) {
7748 @Override
7749 public void run() {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007750 String report;
7751 synchronized (sb) {
7752 report = sb.toString();
7753 sb.delete(0, sb.length());
7754 sb.trimToSize();
7755 }
7756 if (report.length() != 0) {
7757 dbox.addText(dropboxTag, report);
7758 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007759 }
7760 }.start();
7761 return;
7762 }
7763
7764 // System app batching:
7765 if (!bufferWasEmpty) {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007766 // An existing dropbox-writing thread is outstanding, so
7767 // we don't need to start it up. The existing thread will
7768 // catch the buffer appends we just did.
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007769 return;
7770 }
7771
7772 // Worker thread to both batch writes and to avoid blocking the caller on I/O.
7773 // (After this point, we shouldn't access AMS internal data structures.)
7774 new Thread("Error dump: " + dropboxTag) {
7775 @Override
7776 public void run() {
7777 // 5 second sleep to let stacks arrive and be batched together
7778 try {
7779 Thread.sleep(5000); // 5 seconds
7780 } catch (InterruptedException e) {}
7781
7782 String errorReport;
7783 synchronized (mStrictModeBuffer) {
7784 errorReport = mStrictModeBuffer.toString();
7785 if (errorReport.length() == 0) {
7786 return;
7787 }
7788 mStrictModeBuffer.delete(0, mStrictModeBuffer.length());
7789 mStrictModeBuffer.trimToSize();
7790 }
7791 dbox.addText(dropboxTag, errorReport);
7792 }
7793 }.start();
7794 }
7795
Dan Egnor60d87622009-12-16 16:32:58 -08007796 /**
7797 * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors.
7798 * @param app object of the crashing app, null for the system server
7799 * @param tag reported by the caller
7800 * @param crashInfo describing the context of the error
7801 * @return true if the process should exit immediately (WTF is fatal)
7802 */
7803 public boolean handleApplicationWtf(IBinder app, String tag,
Dan Egnorb7f03672009-12-09 16:22:32 -08007804 ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007805 ProcessRecord r = findAppProcess(app, "WTF");
Jeff Sharkeya353d262011-10-28 11:12:06 -07007806 final String processName = app == null ? "system_server"
7807 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08007808
7809 EventLog.writeEvent(EventLogTags.AM_WTF, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07007810 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08007811 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08007812 tag, crashInfo.exceptionMessage);
7813
Jeff Sharkeya353d262011-10-28 11:12:06 -07007814 addErrorToDropBox("wtf", r, processName, null, null, tag, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08007815
Dianne Hackborn1ab43772011-03-15 14:38:02 -07007816 if (r != null && r.pid != Process.myPid() &&
7817 Settings.Secure.getInt(mContext.getContentResolver(),
7818 Settings.Secure.WTF_IS_FATAL, 0) != 0) {
Dan Egnor60d87622009-12-16 16:32:58 -08007819 crashApplication(r, crashInfo);
7820 return true;
7821 } else {
7822 return false;
7823 }
7824 }
7825
7826 /**
7827 * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit})
7828 * @return the corresponding {@link ProcessRecord} object, or null if none could be found
7829 */
Dianne Hackborncb44d962011-03-10 17:02:27 -08007830 private ProcessRecord findAppProcess(IBinder app, String reason) {
Dan Egnor60d87622009-12-16 16:32:58 -08007831 if (app == null) {
7832 return null;
7833 }
7834
7835 synchronized (this) {
7836 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
7837 final int NA = apps.size();
7838 for (int ia=0; ia<NA; ia++) {
7839 ProcessRecord p = apps.valueAt(ia);
7840 if (p.thread != null && p.thread.asBinder() == app) {
7841 return p;
7842 }
7843 }
7844 }
7845
Dianne Hackborncb44d962011-03-10 17:02:27 -08007846 Slog.w(TAG, "Can't find mystery application for " + reason
7847 + " from pid=" + Binder.getCallingPid()
7848 + " uid=" + Binder.getCallingUid() + ": " + app);
Dan Egnor60d87622009-12-16 16:32:58 -08007849 return null;
7850 }
7851 }
7852
7853 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007854 * Utility function for addErrorToDropBox and handleStrictModeViolation's logging
7855 * to append various headers to the dropbox log text.
Dan Egnor60d87622009-12-16 16:32:58 -08007856 */
Jeff Sharkeya353d262011-10-28 11:12:06 -07007857 private void appendDropBoxProcessHeaders(ProcessRecord process, String processName,
7858 StringBuilder sb) {
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08007859 // Watchdog thread ends up invoking this function (with
7860 // a null ProcessRecord) to add the stack file to dropbox.
7861 // Do not acquire a lock on this (am) in such cases, as it
7862 // could cause a potential deadlock, if and when watchdog
7863 // is invoked due to unavailability of lock on am and it
7864 // would prevent watchdog from killing system_server.
7865 if (process == null) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07007866 sb.append("Process: ").append(processName).append("\n");
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08007867 return;
7868 }
Brad Fitzpatrick1e02d362010-09-10 09:19:50 -07007869 // Note: ProcessRecord 'process' is guarded by the service
7870 // instance. (notably process.pkgList, which could otherwise change
7871 // concurrently during execution of this method)
7872 synchronized (this) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07007873 sb.append("Process: ").append(processName).append("\n");
Dan Egnora455d192010-03-12 08:52:28 -08007874 int flags = process.info.flags;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007875 IPackageManager pm = AppGlobals.getPackageManager();
Dan Egnora455d192010-03-12 08:52:28 -08007876 sb.append("Flags: 0x").append(Integer.toString(flags, 16)).append("\n");
7877 for (String pkg : process.pkgList) {
7878 sb.append("Package: ").append(pkg);
Dan Egnor42471dd2010-01-07 17:25:22 -08007879 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07007880 PackageInfo pi = pm.getPackageInfo(pkg, 0, 0);
Dan Egnora455d192010-03-12 08:52:28 -08007881 if (pi != null) {
7882 sb.append(" v").append(pi.versionCode);
7883 if (pi.versionName != null) {
7884 sb.append(" (").append(pi.versionName).append(")");
7885 }
7886 }
7887 } catch (RemoteException e) {
7888 Slog.e(TAG, "Error getting package info: " + pkg, e);
Dan Egnor60d87622009-12-16 16:32:58 -08007889 }
Dan Egnora455d192010-03-12 08:52:28 -08007890 sb.append("\n");
Dan Egnor60d87622009-12-16 16:32:58 -08007891 }
Dan Egnora455d192010-03-12 08:52:28 -08007892 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007893 }
7894
7895 private static String processClass(ProcessRecord process) {
7896 if (process == null || process.pid == MY_PID) {
7897 return "system_server";
7898 } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
7899 return "system_app";
7900 } else {
7901 return "data_app";
7902 }
7903 }
7904
7905 /**
7906 * Write a description of an error (crash, WTF, ANR) to the drop box.
7907 * @param eventType to include in the drop box tag ("crash", "wtf", etc.)
7908 * @param process which caused the error, null means the system server
7909 * @param activity which triggered the error, null if unknown
7910 * @param parent activity related to the error, null if unknown
7911 * @param subject line related to the error, null if absent
7912 * @param report in long form describing the error, null if absent
7913 * @param logFile to include in the report, null if none
7914 * @param crashInfo giving an application stack trace, null if absent
7915 */
7916 public void addErrorToDropBox(String eventType,
Jeff Sharkeya353d262011-10-28 11:12:06 -07007917 ProcessRecord process, String processName, ActivityRecord activity,
7918 ActivityRecord parent, String subject,
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007919 final String report, final File logFile,
7920 final ApplicationErrorReport.CrashInfo crashInfo) {
7921 // NOTE -- this must never acquire the ActivityManagerService lock,
7922 // otherwise the watchdog may be prevented from resetting the system.
7923
7924 final String dropboxTag = processClass(process) + "_" + eventType;
7925 final DropBoxManager dbox = (DropBoxManager)
7926 mContext.getSystemService(Context.DROPBOX_SERVICE);
7927
7928 // Exit early if the dropbox isn't configured to accept this report type.
7929 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
7930
7931 final StringBuilder sb = new StringBuilder(1024);
Jeff Sharkeya353d262011-10-28 11:12:06 -07007932 appendDropBoxProcessHeaders(process, processName, sb);
Dan Egnora455d192010-03-12 08:52:28 -08007933 if (activity != null) {
7934 sb.append("Activity: ").append(activity.shortComponentName).append("\n");
7935 }
7936 if (parent != null && parent.app != null && parent.app.pid != process.pid) {
7937 sb.append("Parent-Process: ").append(parent.app.processName).append("\n");
7938 }
7939 if (parent != null && parent != activity) {
7940 sb.append("Parent-Activity: ").append(parent.shortComponentName).append("\n");
7941 }
7942 if (subject != null) {
7943 sb.append("Subject: ").append(subject).append("\n");
7944 }
7945 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
Christian Lindeberg03d2ca62010-09-28 14:52:20 +02007946 if (Debug.isDebuggerConnected()) {
7947 sb.append("Debugger: Connected\n");
7948 }
Dan Egnora455d192010-03-12 08:52:28 -08007949 sb.append("\n");
7950
7951 // Do the rest in a worker thread to avoid blocking the caller on I/O
7952 // (After this point, we shouldn't access AMS internal data structures.)
7953 Thread worker = new Thread("Error dump: " + dropboxTag) {
7954 @Override
7955 public void run() {
7956 if (report != null) {
7957 sb.append(report);
7958 }
7959 if (logFile != null) {
7960 try {
7961 sb.append(FileUtils.readTextFile(logFile, 128 * 1024, "\n\n[[TRUNCATED]]"));
7962 } catch (IOException e) {
7963 Slog.e(TAG, "Error reading " + logFile, e);
7964 }
7965 }
7966 if (crashInfo != null && crashInfo.stackTrace != null) {
7967 sb.append(crashInfo.stackTrace);
7968 }
7969
7970 String setting = Settings.Secure.ERROR_LOGCAT_PREFIX + dropboxTag;
7971 int lines = Settings.Secure.getInt(mContext.getContentResolver(), setting, 0);
7972 if (lines > 0) {
7973 sb.append("\n");
7974
7975 // Merge several logcat streams, and take the last N lines
7976 InputStreamReader input = null;
7977 try {
7978 java.lang.Process logcat = new ProcessBuilder("/system/bin/logcat",
7979 "-v", "time", "-b", "events", "-b", "system", "-b", "main",
7980 "-t", String.valueOf(lines)).redirectErrorStream(true).start();
7981
7982 try { logcat.getOutputStream().close(); } catch (IOException e) {}
7983 try { logcat.getErrorStream().close(); } catch (IOException e) {}
7984 input = new InputStreamReader(logcat.getInputStream());
7985
7986 int num;
7987 char[] buf = new char[8192];
7988 while ((num = input.read(buf)) > 0) sb.append(buf, 0, num);
7989 } catch (IOException e) {
7990 Slog.e(TAG, "Error running logcat", e);
7991 } finally {
7992 if (input != null) try { input.close(); } catch (IOException e) {}
7993 }
7994 }
7995
7996 dbox.addText(dropboxTag, sb.toString());
Dan Egnor60d87622009-12-16 16:32:58 -08007997 }
Dan Egnora455d192010-03-12 08:52:28 -08007998 };
7999
8000 if (process == null || process.pid == MY_PID) {
8001 worker.run(); // We may be about to die -- need to run this synchronously
8002 } else {
8003 worker.start();
Dan Egnor60d87622009-12-16 16:32:58 -08008004 }
8005 }
8006
8007 /**
8008 * Bring up the "unexpected error" dialog box for a crashing app.
8009 * Deal with edge cases (intercepts from instrumented applications,
8010 * ActivityController, error intent receivers, that sort of thing).
8011 * @param r the application crashing
8012 * @param crashInfo describing the failure
8013 */
8014 private void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008015 long timeMillis = System.currentTimeMillis();
8016 String shortMsg = crashInfo.exceptionClassName;
8017 String longMsg = crashInfo.exceptionMessage;
8018 String stackTrace = crashInfo.stackTrace;
8019 if (shortMsg != null && longMsg != null) {
8020 longMsg = shortMsg + ": " + longMsg;
8021 } else if (shortMsg != null) {
8022 longMsg = shortMsg;
8023 }
8024
Dan Egnor60d87622009-12-16 16:32:58 -08008025 AppErrorResult result = new AppErrorResult();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008026 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008027 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008028 try {
8029 String name = r != null ? r.processName : null;
8030 int pid = r != null ? r.pid : Binder.getCallingPid();
Dan Egnor60d87622009-12-16 16:32:58 -08008031 if (!mController.appCrashed(name, pid,
Dan Egnorb7f03672009-12-09 16:22:32 -08008032 shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008033 Slog.w(TAG, "Force-killing crashed app " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008034 + " at watcher's request");
8035 Process.killProcess(pid);
Dan Egnorb7f03672009-12-09 16:22:32 -08008036 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008037 }
8038 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008039 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008040 }
8041 }
8042
8043 final long origId = Binder.clearCallingIdentity();
8044
8045 // If this process is running instrumentation, finish it.
8046 if (r != null && r.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008047 Slog.w(TAG, "Error in app " + r.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008048 + " running instrumentation " + r.instrumentationClass + ":");
Joe Onorato8a9b2202010-02-26 18:56:32 -08008049 if (shortMsg != null) Slog.w(TAG, " " + shortMsg);
8050 if (longMsg != null) Slog.w(TAG, " " + longMsg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008051 Bundle info = new Bundle();
8052 info.putString("shortMsg", shortMsg);
8053 info.putString("longMsg", longMsg);
8054 finishInstrumentationLocked(r, Activity.RESULT_CANCELED, info);
8055 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008056 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008057 }
8058
Dan Egnor60d87622009-12-16 16:32:58 -08008059 // If we can't identify the process or it's already exceeded its crash quota,
8060 // quit right away without showing a crash dialog.
8061 if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008062 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008063 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008064 }
8065
8066 Message msg = Message.obtain();
8067 msg.what = SHOW_ERROR_MSG;
8068 HashMap data = new HashMap();
8069 data.put("result", result);
8070 data.put("app", r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008071 msg.obj = data;
8072 mHandler.sendMessage(msg);
8073
8074 Binder.restoreCallingIdentity(origId);
8075 }
8076
8077 int res = result.get();
8078
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008079 Intent appErrorIntent = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008080 synchronized (this) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008081 if (r != null && !r.isolated) {
8082 // XXX Can't keep track of crash time for isolated processes,
8083 // since they don't have a persistent identity.
8084 mProcessCrashTimes.put(r.info.processName, r.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008085 SystemClock.uptimeMillis());
8086 }
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008087 if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008088 appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008089 }
8090 }
8091
8092 if (appErrorIntent != null) {
8093 try {
8094 mContext.startActivity(appErrorIntent);
8095 } catch (ActivityNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008096 Slog.w(TAG, "bug report receiver dissappeared", e);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008097 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008098 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008099 }
Dan Egnorb7f03672009-12-09 16:22:32 -08008100
8101 Intent createAppErrorIntentLocked(ProcessRecord r,
8102 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
8103 ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008104 if (report == null) {
8105 return null;
8106 }
8107 Intent result = new Intent(Intent.ACTION_APP_ERROR);
8108 result.setComponent(r.errorReportReceiver);
8109 result.putExtra(Intent.EXTRA_BUG_REPORT, report);
8110 result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
8111 return result;
8112 }
8113
Dan Egnorb7f03672009-12-09 16:22:32 -08008114 private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r,
8115 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008116 if (r.errorReportReceiver == null) {
8117 return null;
8118 }
8119
8120 if (!r.crashing && !r.notResponding) {
8121 return null;
8122 }
8123
Dan Egnorb7f03672009-12-09 16:22:32 -08008124 ApplicationErrorReport report = new ApplicationErrorReport();
8125 report.packageName = r.info.packageName;
8126 report.installerPackageName = r.errorReportReceiver.getPackageName();
8127 report.processName = r.processName;
8128 report.time = timeMillis;
Jacek Surazskie0ee6ef2010-01-07 16:23:03 +01008129 report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008130
Dan Egnorb7f03672009-12-09 16:22:32 -08008131 if (r.crashing) {
8132 report.type = ApplicationErrorReport.TYPE_CRASH;
8133 report.crashInfo = crashInfo;
8134 } else if (r.notResponding) {
8135 report.type = ApplicationErrorReport.TYPE_ANR;
8136 report.anrInfo = new ApplicationErrorReport.AnrInfo();
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008137
Dan Egnorb7f03672009-12-09 16:22:32 -08008138 report.anrInfo.activity = r.notRespondingReport.tag;
8139 report.anrInfo.cause = r.notRespondingReport.shortMsg;
8140 report.anrInfo.info = r.notRespondingReport.longMsg;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008141 }
8142
Dan Egnorb7f03672009-12-09 16:22:32 -08008143 return report;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008144 }
8145
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008146 public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008147 enforceNotIsolatedCaller("getProcessesInErrorState");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008148 // assume our apps are happy - lazy create the list
8149 List<ActivityManager.ProcessErrorStateInfo> errList = null;
8150
8151 synchronized (this) {
8152
8153 // iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008154 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8155 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008156 if ((app.thread != null) && (app.crashing || app.notResponding)) {
8157 // This one's in trouble, so we'll generate a report for it
8158 // crashes are higher priority (in case there's a crash *and* an anr)
8159 ActivityManager.ProcessErrorStateInfo report = null;
8160 if (app.crashing) {
8161 report = app.crashingReport;
8162 } else if (app.notResponding) {
8163 report = app.notRespondingReport;
8164 }
8165
8166 if (report != null) {
8167 if (errList == null) {
8168 errList = new ArrayList<ActivityManager.ProcessErrorStateInfo>(1);
8169 }
8170 errList.add(report);
8171 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008172 Slog.w(TAG, "Missing app error report, app = " + app.processName +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008173 " crashing = " + app.crashing +
8174 " notResponding = " + app.notResponding);
8175 }
8176 }
8177 }
8178 }
8179
8180 return errList;
8181 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07008182
8183 static int oomAdjToImportance(int adj, ActivityManager.RunningAppProcessInfo currApp) {
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008184 if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008185 if (currApp != null) {
8186 currApp.lru = adj - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
8187 }
8188 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008189 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
8190 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008191 } else if (adj >= ProcessList.HOME_APP_ADJ) {
8192 if (currApp != null) {
8193 currApp.lru = 0;
8194 }
8195 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008196 } else if (adj >= ProcessList.SERVICE_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008197 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
8198 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
8199 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
8200 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
8201 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
8202 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
8203 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
8204 } else {
8205 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
8206 }
8207 }
8208
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008209 private void fillInProcMemInfo(ProcessRecord app,
8210 ActivityManager.RunningAppProcessInfo outInfo) {
8211 outInfo.pid = app.pid;
8212 outInfo.uid = app.info.uid;
8213 if (mHeavyWeightProcess == app) {
8214 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_CANT_SAVE_STATE;
8215 }
8216 if (app.persistent) {
8217 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_PERSISTENT;
8218 }
8219 outInfo.lastTrimLevel = app.trimMemoryLevel;
8220 int adj = app.curAdj;
8221 outInfo.importance = oomAdjToImportance(adj, outInfo);
8222 outInfo.importanceReasonCode = app.adjTypeCode;
8223 }
8224
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008225 public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008226 enforceNotIsolatedCaller("getRunningAppProcesses");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008227 // Lazy instantiation of list
8228 List<ActivityManager.RunningAppProcessInfo> runList = null;
8229 synchronized (this) {
8230 // Iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008231 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8232 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008233 if ((app.thread != null) && (!app.crashing && !app.notResponding)) {
8234 // Generate process state info for running application
8235 ActivityManager.RunningAppProcessInfo currApp =
8236 new ActivityManager.RunningAppProcessInfo(app.processName,
8237 app.pid, app.getPackageList());
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008238 fillInProcMemInfo(app, currApp);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008239 if (app.adjSource instanceof ProcessRecord) {
8240 currApp.importanceReasonPid = ((ProcessRecord)app.adjSource).pid;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008241 currApp.importanceReasonImportance = oomAdjToImportance(
8242 app.adjSourceOom, null);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008243 } else if (app.adjSource instanceof ActivityRecord) {
8244 ActivityRecord r = (ActivityRecord)app.adjSource;
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008245 if (r.app != null) currApp.importanceReasonPid = r.app.pid;
8246 }
8247 if (app.adjTarget instanceof ComponentName) {
8248 currApp.importanceReasonComponent = (ComponentName)app.adjTarget;
8249 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08008250 //Slog.v(TAG, "Proc " + app.processName + ": imp=" + currApp.importance
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008251 // + " lru=" + currApp.lru);
8252 if (runList == null) {
8253 runList = new ArrayList<ActivityManager.RunningAppProcessInfo>();
8254 }
8255 runList.add(currApp);
8256 }
8257 }
8258 }
8259 return runList;
8260 }
8261
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008262 public List<ApplicationInfo> getRunningExternalApplications() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008263 enforceNotIsolatedCaller("getRunningExternalApplications");
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008264 List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses();
8265 List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>();
8266 if (runningApps != null && runningApps.size() > 0) {
8267 Set<String> extList = new HashSet<String>();
8268 for (ActivityManager.RunningAppProcessInfo app : runningApps) {
8269 if (app.pkgList != null) {
8270 for (String pkg : app.pkgList) {
8271 extList.add(pkg);
8272 }
8273 }
8274 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008275 IPackageManager pm = AppGlobals.getPackageManager();
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008276 for (String pkg : extList) {
8277 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07008278 ApplicationInfo info = pm.getApplicationInfo(pkg, 0, UserId.getCallingUserId());
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008279 if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
8280 retList.add(info);
8281 }
8282 } catch (RemoteException e) {
8283 }
8284 }
8285 }
8286 return retList;
8287 }
8288
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008289 @Override
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008290 public void getMyMemoryState(ActivityManager.RunningAppProcessInfo outInfo) {
8291 enforceNotIsolatedCaller("getMyMemoryState");
8292 synchronized (this) {
8293 ProcessRecord proc;
8294 synchronized (mPidsSelfLocked) {
8295 proc = mPidsSelfLocked.get(Binder.getCallingPid());
8296 }
8297 fillInProcMemInfo(proc, outInfo);
8298 }
8299 }
8300
8301 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008302 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008303 if (checkCallingPermission(android.Manifest.permission.DUMP)
8304 != PackageManager.PERMISSION_GRANTED) {
8305 pw.println("Permission Denial: can't dump ActivityManager from from pid="
8306 + Binder.getCallingPid()
8307 + ", uid=" + Binder.getCallingUid()
8308 + " without permission "
8309 + android.Manifest.permission.DUMP);
8310 return;
8311 }
8312
8313 boolean dumpAll = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008314 boolean dumpClient = false;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008315 String dumpPackage = null;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008316
8317 int opti = 0;
8318 while (opti < args.length) {
8319 String opt = args[opti];
8320 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
8321 break;
8322 }
8323 opti++;
8324 if ("-a".equals(opt)) {
8325 dumpAll = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008326 } else if ("-c".equals(opt)) {
8327 dumpClient = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008328 } else if ("-h".equals(opt)) {
8329 pw.println("Activity manager dump options:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008330 pw.println(" [-a] [-c] [-h] [cmd] ...");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008331 pw.println(" cmd may be one of:");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008332 pw.println(" a[ctivities]: activity stack state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008333 pw.println(" b[roadcasts] [PACKAGE_NAME]: broadcast state");
8334 pw.println(" i[ntents] [PACKAGE_NAME]: pending intent state");
8335 pw.println(" p[rocesses] [PACKAGE_NAME]: process state");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008336 pw.println(" o[om]: out of memory management");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008337 pw.println(" prov[iders] [COMP_SPEC ...]: content provider state");
Marco Nelissen18cb2872011-11-15 11:19:53 -08008338 pw.println(" provider [COMP_SPEC]: provider client-side state");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008339 pw.println(" s[ervices] [COMP_SPEC ...]: service state");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008340 pw.println(" service [COMP_SPEC]: service client-side state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008341 pw.println(" package [PACKAGE_NAME]: all state related to given package");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008342 pw.println(" all: dump all activities");
8343 pw.println(" top: dump the top activity");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008344 pw.println(" cmd may also be a COMP_SPEC to dump activities.");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008345 pw.println(" COMP_SPEC may be a component name (com.foo/.myApp),");
8346 pw.println(" a partial substring in a component name, a");
8347 pw.println(" hex object identifier.");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008348 pw.println(" -a: include all available server state.");
8349 pw.println(" -c: include client state.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008350 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008351 } else {
8352 pw.println("Unknown argument: " + opt + "; use -h for help");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008353 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008354 }
8355
8356 // Is the caller requesting to dump a particular piece of data?
8357 if (opti < args.length) {
8358 String cmd = args[opti];
8359 opti++;
8360 if ("activities".equals(cmd) || "a".equals(cmd)) {
8361 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008362 dumpActivitiesLocked(fd, pw, args, opti, true, dumpClient, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008363 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008364 return;
8365 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008366 String[] newArgs;
8367 String name;
8368 if (opti >= args.length) {
8369 name = null;
8370 newArgs = EMPTY_STRING_ARRAY;
8371 } else {
8372 name = args[opti];
8373 opti++;
8374 newArgs = new String[args.length - opti];
8375 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8376 args.length - opti);
8377 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008378 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008379 dumpBroadcastsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008380 }
8381 return;
8382 } else if ("intents".equals(cmd) || "i".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008383 String[] newArgs;
8384 String name;
8385 if (opti >= args.length) {
8386 name = null;
8387 newArgs = EMPTY_STRING_ARRAY;
8388 } else {
8389 name = args[opti];
8390 opti++;
8391 newArgs = new String[args.length - opti];
8392 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8393 args.length - opti);
8394 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008395 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008396 dumpPendingIntentsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008397 }
8398 return;
8399 } else if ("processes".equals(cmd) || "p".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008400 String[] newArgs;
8401 String name;
8402 if (opti >= args.length) {
8403 name = null;
8404 newArgs = EMPTY_STRING_ARRAY;
8405 } else {
8406 name = args[opti];
8407 opti++;
8408 newArgs = new String[args.length - opti];
8409 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8410 args.length - opti);
8411 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008412 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008413 dumpProcessesLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008414 }
8415 return;
Dianne Hackborn287952c2010-09-22 22:34:31 -07008416 } else if ("oom".equals(cmd) || "o".equals(cmd)) {
8417 synchronized (this) {
8418 dumpOomLocked(fd, pw, args, opti, true);
8419 }
8420 return;
Marco Nelissen18cb2872011-11-15 11:19:53 -08008421 } else if ("provider".equals(cmd)) {
8422 String[] newArgs;
8423 String name;
8424 if (opti >= args.length) {
8425 name = null;
8426 newArgs = EMPTY_STRING_ARRAY;
8427 } else {
8428 name = args[opti];
8429 opti++;
8430 newArgs = new String[args.length - opti];
8431 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
8432 }
8433 if (!dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) {
8434 pw.println("No providers match: " + name);
8435 pw.println("Use -h for help.");
8436 }
8437 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008438 } else if ("providers".equals(cmd) || "prov".equals(cmd)) {
8439 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008440 dumpProvidersLocked(fd, pw, args, opti, true, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008441 }
8442 return;
8443 } else if ("service".equals(cmd)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008444 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];
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008453 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8454 args.length - opti);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008455 }
8456 if (!dumpService(fd, pw, name, newArgs, 0, dumpAll)) {
8457 pw.println("No services match: " + name);
8458 pw.println("Use -h for help.");
8459 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008460 return;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008461 } else if ("package".equals(cmd)) {
8462 String[] newArgs;
8463 if (opti >= args.length) {
8464 pw.println("package: no package name specified");
8465 pw.println("Use -h for help.");
8466 return;
8467 } else {
8468 dumpPackage = args[opti];
8469 opti++;
8470 newArgs = new String[args.length - opti];
8471 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8472 args.length - opti);
8473 args = newArgs;
8474 opti = 0;
8475 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008476 } else if ("services".equals(cmd) || "s".equals(cmd)) {
8477 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008478 dumpServicesLocked(fd, pw, args, opti, true, dumpClient, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008479 }
8480 return;
Dianne Hackborn625ac272010-09-17 18:29:22 -07008481 } else {
8482 // Dumping a single activity?
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008483 if (!dumpActivity(fd, pw, cmd, args, opti, dumpAll)) {
8484 pw.println("Bad activity command, or no activities match: " + cmd);
8485 pw.println("Use -h for help.");
Dianne Hackborn625ac272010-09-17 18:29:22 -07008486 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08008487 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008488 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008489 }
8490
8491 // No piece of data specified, dump everything.
8492 synchronized (this) {
8493 boolean needSep;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008494 needSep = dumpPendingIntentsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008495 if (needSep) {
8496 pw.println(" ");
8497 }
8498 if (dumpAll) {
8499 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008500 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008501 needSep = dumpBroadcastsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008502 if (needSep) {
8503 pw.println(" ");
8504 }
8505 if (dumpAll) {
8506 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008507 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008508 needSep = dumpProvidersLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008509 if (needSep) {
8510 pw.println(" ");
8511 }
8512 if (dumpAll) {
8513 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008514 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008515 needSep = dumpServicesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008516 if (needSep) {
8517 pw.println(" ");
8518 }
8519 if (dumpAll) {
8520 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008521 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008522 needSep = dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008523 if (needSep) {
8524 pw.println(" ");
8525 }
8526 if (dumpAll) {
8527 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008528 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008529 dumpProcessesLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008530 }
8531 }
8532
8533 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008534 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008535 pw.println("ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
8536 pw.println(" Main stack:");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008537 dumpHistoryList(fd, pw, mMainStack.mHistory, " ", "Hist", true, !dumpAll, dumpClient,
8538 dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008539 pw.println(" ");
8540 pw.println(" Running activities (most recent first):");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008541 dumpHistoryList(fd, pw, mMainStack.mLRUActivities, " ", "Run", false, !dumpAll, false,
8542 dumpPackage);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008543 if (mMainStack.mWaitingVisibleActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008544 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008545 pw.println(" Activities waiting for another to become visible:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008546 dumpHistoryList(fd, pw, mMainStack.mWaitingVisibleActivities, " ", "Wait", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008547 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008548 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008549 if (mMainStack.mStoppingActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008550 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008551 pw.println(" Activities waiting to stop:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008552 dumpHistoryList(fd, pw, mMainStack.mStoppingActivities, " ", "Stop", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008553 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008554 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008555 if (mMainStack.mGoingToSleepActivities.size() > 0) {
8556 pw.println(" ");
8557 pw.println(" Activities waiting to sleep:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008558 dumpHistoryList(fd, pw, mMainStack.mGoingToSleepActivities, " ", "Sleep", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008559 !dumpAll, false, dumpPackage);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008560 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008561 if (mMainStack.mFinishingActivities.size() > 0) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008562 pw.println(" ");
8563 pw.println(" Activities waiting to finish:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008564 dumpHistoryList(fd, pw, mMainStack.mFinishingActivities, " ", "Fin", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008565 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008566 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008567
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008568 pw.println(" ");
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08008569 if (mMainStack.mPausingActivity != null) {
8570 pw.println(" mPausingActivity: " + mMainStack.mPausingActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008571 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008572 pw.println(" mResumedActivity: " + mMainStack.mResumedActivity);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008573 pw.println(" mFocusedActivity: " + mFocusedActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008574 if (dumpAll) {
8575 pw.println(" mLastPausedActivity: " + mMainStack.mLastPausedActivity);
8576 pw.println(" mSleepTimeout: " + mMainStack.mSleepTimeout);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07008577 pw.println(" mDismissKeyguardOnNextActivity: "
8578 + mMainStack.mDismissKeyguardOnNextActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008579 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008580
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008581 if (mRecentTasks.size() > 0) {
8582 pw.println();
8583 pw.println(" Recent tasks:");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008584
8585 final int N = mRecentTasks.size();
8586 for (int i=0; i<N; i++) {
8587 TaskRecord tr = mRecentTasks.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008588 if (dumpPackage != null) {
8589 if (tr.realActivity == null ||
8590 !dumpPackage.equals(tr.realActivity)) {
8591 continue;
8592 }
8593 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008594 pw.print(" * Recent #"); pw.print(i); pw.print(": ");
8595 pw.println(tr);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008596 if (dumpAll) {
8597 mRecentTasks.get(i).dump(pw, " ");
8598 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008599 }
8600 }
8601
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008602 if (dumpAll) {
8603 pw.println(" ");
8604 pw.println(" mCurTask: " + mCurTask);
8605 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008606
8607 return true;
8608 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008609
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008610 boolean dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008611 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008612 boolean needSep = false;
8613 int numPers = 0;
8614
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008615 pw.println("ACTIVITY MANAGER RUNNING PROCESSES (dumpsys activity processes)");
8616
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008617 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008618 for (SparseArray<ProcessRecord> procs : mProcessNames.getMap().values()) {
8619 final int NA = procs.size();
8620 for (int ia=0; ia<NA; ia++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008621 ProcessRecord r = procs.valueAt(ia);
8622 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8623 continue;
8624 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008625 if (!needSep) {
8626 pw.println(" All known processes:");
8627 needSep = true;
8628 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008629 pw.print(r.persistent ? " *PERS*" : " *APP*");
8630 pw.print(" UID "); pw.print(procs.keyAt(ia));
8631 pw.print(" "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008632 r.dump(pw, " ");
8633 if (r.persistent) {
8634 numPers++;
8635 }
8636 }
8637 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008638 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008639
8640 if (mIsolatedProcesses.size() > 0) {
8641 if (needSep) pw.println(" ");
8642 needSep = true;
8643 pw.println(" Isolated process list (sorted by uid):");
8644 for (int i=0; i<mIsolatedProcesses.size(); i++) {
8645 ProcessRecord r = mIsolatedProcesses.valueAt(i);
8646 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8647 continue;
8648 }
8649 pw.println(String.format("%sIsolated #%2d: %s",
8650 " ", i, r.toString()));
8651 }
8652 }
8653
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008654 if (mLruProcesses.size() > 0) {
8655 if (needSep) pw.println(" ");
8656 needSep = true;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008657 pw.println(" Process LRU list (sorted by oom_adj):");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008658 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008659 "Proc", "PERS", false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008660 needSep = true;
8661 }
8662
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008663 if (dumpAll) {
8664 synchronized (mPidsSelfLocked) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008665 boolean printed = false;
8666 for (int i=0; i<mPidsSelfLocked.size(); i++) {
8667 ProcessRecord r = mPidsSelfLocked.valueAt(i);
8668 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8669 continue;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008670 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008671 if (!printed) {
8672 if (needSep) pw.println(" ");
8673 needSep = true;
8674 pw.println(" PID mappings:");
8675 printed = true;
8676 }
8677 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i));
8678 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008679 }
8680 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008681 }
8682
8683 if (mForegroundProcesses.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008684 synchronized (mPidsSelfLocked) {
8685 boolean printed = false;
8686 for (int i=0; i<mForegroundProcesses.size(); i++) {
8687 ProcessRecord r = mPidsSelfLocked.get(
8688 mForegroundProcesses.valueAt(i).pid);
8689 if (dumpPackage != null && (r == null
8690 || !dumpPackage.equals(r.info.packageName))) {
8691 continue;
8692 }
8693 if (!printed) {
8694 if (needSep) pw.println(" ");
8695 needSep = true;
8696 pw.println(" Foreground Processes:");
8697 printed = true;
8698 }
8699 pw.print(" PID #"); pw.print(mForegroundProcesses.keyAt(i));
8700 pw.print(": "); pw.println(mForegroundProcesses.valueAt(i));
8701 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008702 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008703 }
8704
8705 if (mPersistentStartingProcesses.size() > 0) {
8706 if (needSep) pw.println(" ");
8707 needSep = true;
8708 pw.println(" Persisent processes that are starting:");
8709 dumpProcessList(pw, this, mPersistentStartingProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008710 "Starting Norm", "Restarting PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008711 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008712
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008713 if (mRemovedProcesses.size() > 0) {
8714 if (needSep) pw.println(" ");
8715 needSep = true;
8716 pw.println(" Processes that are being removed:");
8717 dumpProcessList(pw, this, mRemovedProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008718 "Removed Norm", "Removed PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008719 }
8720
8721 if (mProcessesOnHold.size() > 0) {
8722 if (needSep) pw.println(" ");
8723 needSep = true;
8724 pw.println(" Processes that are on old until the system is ready:");
8725 dumpProcessList(pw, this, mProcessesOnHold, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008726 "OnHold Norm", "OnHold PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008727 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008728
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008729 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008730
8731 if (mProcessCrashTimes.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008732 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008733 long now = SystemClock.uptimeMillis();
8734 for (Map.Entry<String, SparseArray<Long>> procs
8735 : mProcessCrashTimes.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008736 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008737 SparseArray<Long> uids = procs.getValue();
8738 final int N = uids.size();
8739 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008740 int puid = uids.keyAt(i);
8741 ProcessRecord r = mProcessNames.get(pname, puid);
8742 if (dumpPackage != null && (r == null
8743 || !dumpPackage.equals(r.info.packageName))) {
8744 continue;
8745 }
8746 if (!printed) {
8747 if (needSep) pw.println(" ");
8748 needSep = true;
8749 pw.println(" Time since processes crashed:");
8750 printed = true;
8751 }
8752 pw.print(" Process "); pw.print(pname);
8753 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008754 pw.print(": last crashed ");
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008755 TimeUtils.formatDuration(now-uids.valueAt(i), pw);
8756 pw.println(" ago");
Dianne Hackbornfd12af42009-08-27 00:44:33 -07008757 }
8758 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008759 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008760
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008761 if (mBadProcesses.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008762 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008763 for (Map.Entry<String, SparseArray<Long>> procs
8764 : mBadProcesses.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008765 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008766 SparseArray<Long> uids = procs.getValue();
8767 final int N = uids.size();
8768 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008769 int puid = uids.keyAt(i);
8770 ProcessRecord r = mProcessNames.get(pname, puid);
8771 if (dumpPackage != null && (r == null
8772 || !dumpPackage.equals(r.info.packageName))) {
8773 continue;
8774 }
8775 if (!printed) {
8776 if (needSep) pw.println(" ");
8777 needSep = true;
8778 pw.println(" Bad processes:");
8779 }
8780 pw.print(" Bad process "); pw.print(pname);
8781 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008782 pw.print(": crashed at time ");
8783 pw.println(uids.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008784 }
8785 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008786 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008787
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008788 pw.println();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008789 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07008790 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn50685602011-12-01 12:23:37 -08008791 if (dumpAll) {
8792 StringBuilder sb = new StringBuilder(128);
8793 sb.append(" mPreviousProcessVisibleTime: ");
8794 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
8795 pw.println(sb);
8796 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07008797 if (mHeavyWeightProcess != null) {
8798 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
8799 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008800 pw.println(" mConfiguration: " + mConfiguration);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008801 if (dumpAll) {
8802 pw.println(" mConfigWillChange: " + mMainStack.mConfigWillChange);
Dianne Hackborn3d0724d2011-05-12 15:39:41 -07008803 if (mCompatModePackages.getPackages().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008804 boolean printed = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07008805 for (Map.Entry<String, Integer> entry
8806 : mCompatModePackages.getPackages().entrySet()) {
8807 String pkg = entry.getKey();
8808 int mode = entry.getValue();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008809 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
8810 continue;
8811 }
8812 if (!printed) {
8813 pw.println(" mScreenCompatPackages:");
8814 printed = true;
8815 }
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07008816 pw.print(" "); pw.print(pkg); pw.print(": ");
8817 pw.print(mode); pw.println();
8818 }
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07008819 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008820 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008821 pw.println(" mSleeping=" + mSleeping + " mShuttingDown=" + mShuttingDown);
8822 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
8823 || mOrigWaitForDebugger) {
8824 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp
8825 + " mDebugTransient=" + mDebugTransient
8826 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger);
8827 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08008828 if (mOpenGlTraceApp != null) {
8829 pw.println(" mOpenGlTraceApp=" + mOpenGlTraceApp);
8830 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07008831 if (mProfileApp != null || mProfileProc != null || mProfileFile != null
8832 || mProfileFd != null) {
8833 pw.println(" mProfileApp=" + mProfileApp + " mProfileProc=" + mProfileProc);
8834 pw.println(" mProfileFile=" + mProfileFile + " mProfileFd=" + mProfileFd);
8835 pw.println(" mProfileType=" + mProfileType + " mAutoStopProfiler="
8836 + mAutoStopProfiler);
8837 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008838 if (mAlwaysFinishActivities || mController != null) {
8839 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities
8840 + " mController=" + mController);
8841 }
8842 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008843 pw.println(" Total persistent processes: " + numPers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008844 pw.println(" mStartRunning=" + mStartRunning
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07008845 + " mProcessesReady=" + mProcessesReady
8846 + " mSystemReady=" + mSystemReady);
8847 pw.println(" mBooting=" + mBooting
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008848 + " mBooted=" + mBooted
8849 + " mFactoryTest=" + mFactoryTest);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008850 pw.print(" mLastPowerCheckRealtime=");
8851 TimeUtils.formatDuration(mLastPowerCheckRealtime, pw);
8852 pw.println("");
8853 pw.print(" mLastPowerCheckUptime=");
8854 TimeUtils.formatDuration(mLastPowerCheckUptime, pw);
8855 pw.println("");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008856 pw.println(" mGoingToSleep=" + mMainStack.mGoingToSleep);
8857 pw.println(" mLaunchingActivity=" + mMainStack.mLaunchingActivity);
Dianne Hackborn906497c2010-05-10 15:57:38 -07008858 pw.println(" mAdjSeq=" + mAdjSeq + " mLruSeq=" + mLruSeq);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008859 pw.println(" mNumServiceProcs=" + mNumServiceProcs
8860 + " mNewNumServiceProcs=" + mNewNumServiceProcs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008861 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008862
8863 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008864 }
8865
Dianne Hackborn287952c2010-09-22 22:34:31 -07008866 boolean dumpProcessesToGc(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008867 int opti, boolean needSep, boolean dumpAll, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07008868 if (mProcessesToGc.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008869 boolean printed = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -07008870 long now = SystemClock.uptimeMillis();
8871 for (int i=0; i<mProcessesToGc.size(); i++) {
8872 ProcessRecord proc = mProcessesToGc.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008873 if (dumpPackage != null && !dumpPackage.equals(proc.info.packageName)) {
8874 continue;
8875 }
8876 if (!printed) {
8877 if (needSep) pw.println(" ");
8878 needSep = true;
8879 pw.println(" Processes that are waiting to GC:");
8880 printed = true;
8881 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008882 pw.print(" Process "); pw.println(proc);
8883 pw.print(" lowMem="); pw.print(proc.reportLowMemory);
8884 pw.print(", last gced=");
8885 pw.print(now-proc.lastRequestedGc);
8886 pw.print(" ms ago, last lowMem=");
8887 pw.print(now-proc.lastLowMemory);
8888 pw.println(" ms ago");
8889
8890 }
8891 }
8892 return needSep;
8893 }
8894
8895 boolean dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args,
8896 int opti, boolean dumpAll) {
8897 boolean needSep = false;
8898
8899 if (mLruProcesses.size() > 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07008900 if (needSep) pw.println(" ");
8901 needSep = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -07008902 pw.println(" OOM levels:");
Dianne Hackborn7d608422011-08-07 16:24:18 -07008903 pw.print(" SYSTEM_ADJ: "); pw.println(ProcessList.SYSTEM_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008904 pw.print(" PERSISTENT_PROC_ADJ: "); pw.println(ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07008905 pw.print(" FOREGROUND_APP_ADJ: "); pw.println(ProcessList.FOREGROUND_APP_ADJ);
8906 pw.print(" VISIBLE_APP_ADJ: "); pw.println(ProcessList.VISIBLE_APP_ADJ);
8907 pw.print(" PERCEPTIBLE_APP_ADJ: "); pw.println(ProcessList.PERCEPTIBLE_APP_ADJ);
8908 pw.print(" HEAVY_WEIGHT_APP_ADJ: "); pw.println(ProcessList.HEAVY_WEIGHT_APP_ADJ);
8909 pw.print(" BACKUP_APP_ADJ: "); pw.println(ProcessList.BACKUP_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008910 pw.print(" SERVICE_ADJ: "); pw.println(ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07008911 pw.print(" HOME_APP_ADJ: "); pw.println(ProcessList.HOME_APP_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07008912 pw.print(" PREVIOUS_APP_ADJ: "); pw.println(ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008913 pw.print(" SERVICE_B_ADJ: "); pw.println(ProcessList.SERVICE_B_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07008914 pw.print(" HIDDEN_APP_MIN_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008915 pw.print(" HIDDEN_APP_MAX_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MAX_ADJ);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07008916
8917 if (needSep) pw.println(" ");
8918 needSep = true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07008919 pw.println(" Process OOM control:");
Dianne Hackborn905577f2011-09-07 18:31:28 -07008920 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008921 "Proc", "PERS", true, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008922 needSep = true;
8923 }
8924
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008925 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008926
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008927 pw.println();
Dianne Hackborn287952c2010-09-22 22:34:31 -07008928 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07008929 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008930 if (mHeavyWeightProcess != null) {
8931 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
8932 }
8933
8934 return true;
8935 }
8936
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008937 /**
8938 * There are three ways to call this:
8939 * - no service specified: dump all the services
8940 * - a flattened component name that matched an existing service was specified as the
8941 * first arg: dump that one service
8942 * - the first arg isn't the flattened component name of an existing service:
8943 * dump all services whose component contains the first arg as a substring
8944 */
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008945 protected boolean dumpService(FileDescriptor fd, PrintWriter pw, String name, String[] args,
8946 int opti, boolean dumpAll) {
8947 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008948
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008949 if ("all".equals(name)) {
Dianne Hackborn14bfa392010-07-24 19:58:06 -07008950 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07008951 try {
8952 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
8953 for (UserInfo user : users) {
8954 for (ServiceRecord r1 : mServiceMap.getAllServices(user.id)) {
8955 services.add(r1);
8956 }
8957 }
8958 } catch (RemoteException re) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008959 }
8960 }
8961 } else {
8962 ComponentName componentName = name != null
8963 ? ComponentName.unflattenFromString(name) : null;
8964 int objectId = 0;
8965 if (componentName == null) {
8966 // Not a '/' separated full component name; maybe an object ID?
8967 try {
8968 objectId = Integer.parseInt(name, 16);
8969 name = null;
8970 componentName = null;
8971 } catch (RuntimeException e) {
8972 }
8973 }
8974
8975 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07008976 try {
8977 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
8978 for (UserInfo user : users) {
8979 for (ServiceRecord r1 : mServiceMap.getAllServices(user.id)) {
8980 if (componentName != null) {
8981 if (r1.name.equals(componentName)) {
8982 services.add(r1);
8983 }
8984 } else if (name != null) {
8985 if (r1.name.flattenToString().contains(name)) {
8986 services.add(r1);
8987 }
8988 } else if (System.identityHashCode(r1) == objectId) {
8989 services.add(r1);
8990 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008991 }
Dianne Hackborn14bfa392010-07-24 19:58:06 -07008992 }
Amith Yamasani742a6712011-05-04 14:49:28 -07008993 } catch (RemoteException re) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008994 }
8995 }
8996 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008997
8998 if (services.size() <= 0) {
8999 return false;
9000 }
9001
9002 boolean needSep = false;
9003 for (int i=0; i<services.size(); i++) {
9004 if (needSep) {
9005 pw.println();
9006 }
9007 needSep = true;
9008 dumpService("", fd, pw, services.get(i), args, dumpAll);
9009 }
9010 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009011 }
9012
9013 /**
9014 * Invokes IApplicationThread.dumpService() on the thread of the specified service if
9015 * there is a thread associated with the service.
9016 */
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009017 private void dumpService(String prefix, FileDescriptor fd, PrintWriter pw,
9018 final ServiceRecord r, String[] args, boolean dumpAll) {
9019 String innerPrefix = prefix + " ";
9020 synchronized (this) {
9021 pw.print(prefix); pw.print("SERVICE ");
9022 pw.print(r.shortName); pw.print(" ");
9023 pw.print(Integer.toHexString(System.identityHashCode(r)));
9024 pw.print(" pid=");
9025 if (r.app != null) pw.println(r.app.pid);
9026 else pw.println("(not running)");
9027 if (dumpAll) {
9028 r.dump(pw, innerPrefix);
9029 }
9030 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009031 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009032 pw.print(prefix); pw.println(" Client:");
9033 pw.flush();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009034 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009035 TransferPipe tp = new TransferPipe();
9036 try {
9037 r.app.thread.dumpService(tp.getWriteFd().getFileDescriptor(), r, args);
9038 tp.setBufferPrefix(prefix + " ");
9039 tp.go(fd);
9040 } finally {
9041 tp.kill();
9042 }
9043 } catch (IOException e) {
9044 pw.println(prefix + " Failure while dumping the service: " + e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009045 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009046 pw.println(prefix + " Got a RemoteException while dumping the service");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009047 }
9048 }
9049 }
9050
Marco Nelissen18cb2872011-11-15 11:19:53 -08009051 /**
9052 * There are three ways to call this:
9053 * - no provider specified: dump all the providers
9054 * - a flattened component name that matched an existing provider was specified as the
9055 * first arg: dump that one provider
9056 * - the first arg isn't the flattened component name of an existing provider:
9057 * dump all providers whose component contains the first arg as a substring
9058 */
9059 protected boolean dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9060 int opti, boolean dumpAll) {
Marco Nelissende7408c2012-02-08 14:57:38 -08009061 return mProviderMap.dumpProvider(fd, pw, name, args, opti, dumpAll);
Marco Nelissen18cb2872011-11-15 11:19:53 -08009062 }
9063
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009064 static class ItemMatcher {
9065 ArrayList<ComponentName> components;
9066 ArrayList<String> strings;
9067 ArrayList<Integer> objects;
9068 boolean all;
9069
9070 ItemMatcher() {
9071 all = true;
9072 }
9073
9074 void build(String name) {
9075 ComponentName componentName = ComponentName.unflattenFromString(name);
9076 if (componentName != null) {
9077 if (components == null) {
9078 components = new ArrayList<ComponentName>();
9079 }
9080 components.add(componentName);
9081 all = false;
9082 } else {
9083 int objectId = 0;
9084 // Not a '/' separated full component name; maybe an object ID?
9085 try {
9086 objectId = Integer.parseInt(name, 16);
9087 if (objects == null) {
9088 objects = new ArrayList<Integer>();
9089 }
9090 objects.add(objectId);
9091 all = false;
9092 } catch (RuntimeException e) {
9093 // Not an integer; just do string match.
9094 if (strings == null) {
9095 strings = new ArrayList<String>();
9096 }
9097 strings.add(name);
9098 all = false;
9099 }
9100 }
9101 }
9102
9103 int build(String[] args, int opti) {
9104 for (; opti<args.length; opti++) {
9105 String name = args[opti];
9106 if ("--".equals(name)) {
9107 return opti+1;
9108 }
9109 build(name);
9110 }
9111 return opti;
9112 }
9113
9114 boolean match(Object object, ComponentName comp) {
9115 if (all) {
9116 return true;
9117 }
9118 if (components != null) {
9119 for (int i=0; i<components.size(); i++) {
9120 if (components.get(i).equals(comp)) {
9121 return true;
9122 }
9123 }
9124 }
9125 if (objects != null) {
9126 for (int i=0; i<objects.size(); i++) {
9127 if (System.identityHashCode(object) == objects.get(i)) {
9128 return true;
9129 }
9130 }
9131 }
9132 if (strings != null) {
9133 String flat = comp.flattenToString();
9134 for (int i=0; i<strings.size(); i++) {
9135 if (flat.contains(strings.get(i))) {
9136 return true;
9137 }
9138 }
9139 }
9140 return false;
9141 }
9142 }
9143
Dianne Hackborn625ac272010-09-17 18:29:22 -07009144 /**
9145 * There are three things that cmd can be:
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009146 * - a flattened component name that matches an existing activity
Dianne Hackborn625ac272010-09-17 18:29:22 -07009147 * - the cmd arg isn't the flattened component name of an existing activity:
9148 * dump all activity whose component contains the cmd as a substring
9149 * - A hex number of the ActivityRecord object instance.
9150 */
9151 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9152 int opti, boolean dumpAll) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009153 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009154
9155 if ("all".equals(name)) {
9156 synchronized (this) {
9157 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009158 activities.add(r1);
9159 }
9160 }
Dianne Hackbornf9302322011-06-14 18:36:14 -07009161 } else if ("top".equals(name)) {
9162 synchronized (this) {
9163 final int N = mMainStack.mHistory.size();
9164 if (N > 0) {
9165 activities.add((ActivityRecord)mMainStack.mHistory.get(N-1));
9166 }
9167 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009168 } else {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009169 ItemMatcher matcher = new ItemMatcher();
9170 matcher.build(name);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009171
9172 synchronized (this) {
9173 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009174 if (matcher.match(r1, r1.intent.getComponent())) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009175 activities.add(r1);
9176 }
9177 }
9178 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009179 }
9180
9181 if (activities.size() <= 0) {
9182 return false;
9183 }
9184
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009185 String[] newArgs = new String[args.length - opti];
9186 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
9187
Dianne Hackborn30d71892010-12-11 10:37:55 -08009188 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009189 boolean needSep = false;
Dianne Hackborn30d71892010-12-11 10:37:55 -08009190 for (int i=activities.size()-1; i>=0; i--) {
9191 ActivityRecord r = (ActivityRecord)activities.get(i);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009192 if (needSep) {
9193 pw.println();
9194 }
9195 needSep = true;
9196 synchronized (this) {
9197 if (lastTask != r.task) {
9198 lastTask = r.task;
9199 pw.print("TASK "); pw.print(lastTask.affinity);
9200 pw.print(" id="); pw.println(lastTask.taskId);
9201 if (dumpAll) {
9202 lastTask.dump(pw, " ");
9203 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08009204 }
9205 }
9206 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009207 }
9208 return true;
9209 }
9210
9211 /**
9212 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
9213 * there is a thread associated with the activity.
9214 */
Dianne Hackborn30d71892010-12-11 10:37:55 -08009215 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009216 final ActivityRecord r, String[] args, boolean dumpAll) {
9217 String innerPrefix = prefix + " ";
Dianne Hackborn30d71892010-12-11 10:37:55 -08009218 synchronized (this) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009219 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
9220 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
9221 pw.print(" pid=");
Dianne Hackborn30d71892010-12-11 10:37:55 -08009222 if (r.app != null) pw.println(r.app.pid);
9223 else pw.println("(not running)");
9224 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009225 r.dump(pw, innerPrefix);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009226 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009227 }
9228 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009229 // flush anything that is already in the PrintWriter since the thread is going
9230 // to write to the file descriptor directly
9231 pw.flush();
Dianne Hackborn625ac272010-09-17 18:29:22 -07009232 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009233 TransferPipe tp = new TransferPipe();
9234 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009235 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9236 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009237 tp.go(fd);
9238 } finally {
9239 tp.kill();
9240 }
9241 } catch (IOException e) {
9242 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009243 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009244 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
Dianne Hackborn625ac272010-09-17 18:29:22 -07009245 }
9246 }
9247 }
9248
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009249 boolean dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009250 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009251 boolean needSep = false;
9252
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009253 pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009254 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009255 if (mRegisteredReceivers.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009256 boolean printed = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009257 Iterator it = mRegisteredReceivers.values().iterator();
9258 while (it.hasNext()) {
9259 ReceiverList r = (ReceiverList)it.next();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009260 if (dumpPackage != null && (r.app == null ||
9261 !dumpPackage.equals(r.app.info.packageName))) {
9262 continue;
9263 }
9264 if (!printed) {
9265 pw.println(" Registered Receivers:");
9266 needSep = true;
9267 printed = true;
9268 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009269 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009270 r.dump(pw, " ");
9271 }
9272 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009273
9274 if (mReceiverResolver.dump(pw, needSep ?
9275 "\n Receiver Resolver Table:" : " Receiver Resolver Table:",
9276 " ", dumpPackage, false)) {
9277 needSep = true;
9278 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009279 }
Christopher Tatef46723b2012-01-26 14:19:24 -08009280
9281 for (BroadcastQueue q : mBroadcastQueues) {
9282 needSep = q.dumpLocked(fd, pw, args, opti, dumpAll, dumpPackage, needSep);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009283 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009284
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009285 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009286
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009287 if (mStickyBroadcasts != null && dumpPackage == null) {
9288 if (needSep) {
9289 pw.println();
9290 }
9291 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009292 pw.println(" Sticky broadcasts:");
9293 StringBuilder sb = new StringBuilder(128);
9294 for (Map.Entry<String, ArrayList<Intent>> ent
9295 : mStickyBroadcasts.entrySet()) {
9296 pw.print(" * Sticky action "); pw.print(ent.getKey());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009297 if (dumpAll) {
9298 pw.println(":");
9299 ArrayList<Intent> intents = ent.getValue();
9300 final int N = intents.size();
9301 for (int i=0; i<N; i++) {
9302 sb.setLength(0);
9303 sb.append(" Intent: ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009304 intents.get(i).toShortString(sb, false, true, false, false);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009305 pw.println(sb.toString());
9306 Bundle bundle = intents.get(i).getExtras();
9307 if (bundle != null) {
9308 pw.print(" ");
9309 pw.println(bundle.toString());
9310 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009311 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009312 } else {
9313 pw.println("");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009314 }
9315 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009316 needSep = true;
9317 }
9318
9319 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009320 pw.println();
Christopher Tatef46723b2012-01-26 14:19:24 -08009321 for (BroadcastQueue queue : mBroadcastQueues) {
9322 pw.println(" mBroadcastsScheduled [" + queue.mQueueName + "]="
9323 + queue.mBroadcastsScheduled);
9324 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009325 pw.println(" mHandler:");
9326 mHandler.dump(new PrintWriterPrinter(pw), " ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009327 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009328 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009329
9330 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009331 }
9332
Marco Nelissen18cb2872011-11-15 11:19:53 -08009333 /**
9334 * Prints a list of ServiceRecords (dumpsys activity services)
9335 */
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009336 boolean dumpServicesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009337 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009338 boolean needSep = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009339
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009340 ItemMatcher matcher = new ItemMatcher();
9341 matcher.build(args, opti);
9342
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009343 pw.println("ACTIVITY MANAGER SERVICES (dumpsys activity services)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009344 try {
9345 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
9346 for (UserInfo user : users) {
9347 if (mServiceMap.getAllServices(user.id).size() > 0) {
9348 boolean printed = false;
9349 long nowReal = SystemClock.elapsedRealtime();
9350 Iterator<ServiceRecord> it = mServiceMap.getAllServices(
9351 user.id).iterator();
9352 needSep = false;
9353 while (it.hasNext()) {
9354 ServiceRecord r = it.next();
9355 if (!matcher.match(r, r.name)) {
9356 continue;
9357 }
9358 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9359 continue;
9360 }
9361 if (!printed) {
9362 pw.println(" Active services:");
9363 printed = true;
9364 }
9365 if (needSep) {
9366 pw.println();
9367 }
9368 pw.print(" * ");
9369 pw.println(r);
9370 if (dumpAll) {
9371 r.dump(pw, " ");
9372 needSep = true;
9373 } else {
9374 pw.print(" app=");
9375 pw.println(r.app);
9376 pw.print(" created=");
9377 TimeUtils.formatDuration(r.createTime, nowReal, pw);
9378 pw.print(" started=");
9379 pw.print(r.startRequested);
9380 pw.print(" connections=");
9381 pw.println(r.connections.size());
9382 if (r.connections.size() > 0) {
9383 pw.println(" Connections:");
9384 for (ArrayList<ConnectionRecord> clist : r.connections.values()) {
9385 for (int i = 0; i < clist.size(); i++) {
9386 ConnectionRecord conn = clist.get(i);
9387 pw.print(" ");
9388 pw.print(conn.binding.intent.intent.getIntent()
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009389 .toShortString(false, false, false, false));
Amith Yamasani742a6712011-05-04 14:49:28 -07009390 pw.print(" -> ");
9391 ProcessRecord proc = conn.binding.client;
9392 pw.println(proc != null ? proc.toShortString() : "null");
9393 }
9394 }
Dianne Hackborn8ec8d412011-11-14 18:27:24 -08009395 }
9396 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009397 if (dumpClient && r.app != null && r.app.thread != null) {
9398 pw.println(" Client:");
9399 pw.flush();
9400 try {
9401 TransferPipe tp = new TransferPipe();
9402 try {
9403 r.app.thread.dumpService(tp.getWriteFd().getFileDescriptor(),
9404 r, args);
9405 tp.setBufferPrefix(" ");
9406 // Short timeout, since blocking here can
9407 // deadlock with the application.
9408 tp.go(fd, 2000);
9409 } finally {
9410 tp.kill();
9411 }
9412 } catch (IOException e) {
9413 pw.println(" Failure while dumping the service: " + e);
9414 } catch (RemoteException e) {
9415 pw.println(" Got a RemoteException while dumping the service");
9416 }
9417 needSep = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009418 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009419 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009420 needSep = printed;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009421 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009422 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009423 } catch (RemoteException re) {
9424
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009425 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009426
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009427 if (mPendingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009428 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009429 for (int i=0; i<mPendingServices.size(); i++) {
9430 ServiceRecord r = mPendingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009431 if (!matcher.match(r, r.name)) {
9432 continue;
9433 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009434 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9435 continue;
9436 }
9437 if (!printed) {
9438 if (needSep) pw.println(" ");
9439 needSep = true;
9440 pw.println(" Pending services:");
9441 printed = true;
9442 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009443 pw.print(" * Pending "); pw.println(r);
9444 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009445 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009446 needSep = true;
9447 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009448
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009449 if (mRestartingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009450 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009451 for (int i=0; i<mRestartingServices.size(); i++) {
9452 ServiceRecord r = mRestartingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009453 if (!matcher.match(r, r.name)) {
9454 continue;
9455 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009456 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9457 continue;
9458 }
9459 if (!printed) {
9460 if (needSep) pw.println(" ");
9461 needSep = true;
9462 pw.println(" Restarting services:");
9463 printed = true;
9464 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009465 pw.print(" * Restarting "); pw.println(r);
9466 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009467 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009468 needSep = true;
9469 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009470
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009471 if (mStoppingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009472 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009473 for (int i=0; i<mStoppingServices.size(); i++) {
9474 ServiceRecord r = mStoppingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009475 if (!matcher.match(r, r.name)) {
9476 continue;
9477 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009478 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9479 continue;
9480 }
9481 if (!printed) {
9482 if (needSep) pw.println(" ");
9483 needSep = true;
9484 pw.println(" Stopping services:");
9485 printed = true;
9486 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009487 pw.print(" * Stopping "); pw.println(r);
9488 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009489 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009490 needSep = true;
9491 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009492
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009493 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009494 if (mServiceConnections.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009495 boolean printed = false;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009496 Iterator<ArrayList<ConnectionRecord>> it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009497 = mServiceConnections.values().iterator();
9498 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009499 ArrayList<ConnectionRecord> r = it.next();
9500 for (int i=0; i<r.size(); i++) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009501 ConnectionRecord cr = r.get(i);
9502 if (!matcher.match(cr.binding.service, cr.binding.service.name)) {
9503 continue;
9504 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009505 if (dumpPackage != null && (cr.binding.client == null
9506 || !dumpPackage.equals(cr.binding.client.info.packageName))) {
9507 continue;
9508 }
9509 if (!printed) {
9510 if (needSep) pw.println(" ");
9511 needSep = true;
9512 pw.println(" Connection bindings to services:");
9513 printed = true;
9514 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009515 pw.print(" * "); pw.println(cr);
9516 cr.dump(pw, " ");
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009517 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009518 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009519 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009520 }
9521 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009522
9523 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009524 }
9525
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009526 boolean dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009527 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07009528 boolean needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009529
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009530 ItemMatcher matcher = new ItemMatcher();
9531 matcher.build(args, opti);
9532
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009533 pw.println("ACTIVITY MANAGER CONTENT PROVIDERS (dumpsys activity providers)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009534
9535 mProviderMap.dumpProvidersLocked(pw, dumpAll);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009536
9537 if (mLaunchingProviders.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009538 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009539 for (int i=mLaunchingProviders.size()-1; i>=0; i--) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009540 ContentProviderRecord r = mLaunchingProviders.get(i);
9541 if (dumpPackage != null && !dumpPackage.equals(r.name.getPackageName())) {
9542 continue;
9543 }
9544 if (!printed) {
9545 if (needSep) pw.println(" ");
9546 needSep = true;
9547 pw.println(" Launching content providers:");
9548 printed = true;
9549 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009550 pw.print(" Launching #"); pw.print(i); pw.print(": ");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009551 pw.println(r);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009552 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009553 }
9554
9555 if (mGrantedUriPermissions.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009556 if (needSep) pw.println();
9557 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009558 pw.println("Granted Uri Permissions:");
9559 for (int i=0; i<mGrantedUriPermissions.size(); i++) {
9560 int uid = mGrantedUriPermissions.keyAt(i);
9561 HashMap<Uri, UriPermission> perms
9562 = mGrantedUriPermissions.valueAt(i);
9563 pw.print(" * UID "); pw.print(uid);
9564 pw.println(" holds:");
9565 for (UriPermission perm : perms.values()) {
9566 pw.print(" "); pw.println(perm);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009567 if (dumpAll) {
9568 perm.dump(pw, " ");
9569 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009570 }
9571 }
9572 needSep = true;
9573 }
9574
9575 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009576 }
9577
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009578 boolean dumpPendingIntentsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009579 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009580 boolean needSep = false;
9581
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009582 if (mIntentSenderRecords.size() > 0) {
9583 boolean printed = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009584 Iterator<WeakReference<PendingIntentRecord>> it
9585 = mIntentSenderRecords.values().iterator();
9586 while (it.hasNext()) {
9587 WeakReference<PendingIntentRecord> ref = it.next();
9588 PendingIntentRecord rec = ref != null ? ref.get(): null;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009589 if (dumpPackage != null && (rec == null
9590 || !dumpPackage.equals(rec.key.packageName))) {
9591 continue;
9592 }
9593 if (!printed) {
9594 pw.println("ACTIVITY MANAGER PENDING INTENTS (dumpsys activity intents)");
9595 printed = true;
9596 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009597 needSep = true;
9598 if (rec != null) {
9599 pw.print(" * "); pw.println(rec);
9600 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009601 rec.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009602 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009603 } else {
9604 pw.print(" * "); pw.println(ref);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009605 }
9606 }
9607 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009608
9609 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009610 }
9611
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009612 private static final void dumpHistoryList(FileDescriptor fd, PrintWriter pw, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009613 String prefix, String label, boolean complete, boolean brief, boolean client,
9614 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009615 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009616 boolean needNL = false;
9617 final String innerPrefix = prefix + " ";
9618 final String[] args = new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009619 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009620 final ActivityRecord r = (ActivityRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009621 if (dumpPackage != null && !dumpPackage.equals(r.packageName)) {
9622 continue;
9623 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07009624 final boolean full = !brief && (complete || !r.isInHistory());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009625 if (needNL) {
9626 pw.println(" ");
9627 needNL = false;
9628 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009629 if (lastTask != r.task) {
9630 lastTask = r.task;
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009631 pw.print(prefix);
9632 pw.print(full ? "* " : " ");
9633 pw.println(lastTask);
9634 if (full) {
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009635 lastTask.dump(pw, prefix + " ");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009636 } else if (complete) {
9637 // Complete + brief == give a summary. Isn't that obvious?!?
9638 if (lastTask.intent != null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009639 pw.print(prefix); pw.print(" ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009640 pw.println(lastTask.intent.toInsecureStringWithClip());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009641 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009642 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009643 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009644 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label);
9645 pw.print(" #"); pw.print(i); pw.print(": ");
9646 pw.println(r);
9647 if (full) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009648 r.dump(pw, innerPrefix);
9649 } else if (complete) {
9650 // Complete + brief == give a summary. Isn't that obvious?!?
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009651 pw.print(innerPrefix); pw.println(r.intent.toInsecureString());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009652 if (r.app != null) {
9653 pw.print(innerPrefix); pw.println(r.app);
9654 }
9655 }
9656 if (client && r.app != null && r.app.thread != null) {
9657 // flush anything that is already in the PrintWriter since the thread is going
9658 // to write to the file descriptor directly
9659 pw.flush();
9660 try {
9661 TransferPipe tp = new TransferPipe();
9662 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009663 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9664 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009665 // Short timeout, since blocking here can
9666 // deadlock with the application.
9667 tp.go(fd, 2000);
9668 } finally {
9669 tp.kill();
9670 }
9671 } catch (IOException e) {
9672 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
9673 } catch (RemoteException e) {
9674 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
9675 }
9676 needNL = true;
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009677 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009678 }
9679 }
9680
Dianne Hackborn09c916b2009-12-08 14:50:51 -08009681 private static String buildOomTag(String prefix, String space, int val, int base) {
9682 if (val == base) {
9683 if (space == null) return prefix;
9684 return prefix + " ";
9685 }
9686 return prefix + "+" + Integer.toString(val-base);
9687 }
9688
9689 private static final int dumpProcessList(PrintWriter pw,
9690 ActivityManagerService service, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009691 String prefix, String normalLabel, String persistentLabel,
9692 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009693 int numPers = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07009694 final int N = list.size()-1;
9695 for (int i=N; i>=0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009696 ProcessRecord r = (ProcessRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009697 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9698 continue;
9699 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009700 pw.println(String.format("%s%s #%2d: %s",
9701 prefix, (r.persistent ? persistentLabel : normalLabel),
9702 i, r.toString()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009703 if (r.persistent) {
9704 numPers++;
9705 }
9706 }
9707 return numPers;
9708 }
9709
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009710 private static final boolean dumpProcessOomList(PrintWriter pw,
Dianne Hackborn905577f2011-09-07 18:31:28 -07009711 ActivityManagerService service, List<ProcessRecord> origList,
Dianne Hackborn287952c2010-09-22 22:34:31 -07009712 String prefix, String normalLabel, String persistentLabel,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009713 boolean inclDetails, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009714
Dianne Hackborn905577f2011-09-07 18:31:28 -07009715 ArrayList<Pair<ProcessRecord, Integer>> list
9716 = new ArrayList<Pair<ProcessRecord, Integer>>(origList.size());
9717 for (int i=0; i<origList.size(); i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009718 ProcessRecord r = origList.get(i);
9719 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9720 continue;
9721 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07009722 list.add(new Pair<ProcessRecord, Integer>(origList.get(i), i));
9723 }
9724
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009725 if (list.size() <= 0) {
9726 return false;
9727 }
9728
Dianne Hackborn905577f2011-09-07 18:31:28 -07009729 Comparator<Pair<ProcessRecord, Integer>> comparator
9730 = new Comparator<Pair<ProcessRecord, Integer>>() {
9731 @Override
9732 public int compare(Pair<ProcessRecord, Integer> object1,
9733 Pair<ProcessRecord, Integer> object2) {
9734 if (object1.first.setAdj != object2.first.setAdj) {
9735 return object1.first.setAdj > object2.first.setAdj ? -1 : 1;
9736 }
9737 if (object1.second.intValue() != object2.second.intValue()) {
9738 return object1.second.intValue() > object2.second.intValue() ? -1 : 1;
9739 }
9740 return 0;
9741 }
9742 };
9743
9744 Collections.sort(list, comparator);
9745
Dianne Hackborn287952c2010-09-22 22:34:31 -07009746 final long curRealtime = SystemClock.elapsedRealtime();
9747 final long realtimeSince = curRealtime - service.mLastPowerCheckRealtime;
9748 final long curUptime = SystemClock.uptimeMillis();
9749 final long uptimeSince = curUptime - service.mLastPowerCheckUptime;
9750
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009751 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07009752 ProcessRecord r = list.get(i).first;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009753 String oomAdj;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009754 if (r.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07009755 oomAdj = buildOomTag("bak", " ", r.setAdj, ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009756 } else if (r.setAdj >= ProcessList.SERVICE_B_ADJ) {
9757 oomAdj = buildOomTag("svcb ", null, r.setAdj, ProcessList.SERVICE_B_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009758 } else if (r.setAdj >= ProcessList.PREVIOUS_APP_ADJ) {
9759 oomAdj = buildOomTag("prev ", null, r.setAdj, ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009760 } else if (r.setAdj >= ProcessList.HOME_APP_ADJ) {
9761 oomAdj = buildOomTag("home ", null, r.setAdj, ProcessList.HOME_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009762 } else if (r.setAdj >= ProcessList.SERVICE_ADJ) {
9763 oomAdj = buildOomTag("svc ", null, r.setAdj, ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009764 } else if (r.setAdj >= ProcessList.BACKUP_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08009765 oomAdj = buildOomTag("bkup ", null, r.setAdj, ProcessList.BACKUP_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009766 } else if (r.setAdj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
9767 oomAdj = buildOomTag("hvy ", null, r.setAdj, ProcessList.HEAVY_WEIGHT_APP_ADJ);
9768 } else if (r.setAdj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
9769 oomAdj = buildOomTag("prcp ", null, r.setAdj, ProcessList.PERCEPTIBLE_APP_ADJ);
9770 } else if (r.setAdj >= ProcessList.VISIBLE_APP_ADJ) {
9771 oomAdj = buildOomTag("vis ", null, r.setAdj, ProcessList.VISIBLE_APP_ADJ);
9772 } else if (r.setAdj >= ProcessList.FOREGROUND_APP_ADJ) {
9773 oomAdj = buildOomTag("fore ", null, r.setAdj, ProcessList.FOREGROUND_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009774 } else if (r.setAdj >= ProcessList.PERSISTENT_PROC_ADJ) {
9775 oomAdj = buildOomTag("pers ", null, r.setAdj, ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009776 } else if (r.setAdj >= ProcessList.SYSTEM_ADJ) {
9777 oomAdj = buildOomTag("sys ", null, r.setAdj, ProcessList.SYSTEM_ADJ);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009778 } else {
9779 oomAdj = Integer.toString(r.setAdj);
9780 }
9781 String schedGroup;
9782 switch (r.setSchedGroup) {
9783 case Process.THREAD_GROUP_BG_NONINTERACTIVE:
9784 schedGroup = "B";
9785 break;
9786 case Process.THREAD_GROUP_DEFAULT:
9787 schedGroup = "F";
9788 break;
9789 default:
9790 schedGroup = Integer.toString(r.setSchedGroup);
9791 break;
9792 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07009793 String foreground;
9794 if (r.foregroundActivities) {
9795 foreground = "A";
9796 } else if (r.foregroundServices) {
9797 foreground = "S";
9798 } else {
9799 foreground = " ";
9800 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07009801 pw.println(String.format("%s%s #%2d: adj=%s/%s%s trm=%2d %s (%s)",
Dianne Hackborn287952c2010-09-22 22:34:31 -07009802 prefix, (r.persistent ? persistentLabel : normalLabel),
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009803 (origList.size()-1)-list.get(i).second, oomAdj, schedGroup,
9804 foreground, r.trimMemoryLevel, r.toShortString(), r.adjType));
Dianne Hackborn287952c2010-09-22 22:34:31 -07009805 if (r.adjSource != null || r.adjTarget != null) {
9806 pw.print(prefix);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009807 pw.print(" ");
Dianne Hackborn287952c2010-09-22 22:34:31 -07009808 if (r.adjTarget instanceof ComponentName) {
9809 pw.print(((ComponentName)r.adjTarget).flattenToShortString());
9810 } else if (r.adjTarget != null) {
9811 pw.print(r.adjTarget.toString());
9812 } else {
9813 pw.print("{null}");
9814 }
9815 pw.print("<=");
9816 if (r.adjSource instanceof ProcessRecord) {
9817 pw.print("Proc{");
9818 pw.print(((ProcessRecord)r.adjSource).toShortString());
9819 pw.println("}");
9820 } else if (r.adjSource != null) {
9821 pw.println(r.adjSource.toString());
9822 } else {
9823 pw.println("{null}");
9824 }
9825 }
9826 if (inclDetails) {
9827 pw.print(prefix);
9828 pw.print(" ");
9829 pw.print("oom: max="); pw.print(r.maxAdj);
9830 pw.print(" hidden="); pw.print(r.hiddenAdj);
9831 pw.print(" curRaw="); pw.print(r.curRawAdj);
9832 pw.print(" setRaw="); pw.print(r.setRawAdj);
9833 pw.print(" cur="); pw.print(r.curAdj);
9834 pw.print(" set="); pw.println(r.setAdj);
9835 pw.print(prefix);
9836 pw.print(" ");
9837 pw.print("keeping="); pw.print(r.keeping);
9838 pw.print(" hidden="); pw.print(r.hidden);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009839 pw.print(" empty="); pw.print(r.empty);
9840 pw.print(" hasAboveClient="); pw.println(r.hasAboveClient);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009841
9842 if (!r.keeping) {
9843 if (r.lastWakeTime != 0) {
9844 long wtime;
9845 BatteryStatsImpl stats = service.mBatteryStatsService.getActiveStatistics();
9846 synchronized (stats) {
9847 wtime = stats.getProcessWakeTime(r.info.uid,
9848 r.pid, curRealtime);
9849 }
9850 long timeUsed = wtime - r.lastWakeTime;
9851 pw.print(prefix);
9852 pw.print(" ");
9853 pw.print("keep awake over ");
9854 TimeUtils.formatDuration(realtimeSince, pw);
9855 pw.print(" used ");
9856 TimeUtils.formatDuration(timeUsed, pw);
9857 pw.print(" (");
9858 pw.print((timeUsed*100)/realtimeSince);
9859 pw.println("%)");
9860 }
9861 if (r.lastCpuTime != 0) {
9862 long timeUsed = r.curCpuTime - r.lastCpuTime;
9863 pw.print(prefix);
9864 pw.print(" ");
9865 pw.print("run cpu over ");
9866 TimeUtils.formatDuration(uptimeSince, pw);
9867 pw.print(" used ");
9868 TimeUtils.formatDuration(timeUsed, pw);
9869 pw.print(" (");
9870 pw.print((timeUsed*100)/uptimeSince);
9871 pw.println("%)");
9872 }
9873 }
9874 }
9875 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009876 return true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009877 }
9878
Dianne Hackbornb437e092011-08-05 17:50:29 -07009879 ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, String[] args) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009880 ArrayList<ProcessRecord> procs;
9881 synchronized (this) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009882 if (args != null && args.length > start
9883 && args[start].charAt(0) != '-') {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009884 procs = new ArrayList<ProcessRecord>();
9885 int pid = -1;
9886 try {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009887 pid = Integer.parseInt(args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009888 } catch (NumberFormatException e) {
9889
9890 }
9891 for (int i=mLruProcesses.size()-1; i>=0; i--) {
9892 ProcessRecord proc = mLruProcesses.get(i);
9893 if (proc.pid == pid) {
9894 procs.add(proc);
Dianne Hackbornb437e092011-08-05 17:50:29 -07009895 } else if (proc.processName.equals(args[start])) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009896 procs.add(proc);
9897 }
9898 }
9899 if (procs.size() <= 0) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009900 pw.println("No process found for: " + args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009901 return null;
9902 }
9903 } else {
9904 procs = new ArrayList<ProcessRecord>(mLruProcesses);
9905 }
9906 }
9907 return procs;
9908 }
9909
9910 final void dumpGraphicsHardwareUsage(FileDescriptor fd,
9911 PrintWriter pw, String[] args) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009912 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009913 if (procs == null) {
9914 return;
9915 }
9916
9917 long uptime = SystemClock.uptimeMillis();
9918 long realtime = SystemClock.elapsedRealtime();
9919 pw.println("Applications Graphics Acceleration Info:");
9920 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
9921
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009922 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
9923 ProcessRecord r = procs.get(i);
Chet Haase9c1e23b2011-03-24 10:51:31 -07009924 if (r.thread != null) {
9925 pw.println("\n** Graphics info for pid " + r.pid + " [" + r.processName + "] **");
9926 pw.flush();
9927 try {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009928 TransferPipe tp = new TransferPipe();
9929 try {
9930 r.thread.dumpGfxInfo(tp.getWriteFd().getFileDescriptor(), args);
9931 tp.go(fd);
9932 } finally {
9933 tp.kill();
9934 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009935 } catch (IOException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009936 pw.println("Failure while dumping the app: " + r);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009937 pw.flush();
Chet Haase9c1e23b2011-03-24 10:51:31 -07009938 } catch (RemoteException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009939 pw.println("Got a RemoteException while dumping the app " + r);
Chet Haase9c1e23b2011-03-24 10:51:31 -07009940 pw.flush();
9941 }
9942 }
9943 }
Chet Haase9c1e23b2011-03-24 10:51:31 -07009944 }
9945
Jeff Brown6754ba22011-12-14 20:20:01 -08009946 final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) {
9947 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
9948 if (procs == null) {
9949 return;
9950 }
9951
9952 pw.println("Applications Database Info:");
9953
9954 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
9955 ProcessRecord r = procs.get(i);
9956 if (r.thread != null) {
9957 pw.println("\n** Database info for pid " + r.pid + " [" + r.processName + "] **");
9958 pw.flush();
9959 try {
9960 TransferPipe tp = new TransferPipe();
9961 try {
9962 r.thread.dumpDbInfo(tp.getWriteFd().getFileDescriptor(), args);
9963 tp.go(fd);
9964 } finally {
9965 tp.kill();
9966 }
9967 } catch (IOException e) {
9968 pw.println("Failure while dumping the app: " + r);
9969 pw.flush();
9970 } catch (RemoteException e) {
9971 pw.println("Got a RemoteException while dumping the app " + r);
9972 pw.flush();
9973 }
9974 }
9975 }
9976 }
9977
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009978 final static class MemItem {
9979 final String label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009980 final String shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009981 final long pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009982 final int id;
Dianne Hackborna4bacb82011-08-24 15:12:38 -07009983 ArrayList<MemItem> subitems;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009984
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009985 public MemItem(String _label, String _shortLabel, long _pss, int _id) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009986 label = _label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009987 shortLabel = _shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009988 pss = _pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009989 id = _id;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009990 }
9991 }
9992
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009993 static final void dumpMemItems(PrintWriter pw, String prefix, ArrayList<MemItem> items,
Dianne Hackbornb437e092011-08-05 17:50:29 -07009994 boolean sort) {
9995 if (sort) {
9996 Collections.sort(items, new Comparator<MemItem>() {
9997 @Override
9998 public int compare(MemItem lhs, MemItem rhs) {
9999 if (lhs.pss < rhs.pss) {
10000 return 1;
10001 } else if (lhs.pss > rhs.pss) {
10002 return -1;
10003 }
10004 return 0;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010005 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010006 });
10007 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010008
10009 for (int i=0; i<items.size(); i++) {
10010 MemItem mi = items.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010011 pw.print(prefix); pw.printf("%7d kB: ", mi.pss); pw.println(mi.label);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010012 if (mi.subitems != null) {
10013 dumpMemItems(pw, prefix + " ", mi.subitems, true);
10014 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010015 }
10016 }
10017
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010018 // These are in KB.
10019 static final long[] DUMP_MEM_BUCKETS = new long[] {
10020 5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024,
10021 120*1024, 160*1024, 200*1024,
10022 250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024,
10023 1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024
10024 };
10025
Dianne Hackborn672342c2011-11-29 11:29:02 -080010026 static final void appendMemBucket(StringBuilder out, long memKB, String label,
10027 boolean stackLike) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010028 int start = label.lastIndexOf('.');
10029 if (start >= 0) start++;
10030 else start = 0;
10031 int end = label.length();
10032 for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) {
10033 if (DUMP_MEM_BUCKETS[i] >= memKB) {
10034 long bucket = DUMP_MEM_BUCKETS[i]/1024;
10035 out.append(bucket);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010036 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010037 out.append(label, start, end);
10038 return;
10039 }
10040 }
10041 out.append(memKB/1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010042 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010043 out.append(label, start, end);
10044 }
10045
10046 static final int[] DUMP_MEM_OOM_ADJ = new int[] {
10047 ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ, ProcessList.FOREGROUND_APP_ADJ,
10048 ProcessList.VISIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ,
10049 ProcessList.BACKUP_APP_ADJ, ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ,
10050 ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.HIDDEN_APP_MAX_ADJ
10051 };
10052 static final String[] DUMP_MEM_OOM_LABEL = new String[] {
10053 "System", "Persistent", "Foreground",
10054 "Visible", "Perceptible", "Heavy Weight",
10055 "Backup", "A Services", "Home", "Previous",
10056 "B Services", "Background"
10057 };
10058
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010059 final void dumpApplicationMemoryUsage(FileDescriptor fd,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010060 PrintWriter pw, String prefix, String[] args, boolean brief,
Dianne Hackborn672342c2011-11-29 11:29:02 -080010061 PrintWriter categoryPw, StringBuilder outTag, StringBuilder outStack) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010062 boolean dumpAll = false;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010063 boolean oomOnly = false;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010064
10065 int opti = 0;
10066 while (opti < args.length) {
10067 String opt = args[opti];
10068 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
10069 break;
10070 }
10071 opti++;
10072 if ("-a".equals(opt)) {
10073 dumpAll = true;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010074 } else if ("--oom".equals(opt)) {
10075 oomOnly = true;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010076 } else if ("-h".equals(opt)) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010077 pw.println("meminfo dump options: [-a] [--oom] [process]");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010078 pw.println(" -a: include all available information for each process.");
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010079 pw.println(" --oom: only show processes organized by oom adj.");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010080 pw.println("If [process] is specified it can be the name or ");
10081 pw.println("pid of a specific process to dump.");
10082 return;
10083 } else {
10084 pw.println("Unknown argument: " + opt + "; use -h for help");
10085 }
10086 }
10087
10088 ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010089 if (procs == null) {
10090 return;
10091 }
10092
Dianne Hackborn6447ca32009-04-07 19:50:08 -070010093 final boolean isCheckinRequest = scanArgs(args, "--checkin");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010094 long uptime = SystemClock.uptimeMillis();
10095 long realtime = SystemClock.elapsedRealtime();
Dianne Hackbornb437e092011-08-05 17:50:29 -070010096
10097 if (procs.size() == 1 || isCheckinRequest) {
10098 dumpAll = true;
10099 }
10100
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010101 if (isCheckinRequest) {
10102 // short checkin version
10103 pw.println(uptime + "," + realtime);
10104 pw.flush();
10105 } else {
10106 pw.println("Applications Memory Usage (kB):");
10107 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10108 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010109
Dianne Hackbornb437e092011-08-05 17:50:29 -070010110 String[] innerArgs = new String[args.length-opti];
10111 System.arraycopy(args, opti, innerArgs, 0, args.length-opti);
10112
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010113 ArrayList<MemItem> procMems = new ArrayList<MemItem>();
10114 long nativePss=0, dalvikPss=0, otherPss=0;
10115 long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
10116
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010117 long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length];
10118 ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[])
10119 new ArrayList[DUMP_MEM_OOM_LABEL.length];
Dianne Hackbornb437e092011-08-05 17:50:29 -070010120
10121 long totalPss = 0;
10122
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010123 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10124 ProcessRecord r = procs.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010125 if (r.thread != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010126 if (!isCheckinRequest && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010127 pw.println("\n** MEMINFO in pid " + r.pid + " [" + r.processName + "] **");
10128 pw.flush();
10129 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010130 Debug.MemoryInfo mi = null;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010131 if (dumpAll) {
10132 try {
10133 mi = r.thread.dumpMemInfo(fd, isCheckinRequest, dumpAll, innerArgs);
10134 } catch (RemoteException e) {
10135 if (!isCheckinRequest) {
10136 pw.println("Got RemoteException!");
10137 pw.flush();
10138 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010139 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010140 } else {
10141 mi = new Debug.MemoryInfo();
10142 Debug.getMemoryInfo(r.pid, mi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010143 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010144
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010145 if (!isCheckinRequest && mi != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010146 long myTotalPss = mi.getTotalPss();
10147 totalPss += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010148 MemItem pssItem = new MemItem(r.processName + " (pid " + r.pid + ")",
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010149 r.processName, myTotalPss, 0);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010150 procMems.add(pssItem);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010151
10152 nativePss += mi.nativePss;
10153 dalvikPss += mi.dalvikPss;
10154 otherPss += mi.otherPss;
10155 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
10156 long mem = mi.getOtherPss(j);
10157 miscPss[j] += mem;
10158 otherPss -= mem;
10159 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010160
10161 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010162 if (r.setAdj <= DUMP_MEM_OOM_ADJ[oomIndex]
10163 || oomIndex == (oomPss.length-1)) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010164 oomPss[oomIndex] += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010165 if (oomProcs[oomIndex] == null) {
10166 oomProcs[oomIndex] = new ArrayList<MemItem>();
10167 }
10168 oomProcs[oomIndex].add(pssItem);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010169 break;
10170 }
10171 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010172 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010173 }
10174 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010175
10176 if (!isCheckinRequest && procs.size() > 1) {
10177 ArrayList<MemItem> catMems = new ArrayList<MemItem>();
10178
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010179 catMems.add(new MemItem("Native", "Native", nativePss, -1));
10180 catMems.add(new MemItem("Dalvik", "Dalvik", dalvikPss, -2));
10181 catMems.add(new MemItem("Unknown", "Unknown", otherPss, -3));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010182 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010183 String label = Debug.MemoryInfo.getOtherLabel(j);
10184 catMems.add(new MemItem(label, label, miscPss[j], j));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010185 }
10186
Dianne Hackbornb437e092011-08-05 17:50:29 -070010187 ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
10188 for (int j=0; j<oomPss.length; j++) {
10189 if (oomPss[j] != 0) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010190 String label = DUMP_MEM_OOM_LABEL[j];
10191 MemItem item = new MemItem(label, label, oomPss[j],
10192 DUMP_MEM_OOM_ADJ[j]);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010193 item.subitems = oomProcs[j];
10194 oomMems.add(item);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010195 }
10196 }
10197
Dianne Hackborn672342c2011-11-29 11:29:02 -080010198 if (outTag != null || outStack != null) {
10199 if (outTag != null) {
10200 appendMemBucket(outTag, totalPss, "total", false);
10201 }
10202 if (outStack != null) {
10203 appendMemBucket(outStack, totalPss, "total", true);
10204 }
10205 boolean firstLine = true;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010206 for (int i=0; i<oomMems.size(); i++) {
10207 MemItem miCat = oomMems.get(i);
10208 if (miCat.subitems == null || miCat.subitems.size() < 1) {
10209 continue;
10210 }
10211 if (miCat.id < ProcessList.SERVICE_ADJ
10212 || miCat.id == ProcessList.HOME_APP_ADJ
10213 || miCat.id == ProcessList.PREVIOUS_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010214 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10215 outTag.append(" / ");
10216 }
10217 if (outStack != null) {
10218 if (miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10219 if (firstLine) {
10220 outStack.append(":");
10221 firstLine = false;
10222 }
10223 outStack.append("\n\t at ");
10224 } else {
10225 outStack.append("$");
10226 }
10227 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010228 for (int j=0; j<miCat.subitems.size(); j++) {
10229 MemItem mi = miCat.subitems.get(j);
10230 if (j > 0) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010231 if (outTag != null) {
10232 outTag.append(" ");
10233 }
10234 if (outStack != null) {
10235 outStack.append("$");
10236 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010237 }
Dianne Hackborn672342c2011-11-29 11:29:02 -080010238 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10239 appendMemBucket(outTag, mi.pss, mi.shortLabel, false);
10240 }
10241 if (outStack != null) {
10242 appendMemBucket(outStack, mi.pss, mi.shortLabel, true);
10243 }
10244 }
10245 if (outStack != null && miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10246 outStack.append("(");
10247 for (int k=0; k<DUMP_MEM_OOM_ADJ.length; k++) {
10248 if (DUMP_MEM_OOM_ADJ[k] == miCat.id) {
10249 outStack.append(DUMP_MEM_OOM_LABEL[k]);
10250 outStack.append(":");
10251 outStack.append(DUMP_MEM_OOM_ADJ[k]);
10252 }
10253 }
10254 outStack.append(")");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010255 }
10256 }
10257 }
10258 }
10259
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010260 if (!brief && !oomOnly) {
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010261 pw.println();
10262 pw.println("Total PSS by process:");
10263 dumpMemItems(pw, " ", procMems, true);
10264 pw.println();
10265 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010266 pw.println("Total PSS by OOM adjustment:");
10267 dumpMemItems(pw, " ", oomMems, false);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010268 if (!oomOnly) {
10269 PrintWriter out = categoryPw != null ? categoryPw : pw;
10270 out.println();
10271 out.println("Total PSS by category:");
10272 dumpMemItems(out, " ", catMems, true);
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010273 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010274 pw.println();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010275 pw.print("Total PSS: "); pw.print(totalPss); pw.println(" kB");
Dianne Hackbornd3e677b2012-04-05 14:58:18 -070010276 final int[] SINGLE_LONG_FORMAT = new int[] {
10277 Process.PROC_SPACE_TERM|Process.PROC_OUT_LONG
10278 };
10279 long[] longOut = new long[1];
10280 Process.readProcFile("/sys/kernel/mm/ksm/pages_shared",
10281 SINGLE_LONG_FORMAT, null, longOut, null);
10282 long shared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10283 longOut[0] = 0;
10284 Process.readProcFile("/sys/kernel/mm/ksm/pages_sharing",
10285 SINGLE_LONG_FORMAT, null, longOut, null);
10286 long sharing = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10287 longOut[0] = 0;
10288 Process.readProcFile("/sys/kernel/mm/ksm/pages_unshared",
10289 SINGLE_LONG_FORMAT, null, longOut, null);
10290 long unshared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10291 longOut[0] = 0;
10292 Process.readProcFile("/sys/kernel/mm/ksm/pages_volatile",
10293 SINGLE_LONG_FORMAT, null, longOut, null);
10294 long voltile = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10295 pw.print(" KSM: "); pw.print(sharing); pw.print(" kB saved from shared ");
10296 pw.print(shared); pw.println(" kB");
10297 pw.print(" "); pw.print(unshared); pw.print(" kB unshared; ");
10298 pw.print(voltile); pw.println(" kB volatile");
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010299 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010300 }
10301
10302 /**
10303 * Searches array of arguments for the specified string
10304 * @param args array of argument strings
10305 * @param value value to search for
10306 * @return true if the value is contained in the array
10307 */
10308 private static boolean scanArgs(String[] args, String value) {
10309 if (args != null) {
10310 for (String arg : args) {
10311 if (value.equals(arg)) {
10312 return true;
10313 }
10314 }
10315 }
10316 return false;
10317 }
10318
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010319 private final void killServicesLocked(ProcessRecord app,
10320 boolean allowRestart) {
10321 // Report disconnected services.
10322 if (false) {
10323 // XXX we are letting the client link to the service for
10324 // death notifications.
10325 if (app.services.size() > 0) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010326 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010327 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010328 ServiceRecord r = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010329 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010330 Iterator<ArrayList<ConnectionRecord>> jt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010331 = r.connections.values().iterator();
10332 while (jt.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010333 ArrayList<ConnectionRecord> cl = jt.next();
10334 for (int i=0; i<cl.size(); i++) {
10335 ConnectionRecord c = cl.get(i);
10336 if (c.binding.client != app) {
10337 try {
10338 //c.conn.connected(r.className, null);
10339 } catch (Exception e) {
10340 // todo: this should be asynchronous!
10341 Slog.w(TAG, "Exception thrown disconnected servce "
10342 + r.shortName
10343 + " from app " + app.processName, e);
10344 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010345 }
10346 }
10347 }
10348 }
10349 }
10350 }
10351 }
10352
10353 // Clean up any connections this application has to other services.
10354 if (app.connections.size() > 0) {
10355 Iterator<ConnectionRecord> it = app.connections.iterator();
10356 while (it.hasNext()) {
10357 ConnectionRecord r = it.next();
10358 removeConnectionLocked(r, app, null);
10359 }
10360 }
10361 app.connections.clear();
10362
10363 if (app.services.size() != 0) {
10364 // Any services running in the application need to be placed
10365 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -070010366 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010367 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010368 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010369 synchronized (sr.stats.getBatteryStats()) {
10370 sr.stats.stopLaunchedLocked();
10371 }
10372 sr.app = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010373 sr.isolatedProc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010374 sr.executeNesting = 0;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010375 if (mStoppingServices.remove(sr)) {
10376 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
10377 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010378
10379 boolean hasClients = sr.bindings.size() > 0;
10380 if (hasClients) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010381 Iterator<IntentBindRecord> bindings
10382 = sr.bindings.values().iterator();
10383 while (bindings.hasNext()) {
10384 IntentBindRecord b = bindings.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -080010385 if (DEBUG_SERVICE) Slog.v(TAG, "Killing binding " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010386 + ": shouldUnbind=" + b.hasBound);
10387 b.binder = null;
10388 b.requested = b.received = b.hasBound = false;
10389 }
10390 }
10391
Dianne Hackborn070783f2010-12-29 16:46:28 -080010392 if (sr.crashCount >= 2 && (sr.serviceInfo.applicationInfo.flags
10393 &ApplicationInfo.FLAG_PERSISTENT) == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010394 Slog.w(TAG, "Service crashed " + sr.crashCount
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010395 + " times, stopping: " + sr);
Doug Zongker2bec3d42009-12-04 12:52:44 -080010396 EventLog.writeEvent(EventLogTags.AM_SERVICE_CRASHED_TOO_MUCH,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010397 sr.crashCount, sr.shortName, app.pid);
10398 bringDownServiceLocked(sr, true);
10399 } else if (!allowRestart) {
10400 bringDownServiceLocked(sr, true);
10401 } else {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010402 boolean canceled = scheduleServiceRestartLocked(sr, true);
10403
10404 // Should the service remain running? Note that in the
10405 // extreme case of so many attempts to deliver a command
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010406 // that it failed we also will stop it here.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010407 if (sr.startRequested && (sr.stopIfKilled || canceled)) {
10408 if (sr.pendingStarts.size() == 0) {
10409 sr.startRequested = false;
10410 if (!hasClients) {
10411 // Whoops, no reason to restart!
10412 bringDownServiceLocked(sr, true);
10413 }
10414 }
10415 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010416 }
10417 }
10418
10419 if (!allowRestart) {
10420 app.services.clear();
10421 }
10422 }
10423
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010424 // Make sure we have no more records on the stopping list.
10425 int i = mStoppingServices.size();
10426 while (i > 0) {
10427 i--;
10428 ServiceRecord sr = mStoppingServices.get(i);
10429 if (sr.app == app) {
10430 mStoppingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010431 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010432 }
10433 }
10434
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010435 app.executingServices.clear();
10436 }
10437
10438 private final void removeDyingProviderLocked(ProcessRecord proc,
10439 ContentProviderRecord cpr) {
10440 synchronized (cpr) {
10441 cpr.launchingApp = null;
10442 cpr.notifyAll();
10443 }
10444
Amith Yamasani742a6712011-05-04 14:49:28 -070010445 mProviderMap.removeProviderByClass(cpr.name, UserId.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010446 String names[] = cpr.info.authority.split(";");
10447 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010448 mProviderMap.removeProviderByName(names[j], UserId.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010449 }
10450
10451 Iterator<ProcessRecord> cit = cpr.clients.iterator();
10452 while (cit.hasNext()) {
10453 ProcessRecord capp = cit.next();
10454 if (!capp.persistent && capp.thread != null
10455 && capp.pid != 0
10456 && capp.pid != MY_PID) {
Dianne Hackborn8633e682010-04-22 16:03:41 -070010457 Slog.i(TAG, "Kill " + capp.processName
10458 + " (pid " + capp.pid + "): provider " + cpr.info.name
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010459 + " in dying process " + (proc != null ? proc.processName : "??"));
Dianne Hackborn8633e682010-04-22 16:03:41 -070010460 EventLog.writeEvent(EventLogTags.AM_KILL, capp.pid,
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010461 capp.processName, capp.setAdj, "dying provider "
10462 + cpr.name.toShortString());
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070010463 Process.killProcessQuiet(capp.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010464 }
10465 }
10466
10467 mLaunchingProviders.remove(cpr);
10468 }
10469
10470 /**
10471 * Main code for cleaning up a process when it has gone away. This is
10472 * called both as a result of the process dying, or directly when stopping
10473 * a process when running in single process mode.
10474 */
10475 private final void cleanUpApplicationRecordLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010476 boolean restarting, boolean allowRestart, int index) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010477 if (index >= 0) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010478 mLruProcesses.remove(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010479 }
10480
Dianne Hackborn36124872009-10-08 16:22:03 -070010481 mProcessesToGc.remove(app);
10482
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010483 // Dismiss any open dialogs.
10484 if (app.crashDialog != null) {
10485 app.crashDialog.dismiss();
10486 app.crashDialog = null;
10487 }
10488 if (app.anrDialog != null) {
10489 app.anrDialog.dismiss();
10490 app.anrDialog = null;
10491 }
10492 if (app.waitDialog != null) {
10493 app.waitDialog.dismiss();
10494 app.waitDialog = null;
10495 }
10496
10497 app.crashing = false;
10498 app.notResponding = false;
10499
10500 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -070010501 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010502 app.thread = null;
10503 app.forcingToForeground = null;
10504 app.foregroundServices = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010505 app.foregroundActivities = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070010506 app.hasShownUi = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010507 app.hasAboveClient = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010508
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010509 killServicesLocked(app, allowRestart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010510
10511 boolean restart = false;
10512
10513 int NL = mLaunchingProviders.size();
10514
10515 // Remove published content providers.
10516 if (!app.pubProviders.isEmpty()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010517 Iterator<ContentProviderRecord> it = app.pubProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010518 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010519 ContentProviderRecord cpr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010520 cpr.provider = null;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010521 cpr.proc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010522
10523 // See if someone is waiting for this provider... in which
10524 // case we don't remove it, but just let it restart.
10525 int i = 0;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010526 if (!app.bad && allowRestart) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010527 for (; i<NL; i++) {
10528 if (mLaunchingProviders.get(i) == cpr) {
10529 restart = true;
10530 break;
10531 }
10532 }
10533 } else {
10534 i = NL;
10535 }
10536
10537 if (i >= NL) {
10538 removeDyingProviderLocked(app, cpr);
10539 NL = mLaunchingProviders.size();
10540 }
10541 }
10542 app.pubProviders.clear();
10543 }
10544
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010545 // Take care of any launching providers waiting for this process.
10546 if (checkAppInLaunchingProvidersLocked(app, false)) {
10547 restart = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010548 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010549
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010550 // Unregister from connected content providers.
10551 if (!app.conProviders.isEmpty()) {
Dianne Hackborn0c3154d2009-10-06 17:18:05 -070010552 Iterator it = app.conProviders.keySet().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010553 while (it.hasNext()) {
10554 ContentProviderRecord cpr = (ContentProviderRecord)it.next();
10555 cpr.clients.remove(app);
10556 }
10557 app.conProviders.clear();
10558 }
10559
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010560 // At this point there may be remaining entries in mLaunchingProviders
10561 // where we were the only one waiting, so they are no longer of use.
10562 // Look for these and clean up if found.
10563 // XXX Commented out for now. Trying to figure out a way to reproduce
10564 // the actual situation to identify what is actually going on.
10565 if (false) {
10566 for (int i=0; i<NL; i++) {
10567 ContentProviderRecord cpr = (ContentProviderRecord)
10568 mLaunchingProviders.get(i);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080010569 if (cpr.clients.size() <= 0 && !cpr.hasExternalProcessHandles()) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010570 synchronized (cpr) {
10571 cpr.launchingApp = null;
10572 cpr.notifyAll();
10573 }
10574 }
10575 }
10576 }
10577
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010578 skipCurrentReceiverLocked(app);
10579
10580 // Unregister any receivers.
10581 if (app.receivers.size() > 0) {
10582 Iterator<ReceiverList> it = app.receivers.iterator();
10583 while (it.hasNext()) {
10584 removeReceiverLocked(it.next());
10585 }
10586 app.receivers.clear();
10587 }
10588
Christopher Tate181fafa2009-05-14 11:12:14 -070010589 // If the app is undergoing backup, tell the backup manager about it
10590 if (mBackupTarget != null && app.pid == mBackupTarget.app.pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010591 if (DEBUG_BACKUP) Slog.d(TAG, "App " + mBackupTarget.appInfo + " died during backup");
Christopher Tate181fafa2009-05-14 11:12:14 -070010592 try {
10593 IBackupManager bm = IBackupManager.Stub.asInterface(
10594 ServiceManager.getService(Context.BACKUP_SERVICE));
10595 bm.agentDisconnected(app.info.packageName);
10596 } catch (RemoteException e) {
10597 // can't happen; backup manager is local
10598 }
10599 }
10600
Jeff Sharkey287bd832011-05-28 19:36:26 -070010601 mHandler.obtainMessage(DISPATCH_PROCESS_DIED, app.pid, app.info.uid, null).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010602
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010603 // If the caller is restarting this app, then leave it in its
10604 // current lists and let the caller take care of it.
10605 if (restarting) {
10606 return;
10607 }
10608
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010609 if (!app.persistent || app.isolated) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010610 if (DEBUG_PROCESSES) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010611 "Removing non-persistent process during cleanup: " + app);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010612 mProcessNames.remove(app.processName, app.uid);
10613 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -070010614 if (mHeavyWeightProcess == app) {
10615 mHeavyWeightProcess = null;
10616 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
10617 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010618 } else if (!app.removed) {
10619 // This app is persistent, so we need to keep its record around.
10620 // If it is not already on the pending app list, add it there
10621 // and start a new process for it.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010622 if (mPersistentStartingProcesses.indexOf(app) < 0) {
10623 mPersistentStartingProcesses.add(app);
10624 restart = true;
10625 }
10626 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070010627 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
10628 "Clean-up removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010629 mProcessesOnHold.remove(app);
10630
The Android Open Source Project4df24232009-03-05 14:34:35 -080010631 if (app == mHomeProcess) {
10632 mHomeProcess = null;
10633 }
Dianne Hackbornf35fe232011-11-01 19:25:20 -070010634 if (app == mPreviousProcess) {
10635 mPreviousProcess = null;
10636 }
10637
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010638 if (restart && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010639 // We have components that still need to be running in the
10640 // process, so re-launch it.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010641 mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010642 startProcessLocked(app, "restart", app.processName);
10643 } else if (app.pid > 0 && app.pid != MY_PID) {
10644 // Goodbye!
10645 synchronized (mPidsSelfLocked) {
10646 mPidsSelfLocked.remove(app.pid);
10647 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
10648 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010649 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010650 }
10651 }
10652
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010653 boolean checkAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) {
10654 // Look through the content providers we are waiting to have launched,
10655 // and if any run in this process then either schedule a restart of
10656 // the process or kill the client waiting for it if this process has
10657 // gone bad.
10658 int NL = mLaunchingProviders.size();
10659 boolean restart = false;
10660 for (int i=0; i<NL; i++) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010661 ContentProviderRecord cpr = mLaunchingProviders.get(i);
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010662 if (cpr.launchingApp == app) {
10663 if (!alwaysBad && !app.bad) {
10664 restart = true;
10665 } else {
10666 removeDyingProviderLocked(app, cpr);
10667 NL = mLaunchingProviders.size();
10668 }
10669 }
10670 }
10671 return restart;
10672 }
10673
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010674 // =========================================================
10675 // SERVICES
10676 // =========================================================
10677
10678 ActivityManager.RunningServiceInfo makeRunningServiceInfoLocked(ServiceRecord r) {
10679 ActivityManager.RunningServiceInfo info =
10680 new ActivityManager.RunningServiceInfo();
10681 info.service = r.name;
10682 if (r.app != null) {
10683 info.pid = r.app.pid;
10684 }
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010685 info.uid = r.appInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010686 info.process = r.processName;
10687 info.foreground = r.isForeground;
10688 info.activeSince = r.createTime;
10689 info.started = r.startRequested;
10690 info.clientCount = r.connections.size();
10691 info.crashCount = r.crashCount;
10692 info.lastActivityTime = r.lastActivity;
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010693 if (r.isForeground) {
10694 info.flags |= ActivityManager.RunningServiceInfo.FLAG_FOREGROUND;
10695 }
10696 if (r.startRequested) {
10697 info.flags |= ActivityManager.RunningServiceInfo.FLAG_STARTED;
10698 }
Dan Egnor42471dd2010-01-07 17:25:22 -080010699 if (r.app != null && r.app.pid == MY_PID) {
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010700 info.flags |= ActivityManager.RunningServiceInfo.FLAG_SYSTEM_PROCESS;
10701 }
10702 if (r.app != null && r.app.persistent) {
10703 info.flags |= ActivityManager.RunningServiceInfo.FLAG_PERSISTENT_PROCESS;
10704 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010705
10706 for (ArrayList<ConnectionRecord> connl : r.connections.values()) {
10707 for (int i=0; i<connl.size(); i++) {
10708 ConnectionRecord conn = connl.get(i);
10709 if (conn.clientLabel != 0) {
10710 info.clientPackage = conn.binding.client.info.packageName;
10711 info.clientLabel = conn.clientLabel;
10712 return info;
10713 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010714 }
10715 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010716 return info;
10717 }
10718
10719 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum,
10720 int flags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010721 enforceNotIsolatedCaller("getServices");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010722 synchronized (this) {
10723 ArrayList<ActivityManager.RunningServiceInfo> res
10724 = new ArrayList<ActivityManager.RunningServiceInfo>();
10725
Amith Yamasani742a6712011-05-04 14:49:28 -070010726 int userId = UserId.getUserId(Binder.getCallingUid());
10727 if (mServiceMap.getAllServices(userId).size() > 0) {
10728 Iterator<ServiceRecord> it
10729 = mServiceMap.getAllServices(userId).iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010730 while (it.hasNext() && res.size() < maxNum) {
10731 res.add(makeRunningServiceInfoLocked(it.next()));
10732 }
10733 }
10734
10735 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
10736 ServiceRecord r = mRestartingServices.get(i);
10737 ActivityManager.RunningServiceInfo info =
10738 makeRunningServiceInfoLocked(r);
10739 info.restarting = r.nextRestartTime;
10740 res.add(info);
10741 }
10742
10743 return res;
10744 }
10745 }
10746
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010747 public PendingIntent getRunningServiceControlPanel(ComponentName name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010748 enforceNotIsolatedCaller("getRunningServiceControlPanel");
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010749 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010750 int userId = UserId.getUserId(Binder.getCallingUid());
10751 ServiceRecord r = mServiceMap.getServiceByName(name, userId);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010752 if (r != null) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010753 for (ArrayList<ConnectionRecord> conn : r.connections.values()) {
10754 for (int i=0; i<conn.size(); i++) {
10755 if (conn.get(i).clientIntent != null) {
10756 return conn.get(i).clientIntent;
10757 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010758 }
10759 }
10760 }
10761 }
10762 return null;
10763 }
10764
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010765 private final ServiceRecord findServiceLocked(ComponentName name,
10766 IBinder token) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010767 ServiceRecord r = mServiceMap.getServiceByName(name, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010768 return r == token ? r : null;
10769 }
10770
10771 private final class ServiceLookupResult {
10772 final ServiceRecord record;
10773 final String permission;
10774
10775 ServiceLookupResult(ServiceRecord _record, String _permission) {
10776 record = _record;
10777 permission = _permission;
10778 }
10779 };
10780
10781 private ServiceLookupResult findServiceLocked(Intent service,
Amith Yamasani483f3b02012-03-13 16:08:00 -070010782 String resolvedType, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010783 ServiceRecord r = null;
10784 if (service.getComponent() != null) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070010785 r = mServiceMap.getServiceByName(service.getComponent(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010786 }
10787 if (r == null) {
10788 Intent.FilterComparison filter = new Intent.FilterComparison(service);
Amith Yamasani483f3b02012-03-13 16:08:00 -070010789 r = mServiceMap.getServiceByIntent(filter, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010790 }
10791
10792 if (r == null) {
10793 try {
10794 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070010795 AppGlobals.getPackageManager().resolveService(
Amith Yamasani483f3b02012-03-13 16:08:00 -070010796 service, resolvedType, 0, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010797 ServiceInfo sInfo =
10798 rInfo != null ? rInfo.serviceInfo : null;
10799 if (sInfo == null) {
10800 return null;
10801 }
10802
10803 ComponentName name = new ComponentName(
10804 sInfo.applicationInfo.packageName, sInfo.name);
Amith Yamasani742a6712011-05-04 14:49:28 -070010805 r = mServiceMap.getServiceByName(name, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010806 } catch (RemoteException ex) {
10807 // pm is in same process, this will never happen.
10808 }
10809 }
10810 if (r != null) {
10811 int callingPid = Binder.getCallingPid();
10812 int callingUid = Binder.getCallingUid();
10813 if (checkComponentPermission(r.permission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010814 callingPid, callingUid, r.appInfo.uid, r.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010815 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010816 if (!r.exported) {
10817 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
10818 + " from pid=" + callingPid
10819 + ", uid=" + callingUid
10820 + " that is not exported from uid " + r.appInfo.uid);
10821 return new ServiceLookupResult(null, "not exported from uid "
10822 + r.appInfo.uid);
10823 }
Joe Onorato8a9b2202010-02-26 18:56:32 -080010824 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010825 + " from pid=" + callingPid
10826 + ", uid=" + callingUid
10827 + " requires " + r.permission);
10828 return new ServiceLookupResult(null, r.permission);
10829 }
10830 return new ServiceLookupResult(r, null);
10831 }
10832 return null;
10833 }
10834
10835 private class ServiceRestarter implements Runnable {
10836 private ServiceRecord mService;
10837
10838 void setService(ServiceRecord service) {
10839 mService = service;
10840 }
10841
10842 public void run() {
10843 synchronized(ActivityManagerService.this) {
10844 performServiceRestartLocked(mService);
10845 }
10846 }
10847 }
10848
10849 private ServiceLookupResult retrieveServiceLocked(Intent service,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010850 String resolvedType, int callingPid, int callingUid, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010851 ServiceRecord r = null;
Amith Yamasani742a6712011-05-04 14:49:28 -070010852 if (DEBUG_SERVICE)
10853 Slog.v(TAG, "retrieveServiceLocked: " + service + " type=" + resolvedType
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010854 + " callingUid=" + callingUid);
Amith Yamasani742a6712011-05-04 14:49:28 -070010855
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010856 if (service.getComponent() != null) {
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010857 r = mServiceMap.getServiceByName(service.getComponent(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010858 }
Amith Yamasani742a6712011-05-04 14:49:28 -070010859 if (r == null) {
10860 Intent.FilterComparison filter = new Intent.FilterComparison(service);
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010861 r = mServiceMap.getServiceByIntent(filter, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -070010862 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010863 if (r == null) {
10864 try {
10865 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070010866 AppGlobals.getPackageManager().resolveService(
Amith Yamasani483f3b02012-03-13 16:08:00 -070010867 service, resolvedType, STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010868 ServiceInfo sInfo =
10869 rInfo != null ? rInfo.serviceInfo : null;
10870 if (sInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010871 Slog.w(TAG, "Unable to start service " + service +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010872 ": not found");
10873 return null;
10874 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010875 if (userId > 0) {
10876 sInfo.applicationInfo = getAppInfoForUser(sInfo.applicationInfo, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -070010877 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010878 ComponentName name = new ComponentName(
10879 sInfo.applicationInfo.packageName, sInfo.name);
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010880 r = mServiceMap.getServiceByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010881 if (r == null) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010882 Intent.FilterComparison filter = new Intent.FilterComparison(
10883 service.cloneFilter());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010884 ServiceRestarter res = new ServiceRestarter();
10885 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
10886 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
10887 synchronized (stats) {
10888 ss = stats.getServiceStatsLocked(
10889 sInfo.applicationInfo.uid, sInfo.packageName,
10890 sInfo.name);
10891 }
Dianne Hackbornb1c4a2a2010-01-19 15:36:42 -080010892 r = new ServiceRecord(this, ss, name, filter, sInfo, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010893 res.setService(r);
Amith Yamasani742a6712011-05-04 14:49:28 -070010894 mServiceMap.putServiceByName(name, UserId.getUserId(r.appInfo.uid), r);
10895 mServiceMap.putServiceByIntent(filter, UserId.getUserId(r.appInfo.uid), r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010896
10897 // Make sure this component isn't in the pending list.
10898 int N = mPendingServices.size();
10899 for (int i=0; i<N; i++) {
10900 ServiceRecord pr = mPendingServices.get(i);
10901 if (pr.name.equals(name)) {
10902 mPendingServices.remove(i);
10903 i--;
10904 N--;
10905 }
10906 }
10907 }
10908 } catch (RemoteException ex) {
10909 // pm is in same process, this will never happen.
10910 }
10911 }
10912 if (r != null) {
10913 if (checkComponentPermission(r.permission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010914 callingPid, callingUid, r.appInfo.uid, r.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010915 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010916 if (!r.exported) {
10917 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
10918 + " from pid=" + callingPid
10919 + ", uid=" + callingUid
10920 + " that is not exported from uid " + r.appInfo.uid);
10921 return new ServiceLookupResult(null, "not exported from uid "
10922 + r.appInfo.uid);
10923 }
Joe Onorato8a9b2202010-02-26 18:56:32 -080010924 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010925 + " from pid=" + callingPid
10926 + ", uid=" + callingUid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010927 + " requires " + r.permission);
10928 return new ServiceLookupResult(null, r.permission);
10929 }
10930 return new ServiceLookupResult(r, null);
10931 }
10932 return null;
10933 }
10934
Dianne Hackborn287952c2010-09-22 22:34:31 -070010935 private final void bumpServiceExecutingLocked(ServiceRecord r, String why) {
10936 if (DEBUG_SERVICE) Log.v(TAG, ">>> EXECUTING "
10937 + why + " of " + r + " in app " + r.app);
10938 else if (DEBUG_SERVICE_EXECUTING) Log.v(TAG, ">>> EXECUTING "
10939 + why + " of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010940 long now = SystemClock.uptimeMillis();
10941 if (r.executeNesting == 0 && r.app != null) {
10942 if (r.app.executingServices.size() == 0) {
10943 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
10944 msg.obj = r.app;
10945 mHandler.sendMessageAtTime(msg, now+SERVICE_TIMEOUT);
10946 }
10947 r.app.executingServices.add(r);
10948 }
10949 r.executeNesting++;
10950 r.executingStart = now;
10951 }
10952
10953 private final void sendServiceArgsLocked(ServiceRecord r,
10954 boolean oomAdjusted) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010955 final int N = r.pendingStarts.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010956 if (N == 0) {
10957 return;
10958 }
10959
Dianne Hackborn39792d22010-08-19 18:01:52 -070010960 while (r.pendingStarts.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010961 try {
Dianne Hackborn39792d22010-08-19 18:01:52 -070010962 ServiceRecord.StartItem si = r.pendingStarts.remove(0);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010963 if (DEBUG_SERVICE) Slog.v(TAG, "Sending arguments to: "
10964 + r + " " + r.intent + " args=" + si.intent);
Dianne Hackborn3a28f222011-03-01 12:25:54 -080010965 if (si.intent == null && N > 1) {
10966 // If somehow we got a dummy null intent in the middle,
10967 // then skip it. DO NOT skip a null intent when it is
10968 // the only one in the list -- this is to support the
10969 // onStartCommand(null) case.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010970 continue;
10971 }
Dianne Hackborn39792d22010-08-19 18:01:52 -070010972 si.deliveredTime = SystemClock.uptimeMillis();
10973 r.deliveredStarts.add(si);
10974 si.deliveryCount++;
Dianne Hackborn21c241e2012-03-08 13:57:23 -080010975 if (si.neededGrants != null) {
10976 grantUriPermissionUncheckedFromIntentLocked(si.neededGrants,
10977 si.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -070010978 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070010979 bumpServiceExecutingLocked(r, "start");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010980 if (!oomAdjusted) {
10981 oomAdjusted = true;
10982 updateOomAdjLocked(r.app);
10983 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010984 int flags = 0;
10985 if (si.deliveryCount > 0) {
10986 flags |= Service.START_FLAG_RETRY;
10987 }
10988 if (si.doneExecutingCount > 0) {
10989 flags |= Service.START_FLAG_REDELIVERY;
10990 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070010991 r.app.thread.scheduleServiceArgs(r, si.taskRemoved, si.id, flags, si.intent);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010992 } catch (RemoteException e) {
10993 // Remote process gone... we'll let the normal cleanup take
10994 // care of this.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010995 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while scheduling start: " + r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010996 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010997 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010998 Slog.w(TAG, "Unexpected exception", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010999 break;
11000 }
11001 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011002 }
11003
11004 private final boolean requestServiceBindingLocked(ServiceRecord r,
11005 IntentBindRecord i, boolean rebind) {
11006 if (r.app == null || r.app.thread == null) {
11007 // If service is not currently running, can't yet bind.
11008 return false;
11009 }
11010 if ((!i.requested || rebind) && i.apps.size() > 0) {
11011 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011012 bumpServiceExecutingLocked(r, "bind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011013 r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind);
11014 if (!rebind) {
11015 i.requested = true;
11016 }
11017 i.hasBound = true;
11018 i.doRebind = false;
11019 } catch (RemoteException e) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011020 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while binding " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011021 return false;
11022 }
11023 }
11024 return true;
11025 }
11026
11027 private final void requestServiceBindingsLocked(ServiceRecord r) {
11028 Iterator<IntentBindRecord> bindings = r.bindings.values().iterator();
11029 while (bindings.hasNext()) {
11030 IntentBindRecord i = bindings.next();
11031 if (!requestServiceBindingLocked(r, i, false)) {
11032 break;
11033 }
11034 }
11035 }
11036
11037 private final void realStartServiceLocked(ServiceRecord r,
11038 ProcessRecord app) throws RemoteException {
11039 if (app.thread == null) {
11040 throw new RemoteException();
11041 }
Amith Yamasani742a6712011-05-04 14:49:28 -070011042 if (DEBUG_MU)
11043 Slog.v(TAG_MU, "realStartServiceLocked, ServiceRecord.uid = " + r.appInfo.uid
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011044 + ", ProcessRecord.uid = " + app.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011045 r.app = app;
The Android Open Source Project10592532009-03-18 17:39:46 -070011046 r.restartTime = r.lastActivity = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011047
11048 app.services.add(r);
Dianne Hackborn287952c2010-09-22 22:34:31 -070011049 bumpServiceExecutingLocked(r, "create");
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011050 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011051
11052 boolean created = false;
11053 try {
Dianne Hackborna33e3f72009-09-29 17:28:24 -070011054 mStringBuilder.setLength(0);
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011055 r.intent.getIntent().toShortString(mStringBuilder, true, false, true, false);
Doug Zongker2bec3d42009-12-04 12:52:44 -080011056 EventLog.writeEvent(EventLogTags.AM_CREATE_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011057 System.identityHashCode(r), r.shortName,
Dianne Hackborna33e3f72009-09-29 17:28:24 -070011058 mStringBuilder.toString(), r.app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011059 synchronized (r.stats.getBatteryStats()) {
11060 r.stats.startLaunchedLocked();
11061 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -070011062 ensurePackageDexOpt(r.serviceInfo.packageName);
Dianne Hackborne2515ee2011-04-27 18:52:56 -040011063 app.thread.scheduleCreateService(r, r.serviceInfo,
11064 compatibilityInfoForPackageLocked(r.serviceInfo.applicationInfo));
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011065 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011066 created = true;
11067 } finally {
11068 if (!created) {
11069 app.services.remove(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011070 scheduleServiceRestartLocked(r, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011071 }
11072 }
11073
11074 requestServiceBindingsLocked(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011075
11076 // If the service is in the started state, and there are no
11077 // pending arguments, then fake up one so its onStartCommand() will
11078 // be called.
11079 if (r.startRequested && r.callStart && r.pendingStarts.size() == 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011080 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011081 null, null));
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011082 }
11083
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011084 sendServiceArgsLocked(r, true);
11085 }
11086
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011087 private final boolean scheduleServiceRestartLocked(ServiceRecord r,
11088 boolean allowCancel) {
11089 boolean canceled = false;
11090
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011091 final long now = SystemClock.uptimeMillis();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011092 long minDuration = SERVICE_RESTART_DURATION;
Dianne Hackborn6ccd2af2009-08-27 12:26:44 -070011093 long resetTime = SERVICE_RESET_RUN_DURATION;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011094
Dianne Hackborn070783f2010-12-29 16:46:28 -080011095 if ((r.serviceInfo.applicationInfo.flags
11096 &ApplicationInfo.FLAG_PERSISTENT) != 0) {
11097 minDuration /= 4;
11098 }
11099
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011100 // Any delivered but not yet finished starts should be put back
11101 // on the pending list.
11102 final int N = r.deliveredStarts.size();
11103 if (N > 0) {
11104 for (int i=N-1; i>=0; i--) {
11105 ServiceRecord.StartItem si = r.deliveredStarts.get(i);
Dianne Hackborn39792d22010-08-19 18:01:52 -070011106 si.removeUriPermissionsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011107 if (si.intent == null) {
11108 // We'll generate this again if needed.
11109 } else if (!allowCancel || (si.deliveryCount < ServiceRecord.MAX_DELIVERY_COUNT
11110 && si.doneExecutingCount < ServiceRecord.MAX_DONE_EXECUTING_COUNT)) {
11111 r.pendingStarts.add(0, si);
11112 long dur = SystemClock.uptimeMillis() - si.deliveredTime;
11113 dur *= 2;
11114 if (minDuration < dur) minDuration = dur;
11115 if (resetTime < dur) resetTime = dur;
11116 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011117 Slog.w(TAG, "Canceling start item " + si.intent + " in service "
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011118 + r.name);
11119 canceled = true;
11120 }
11121 }
11122 r.deliveredStarts.clear();
11123 }
11124
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011125 r.totalRestartCount++;
11126 if (r.restartDelay == 0) {
11127 r.restartCount++;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011128 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011129 } else {
11130 // If it has been a "reasonably long time" since the service
11131 // was started, then reset our restart duration back to
11132 // the beginning, so we don't infinitely increase the duration
11133 // on a service that just occasionally gets killed (which is
11134 // a normal case, due to process being killed to reclaim memory).
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011135 if (now > (r.restartTime+resetTime)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011136 r.restartCount = 1;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011137 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011138 } else {
Dianne Hackborn070783f2010-12-29 16:46:28 -080011139 if ((r.serviceInfo.applicationInfo.flags
11140 &ApplicationInfo.FLAG_PERSISTENT) != 0) {
11141 // Services in peristent processes will restart much more
11142 // quickly, since they are pretty important. (Think SystemUI).
11143 r.restartDelay += minDuration/2;
11144 } else {
11145 r.restartDelay *= SERVICE_RESTART_DURATION_FACTOR;
11146 if (r.restartDelay < minDuration) {
11147 r.restartDelay = minDuration;
11148 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011149 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011150 }
11151 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011152
11153 r.nextRestartTime = now + r.restartDelay;
11154
11155 // Make sure that we don't end up restarting a bunch of services
11156 // all at the same time.
11157 boolean repeat;
11158 do {
11159 repeat = false;
11160 for (int i=mRestartingServices.size()-1; i>=0; i--) {
11161 ServiceRecord r2 = mRestartingServices.get(i);
11162 if (r2 != r && r.nextRestartTime
11163 >= (r2.nextRestartTime-SERVICE_MIN_RESTART_TIME_BETWEEN)
11164 && r.nextRestartTime
11165 < (r2.nextRestartTime+SERVICE_MIN_RESTART_TIME_BETWEEN)) {
11166 r.nextRestartTime = r2.nextRestartTime + SERVICE_MIN_RESTART_TIME_BETWEEN;
11167 r.restartDelay = r.nextRestartTime - now;
11168 repeat = true;
11169 break;
11170 }
11171 }
11172 } while (repeat);
11173
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011174 if (!mRestartingServices.contains(r)) {
11175 mRestartingServices.add(r);
11176 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011177
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011178 r.cancelNotification();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011179
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011180 mHandler.removeCallbacks(r.restarter);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011181 mHandler.postAtTime(r.restarter, r.nextRestartTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011182 r.nextRestartTime = SystemClock.uptimeMillis() + r.restartDelay;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011183 Slog.w(TAG, "Scheduling restart of crashed service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011184 + r.shortName + " in " + r.restartDelay + "ms");
Doug Zongker2bec3d42009-12-04 12:52:44 -080011185 EventLog.writeEvent(EventLogTags.AM_SCHEDULE_SERVICE_RESTART,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011186 r.shortName, r.restartDelay);
11187
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011188 return canceled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011189 }
11190
11191 final void performServiceRestartLocked(ServiceRecord r) {
11192 if (!mRestartingServices.contains(r)) {
11193 return;
11194 }
11195 bringUpServiceLocked(r, r.intent.getIntent().getFlags(), true);
11196 }
11197
11198 private final boolean unscheduleServiceRestartLocked(ServiceRecord r) {
11199 if (r.restartDelay == 0) {
11200 return false;
11201 }
11202 r.resetRestartCounter();
11203 mRestartingServices.remove(r);
11204 mHandler.removeCallbacks(r.restarter);
11205 return true;
11206 }
11207
11208 private final boolean bringUpServiceLocked(ServiceRecord r,
11209 int intentFlags, boolean whileRestarting) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011210 //Slog.i(TAG, "Bring up service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011211 //r.dump(" ");
11212
Dianne Hackborn36124872009-10-08 16:22:03 -070011213 if (r.app != null && r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011214 sendServiceArgsLocked(r, false);
11215 return true;
11216 }
11217
11218 if (!whileRestarting && r.restartDelay > 0) {
11219 // If waiting for a restart, then do nothing.
11220 return true;
11221 }
11222
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011223 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing up " + r + " " + r.intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011224
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011225 // We are now bringing the service up, so no longer in the
11226 // restarting state.
11227 mRestartingServices.remove(r);
11228
Dianne Hackborne7f97212011-02-24 14:40:20 -080011229 // Service is now being launched, its package can't be stopped.
11230 try {
11231 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -070011232 r.packageName, false, r.userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -080011233 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080011234 } catch (IllegalArgumentException e) {
11235 Slog.w(TAG, "Failed trying to unstop package "
11236 + r.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080011237 }
11238
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011239 final boolean isolated = (r.serviceInfo.flags&ServiceInfo.FLAG_ISOLATED_PROCESS) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011240 final String appName = r.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011241 ProcessRecord app;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011242
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011243 if (!isolated) {
11244 app = getProcessRecordLocked(appName, r.appInfo.uid);
11245 if (DEBUG_MU)
11246 Slog.v(TAG_MU, "bringUpServiceLocked: appInfo.uid=" + r.appInfo.uid + " app=" + app);
11247 if (app != null && app.thread != null) {
11248 try {
11249 app.addPackage(r.appInfo.packageName);
11250 realStartServiceLocked(r, app);
11251 return true;
11252 } catch (RemoteException e) {
11253 Slog.w(TAG, "Exception when starting service " + r.shortName, e);
11254 }
11255
11256 // If a dead object exception was thrown -- fall through to
11257 // restart the application.
11258 }
11259 } else {
11260 // If this service runs in an isolated process, then each time
11261 // we call startProcessLocked() we will get a new isolated
11262 // process, starting another process if we are currently waiting
11263 // for a previous process to come up. To deal with this, we store
11264 // in the service any current isolated process it is running in or
11265 // waiting to have come up.
11266 app = r.isolatedProc;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011267 }
11268
Dianne Hackborn36124872009-10-08 16:22:03 -070011269 // Not running -- get it started, and enqueue this service record
11270 // to be executed when the app comes up.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011271 if (app == null) {
11272 if ((app=startProcessLocked(appName, r.appInfo, true, intentFlags,
11273 "service", r.name, false, isolated)) == null) {
11274 Slog.w(TAG, "Unable to launch app "
11275 + r.appInfo.packageName + "/"
11276 + r.appInfo.uid + " for service "
11277 + r.intent.getIntent() + ": process is bad");
11278 bringDownServiceLocked(r, true);
11279 return false;
11280 }
11281 if (isolated) {
11282 r.isolatedProc = app;
11283 }
Dianne Hackborn36124872009-10-08 16:22:03 -070011284 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011285
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011286 if (!mPendingServices.contains(r)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011287 mPendingServices.add(r);
11288 }
Dianne Hackborn36124872009-10-08 16:22:03 -070011289
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011290 return true;
11291 }
11292
11293 private final void bringDownServiceLocked(ServiceRecord r, boolean force) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011294 //Slog.i(TAG, "Bring down service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011295 //r.dump(" ");
11296
11297 // Does it still need to run?
11298 if (!force && r.startRequested) {
11299 return;
11300 }
11301 if (r.connections.size() > 0) {
11302 if (!force) {
11303 // XXX should probably keep a count of the number of auto-create
11304 // connections directly in the service.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011305 Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011306 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011307 ArrayList<ConnectionRecord> cr = it.next();
11308 for (int i=0; i<cr.size(); i++) {
11309 if ((cr.get(i).flags&Context.BIND_AUTO_CREATE) != 0) {
11310 return;
11311 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011312 }
11313 }
11314 }
11315
11316 // Report to all of the connections that the service is no longer
11317 // available.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011318 Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011319 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011320 ArrayList<ConnectionRecord> c = it.next();
11321 for (int i=0; i<c.size(); i++) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011322 ConnectionRecord cr = c.get(i);
11323 // There is still a connection to the service that is
11324 // being brought down. Mark it as dead.
11325 cr.serviceDead = true;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011326 try {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011327 cr.conn.connected(r.name, null);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011328 } catch (Exception e) {
11329 Slog.w(TAG, "Failure disconnecting service " + r.name +
11330 " to connection " + c.get(i).conn.asBinder() +
11331 " (in " + c.get(i).binding.client.processName + ")", e);
11332 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011333 }
11334 }
11335 }
11336
11337 // Tell the service that it has been unbound.
11338 if (r.bindings.size() > 0 && r.app != null && r.app.thread != null) {
11339 Iterator<IntentBindRecord> it = r.bindings.values().iterator();
11340 while (it.hasNext()) {
11341 IntentBindRecord ibr = it.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -080011342 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down binding " + ibr
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011343 + ": hasBound=" + ibr.hasBound);
11344 if (r.app != null && r.app.thread != null && ibr.hasBound) {
11345 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011346 bumpServiceExecutingLocked(r, "bring down unbind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011347 updateOomAdjLocked(r.app);
11348 ibr.hasBound = false;
11349 r.app.thread.scheduleUnbindService(r,
11350 ibr.intent.getIntent());
11351 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011352 Slog.w(TAG, "Exception when unbinding service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011353 + r.shortName, e);
11354 serviceDoneExecutingLocked(r, true);
11355 }
11356 }
11357 }
11358 }
11359
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011360 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down " + r + " " + r.intent);
Doug Zongker2bec3d42009-12-04 12:52:44 -080011361 EventLog.writeEvent(EventLogTags.AM_DESTROY_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011362 System.identityHashCode(r), r.shortName,
11363 (r.app != null) ? r.app.pid : -1);
11364
Amith Yamasani742a6712011-05-04 14:49:28 -070011365 mServiceMap.removeServiceByName(r.name, r.userId);
11366 mServiceMap.removeServiceByIntent(r.intent, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011367 r.totalRestartCount = 0;
11368 unscheduleServiceRestartLocked(r);
11369
11370 // Also make sure it is not on the pending list.
11371 int N = mPendingServices.size();
11372 for (int i=0; i<N; i++) {
11373 if (mPendingServices.get(i) == r) {
11374 mPendingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011375 if (DEBUG_SERVICE) Slog.v(TAG, "Removed pending: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011376 i--;
11377 N--;
11378 }
11379 }
11380
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011381 r.cancelNotification();
11382 r.isForeground = false;
11383 r.foregroundId = 0;
11384 r.foregroundNoti = null;
11385
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011386 // Clear start entries.
Dianne Hackborn39792d22010-08-19 18:01:52 -070011387 r.clearDeliveredStartsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011388 r.pendingStarts.clear();
11389
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011390 if (r.app != null) {
11391 synchronized (r.stats.getBatteryStats()) {
11392 r.stats.stopLaunchedLocked();
11393 }
11394 r.app.services.remove(r);
11395 if (r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011396 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011397 bumpServiceExecutingLocked(r, "stop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011398 mStoppingServices.add(r);
11399 updateOomAdjLocked(r.app);
11400 r.app.thread.scheduleStopService(r);
11401 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011402 Slog.w(TAG, "Exception when stopping service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011403 + r.shortName, e);
11404 serviceDoneExecutingLocked(r, true);
11405 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011406 updateServiceForegroundLocked(r.app, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011407 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011408 if (DEBUG_SERVICE) Slog.v(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011409 TAG, "Removed service that has no process: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011410 }
11411 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011412 if (DEBUG_SERVICE) Slog.v(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011413 TAG, "Removed service that is not running: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011414 }
Vairavan Srinivasana207ce22010-12-23 13:51:48 -080011415
11416 if (r.bindings.size() > 0) {
11417 r.bindings.clear();
11418 }
11419
11420 if (r.restarter instanceof ServiceRestarter) {
11421 ((ServiceRestarter)r.restarter).setService(null);
11422 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011423 }
11424
11425 ComponentName startServiceLocked(IApplicationThread caller,
11426 Intent service, String resolvedType,
11427 int callingPid, int callingUid) {
11428 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011429 if (DEBUG_SERVICE) Slog.v(TAG, "startService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011430 + " type=" + resolvedType + " args=" + service.getExtras());
11431
11432 if (caller != null) {
11433 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11434 if (callerApp == null) {
11435 throw new SecurityException(
11436 "Unable to find app for caller " + caller
11437 + " (pid=" + Binder.getCallingPid()
11438 + ") when starting service " + service);
11439 }
11440 }
11441
11442 ServiceLookupResult res =
11443 retrieveServiceLocked(service, resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011444 callingPid, callingUid, UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011445 if (res == null) {
11446 return null;
11447 }
11448 if (res.record == null) {
11449 return new ComponentName("!", res.permission != null
11450 ? res.permission : "private to package");
11451 }
11452 ServiceRecord r = res.record;
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011453 NeededUriGrants neededGrants = checkGrantUriPermissionFromIntentLocked(
11454 callingUid, r.packageName, service, service.getFlags(), null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011455 if (unscheduleServiceRestartLocked(r)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011456 if (DEBUG_SERVICE) Slog.v(TAG, "START SERVICE WHILE RESTART PENDING: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011457 }
11458 r.startRequested = true;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011459 r.callStart = false;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011460 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011461 service, neededGrants));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011462 r.lastActivity = SystemClock.uptimeMillis();
11463 synchronized (r.stats.getBatteryStats()) {
11464 r.stats.startRunningLocked();
11465 }
11466 if (!bringUpServiceLocked(r, service.getFlags(), false)) {
11467 return new ComponentName("!", "Service process is bad");
11468 }
11469 return r.name;
11470 }
11471 }
11472
11473 public ComponentName startService(IApplicationThread caller, Intent service,
11474 String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011475 enforceNotIsolatedCaller("startService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011476 // Refuse possible leaked file descriptors
11477 if (service != null && service.hasFileDescriptors() == true) {
11478 throw new IllegalArgumentException("File descriptors passed in Intent");
11479 }
11480
Amith Yamasani742a6712011-05-04 14:49:28 -070011481 if (DEBUG_SERVICE)
11482 Slog.v(TAG, "startService: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011483 synchronized(this) {
11484 final int callingPid = Binder.getCallingPid();
11485 final int callingUid = Binder.getCallingUid();
11486 final long origId = Binder.clearCallingIdentity();
11487 ComponentName res = startServiceLocked(caller, service,
11488 resolvedType, callingPid, callingUid);
11489 Binder.restoreCallingIdentity(origId);
11490 return res;
11491 }
11492 }
11493
11494 ComponentName startServiceInPackage(int uid,
11495 Intent service, String resolvedType) {
11496 synchronized(this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070011497 if (DEBUG_SERVICE)
11498 Slog.v(TAG, "startServiceInPackage: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011499 final long origId = Binder.clearCallingIdentity();
11500 ComponentName res = startServiceLocked(null, service,
11501 resolvedType, -1, uid);
11502 Binder.restoreCallingIdentity(origId);
11503 return res;
11504 }
11505 }
11506
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011507 private void stopServiceLocked(ServiceRecord service) {
11508 synchronized (service.stats.getBatteryStats()) {
11509 service.stats.stopRunningLocked();
11510 }
11511 service.startRequested = false;
11512 service.callStart = false;
11513 bringDownServiceLocked(service, false);
11514 }
11515
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011516 public int stopService(IApplicationThread caller, Intent service,
11517 String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011518 enforceNotIsolatedCaller("stopService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011519 // Refuse possible leaked file descriptors
11520 if (service != null && service.hasFileDescriptors() == true) {
11521 throw new IllegalArgumentException("File descriptors passed in Intent");
11522 }
11523
11524 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011525 if (DEBUG_SERVICE) Slog.v(TAG, "stopService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011526 + " type=" + resolvedType);
11527
11528 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11529 if (caller != null && callerApp == null) {
11530 throw new SecurityException(
11531 "Unable to find app for caller " + caller
11532 + " (pid=" + Binder.getCallingPid()
11533 + ") when stopping service " + service);
11534 }
11535
11536 // If this service is active, make sure it is stopped.
Amith Yamasani483f3b02012-03-13 16:08:00 -070011537 ServiceLookupResult r = findServiceLocked(service, resolvedType,
11538 callerApp == null ? UserId.getCallingUserId() : callerApp.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011539 if (r != null) {
11540 if (r.record != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011541 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011542 try {
11543 stopServiceLocked(r.record);
11544 } finally {
11545 Binder.restoreCallingIdentity(origId);
11546 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011547 return 1;
11548 }
11549 return -1;
11550 }
11551 }
11552
11553 return 0;
11554 }
11555
11556 public IBinder peekService(Intent service, String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011557 enforceNotIsolatedCaller("peekService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011558 // Refuse possible leaked file descriptors
11559 if (service != null && service.hasFileDescriptors() == true) {
11560 throw new IllegalArgumentException("File descriptors passed in Intent");
11561 }
11562
11563 IBinder ret = null;
11564
11565 synchronized(this) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070011566 ServiceLookupResult r = findServiceLocked(service, resolvedType,
11567 UserId.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011568
11569 if (r != null) {
11570 // r.record is null if findServiceLocked() failed the caller permission check
11571 if (r.record == null) {
11572 throw new SecurityException(
11573 "Permission Denial: Accessing service " + r.record.name
11574 + " from pid=" + Binder.getCallingPid()
11575 + ", uid=" + Binder.getCallingUid()
11576 + " requires " + r.permission);
11577 }
11578 IntentBindRecord ib = r.record.bindings.get(r.record.intent);
11579 if (ib != null) {
11580 ret = ib.binder;
11581 }
11582 }
11583 }
11584
11585 return ret;
11586 }
11587
11588 public boolean stopServiceToken(ComponentName className, IBinder token,
11589 int startId) {
11590 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011591 if (DEBUG_SERVICE) Slog.v(TAG, "stopServiceToken: " + className
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011592 + " " + token + " startId=" + startId);
11593 ServiceRecord r = findServiceLocked(className, token);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011594 if (r != null) {
11595 if (startId >= 0) {
11596 // Asked to only stop if done with all work. Note that
11597 // to avoid leaks, we will take this as dropping all
11598 // start items up to and including this one.
11599 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
11600 if (si != null) {
11601 while (r.deliveredStarts.size() > 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -070011602 ServiceRecord.StartItem cur = r.deliveredStarts.remove(0);
11603 cur.removeUriPermissionsLocked();
11604 if (cur == si) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011605 break;
11606 }
11607 }
11608 }
11609
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011610 if (r.getLastStartId() != startId) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011611 return false;
11612 }
11613
11614 if (r.deliveredStarts.size() > 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011615 Slog.w(TAG, "stopServiceToken startId " + startId
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011616 + " is last, but have " + r.deliveredStarts.size()
11617 + " remaining args");
11618 }
11619 }
11620
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011621 synchronized (r.stats.getBatteryStats()) {
11622 r.stats.stopRunningLocked();
11623 r.startRequested = false;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011624 r.callStart = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011625 }
11626 final long origId = Binder.clearCallingIdentity();
11627 bringDownServiceLocked(r, false);
11628 Binder.restoreCallingIdentity(origId);
11629 return true;
11630 }
11631 }
11632 return false;
11633 }
11634
11635 public void setServiceForeground(ComponentName className, IBinder token,
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011636 int id, Notification notification, boolean removeNotification) {
11637 final long origId = Binder.clearCallingIdentity();
11638 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011639 synchronized(this) {
11640 ServiceRecord r = findServiceLocked(className, token);
11641 if (r != null) {
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011642 if (id != 0) {
11643 if (notification == null) {
11644 throw new IllegalArgumentException("null notification");
11645 }
11646 if (r.foregroundId != id) {
11647 r.cancelNotification();
11648 r.foregroundId = id;
11649 }
11650 notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
11651 r.foregroundNoti = notification;
11652 r.isForeground = true;
11653 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011654 if (r.app != null) {
11655 updateServiceForegroundLocked(r.app, true);
11656 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011657 } else {
11658 if (r.isForeground) {
11659 r.isForeground = false;
11660 if (r.app != null) {
Dianne Hackborn8633e682010-04-22 16:03:41 -070011661 updateLruProcessLocked(r.app, false, true);
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011662 updateServiceForegroundLocked(r.app, true);
11663 }
11664 }
11665 if (removeNotification) {
11666 r.cancelNotification();
11667 r.foregroundId = 0;
11668 r.foregroundNoti = null;
11669 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011670 }
11671 }
11672 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011673 } finally {
11674 Binder.restoreCallingIdentity(origId);
11675 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011676 }
11677
11678 public void updateServiceForegroundLocked(ProcessRecord proc, boolean oomAdj) {
11679 boolean anyForeground = false;
Dianne Hackborn860755f2010-06-03 18:47:52 -070011680 for (ServiceRecord sr : proc.services) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011681 if (sr.isForeground) {
11682 anyForeground = true;
11683 break;
11684 }
11685 }
11686 if (anyForeground != proc.foregroundServices) {
11687 proc.foregroundServices = anyForeground;
11688 if (oomAdj) {
11689 updateOomAdjLocked();
11690 }
11691 }
11692 }
11693
11694 public int bindService(IApplicationThread caller, IBinder token,
11695 Intent service, String resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011696 IServiceConnection connection, int flags, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011697 enforceNotIsolatedCaller("bindService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011698 // Refuse possible leaked file descriptors
11699 if (service != null && service.hasFileDescriptors() == true) {
11700 throw new IllegalArgumentException("File descriptors passed in Intent");
11701 }
11702
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011703 checkValidCaller(Binder.getCallingUid(), userId);
11704
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011705 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011706 if (DEBUG_SERVICE) Slog.v(TAG, "bindService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011707 + " type=" + resolvedType + " conn=" + connection.asBinder()
11708 + " flags=0x" + Integer.toHexString(flags));
Amith Yamasani742a6712011-05-04 14:49:28 -070011709 if (DEBUG_MU)
11710 Slog.i(TAG_MU, "bindService uid=" + Binder.getCallingUid() + " origUid="
11711 + Binder.getOrigCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011712 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11713 if (callerApp == null) {
11714 throw new SecurityException(
11715 "Unable to find app for caller " + caller
11716 + " (pid=" + Binder.getCallingPid()
11717 + ") when binding service " + service);
11718 }
11719
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011720 ActivityRecord activity = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011721 if (token != null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070011722 activity = mMainStack.isInStackLocked(token);
11723 if (activity == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011724 Slog.w(TAG, "Binding with unknown activity: " + token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011725 return 0;
11726 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011727 }
11728
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011729 int clientLabel = 0;
11730 PendingIntent clientIntent = null;
11731
11732 if (callerApp.info.uid == Process.SYSTEM_UID) {
11733 // Hacky kind of thing -- allow system stuff to tell us
11734 // what they are, so we can report this elsewhere for
11735 // others to know why certain services are running.
11736 try {
11737 clientIntent = (PendingIntent)service.getParcelableExtra(
11738 Intent.EXTRA_CLIENT_INTENT);
11739 } catch (RuntimeException e) {
11740 }
11741 if (clientIntent != null) {
11742 clientLabel = service.getIntExtra(Intent.EXTRA_CLIENT_LABEL, 0);
11743 if (clientLabel != 0) {
11744 // There are no useful extras in the intent, trash them.
11745 // System code calling with this stuff just needs to know
11746 // this will happen.
11747 service = service.cloneFilter();
11748 }
11749 }
11750 }
11751
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011752 ServiceLookupResult res =
11753 retrieveServiceLocked(service, resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011754 Binder.getCallingPid(), Binder.getCallingUid(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011755 if (res == null) {
11756 return 0;
11757 }
11758 if (res.record == null) {
11759 return -1;
11760 }
11761 ServiceRecord s = res.record;
11762
11763 final long origId = Binder.clearCallingIdentity();
11764
11765 if (unscheduleServiceRestartLocked(s)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011766 if (DEBUG_SERVICE) Slog.v(TAG, "BIND SERVICE WHILE RESTART PENDING: "
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011767 + s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011768 }
11769
11770 AppBindRecord b = s.retrieveAppBindingLocked(service, callerApp);
11771 ConnectionRecord c = new ConnectionRecord(b, activity,
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011772 connection, flags, clientLabel, clientIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011773
11774 IBinder binder = connection.asBinder();
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011775 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
11776 if (clist == null) {
11777 clist = new ArrayList<ConnectionRecord>();
11778 s.connections.put(binder, clist);
11779 }
11780 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011781 b.connections.add(c);
11782 if (activity != null) {
11783 if (activity.connections == null) {
11784 activity.connections = new HashSet<ConnectionRecord>();
11785 }
11786 activity.connections.add(c);
11787 }
11788 b.client.connections.add(c);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070011789 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
11790 b.client.hasAboveClient = true;
11791 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011792 clist = mServiceConnections.get(binder);
11793 if (clist == null) {
11794 clist = new ArrayList<ConnectionRecord>();
11795 mServiceConnections.put(binder, clist);
11796 }
11797 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011798
11799 if ((flags&Context.BIND_AUTO_CREATE) != 0) {
11800 s.lastActivity = SystemClock.uptimeMillis();
11801 if (!bringUpServiceLocked(s, service.getFlags(), false)) {
11802 return 0;
11803 }
11804 }
11805
11806 if (s.app != null) {
11807 // This could have made the service more important.
11808 updateOomAdjLocked(s.app);
11809 }
11810
Joe Onorato8a9b2202010-02-26 18:56:32 -080011811 if (DEBUG_SERVICE) Slog.v(TAG, "Bind " + s + " with " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011812 + ": received=" + b.intent.received
11813 + " apps=" + b.intent.apps.size()
11814 + " doRebind=" + b.intent.doRebind);
11815
11816 if (s.app != null && b.intent.received) {
11817 // Service is already running, so we can immediately
11818 // publish the connection.
11819 try {
11820 c.conn.connected(s.name, b.intent.binder);
11821 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011822 Slog.w(TAG, "Failure sending service " + s.shortName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011823 + " to connection " + c.conn.asBinder()
11824 + " (in " + c.binding.client.processName + ")", e);
11825 }
11826
11827 // If this is the first app connected back to this binding,
11828 // and the service had previously asked to be told when
11829 // rebound, then do so.
11830 if (b.intent.apps.size() == 1 && b.intent.doRebind) {
11831 requestServiceBindingLocked(s, b.intent, true);
11832 }
11833 } else if (!b.intent.requested) {
11834 requestServiceBindingLocked(s, b.intent, false);
11835 }
11836
11837 Binder.restoreCallingIdentity(origId);
11838 }
11839
11840 return 1;
11841 }
11842
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070011843 void removeConnectionLocked(
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011844 ConnectionRecord c, ProcessRecord skipApp, ActivityRecord skipAct) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011845 IBinder binder = c.conn.asBinder();
11846 AppBindRecord b = c.binding;
11847 ServiceRecord s = b.service;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011848 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
11849 if (clist != null) {
11850 clist.remove(c);
11851 if (clist.size() == 0) {
11852 s.connections.remove(binder);
11853 }
11854 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011855 b.connections.remove(c);
11856 if (c.activity != null && c.activity != skipAct) {
11857 if (c.activity.connections != null) {
11858 c.activity.connections.remove(c);
11859 }
11860 }
11861 if (b.client != skipApp) {
11862 b.client.connections.remove(c);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070011863 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
11864 b.client.updateHasAboveClientLocked();
11865 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011866 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011867 clist = mServiceConnections.get(binder);
11868 if (clist != null) {
11869 clist.remove(c);
11870 if (clist.size() == 0) {
11871 mServiceConnections.remove(binder);
11872 }
11873 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011874
11875 if (b.connections.size() == 0) {
11876 b.intent.apps.remove(b.client);
11877 }
11878
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011879 if (!c.serviceDead) {
11880 if (DEBUG_SERVICE) Slog.v(TAG, "Disconnecting binding " + b.intent
11881 + ": shouldUnbind=" + b.intent.hasBound);
11882 if (s.app != null && s.app.thread != null && b.intent.apps.size() == 0
11883 && b.intent.hasBound) {
11884 try {
11885 bumpServiceExecutingLocked(s, "unbind");
11886 updateOomAdjLocked(s.app);
11887 b.intent.hasBound = false;
11888 // Assume the client doesn't want to know about a rebind;
11889 // we will deal with that later if it asks for one.
11890 b.intent.doRebind = false;
11891 s.app.thread.scheduleUnbindService(s, b.intent.intent.getIntent());
11892 } catch (Exception e) {
11893 Slog.w(TAG, "Exception when unbinding service " + s.shortName, e);
11894 serviceDoneExecutingLocked(s, true);
11895 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011896 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011897
11898 if ((c.flags&Context.BIND_AUTO_CREATE) != 0) {
11899 bringDownServiceLocked(s, false);
11900 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011901 }
11902 }
11903
11904 public boolean unbindService(IServiceConnection connection) {
11905 synchronized (this) {
11906 IBinder binder = connection.asBinder();
Joe Onorato8a9b2202010-02-26 18:56:32 -080011907 if (DEBUG_SERVICE) Slog.v(TAG, "unbindService: conn=" + binder);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011908 ArrayList<ConnectionRecord> clist = mServiceConnections.get(binder);
11909 if (clist == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011910 Slog.w(TAG, "Unbind failed: could not find connection for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011911 + connection.asBinder());
11912 return false;
11913 }
11914
11915 final long origId = Binder.clearCallingIdentity();
11916
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011917 while (clist.size() > 0) {
11918 ConnectionRecord r = clist.get(0);
11919 removeConnectionLocked(r, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011920
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011921 if (r.binding.service.app != null) {
11922 // This could have made the service less important.
11923 updateOomAdjLocked(r.binding.service.app);
11924 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011925 }
11926
11927 Binder.restoreCallingIdentity(origId);
11928 }
11929
11930 return true;
11931 }
11932
11933 public void publishService(IBinder token, Intent intent, IBinder service) {
11934 // Refuse possible leaked file descriptors
11935 if (intent != null && intent.hasFileDescriptors() == true) {
11936 throw new IllegalArgumentException("File descriptors passed in Intent");
11937 }
11938
11939 synchronized(this) {
11940 if (!(token instanceof ServiceRecord)) {
11941 throw new IllegalArgumentException("Invalid service token");
11942 }
11943 ServiceRecord r = (ServiceRecord)token;
11944
11945 final long origId = Binder.clearCallingIdentity();
11946
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011947 if (DEBUG_SERVICE) Slog.v(TAG, "PUBLISHING " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011948 + " " + intent + ": " + service);
11949 if (r != null) {
11950 Intent.FilterComparison filter
11951 = new Intent.FilterComparison(intent);
11952 IntentBindRecord b = r.bindings.get(filter);
11953 if (b != null && !b.received) {
11954 b.binder = service;
11955 b.requested = true;
11956 b.received = true;
11957 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011958 Iterator<ArrayList<ConnectionRecord>> it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011959 = r.connections.values().iterator();
11960 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011961 ArrayList<ConnectionRecord> clist = it.next();
11962 for (int i=0; i<clist.size(); i++) {
11963 ConnectionRecord c = clist.get(i);
11964 if (!filter.equals(c.binding.intent.intent)) {
11965 if (DEBUG_SERVICE) Slog.v(
11966 TAG, "Not publishing to: " + c);
11967 if (DEBUG_SERVICE) Slog.v(
11968 TAG, "Bound intent: " + c.binding.intent.intent);
11969 if (DEBUG_SERVICE) Slog.v(
11970 TAG, "Published intent: " + intent);
11971 continue;
11972 }
11973 if (DEBUG_SERVICE) Slog.v(TAG, "Publishing to: " + c);
11974 try {
11975 c.conn.connected(r.name, service);
11976 } catch (Exception e) {
11977 Slog.w(TAG, "Failure sending service " + r.name +
11978 " to connection " + c.conn.asBinder() +
11979 " (in " + c.binding.client.processName + ")", e);
11980 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011981 }
11982 }
11983 }
11984 }
11985
11986 serviceDoneExecutingLocked(r, mStoppingServices.contains(r));
11987
11988 Binder.restoreCallingIdentity(origId);
11989 }
11990 }
11991 }
11992
11993 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
11994 // Refuse possible leaked file descriptors
11995 if (intent != null && intent.hasFileDescriptors() == true) {
11996 throw new IllegalArgumentException("File descriptors passed in Intent");
11997 }
11998
11999 synchronized(this) {
12000 if (!(token instanceof ServiceRecord)) {
12001 throw new IllegalArgumentException("Invalid service token");
12002 }
12003 ServiceRecord r = (ServiceRecord)token;
12004
12005 final long origId = Binder.clearCallingIdentity();
12006
12007 if (r != null) {
12008 Intent.FilterComparison filter
12009 = new Intent.FilterComparison(intent);
12010 IntentBindRecord b = r.bindings.get(filter);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012011 if (DEBUG_SERVICE) Slog.v(TAG, "unbindFinished in " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012012 + " at " + b + ": apps="
12013 + (b != null ? b.apps.size() : 0));
Per Edelberg78f9fff2010-08-30 20:01:35 +020012014
12015 boolean inStopping = mStoppingServices.contains(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012016 if (b != null) {
Per Edelberg78f9fff2010-08-30 20:01:35 +020012017 if (b.apps.size() > 0 && !inStopping) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012018 // Applications have already bound since the last
12019 // unbind, so just rebind right here.
12020 requestServiceBindingLocked(r, b, true);
12021 } else {
12022 // Note to tell the service the next time there is
12023 // a new client.
12024 b.doRebind = true;
12025 }
12026 }
12027
Per Edelberg78f9fff2010-08-30 20:01:35 +020012028 serviceDoneExecutingLocked(r, inStopping);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012029
12030 Binder.restoreCallingIdentity(origId);
12031 }
12032 }
12033 }
12034
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012035 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012036 synchronized(this) {
12037 if (!(token instanceof ServiceRecord)) {
12038 throw new IllegalArgumentException("Invalid service token");
12039 }
12040 ServiceRecord r = (ServiceRecord)token;
12041 boolean inStopping = mStoppingServices.contains(token);
12042 if (r != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012043 if (r != token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012044 Slog.w(TAG, "Done executing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012045 + " with incorrect token: given " + token
12046 + ", expected " + r);
12047 return;
12048 }
12049
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012050 if (type == 1) {
12051 // This is a call from a service start... take care of
12052 // book-keeping.
12053 r.callStart = true;
12054 switch (res) {
12055 case Service.START_STICKY_COMPATIBILITY:
12056 case Service.START_STICKY: {
12057 // We are done with the associated start arguments.
12058 r.findDeliveredStart(startId, true);
12059 // Don't stop if killed.
12060 r.stopIfKilled = false;
12061 break;
12062 }
12063 case Service.START_NOT_STICKY: {
12064 // We are done with the associated start arguments.
12065 r.findDeliveredStart(startId, true);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070012066 if (r.getLastStartId() == startId) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012067 // There is no more work, and this service
12068 // doesn't want to hang around if killed.
12069 r.stopIfKilled = true;
12070 }
12071 break;
12072 }
12073 case Service.START_REDELIVER_INTENT: {
12074 // We'll keep this item until they explicitly
12075 // call stop for it, but keep track of the fact
12076 // that it was delivered.
12077 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
12078 if (si != null) {
12079 si.deliveryCount = 0;
12080 si.doneExecutingCount++;
12081 // Don't stop if killed.
12082 r.stopIfKilled = true;
12083 }
12084 break;
12085 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070012086 case Service.START_TASK_REMOVED_COMPLETE: {
12087 // Special processing for onTaskRemoved(). Don't
12088 // impact normal onStartCommand() processing.
12089 r.findDeliveredStart(startId, true);
12090 break;
12091 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012092 default:
12093 throw new IllegalArgumentException(
12094 "Unknown service start result: " + res);
12095 }
12096 if (res == Service.START_STICKY_COMPATIBILITY) {
12097 r.callStart = false;
12098 }
12099 }
Amith Yamasani742a6712011-05-04 14:49:28 -070012100 if (DEBUG_MU)
12101 Slog.v(TAG_MU, "before serviceDontExecutingLocked, uid="
12102 + Binder.getOrigCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012103 final long origId = Binder.clearCallingIdentity();
12104 serviceDoneExecutingLocked(r, inStopping);
12105 Binder.restoreCallingIdentity(origId);
12106 } else {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012107 Slog.w(TAG, "Done executing unknown service from pid "
12108 + Binder.getCallingPid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012109 }
12110 }
12111 }
12112
12113 public void serviceDoneExecutingLocked(ServiceRecord r, boolean inStopping) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012114 if (DEBUG_SERVICE) Slog.v(TAG, "<<< DONE EXECUTING " + r
12115 + ": nesting=" + r.executeNesting
12116 + ", inStopping=" + inStopping + ", app=" + r.app);
Dianne Hackborn287952c2010-09-22 22:34:31 -070012117 else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG, "<<< DONE EXECUTING " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012118 r.executeNesting--;
12119 if (r.executeNesting <= 0 && r.app != null) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012120 if (DEBUG_SERVICE) Slog.v(TAG,
12121 "Nesting at 0 of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012122 r.app.executingServices.remove(r);
12123 if (r.app.executingServices.size() == 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012124 if (DEBUG_SERVICE || DEBUG_SERVICE_EXECUTING) Slog.v(TAG,
12125 "No more executingServices of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012126 mHandler.removeMessages(SERVICE_TIMEOUT_MSG, r.app);
12127 }
12128 if (inStopping) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012129 if (DEBUG_SERVICE) Slog.v(TAG,
12130 "doneExecuting remove stopping " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012131 mStoppingServices.remove(r);
Mattias Petersson3996b412010-10-27 09:32:51 +020012132 r.bindings.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012133 }
12134 updateOomAdjLocked(r.app);
12135 }
12136 }
12137
12138 void serviceTimeout(ProcessRecord proc) {
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012139 String anrMessage = null;
12140
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012141 synchronized(this) {
12142 if (proc.executingServices.size() == 0 || proc.thread == null) {
12143 return;
12144 }
12145 long maxTime = SystemClock.uptimeMillis() - SERVICE_TIMEOUT;
12146 Iterator<ServiceRecord> it = proc.executingServices.iterator();
12147 ServiceRecord timeout = null;
12148 long nextTime = 0;
12149 while (it.hasNext()) {
12150 ServiceRecord sr = it.next();
12151 if (sr.executingStart < maxTime) {
12152 timeout = sr;
12153 break;
12154 }
12155 if (sr.executingStart > nextTime) {
12156 nextTime = sr.executingStart;
12157 }
12158 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012159 if (timeout != null && mLruProcesses.contains(proc)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012160 Slog.w(TAG, "Timeout executing service: " + timeout);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012161 anrMessage = "Executing service " + timeout.shortName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012162 } else {
12163 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
12164 msg.obj = proc;
12165 mHandler.sendMessageAtTime(msg, nextTime+SERVICE_TIMEOUT);
12166 }
12167 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012168
12169 if (anrMessage != null) {
12170 appNotResponding(proc, null, null, anrMessage);
12171 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012172 }
12173
12174 // =========================================================
Christopher Tate181fafa2009-05-14 11:12:14 -070012175 // BACKUP AND RESTORE
12176 // =========================================================
12177
12178 // Cause the target app to be launched if necessary and its backup agent
12179 // instantiated. The backup agent will invoke backupAgentCreated() on the
12180 // activity manager to announce its creation.
12181 public boolean bindBackupAgent(ApplicationInfo app, int backupMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012182 if (DEBUG_BACKUP) Slog.v(TAG, "startBackupAgent: app=" + app + " mode=" + backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070012183 enforceCallingPermission("android.permission.BACKUP", "startBackupAgent");
12184
12185 synchronized(this) {
12186 // !!! TODO: currently no check here that we're already bound
12187 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
12188 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
12189 synchronized (stats) {
12190 ss = stats.getServiceStatsLocked(app.uid, app.packageName, app.name);
12191 }
12192
Dianne Hackborne7f97212011-02-24 14:40:20 -080012193 // Backup agent is now in use, its package can't be stopped.
12194 try {
12195 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -070012196 app.packageName, false, UserId.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -080012197 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080012198 } catch (IllegalArgumentException e) {
12199 Slog.w(TAG, "Failed trying to unstop package "
12200 + app.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080012201 }
12202
Christopher Tate181fafa2009-05-14 11:12:14 -070012203 BackupRecord r = new BackupRecord(ss, app, backupMode);
Christopher Tate4a627c72011-04-01 14:43:32 -070012204 ComponentName hostingName = (backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL)
12205 ? new ComponentName(app.packageName, app.backupAgentName)
12206 : new ComponentName("android", "FullBackupAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -070012207 // startProcessLocked() returns existing proc's record if it's already running
12208 ProcessRecord proc = startProcessLocked(app.processName, app,
Dianne Hackborna0c283e2012-02-09 10:47:01 -080012209 false, 0, "backup", hostingName, false, false);
Christopher Tate181fafa2009-05-14 11:12:14 -070012210 if (proc == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012211 Slog.e(TAG, "Unable to start backup agent process " + r);
Christopher Tate181fafa2009-05-14 11:12:14 -070012212 return false;
12213 }
12214
12215 r.app = proc;
12216 mBackupTarget = r;
12217 mBackupAppName = app.packageName;
12218
Christopher Tate6fa95972009-06-05 18:43:55 -070012219 // Try not to kill the process during backup
12220 updateOomAdjLocked(proc);
12221
Christopher Tate181fafa2009-05-14 11:12:14 -070012222 // If the process is already attached, schedule the creation of the backup agent now.
12223 // If it is not yet live, this will be done when it attaches to the framework.
12224 if (proc.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012225 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc already running: " + proc);
Christopher Tate181fafa2009-05-14 11:12:14 -070012226 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040012227 proc.thread.scheduleCreateBackupAgent(app,
12228 compatibilityInfoForPackageLocked(app), backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070012229 } catch (RemoteException e) {
Christopher Tate436344a2009-09-30 16:17:37 -070012230 // Will time out on the backup manager side
Christopher Tate181fafa2009-05-14 11:12:14 -070012231 }
12232 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012233 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc not running, waiting for attach");
Christopher Tate181fafa2009-05-14 11:12:14 -070012234 }
12235 // Invariants: at this point, the target app process exists and the application
12236 // is either already running or in the process of coming up. mBackupTarget and
12237 // mBackupAppName describe the app, so that when it binds back to the AM we
12238 // know that it's scheduled for a backup-agent operation.
12239 }
12240
12241 return true;
12242 }
12243
12244 // A backup agent has just come up
12245 public void backupAgentCreated(String agentPackageName, IBinder agent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012246 if (DEBUG_BACKUP) Slog.v(TAG, "backupAgentCreated: " + agentPackageName
Christopher Tate181fafa2009-05-14 11:12:14 -070012247 + " = " + agent);
12248
12249 synchronized(this) {
12250 if (!agentPackageName.equals(mBackupAppName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012251 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
Christopher Tate181fafa2009-05-14 11:12:14 -070012252 return;
12253 }
Dianne Hackborn06740692010-09-22 22:46:21 -070012254 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012255
Dianne Hackborn06740692010-09-22 22:46:21 -070012256 long oldIdent = Binder.clearCallingIdentity();
12257 try {
12258 IBackupManager bm = IBackupManager.Stub.asInterface(
12259 ServiceManager.getService(Context.BACKUP_SERVICE));
12260 bm.agentConnected(agentPackageName, agent);
12261 } catch (RemoteException e) {
12262 // can't happen; the backup manager service is local
12263 } catch (Exception e) {
12264 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: ");
12265 e.printStackTrace();
12266 } finally {
12267 Binder.restoreCallingIdentity(oldIdent);
Christopher Tate181fafa2009-05-14 11:12:14 -070012268 }
12269 }
12270
12271 // done with this agent
12272 public void unbindBackupAgent(ApplicationInfo appInfo) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012273 if (DEBUG_BACKUP) Slog.v(TAG, "unbindBackupAgent: " + appInfo);
Christopher Tate8a27f922009-06-26 11:49:18 -070012274 if (appInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012275 Slog.w(TAG, "unbind backup agent for null app");
Christopher Tate8a27f922009-06-26 11:49:18 -070012276 return;
12277 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012278
12279 synchronized(this) {
Christopher Tate8a27f922009-06-26 11:49:18 -070012280 if (mBackupAppName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012281 Slog.w(TAG, "Unbinding backup agent with no active backup");
Christopher Tate8a27f922009-06-26 11:49:18 -070012282 return;
12283 }
12284
Christopher Tate181fafa2009-05-14 11:12:14 -070012285 if (!mBackupAppName.equals(appInfo.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012286 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
Christopher Tate181fafa2009-05-14 11:12:14 -070012287 return;
12288 }
12289
Christopher Tate6fa95972009-06-05 18:43:55 -070012290 ProcessRecord proc = mBackupTarget.app;
12291 mBackupTarget = null;
12292 mBackupAppName = null;
12293
12294 // Not backing this app up any more; reset its OOM adjustment
12295 updateOomAdjLocked(proc);
12296
Christopher Tatec7b31e32009-06-10 15:49:30 -070012297 // If the app crashed during backup, 'thread' will be null here
12298 if (proc.thread != null) {
12299 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040012300 proc.thread.scheduleDestroyBackupAgent(appInfo,
12301 compatibilityInfoForPackageLocked(appInfo));
Christopher Tatec7b31e32009-06-10 15:49:30 -070012302 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012303 Slog.e(TAG, "Exception when unbinding backup agent:");
Christopher Tatec7b31e32009-06-10 15:49:30 -070012304 e.printStackTrace();
12305 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012306 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012307 }
12308 }
12309 // =========================================================
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012310 // BROADCASTS
12311 // =========================================================
12312
Josh Bartel7f208742010-02-25 11:01:44 -060012313 private final List getStickiesLocked(String action, IntentFilter filter,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012314 List cur) {
12315 final ContentResolver resolver = mContext.getContentResolver();
12316 final ArrayList<Intent> list = mStickyBroadcasts.get(action);
12317 if (list == null) {
12318 return cur;
12319 }
12320 int N = list.size();
12321 for (int i=0; i<N; i++) {
12322 Intent intent = list.get(i);
12323 if (filter.match(resolver, intent, true, TAG) >= 0) {
12324 if (cur == null) {
12325 cur = new ArrayList<Intent>();
12326 }
12327 cur.add(intent);
12328 }
12329 }
12330 return cur;
12331 }
12332
Christopher Tatef46723b2012-01-26 14:19:24 -080012333 boolean isPendingBroadcastProcessLocked(int pid) {
12334 return mFgBroadcastQueue.isPendingBroadcastProcessLocked(pid)
12335 || mBgBroadcastQueue.isPendingBroadcastProcessLocked(pid);
12336 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012337
Christopher Tatef46723b2012-01-26 14:19:24 -080012338 void skipPendingBroadcastLocked(int pid) {
12339 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
12340 for (BroadcastQueue queue : mBroadcastQueues) {
12341 queue.skipPendingBroadcastLocked(pid);
12342 }
12343 }
12344
12345 // The app just attached; send any pending broadcasts that it should receive
12346 boolean sendPendingBroadcastsLocked(ProcessRecord app) {
12347 boolean didSomething = false;
12348 for (BroadcastQueue queue : mBroadcastQueues) {
12349 didSomething |= queue.sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012350 }
Christopher Tatef46723b2012-01-26 14:19:24 -080012351 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012352 }
12353
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012354 public Intent registerReceiver(IApplicationThread caller, String callerPackage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012355 IIntentReceiver receiver, IntentFilter filter, String permission) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012356 enforceNotIsolatedCaller("registerReceiver");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012357 synchronized(this) {
12358 ProcessRecord callerApp = null;
12359 if (caller != null) {
12360 callerApp = getRecordForAppLocked(caller);
12361 if (callerApp == null) {
12362 throw new SecurityException(
12363 "Unable to find app for caller " + caller
12364 + " (pid=" + Binder.getCallingPid()
12365 + ") when registering receiver " + receiver);
12366 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012367 if (callerApp.info.uid != Process.SYSTEM_UID &&
12368 !callerApp.pkgList.contains(callerPackage)) {
12369 throw new SecurityException("Given caller package " + callerPackage
12370 + " is not running in process " + callerApp);
12371 }
12372 } else {
12373 callerPackage = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012374 }
12375
12376 List allSticky = null;
12377
12378 // Look for any matching sticky broadcasts...
12379 Iterator actions = filter.actionsIterator();
12380 if (actions != null) {
12381 while (actions.hasNext()) {
12382 String action = (String)actions.next();
Josh Bartel7f208742010-02-25 11:01:44 -060012383 allSticky = getStickiesLocked(action, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012384 }
12385 } else {
Josh Bartel7f208742010-02-25 11:01:44 -060012386 allSticky = getStickiesLocked(null, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012387 }
12388
12389 // The first sticky in the list is returned directly back to
12390 // the client.
12391 Intent sticky = allSticky != null ? (Intent)allSticky.get(0) : null;
12392
Joe Onorato8a9b2202010-02-26 18:56:32 -080012393 if (DEBUG_BROADCAST) Slog.v(TAG, "Register receiver " + filter
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012394 + ": " + sticky);
12395
12396 if (receiver == null) {
12397 return sticky;
12398 }
12399
12400 ReceiverList rl
12401 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
12402 if (rl == null) {
12403 rl = new ReceiverList(this, callerApp,
12404 Binder.getCallingPid(),
12405 Binder.getCallingUid(), receiver);
12406 if (rl.app != null) {
12407 rl.app.receivers.add(rl);
12408 } else {
12409 try {
12410 receiver.asBinder().linkToDeath(rl, 0);
12411 } catch (RemoteException e) {
12412 return sticky;
12413 }
12414 rl.linkedToDeath = true;
12415 }
12416 mRegisteredReceivers.put(receiver.asBinder(), rl);
12417 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012418 BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage, permission);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012419 rl.add(bf);
12420 if (!bf.debugCheck()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012421 Slog.w(TAG, "==> For Dynamic broadast");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012422 }
12423 mReceiverResolver.addFilter(bf);
12424
12425 // Enqueue broadcasts for all existing stickies that match
12426 // this filter.
12427 if (allSticky != null) {
12428 ArrayList receivers = new ArrayList();
12429 receivers.add(bf);
12430
12431 int N = allSticky.size();
12432 for (int i=0; i<N; i++) {
12433 Intent intent = (Intent)allSticky.get(i);
Christopher Tatef46723b2012-01-26 14:19:24 -080012434 BroadcastQueue queue = broadcastQueueForIntent(intent);
12435 BroadcastRecord r = new BroadcastRecord(queue, intent, null,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012436 null, -1, -1, null, receivers, null, 0, null, null,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012437 false, true, true);
Christopher Tatef46723b2012-01-26 14:19:24 -080012438 queue.enqueueParallelBroadcastLocked(r);
12439 queue.scheduleBroadcastsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012440 }
12441 }
12442
12443 return sticky;
12444 }
12445 }
12446
12447 public void unregisterReceiver(IIntentReceiver receiver) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012448 if (DEBUG_BROADCAST) Slog.v(TAG, "Unregister receiver: " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012449
Christopher Tatef46723b2012-01-26 14:19:24 -080012450 final long origId = Binder.clearCallingIdentity();
12451 try {
12452 boolean doTrim = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012453
Christopher Tatef46723b2012-01-26 14:19:24 -080012454 synchronized(this) {
12455 ReceiverList rl
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012456 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
Christopher Tatef46723b2012-01-26 14:19:24 -080012457 if (rl != null) {
12458 if (rl.curBroadcast != null) {
12459 BroadcastRecord r = rl.curBroadcast;
12460 final boolean doNext = finishReceiverLocked(
12461 receiver.asBinder(), r.resultCode, r.resultData,
12462 r.resultExtras, r.resultAbort, true);
12463 if (doNext) {
12464 doTrim = true;
12465 r.queue.processNextBroadcast(false);
12466 }
12467 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012468
Christopher Tatef46723b2012-01-26 14:19:24 -080012469 if (rl.app != null) {
12470 rl.app.receivers.remove(rl);
12471 }
12472 removeReceiverLocked(rl);
12473 if (rl.linkedToDeath) {
12474 rl.linkedToDeath = false;
12475 rl.receiver.asBinder().unlinkToDeath(rl, 0);
12476 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012477 }
12478 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012479
Christopher Tatef46723b2012-01-26 14:19:24 -080012480 // If we actually concluded any broadcasts, we might now be able
12481 // to trim the recipients' apps from our working set
12482 if (doTrim) {
12483 trimApplications();
12484 return;
12485 }
12486
12487 } finally {
12488 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012489 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012490 }
12491
12492 void removeReceiverLocked(ReceiverList rl) {
12493 mRegisteredReceivers.remove(rl.receiver.asBinder());
12494 int N = rl.size();
12495 for (int i=0; i<N; i++) {
12496 mReceiverResolver.removeFilter(rl.get(i));
12497 }
12498 }
12499
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012500 private final void sendPackageBroadcastLocked(int cmd, String[] packages) {
12501 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
12502 ProcessRecord r = mLruProcesses.get(i);
12503 if (r.thread != null) {
12504 try {
12505 r.thread.dispatchPackageBroadcast(cmd, packages);
12506 } catch (RemoteException ex) {
12507 }
12508 }
12509 }
12510 }
12511
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012512 private final int broadcastIntentLocked(ProcessRecord callerApp,
12513 String callerPackage, Intent intent, String resolvedType,
12514 IIntentReceiver resultTo, int resultCode, String resultData,
12515 Bundle map, String requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070012516 boolean ordered, boolean sticky, int callingPid, int callingUid,
12517 int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012518 intent = new Intent(intent);
12519
Dianne Hackborne7f97212011-02-24 14:40:20 -080012520 // By default broadcasts do not go to stopped apps.
12521 intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
12522
Joe Onorato8a9b2202010-02-26 18:56:32 -080012523 if (DEBUG_BROADCAST_LIGHT) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012524 TAG, (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
Amith Yamasani13593602012-03-22 16:16:17 -070012525 + " ordered=" + ordered + " userid=" + userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012526 if ((resultTo != null) && !ordered) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012527 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012528 }
12529
12530 // Handle special intents: if this broadcast is from the package
12531 // manager about a package being removed, we need to remove all of
12532 // its activities from the history stack.
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012533 final boolean uidRemoved = Intent.ACTION_UID_REMOVED.equals(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012534 intent.getAction());
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012535 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())
12536 || Intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction())
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080012537 || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012538 || uidRemoved) {
12539 if (checkComponentPermission(
12540 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080012541 callingPid, callingUid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012542 == PackageManager.PERMISSION_GRANTED) {
12543 if (uidRemoved) {
12544 final Bundle intentExtras = intent.getExtras();
12545 final int uid = intentExtras != null
12546 ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
12547 if (uid >= 0) {
12548 BatteryStatsImpl bs = mBatteryStatsService.getActiveStatistics();
12549 synchronized (bs) {
12550 bs.removeUidStatsLocked(uid);
12551 }
12552 }
12553 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012554 // If resources are unvailble just force stop all
12555 // those packages and flush the attribute cache as well.
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080012556 if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012557 String list[] = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
12558 if (list != null && (list.length > 0)) {
12559 for (String pkg : list) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070012560 forceStopPackageLocked(pkg, -1, false, true, true, false, userId);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012561 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012562 sendPackageBroadcastLocked(
12563 IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE, list);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012564 }
12565 } else {
12566 Uri data = intent.getData();
12567 String ssp;
12568 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
12569 if (!intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false)) {
12570 forceStopPackageLocked(ssp,
Amith Yamasani483f3b02012-03-13 16:08:00 -070012571 intent.getIntExtra(Intent.EXTRA_UID, -1), false, true, true,
12572 false, userId);
Dianne Hackbornde7faf62009-06-30 13:27:30 -070012573 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012574 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012575 sendPackageBroadcastLocked(IApplicationThread.PACKAGE_REMOVED,
12576 new String[] {ssp});
12577 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012578 }
12579 }
12580 }
12581 } else {
12582 String msg = "Permission Denial: " + intent.getAction()
12583 + " broadcast from " + callerPackage + " (pid=" + callingPid
12584 + ", uid=" + callingUid + ")"
12585 + " requires "
12586 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012587 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012588 throw new SecurityException(msg);
12589 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012590
12591 // Special case for adding a package: by default turn on compatibility
12592 // mode.
12593 } else if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -070012594 Uri data = intent.getData();
12595 String ssp;
12596 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
12597 mCompatModePackages.handlePackageAddedLocked(ssp,
12598 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false));
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012599 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012600 }
12601
12602 /*
12603 * If this is the time zone changed action, queue up a message that will reset the timezone
12604 * of all currently running processes. This message will get queued up before the broadcast
12605 * happens.
12606 */
12607 if (intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) {
12608 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
12609 }
12610
Robert Greenwalt03595d02010-11-02 14:08:23 -070012611 if (intent.ACTION_CLEAR_DNS_CACHE.equals(intent.getAction())) {
12612 mHandler.sendEmptyMessage(CLEAR_DNS_CACHE);
12613 }
12614
Robert Greenwalt434203a2010-10-11 16:00:27 -070012615 if (Proxy.PROXY_CHANGE_ACTION.equals(intent.getAction())) {
12616 ProxyProperties proxy = intent.getParcelableExtra("proxy");
12617 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY, proxy));
12618 }
12619
Dianne Hackborn854060af2009-07-09 18:14:31 -070012620 /*
12621 * Prevent non-system code (defined here to be non-persistent
12622 * processes) from sending protected broadcasts.
12623 */
12624 if (callingUid == Process.SYSTEM_UID || callingUid == Process.PHONE_UID
12625 || callingUid == Process.SHELL_UID || callingUid == 0) {
12626 // Always okay.
12627 } else if (callerApp == null || !callerApp.persistent) {
12628 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012629 if (AppGlobals.getPackageManager().isProtectedBroadcast(
Dianne Hackborn854060af2009-07-09 18:14:31 -070012630 intent.getAction())) {
12631 String msg = "Permission Denial: not allowed to send broadcast "
12632 + intent.getAction() + " from pid="
12633 + callingPid + ", uid=" + callingUid;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012634 Slog.w(TAG, msg);
Dianne Hackborn854060af2009-07-09 18:14:31 -070012635 throw new SecurityException(msg);
12636 }
12637 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012638 Slog.w(TAG, "Remote exception", e);
Dianne Hackborna4972e92012-03-14 10:38:05 -070012639 return ActivityManager.BROADCAST_SUCCESS;
Dianne Hackborn854060af2009-07-09 18:14:31 -070012640 }
12641 }
12642
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012643 // Add to the sticky list if requested.
12644 if (sticky) {
12645 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
12646 callingPid, callingUid)
12647 != PackageManager.PERMISSION_GRANTED) {
12648 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
12649 + callingPid + ", uid=" + callingUid
12650 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012651 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012652 throw new SecurityException(msg);
12653 }
12654 if (requiredPermission != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012655 Slog.w(TAG, "Can't broadcast sticky intent " + intent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012656 + " and enforce permission " + requiredPermission);
Dianne Hackborna4972e92012-03-14 10:38:05 -070012657 return ActivityManager.BROADCAST_STICKY_CANT_HAVE_PERMISSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012658 }
12659 if (intent.getComponent() != null) {
12660 throw new SecurityException(
12661 "Sticky broadcasts can't target a specific component");
12662 }
12663 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
12664 if (list == null) {
12665 list = new ArrayList<Intent>();
12666 mStickyBroadcasts.put(intent.getAction(), list);
12667 }
12668 int N = list.size();
12669 int i;
12670 for (i=0; i<N; i++) {
12671 if (intent.filterEquals(list.get(i))) {
12672 // This sticky already exists, replace it.
12673 list.set(i, new Intent(intent));
12674 break;
12675 }
12676 }
12677 if (i >= N) {
12678 list.add(new Intent(intent));
12679 }
12680 }
12681
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012682 // Figure out who all will receive this broadcast.
12683 List receivers = null;
12684 List<BroadcastFilter> registeredReceivers = null;
12685 try {
12686 if (intent.getComponent() != null) {
12687 // Broadcast is going to one specific receiver class...
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012688 ActivityInfo ai = AppGlobals.getPackageManager().
Amith Yamasani483f3b02012-03-13 16:08:00 -070012689 getReceiverInfo(intent.getComponent(), STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012690 if (ai != null) {
12691 receivers = new ArrayList();
12692 ResolveInfo ri = new ResolveInfo();
Amith Yamasani742a6712011-05-04 14:49:28 -070012693 ri.activityInfo = getActivityInfoForUser(ai, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012694 receivers.add(ri);
12695 }
12696 } else {
12697 // Need to resolve the intent to interested receivers...
12698 if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
12699 == 0) {
12700 receivers =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012701 AppGlobals.getPackageManager().queryIntentReceivers(
Amith Yamasani483f3b02012-03-13 16:08:00 -070012702 intent, resolvedType, STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012703 }
Amith Yamasani483f3b02012-03-13 16:08:00 -070012704 registeredReceivers = mReceiverResolver.queryIntent(intent, resolvedType, false,
12705 userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012706 }
12707 } catch (RemoteException ex) {
12708 // pm is in same process, this will never happen.
12709 }
12710
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012711 final boolean replacePending =
12712 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
12713
Joe Onorato8a9b2202010-02-26 18:56:32 -080012714 if (DEBUG_BROADCAST) Slog.v(TAG, "Enqueing broadcast: " + intent.getAction()
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012715 + " replacePending=" + replacePending);
12716
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012717 int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
12718 if (!ordered && NR > 0) {
12719 // If we are not serializing this broadcast, then send the
12720 // registered receivers separately so they don't wait for the
12721 // components to be launched.
Christopher Tatef46723b2012-01-26 14:19:24 -080012722 final BroadcastQueue queue = broadcastQueueForIntent(intent);
12723 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012724 callerPackage, callingPid, callingUid, requiredPermission,
12725 registeredReceivers, resultTo, resultCode, resultData, map,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012726 ordered, sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012727 if (DEBUG_BROADCAST) Slog.v(
Christopher Tatef46723b2012-01-26 14:19:24 -080012728 TAG, "Enqueueing parallel broadcast " + r);
12729 final boolean replaced = replacePending && queue.replaceParallelBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012730 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012731 queue.enqueueParallelBroadcastLocked(r);
12732 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012733 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012734 registeredReceivers = null;
12735 NR = 0;
12736 }
12737
12738 // Merge into one list.
12739 int ir = 0;
12740 if (receivers != null) {
12741 // A special case for PACKAGE_ADDED: do not allow the package
12742 // being added to see this broadcast. This prevents them from
12743 // using this as a back door to get run as soon as they are
12744 // installed. Maybe in the future we want to have a special install
12745 // broadcast or such for apps, but we'd like to deliberately make
12746 // this decision.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012747 String skipPackages[] = null;
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012748 if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
12749 || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
12750 || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012751 Uri data = intent.getData();
12752 if (data != null) {
12753 String pkgName = data.getSchemeSpecificPart();
12754 if (pkgName != null) {
12755 skipPackages = new String[] { pkgName };
12756 }
12757 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012758 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012759 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
The Android Open Source Project10592532009-03-18 17:39:46 -070012760 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012761 if (skipPackages != null && (skipPackages.length > 0)) {
12762 for (String skipPackage : skipPackages) {
12763 if (skipPackage != null) {
12764 int NT = receivers.size();
12765 for (int it=0; it<NT; it++) {
12766 ResolveInfo curt = (ResolveInfo)receivers.get(it);
12767 if (curt.activityInfo.packageName.equals(skipPackage)) {
12768 receivers.remove(it);
12769 it--;
12770 NT--;
12771 }
12772 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012773 }
12774 }
12775 }
12776
12777 int NT = receivers != null ? receivers.size() : 0;
12778 int it = 0;
12779 ResolveInfo curt = null;
12780 BroadcastFilter curr = null;
12781 while (it < NT && ir < NR) {
12782 if (curt == null) {
12783 curt = (ResolveInfo)receivers.get(it);
12784 }
12785 if (curr == null) {
12786 curr = registeredReceivers.get(ir);
12787 }
12788 if (curr.getPriority() >= curt.priority) {
12789 // Insert this broadcast record into the final list.
12790 receivers.add(it, curr);
12791 ir++;
12792 curr = null;
12793 it++;
12794 NT++;
12795 } else {
12796 // Skip to the next ResolveInfo in the final list.
12797 it++;
12798 curt = null;
12799 }
12800 }
12801 }
12802 while (ir < NR) {
12803 if (receivers == null) {
12804 receivers = new ArrayList();
12805 }
12806 receivers.add(registeredReceivers.get(ir));
12807 ir++;
12808 }
12809
12810 if ((receivers != null && receivers.size() > 0)
12811 || resultTo != null) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012812 BroadcastQueue queue = broadcastQueueForIntent(intent);
12813 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012814 callerPackage, callingPid, callingUid, requiredPermission,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012815 receivers, resultTo, resultCode, resultData, map, ordered,
12816 sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012817 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012818 TAG, "Enqueueing ordered broadcast " + r
Christopher Tatef46723b2012-01-26 14:19:24 -080012819 + ": prev had " + queue.mOrderedBroadcasts.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012820 if (DEBUG_BROADCAST) {
12821 int seq = r.intent.getIntExtra("seq", -1);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012822 Slog.i(TAG, "Enqueueing broadcast " + r.intent.getAction() + " seq=" + seq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012823 }
Christopher Tatef46723b2012-01-26 14:19:24 -080012824 boolean replaced = replacePending && queue.replaceOrderedBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012825 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012826 queue.enqueueOrderedBroadcastLocked(r);
12827 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012828 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012829 }
12830
Dianne Hackborna4972e92012-03-14 10:38:05 -070012831 return ActivityManager.BROADCAST_SUCCESS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012832 }
12833
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012834 final Intent verifyBroadcastLocked(Intent intent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012835 // Refuse possible leaked file descriptors
12836 if (intent != null && intent.hasFileDescriptors() == true) {
12837 throw new IllegalArgumentException("File descriptors passed in Intent");
12838 }
12839
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012840 int flags = intent.getFlags();
12841
12842 if (!mProcessesReady) {
12843 // if the caller really truly claims to know what they're doing, go
12844 // ahead and allow the broadcast without launching any receivers
12845 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
12846 intent = new Intent(intent);
12847 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
12848 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
12849 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
12850 + " before boot completion");
12851 throw new IllegalStateException("Cannot broadcast before boot completed");
12852 }
12853 }
12854
12855 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
12856 throw new IllegalArgumentException(
12857 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
12858 }
12859
12860 return intent;
12861 }
12862
12863 public final int broadcastIntent(IApplicationThread caller,
12864 Intent intent, String resolvedType, IIntentReceiver resultTo,
12865 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070012866 String requiredPermission, boolean serialized, boolean sticky, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012867 enforceNotIsolatedCaller("broadcastIntent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012868 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012869 intent = verifyBroadcastLocked(intent);
Dianne Hackborn9acc0302009-08-25 00:27:12 -070012870
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012871 final ProcessRecord callerApp = getRecordForAppLocked(caller);
12872 final int callingPid = Binder.getCallingPid();
12873 final int callingUid = Binder.getCallingUid();
12874 final long origId = Binder.clearCallingIdentity();
12875 int res = broadcastIntentLocked(callerApp,
12876 callerApp != null ? callerApp.info.packageName : null,
12877 intent, resolvedType, resultTo,
Amith Yamasani742a6712011-05-04 14:49:28 -070012878 resultCode, resultData, map, requiredPermission, serialized, sticky,
12879 callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012880 Binder.restoreCallingIdentity(origId);
12881 return res;
12882 }
12883 }
12884
12885 int broadcastIntentInPackage(String packageName, int uid,
12886 Intent intent, String resolvedType, IIntentReceiver resultTo,
12887 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070012888 String requiredPermission, boolean serialized, boolean sticky, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012889 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012890 intent = verifyBroadcastLocked(intent);
12891
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012892 final long origId = Binder.clearCallingIdentity();
12893 int res = broadcastIntentLocked(null, packageName, intent, resolvedType,
12894 resultTo, resultCode, resultData, map, requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070012895 serialized, sticky, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012896 Binder.restoreCallingIdentity(origId);
12897 return res;
12898 }
12899 }
12900
Amith Yamasani742a6712011-05-04 14:49:28 -070012901 // TODO: Use the userId; maybe mStickyBroadcasts need to be tied to the user.
12902 public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012903 // Refuse possible leaked file descriptors
12904 if (intent != null && intent.hasFileDescriptors() == true) {
12905 throw new IllegalArgumentException("File descriptors passed in Intent");
12906 }
12907
12908 synchronized(this) {
12909 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
12910 != PackageManager.PERMISSION_GRANTED) {
12911 String msg = "Permission Denial: unbroadcastIntent() from pid="
12912 + Binder.getCallingPid()
12913 + ", uid=" + Binder.getCallingUid()
12914 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012915 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012916 throw new SecurityException(msg);
12917 }
12918 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
12919 if (list != null) {
12920 int N = list.size();
12921 int i;
12922 for (i=0; i<N; i++) {
12923 if (intent.filterEquals(list.get(i))) {
12924 list.remove(i);
12925 break;
12926 }
12927 }
12928 }
12929 }
12930 }
12931
12932 private final boolean finishReceiverLocked(IBinder receiver, int resultCode,
12933 String resultData, Bundle resultExtras, boolean resultAbort,
12934 boolean explicit) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012935 final BroadcastRecord r = broadcastRecordForReceiverLocked(receiver);
12936 if (r == null) {
12937 Slog.w(TAG, "finishReceiver called but not found on queue");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012938 return false;
12939 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012940
Christopher Tatef46723b2012-01-26 14:19:24 -080012941 return r.queue.finishReceiverLocked(r, resultCode, resultData, resultExtras, resultAbort,
12942 explicit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012943 }
12944
12945 public void finishReceiver(IBinder who, int resultCode, String resultData,
12946 Bundle resultExtras, boolean resultAbort) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012947 if (DEBUG_BROADCAST) Slog.v(TAG, "Finish receiver: " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012948
12949 // Refuse possible leaked file descriptors
12950 if (resultExtras != null && resultExtras.hasFileDescriptors()) {
12951 throw new IllegalArgumentException("File descriptors passed in Bundle");
12952 }
12953
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012954 final long origId = Binder.clearCallingIdentity();
Christopher Tatef46723b2012-01-26 14:19:24 -080012955 try {
12956 boolean doNext = false;
12957 BroadcastRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012958
Christopher Tatef46723b2012-01-26 14:19:24 -080012959 synchronized(this) {
12960 r = broadcastRecordForReceiverLocked(who);
12961 if (r != null) {
12962 doNext = r.queue.finishReceiverLocked(r, resultCode,
12963 resultData, resultExtras, resultAbort, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012964 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012965 }
Jeff Brown4d94a762010-09-23 11:33:28 -070012966
Christopher Tatef46723b2012-01-26 14:19:24 -080012967 if (doNext) {
12968 r.queue.processNextBroadcast(false);
12969 }
12970 trimApplications();
12971 } finally {
12972 Binder.restoreCallingIdentity(origId);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012973 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012974 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012975
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012976 // =========================================================
12977 // INSTRUMENTATION
12978 // =========================================================
12979
12980 public boolean startInstrumentation(ComponentName className,
12981 String profileFile, int flags, Bundle arguments,
12982 IInstrumentationWatcher watcher) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012983 enforceNotIsolatedCaller("startInstrumentation");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012984 // Refuse possible leaked file descriptors
12985 if (arguments != null && arguments.hasFileDescriptors()) {
12986 throw new IllegalArgumentException("File descriptors passed in Bundle");
12987 }
12988
12989 synchronized(this) {
12990 InstrumentationInfo ii = null;
12991 ApplicationInfo ai = null;
12992 try {
12993 ii = mContext.getPackageManager().getInstrumentationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070012994 className, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012995 ai = mContext.getPackageManager().getApplicationInfo(
Amith Yamasani483f3b02012-03-13 16:08:00 -070012996 ii.targetPackage, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012997 } catch (PackageManager.NameNotFoundException e) {
12998 }
12999 if (ii == null) {
13000 reportStartInstrumentationFailure(watcher, className,
13001 "Unable to find instrumentation info for: " + className);
13002 return false;
13003 }
13004 if (ai == null) {
13005 reportStartInstrumentationFailure(watcher, className,
13006 "Unable to find instrumentation target package: " + ii.targetPackage);
13007 return false;
13008 }
13009
13010 int match = mContext.getPackageManager().checkSignatures(
13011 ii.targetPackage, ii.packageName);
13012 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
13013 String msg = "Permission Denial: starting instrumentation "
13014 + className + " from pid="
13015 + Binder.getCallingPid()
13016 + ", uid=" + Binder.getCallingPid()
13017 + " not allowed because package " + ii.packageName
13018 + " does not have a signature matching the target "
13019 + ii.targetPackage;
13020 reportStartInstrumentationFailure(watcher, className, msg);
13021 throw new SecurityException(msg);
13022 }
13023
Amith Yamasani483f3b02012-03-13 16:08:00 -070013024 int userId = UserId.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013025 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -070013026 // Instrumentation can kill and relaunch even persistent processes
Amith Yamasani483f3b02012-03-13 16:08:00 -070013027 forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true, userId);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013028 ProcessRecord app = addAppLocked(ai, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013029 app.instrumentationClass = className;
Dianne Hackborn1655be42009-05-08 14:29:01 -070013030 app.instrumentationInfo = ai;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013031 app.instrumentationProfileFile = profileFile;
13032 app.instrumentationArguments = arguments;
13033 app.instrumentationWatcher = watcher;
13034 app.instrumentationResultClass = className;
13035 Binder.restoreCallingIdentity(origId);
13036 }
13037
13038 return true;
13039 }
13040
13041 /**
13042 * Report errors that occur while attempting to start Instrumentation. Always writes the
13043 * error to the logs, but if somebody is watching, send the report there too. This enables
13044 * the "am" command to report errors with more information.
13045 *
13046 * @param watcher The IInstrumentationWatcher. Null if there isn't one.
13047 * @param cn The component name of the instrumentation.
13048 * @param report The error report.
13049 */
13050 private void reportStartInstrumentationFailure(IInstrumentationWatcher watcher,
13051 ComponentName cn, String report) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013052 Slog.w(TAG, report);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013053 try {
13054 if (watcher != null) {
13055 Bundle results = new Bundle();
13056 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
13057 results.putString("Error", report);
13058 watcher.instrumentationStatus(cn, -1, results);
13059 }
13060 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013061 Slog.w(TAG, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013062 }
13063 }
13064
13065 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
13066 if (app.instrumentationWatcher != null) {
13067 try {
13068 // NOTE: IInstrumentationWatcher *must* be oneway here
13069 app.instrumentationWatcher.instrumentationFinished(
13070 app.instrumentationClass,
13071 resultCode,
13072 results);
13073 } catch (RemoteException e) {
13074 }
13075 }
13076 app.instrumentationWatcher = null;
13077 app.instrumentationClass = null;
Dianne Hackborn1655be42009-05-08 14:29:01 -070013078 app.instrumentationInfo = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013079 app.instrumentationProfileFile = null;
13080 app.instrumentationArguments = null;
13081
Amith Yamasani483f3b02012-03-13 16:08:00 -070013082 forceStopPackageLocked(app.processName, -1, false, false, true, true, app.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013083 }
13084
13085 public void finishInstrumentation(IApplicationThread target,
13086 int resultCode, Bundle results) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070013087 int userId = UserId.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013088 // Refuse possible leaked file descriptors
13089 if (results != null && results.hasFileDescriptors()) {
13090 throw new IllegalArgumentException("File descriptors passed in Intent");
13091 }
13092
13093 synchronized(this) {
13094 ProcessRecord app = getRecordForAppLocked(target);
13095 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013096 Slog.w(TAG, "finishInstrumentation: no app for " + target);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013097 return;
13098 }
13099 final long origId = Binder.clearCallingIdentity();
13100 finishInstrumentationLocked(app, resultCode, results);
13101 Binder.restoreCallingIdentity(origId);
13102 }
13103 }
13104
13105 // =========================================================
13106 // CONFIGURATION
13107 // =========================================================
13108
13109 public ConfigurationInfo getDeviceConfigurationInfo() {
13110 ConfigurationInfo config = new ConfigurationInfo();
13111 synchronized (this) {
13112 config.reqTouchScreen = mConfiguration.touchscreen;
13113 config.reqKeyboardType = mConfiguration.keyboard;
13114 config.reqNavigation = mConfiguration.navigation;
Dianne Hackbornfae76f52009-07-16 13:41:23 -070013115 if (mConfiguration.navigation == Configuration.NAVIGATION_DPAD
13116 || mConfiguration.navigation == Configuration.NAVIGATION_TRACKBALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013117 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
13118 }
Dianne Hackbornfae76f52009-07-16 13:41:23 -070013119 if (mConfiguration.keyboard != Configuration.KEYBOARD_UNDEFINED
13120 && mConfiguration.keyboard != Configuration.KEYBOARD_NOKEYS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013121 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
13122 }
Jack Palevichb90d28c2009-07-22 15:35:24 -070013123 config.reqGlEsVersion = GL_ES_VERSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013124 }
13125 return config;
13126 }
13127
13128 public Configuration getConfiguration() {
13129 Configuration ci;
13130 synchronized(this) {
13131 ci = new Configuration(mConfiguration);
13132 }
13133 return ci;
13134 }
13135
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013136 public void updatePersistentConfiguration(Configuration values) {
13137 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
13138 "updateConfiguration()");
13139 enforceCallingPermission(android.Manifest.permission.WRITE_SETTINGS,
13140 "updateConfiguration()");
13141 if (values == null) {
13142 throw new NullPointerException("Configuration must not be null");
13143 }
13144
13145 synchronized(this) {
13146 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn813075a62011-11-14 17:45:19 -080013147 updateConfigurationLocked(values, null, true, false);
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013148 Binder.restoreCallingIdentity(origId);
13149 }
13150 }
13151
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013152 public void updateConfiguration(Configuration values) {
13153 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
13154 "updateConfiguration()");
13155
13156 synchronized(this) {
13157 if (values == null && mWindowManager != null) {
13158 // sentinel: fetch the current configuration from the window manager
13159 values = mWindowManager.computeNewConfiguration();
13160 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013161
13162 if (mWindowManager != null) {
13163 mProcessList.applyDisplaySize(mWindowManager);
13164 }
13165
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013166 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013167 if (values != null) {
13168 Settings.System.clearConfiguration(values);
13169 }
Dianne Hackborn813075a62011-11-14 17:45:19 -080013170 updateConfigurationLocked(values, null, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013171 Binder.restoreCallingIdentity(origId);
13172 }
13173 }
13174
13175 /**
13176 * Do either or both things: (1) change the current configuration, and (2)
13177 * make sure the given activity is running with the (now) current
13178 * configuration. Returns true if the activity has been left running, or
13179 * false if <var>starting</var> is being destroyed to match the new
13180 * configuration.
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013181 * @param persistent TODO
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013182 */
Dianne Hackborna573f6a2012-02-09 16:12:18 -080013183 boolean updateConfigurationLocked(Configuration values,
Dianne Hackborn813075a62011-11-14 17:45:19 -080013184 ActivityRecord starting, boolean persistent, boolean initLocale) {
Mike Lockwood3a74bd32011-08-12 13:55:22 -070013185 // do nothing if we are headless
13186 if (mHeadless) return true;
13187
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013188 int changes = 0;
13189
13190 boolean kept = true;
13191
13192 if (values != null) {
13193 Configuration newConfig = new Configuration(mConfiguration);
13194 changes = newConfig.updateFrom(values);
13195 if (changes != 0) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013196 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013197 Slog.i(TAG, "Updating configuration to: " + values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013198 }
13199
Doug Zongker2bec3d42009-12-04 12:52:44 -080013200 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013201
Dianne Hackborn813075a62011-11-14 17:45:19 -080013202 if (values.locale != null && !initLocale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013203 saveLocaleLocked(values.locale,
13204 !values.locale.equals(mConfiguration.locale),
13205 values.userSetLocale);
13206 }
13207
Dianne Hackborne36d6e22010-02-17 19:46:25 -080013208 mConfigurationSeq++;
13209 if (mConfigurationSeq <= 0) {
13210 mConfigurationSeq = 1;
13211 }
13212 newConfig.seq = mConfigurationSeq;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013213 mConfiguration = newConfig;
Joe Onorato8a9b2202010-02-26 18:56:32 -080013214 Slog.i(TAG, "Config changed: " + newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013215
13216 final Configuration configCopy = new Configuration(mConfiguration);
Joe Onorato54a4a412011-11-02 20:50:08 -070013217
13218 // TODO: If our config changes, should we auto dismiss any currently
13219 // showing dialogs?
13220 mShowDialogs = shouldShowDialogs(newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013221
Dianne Hackborn826d17c2009-11-12 12:55:51 -080013222 AttributeCache ac = AttributeCache.instance();
13223 if (ac != null) {
Dianne Hackborn813075a62011-11-14 17:45:19 -080013224 ac.updateConfiguration(configCopy);
Dianne Hackborn826d17c2009-11-12 12:55:51 -080013225 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013226
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070013227 // Make sure all resources in our process are updated
13228 // right now, so that anyone who is going to retrieve
13229 // resource values after we return will be sure to get
13230 // the new ones. This is especially important during
13231 // boot, where the first config change needs to guarantee
13232 // all resources have that config before following boot
13233 // code is executed.
Dianne Hackborn813075a62011-11-14 17:45:19 -080013234 mSystemThread.applyConfigurationToResources(configCopy);
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070013235
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013236 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080013237 Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013238 msg.obj = new Configuration(configCopy);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080013239 mHandler.sendMessage(msg);
13240 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013241
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013242 for (int i=mLruProcesses.size()-1; i>=0; i--) {
13243 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013244 try {
13245 if (app.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013246 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending to proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013247 + app.processName + " new config " + mConfiguration);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013248 app.thread.scheduleConfigurationChanged(configCopy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013249 }
13250 } catch (Exception e) {
13251 }
13252 }
13253 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080013254 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
13255 | Intent.FLAG_RECEIVER_REPLACE_PENDING);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013256 broadcastIntentLocked(null, null, intent, null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070013257 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080013258 if ((changes&ActivityInfo.CONFIG_LOCALE) != 0) {
13259 broadcastIntentLocked(null, null,
13260 new Intent(Intent.ACTION_LOCALE_CHANGED),
13261 null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070013262 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080013263 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013264 }
13265 }
13266
13267 if (changes != 0 && starting == null) {
13268 // If the configuration changed, and the caller is not already
13269 // in the process of starting an activity, then find the top
13270 // activity to check if its configuration needs to change.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013271 starting = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013272 }
13273
13274 if (starting != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013275 kept = mMainStack.ensureActivityConfigurationLocked(starting, changes);
Dianne Hackborn5f4d6432010-12-21 20:40:11 -080013276 // And we need to make sure at this point that all other activities
13277 // are made visible with the correct configuration.
13278 mMainStack.ensureActivitiesVisibleLocked(starting, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013279 }
13280
Dianne Hackborne36d6e22010-02-17 19:46:25 -080013281 if (values != null && mWindowManager != null) {
13282 mWindowManager.setNewConfiguration(mConfiguration);
13283 }
13284
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013285 return kept;
13286 }
Joe Onorato54a4a412011-11-02 20:50:08 -070013287
13288 /**
13289 * Decide based on the configuration whether we should shouw the ANR,
13290 * crash, etc dialogs. The idea is that if there is no affordnace to
13291 * press the on-screen buttons, we shouldn't show the dialog.
13292 *
13293 * A thought: SystemUI might also want to get told about this, the Power
13294 * dialog / global actions also might want different behaviors.
13295 */
13296 private static final boolean shouldShowDialogs(Configuration config) {
13297 return !(config.keyboard == Configuration.KEYBOARD_NOKEYS
13298 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH);
13299 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013300
13301 /**
13302 * Save the locale. You must be inside a synchronized (this) block.
13303 */
13304 private void saveLocaleLocked(Locale l, boolean isDiff, boolean isPersist) {
13305 if(isDiff) {
13306 SystemProperties.set("user.language", l.getLanguage());
13307 SystemProperties.set("user.region", l.getCountry());
13308 }
13309
13310 if(isPersist) {
13311 SystemProperties.set("persist.sys.language", l.getLanguage());
13312 SystemProperties.set("persist.sys.country", l.getCountry());
13313 SystemProperties.set("persist.sys.localevar", l.getVariant());
13314 }
13315 }
13316
Adam Powelldd8fab22012-03-22 17:47:27 -070013317 @Override
13318 public boolean targetTaskAffinityMatchesActivity(IBinder token, String destAffinity) {
13319 ActivityRecord srec = ActivityRecord.forToken(token);
13320 return srec.task.affinity != null && srec.task.affinity.equals(destAffinity);
13321 }
13322
13323 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
13324 Intent resultData) {
13325 ComponentName dest = destIntent.getComponent();
13326
13327 synchronized (this) {
13328 ActivityRecord srec = ActivityRecord.forToken(token);
13329 ArrayList<ActivityRecord> history = srec.stack.mHistory;
13330 final int start = history.indexOf(srec);
13331 if (start < 0) {
13332 // Current activity is not in history stack; do nothing.
13333 return false;
13334 }
13335 int finishTo = start - 1;
13336 ActivityRecord parent = null;
13337 boolean foundParentInTask = false;
13338 if (dest != null) {
13339 TaskRecord tr = srec.task;
13340 for (int i = start - 1; i >= 0; i--) {
13341 ActivityRecord r = history.get(i);
13342 if (tr != r.task) {
13343 // Couldn't find parent in the same task; stop at the one above this.
13344 // (Root of current task; in-app "home" behavior)
13345 // Always at least finish the current activity.
13346 finishTo = Math.min(start - 1, i + 1);
13347 parent = history.get(finishTo);
13348 break;
13349 } else if (r.info.packageName.equals(dest.getPackageName()) &&
13350 r.info.name.equals(dest.getClassName())) {
13351 finishTo = i;
13352 parent = r;
13353 foundParentInTask = true;
13354 break;
13355 }
13356 }
13357 }
13358
13359 if (mController != null) {
13360 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
13361 if (next != null) {
13362 // ask watcher if this is allowed
13363 boolean resumeOK = true;
13364 try {
13365 resumeOK = mController.activityResuming(next.packageName);
13366 } catch (RemoteException e) {
13367 mController = null;
13368 }
13369
13370 if (!resumeOK) {
13371 return false;
13372 }
13373 }
13374 }
13375 final long origId = Binder.clearCallingIdentity();
13376 for (int i = start; i > finishTo; i--) {
13377 ActivityRecord r = history.get(i);
13378 mMainStack.requestFinishActivityLocked(r.appToken, resultCode, resultData,
13379 "navigate-up");
13380 // Only return the supplied result for the first activity finished
13381 resultCode = Activity.RESULT_CANCELED;
13382 resultData = null;
13383 }
13384
13385 if (parent != null && foundParentInTask) {
13386 final int parentLaunchMode = parent.info.launchMode;
13387 final int destIntentFlags = destIntent.getFlags();
13388 if (parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE ||
13389 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TASK ||
13390 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TOP ||
13391 (destIntentFlags & Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
13392 parent.deliverNewIntentLocked(srec.app.uid, destIntent);
13393 } else {
13394 try {
13395 ActivityInfo aInfo = AppGlobals.getPackageManager().getActivityInfo(
13396 destIntent.getComponent(), 0, UserId.getCallingUserId());
13397 int res = mMainStack.startActivityLocked(srec.app.thread, destIntent,
13398 null, aInfo, parent.appToken, null,
13399 0, -1, parent.launchedFromUid, 0, null, true, null);
13400 foundParentInTask = res == ActivityManager.START_SUCCESS;
13401 } catch (RemoteException e) {
13402 foundParentInTask = false;
13403 }
13404 mMainStack.requestFinishActivityLocked(parent.appToken, resultCode,
13405 resultData, "navigate-up");
13406 }
13407 }
13408 Binder.restoreCallingIdentity(origId);
13409 return foundParentInTask;
13410 }
13411 }
13412
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013413 // =========================================================
13414 // LIFETIME MANAGEMENT
13415 // =========================================================
13416
Christopher Tatef46723b2012-01-26 14:19:24 -080013417 // Returns which broadcast queue the app is the current [or imminent] receiver
13418 // on, or 'null' if the app is not an active broadcast recipient.
13419 private BroadcastQueue isReceivingBroadcast(ProcessRecord app) {
13420 BroadcastRecord r = app.curReceiver;
13421 if (r != null) {
13422 return r.queue;
13423 }
13424
13425 // It's not the current receiver, but it might be starting up to become one
13426 synchronized (this) {
13427 for (BroadcastQueue queue : mBroadcastQueues) {
13428 r = queue.mPendingBroadcast;
13429 if (r != null && r.curApp == app) {
13430 // found it; report which queue it's in
13431 return queue;
13432 }
13433 }
13434 }
13435
13436 return null;
13437 }
13438
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013439 private final int computeOomAdjLocked(ProcessRecord app, int hiddenAdj,
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013440 ProcessRecord TOP_APP, boolean recursed, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013441 if (mAdjSeq == app.adjSeq) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013442 // This adjustment has already been computed. If we are calling
13443 // from the top, we may have already computed our adjustment with
13444 // an earlier hidden adjustment that isn't really for us... if
13445 // so, use the new hidden adjustment.
13446 if (!recursed && app.hidden) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013447 app.curAdj = app.curRawAdj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013448 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013449 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013450 }
13451
13452 if (app.thread == null) {
13453 app.adjSeq = mAdjSeq;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013454 app.curSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013455 return (app.curAdj=ProcessList.HIDDEN_APP_MAX_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013456 }
13457
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013458 app.adjTypeCode = ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN;
13459 app.adjSource = null;
13460 app.adjTarget = null;
13461 app.empty = false;
13462 app.hidden = false;
13463
13464 final int activitiesSize = app.activities.size();
13465
Dianne Hackborn7d608422011-08-07 16:24:18 -070013466 if (app.maxAdj <= ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013467 // The max adjustment doesn't allow this app to be anything
13468 // below foreground, so it is not worth doing work for it.
13469 app.adjType = "fixed";
13470 app.adjSeq = mAdjSeq;
13471 app.curRawAdj = app.maxAdj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013472 app.foregroundActivities = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013473 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013474 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013475 // System process can do UI, and when they do we want to have
13476 // them trim their memory after the user leaves the UI. To
13477 // facilitate this, here we need to determine whether or not it
13478 // is currently showing UI.
13479 app.systemNoUi = true;
13480 if (app == TOP_APP) {
13481 app.systemNoUi = false;
13482 } else if (activitiesSize > 0) {
13483 for (int j = 0; j < activitiesSize; j++) {
13484 final ActivityRecord r = app.activities.get(j);
13485 if (r.visible) {
13486 app.systemNoUi = false;
13487 break;
13488 }
13489 }
13490 }
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013491 return (app.curAdj=app.maxAdj);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013492 }
13493
13494 final boolean hadForegroundActivities = app.foregroundActivities;
13495
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013496 app.foregroundActivities = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013497 app.keeping = false;
13498 app.systemNoUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013499
The Android Open Source Project4df24232009-03-05 14:34:35 -080013500 // Determine the importance of the process, starting with most
13501 // important to least, and assign an appropriate OOM adjustment.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013502 int adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013503 int schedGroup;
Christopher Tatef46723b2012-01-26 14:19:24 -080013504 BroadcastQueue queue;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013505 if (app == TOP_APP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013506 // The last app on the list is the foreground app.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013507 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013508 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013509 app.adjType = "top-activity";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013510 app.foregroundActivities = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013511 } else if (app.instrumentationClass != null) {
13512 // Don't want to kill running instrumentation.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013513 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013514 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013515 app.adjType = "instrumentation";
Christopher Tatef46723b2012-01-26 14:19:24 -080013516 } else if ((queue = isReceivingBroadcast(app)) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013517 // An app that is currently receiving a broadcast also
Christopher Tatef46723b2012-01-26 14:19:24 -080013518 // counts as being in the foreground for OOM killer purposes.
13519 // It's placed in a sched group based on the nature of the
13520 // broadcast as reflected by which queue it's active in.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013521 adj = ProcessList.FOREGROUND_APP_ADJ;
Christopher Tatef46723b2012-01-26 14:19:24 -080013522 schedGroup = (queue == mFgBroadcastQueue)
13523 ? Process.THREAD_GROUP_DEFAULT : Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013524 app.adjType = "broadcast";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013525 } else if (app.executingServices.size() > 0) {
13526 // An app that is currently executing a service callback also
13527 // counts as being in the foreground.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013528 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013529 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013530 app.adjType = "exec-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013531 } else if (activitiesSize > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013532 // This app is in the background with paused activities.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013533 // We inspect activities to potentially upgrade adjustment further below.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013534 adj = hiddenAdj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013535 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013536 app.hidden = true;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013537 app.adjType = "bg-activities";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013538 } else {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013539 // A very not-needed process. If this is lower in the lru list,
13540 // we will push it in to the empty bucket.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013541 adj = hiddenAdj;
13542 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013543 app.hidden = true;
13544 app.empty = true;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013545 app.adjType = "bg-empty";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013546 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013547
13548 // Examine all activities if not already foreground.
13549 if (!app.foregroundActivities && activitiesSize > 0) {
13550 for (int j = 0; j < activitiesSize; j++) {
13551 final ActivityRecord r = app.activities.get(j);
13552 if (r.visible) {
13553 // App has a visible activity; only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013554 if (adj > ProcessList.VISIBLE_APP_ADJ) {
13555 adj = ProcessList.VISIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013556 app.adjType = "visible";
13557 }
13558 schedGroup = Process.THREAD_GROUP_DEFAULT;
13559 app.hidden = false;
13560 app.foregroundActivities = true;
13561 break;
13562 } else if (r.state == ActivityState.PAUSING || r.state == ActivityState.PAUSED
13563 || r.state == ActivityState.STOPPING) {
13564 // Only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013565 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13566 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013567 app.adjType = "stopping";
13568 }
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -080013569 app.hidden = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013570 app.foregroundActivities = true;
13571 }
13572 }
13573 }
13574
Dianne Hackborn7d608422011-08-07 16:24:18 -070013575 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013576 if (app.foregroundServices) {
13577 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013578 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013579 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013580 app.adjType = "foreground-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013581 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013582 } else if (app.forcingToForeground != null) {
13583 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013584 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013585 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013586 app.adjType = "force-foreground";
13587 app.adjSource = app.forcingToForeground;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013588 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013589 }
13590 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013591
Dianne Hackborn7d608422011-08-07 16:24:18 -070013592 if (adj > ProcessList.HEAVY_WEIGHT_APP_ADJ && app == mHeavyWeightProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013593 // We don't want to kill the current heavy-weight process.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013594 adj = ProcessList.HEAVY_WEIGHT_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013595 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013596 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013597 app.adjType = "heavy";
13598 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013599
Dianne Hackborn7d608422011-08-07 16:24:18 -070013600 if (adj > ProcessList.HOME_APP_ADJ && app == mHomeProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013601 // This process is hosting what we currently consider to be the
13602 // home app, so we don't want to let it go into the background.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013603 adj = ProcessList.HOME_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013604 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013605 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013606 app.adjType = "home";
13607 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013608
Dianne Hackbornf35fe232011-11-01 19:25:20 -070013609 if (adj > ProcessList.PREVIOUS_APP_ADJ && app == mPreviousProcess
13610 && app.activities.size() > 0) {
13611 // This was the previous process that showed UI to the user.
13612 // We want to try to keep it around more aggressively, to give
13613 // a good experience around switching between two apps.
13614 adj = ProcessList.PREVIOUS_APP_ADJ;
13615 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
13616 app.hidden = false;
13617 app.adjType = "previous";
13618 }
13619
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013620 if (false) Slog.i(TAG, "OOM " + app + ": initial adj=" + adj
13621 + " reason=" + app.adjType);
13622
The Android Open Source Project4df24232009-03-05 14:34:35 -080013623 // By default, we use the computed adjustment. It may be changed if
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013624 // there are applications dependent on our services or providers, but
13625 // this gives us a baseline and makes sure we don't get into an
13626 // infinite recursion.
13627 app.adjSeq = mAdjSeq;
13628 app.curRawAdj = adj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013629
Christopher Tate6fa95972009-06-05 18:43:55 -070013630 if (mBackupTarget != null && app == mBackupTarget.app) {
13631 // If possible we want to avoid killing apps while they're being backed up
Dianne Hackborn7d608422011-08-07 16:24:18 -070013632 if (adj > ProcessList.BACKUP_APP_ADJ) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013633 if (DEBUG_BACKUP) Slog.v(TAG, "oom BACKUP_APP_ADJ for " + app);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013634 adj = ProcessList.BACKUP_APP_ADJ;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013635 app.adjType = "backup";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013636 app.hidden = false;
Christopher Tate6fa95972009-06-05 18:43:55 -070013637 }
13638 }
13639
Dianne Hackborn7d608422011-08-07 16:24:18 -070013640 if (app.services.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013641 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013642 final long now = SystemClock.uptimeMillis();
13643 // This process is more important if the top activity is
13644 // bound to the service.
Dianne Hackborn860755f2010-06-03 18:47:52 -070013645 Iterator<ServiceRecord> jt = app.services.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013646 while (jt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013647 ServiceRecord s = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013648 if (s.startRequested) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013649 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013650 // If this process has shown some UI, let it immediately
13651 // go to the LRU list because it may be pretty heavy with
13652 // UI stuff. We'll tag it with a label just to help
13653 // debug and understand what is going on.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013654 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013655 app.adjType = "started-bg-ui-services";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013656 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013657 } else {
13658 if (now < (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
13659 // This service has seen some activity within
13660 // recent memory, so we will keep its process ahead
13661 // of the background processes.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013662 if (adj > ProcessList.SERVICE_ADJ) {
13663 adj = ProcessList.SERVICE_ADJ;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013664 app.adjType = "started-services";
13665 app.hidden = false;
13666 }
13667 }
13668 // If we have let the service slide into the background
13669 // state, still have some text describing what it is doing
13670 // even though the service no longer has an impact.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013671 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013672 app.adjType = "started-bg-services";
13673 }
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080013674 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013675 // Don't kill this process because it is doing work; it
13676 // has said it is doing work.
13677 app.keeping = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013678 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013679 if (s.connections.size() > 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013680 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013681 Iterator<ArrayList<ConnectionRecord>> kt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013682 = s.connections.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013683 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013684 ArrayList<ConnectionRecord> clist = kt.next();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013685 for (int i=0; i<clist.size() && adj > ProcessList.FOREGROUND_APP_ADJ; i++) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013686 // XXX should compute this based on the max of
13687 // all connected clients.
13688 ConnectionRecord cr = clist.get(i);
13689 if (cr.binding.client == app) {
13690 // Binding to ourself is not interesting.
13691 continue;
13692 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013693 if ((cr.flags&Context.BIND_WAIVE_PRIORITY) == 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013694 ProcessRecord client = cr.binding.client;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013695 int clientAdj = adj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013696 int myHiddenAdj = hiddenAdj;
13697 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013698 if (client.hiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013699 myHiddenAdj = client.hiddenAdj;
13700 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013701 myHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013702 }
13703 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013704 clientAdj = computeOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013705 client, myHiddenAdj, TOP_APP, true, doingAll);
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013706 String adjType = null;
13707 if ((cr.flags&Context.BIND_ALLOW_OOM_MANAGEMENT) != 0) {
13708 // Not doing bind OOM management, so treat
13709 // this guy more like a started service.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013710 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013711 // If this process has shown some UI, let it immediately
13712 // go to the LRU list because it may be pretty heavy with
13713 // UI stuff. We'll tag it with a label just to help
13714 // debug and understand what is going on.
13715 if (adj > clientAdj) {
13716 adjType = "bound-bg-ui-services";
13717 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013718 app.hidden = false;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013719 clientAdj = adj;
13720 } else {
13721 if (now >= (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
13722 // This service has not seen activity within
13723 // recent memory, so allow it to drop to the
13724 // LRU list if there is no other reason to keep
13725 // it around. We'll also tag it with a label just
13726 // to help debug and undertand what is going on.
13727 if (adj > clientAdj) {
13728 adjType = "bound-bg-services";
13729 }
13730 clientAdj = adj;
13731 }
13732 }
13733 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013734 if (adj > clientAdj) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013735 // If this process has recently shown UI, and
13736 // the process that is binding to it is less
13737 // important than being visible, then we don't
13738 // care about the binding as much as we care
13739 // about letting this process get into the LRU
13740 // list to be killed and restarted if needed for
13741 // memory.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013742 if (app.hasShownUi && app != mHomeProcess
13743 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013744 adjType = "bound-bg-ui-services";
13745 } else {
13746 if ((cr.flags&(Context.BIND_ABOVE_CLIENT
13747 |Context.BIND_IMPORTANT)) != 0) {
13748 adj = clientAdj;
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070013749 } else if ((cr.flags&Context.BIND_NOT_VISIBLE) != 0
13750 && clientAdj < ProcessList.PERCEPTIBLE_APP_ADJ
13751 && adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13752 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13753 } else if (clientAdj > ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013754 adj = clientAdj;
13755 } else {
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070013756 app.pendingUiClean = true;
13757 if (adj > ProcessList.VISIBLE_APP_ADJ) {
13758 adj = ProcessList.VISIBLE_APP_ADJ;
13759 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013760 }
13761 if (!client.hidden) {
13762 app.hidden = false;
13763 }
13764 if (client.keeping) {
13765 app.keeping = true;
13766 }
13767 adjType = "service";
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013768 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013769 }
13770 if (adjType != null) {
13771 app.adjType = adjType;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013772 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13773 .REASON_SERVICE_IN_USE;
13774 app.adjSource = cr.binding.client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013775 app.adjSourceOom = clientAdj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013776 app.adjTarget = s.name;
13777 }
13778 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
13779 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
13780 schedGroup = Process.THREAD_GROUP_DEFAULT;
13781 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013782 }
13783 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013784 if ((cr.flags&Context.BIND_ADJUST_WITH_ACTIVITY) != 0) {
13785 ActivityRecord a = cr.activity;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013786 if (a != null && adj > ProcessList.FOREGROUND_APP_ADJ &&
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013787 (a.visible || a.state == ActivityState.RESUMED
13788 || a.state == ActivityState.PAUSING)) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013789 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013790 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
13791 schedGroup = Process.THREAD_GROUP_DEFAULT;
13792 }
13793 app.hidden = false;
13794 app.adjType = "service";
13795 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13796 .REASON_SERVICE_IN_USE;
13797 app.adjSource = a;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013798 app.adjSourceOom = adj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013799 app.adjTarget = s.name;
13800 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013801 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013802 }
13803 }
13804 }
13805 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013806
Dianne Hackborn287952c2010-09-22 22:34:31 -070013807 // Finally, if this process has active services running in it, we
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013808 // would like to avoid killing it unless it would prevent the current
13809 // application from running. By default we put the process in
13810 // with the rest of the background processes; as we scan through
13811 // its services we may bump it up from there.
13812 if (adj > hiddenAdj) {
13813 adj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013814 app.hidden = false;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013815 app.adjType = "bg-services";
13816 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013817 }
13818
Dianne Hackborn7d608422011-08-07 16:24:18 -070013819 if (app.pubProviders.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013820 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013821 Iterator<ContentProviderRecord> jt = app.pubProviders.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013822 while (jt.hasNext() && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013823 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013824 ContentProviderRecord cpr = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013825 if (cpr.clients.size() != 0) {
13826 Iterator<ProcessRecord> kt = cpr.clients.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013827 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013828 ProcessRecord client = kt.next();
The Android Open Source Project10592532009-03-18 17:39:46 -070013829 if (client == app) {
13830 // Being our own client is not interesting.
13831 continue;
13832 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013833 int myHiddenAdj = hiddenAdj;
13834 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013835 if (client.hiddenAdj > ProcessList.FOREGROUND_APP_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013836 myHiddenAdj = client.hiddenAdj;
13837 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013838 myHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013839 }
13840 }
13841 int clientAdj = computeOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013842 client, myHiddenAdj, TOP_APP, true, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013843 if (adj > clientAdj) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013844 if (app.hasShownUi && app != mHomeProcess
13845 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013846 app.adjType = "bg-ui-provider";
13847 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013848 adj = clientAdj > ProcessList.FOREGROUND_APP_ADJ
13849 ? clientAdj : ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013850 app.adjType = "provider";
13851 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013852 if (!client.hidden) {
13853 app.hidden = false;
13854 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013855 if (client.keeping) {
13856 app.keeping = true;
13857 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070013858 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13859 .REASON_PROVIDER_IN_USE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013860 app.adjSource = client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013861 app.adjSourceOom = clientAdj;
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070013862 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013863 }
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013864 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
13865 schedGroup = Process.THREAD_GROUP_DEFAULT;
13866 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013867 }
13868 }
13869 // If the provider has external (non-framework) process
13870 // dependencies, ensure that its adjustment is at least
13871 // FOREGROUND_APP_ADJ.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080013872 if (cpr.hasExternalProcessHandles()) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013873 if (adj > ProcessList.FOREGROUND_APP_ADJ) {
13874 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013875 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013876 app.hidden = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013877 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013878 app.adjType = "provider";
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070013879 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013880 }
13881 }
13882 }
13883 }
13884
13885 app.curRawAdj = adj;
13886
Joe Onorato8a9b2202010-02-26 18:56:32 -080013887 //Slog.i(TAG, "OOM ADJ " + app + ": pid=" + app.pid +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013888 // " adj=" + adj + " curAdj=" + app.curAdj + " maxAdj=" + app.maxAdj);
13889 if (adj > app.maxAdj) {
13890 adj = app.maxAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013891 if (app.maxAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013892 schedGroup = Process.THREAD_GROUP_DEFAULT;
13893 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013894 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013895 if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070013896 app.keeping = true;
13897 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013898
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013899 if (app.hasAboveClient) {
13900 // If this process has bound to any services with BIND_ABOVE_CLIENT,
13901 // then we need to drop its adjustment to be lower than the service's
13902 // in order to honor the request. We want to drop it by one adjustment
13903 // level... but there is special meaning applied to various levels so
13904 // we will skip some of them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013905 if (adj < ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013906 // System process will not get dropped, ever
Dianne Hackborn7d608422011-08-07 16:24:18 -070013907 } else if (adj < ProcessList.VISIBLE_APP_ADJ) {
13908 adj = ProcessList.VISIBLE_APP_ADJ;
13909 } else if (adj < ProcessList.PERCEPTIBLE_APP_ADJ) {
13910 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13911 } else if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
13912 adj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013913 } else if (adj < ProcessList.HIDDEN_APP_MAX_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013914 adj++;
13915 }
13916 }
13917
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013918 if (adj == ProcessList.SERVICE_ADJ) {
13919 if (doingAll) {
13920 app.serviceb = mNewNumServiceProcs > (mNumServiceProcs/3);
13921 mNewNumServiceProcs++;
13922 }
13923 if (app.serviceb) {
13924 adj = ProcessList.SERVICE_B_ADJ;
13925 }
13926 } else {
13927 app.serviceb = false;
13928 }
13929
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013930 app.curAdj = adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013931 app.curSchedGroup = schedGroup;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013932
13933 if (hadForegroundActivities != app.foregroundActivities) {
Jeff Sharkey287bd832011-05-28 19:36:26 -070013934 mHandler.obtainMessage(DISPATCH_FOREGROUND_ACTIVITIES_CHANGED, app.pid, app.info.uid,
13935 app.foregroundActivities).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013936 }
13937
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013938 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013939 }
13940
13941 /**
13942 * Ask a given process to GC right now.
13943 */
13944 final void performAppGcLocked(ProcessRecord app) {
13945 try {
13946 app.lastRequestedGc = SystemClock.uptimeMillis();
13947 if (app.thread != null) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013948 if (app.reportLowMemory) {
13949 app.reportLowMemory = false;
13950 app.thread.scheduleLowMemory();
13951 } else {
13952 app.thread.processInBackground();
13953 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013954 }
13955 } catch (Exception e) {
13956 // whatever.
13957 }
13958 }
13959
13960 /**
13961 * Returns true if things are idle enough to perform GCs.
13962 */
Josh Bartel7f208742010-02-25 11:01:44 -060013963 private final boolean canGcNowLocked() {
Christopher Tatef46723b2012-01-26 14:19:24 -080013964 boolean processingBroadcasts = false;
13965 for (BroadcastQueue q : mBroadcastQueues) {
13966 if (q.mParallelBroadcasts.size() != 0 || q.mOrderedBroadcasts.size() != 0) {
13967 processingBroadcasts = true;
13968 }
13969 }
13970 return !processingBroadcasts
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013971 && (mSleeping || (mMainStack.mResumedActivity != null &&
13972 mMainStack.mResumedActivity.idle));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013973 }
13974
13975 /**
13976 * Perform GCs on all processes that are waiting for it, but only
13977 * if things are idle.
13978 */
13979 final void performAppGcsLocked() {
13980 final int N = mProcessesToGc.size();
13981 if (N <= 0) {
13982 return;
13983 }
Josh Bartel7f208742010-02-25 11:01:44 -060013984 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013985 while (mProcessesToGc.size() > 0) {
13986 ProcessRecord proc = mProcessesToGc.remove(0);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013987 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013988 if ((proc.lastRequestedGc+GC_MIN_INTERVAL)
13989 <= SystemClock.uptimeMillis()) {
13990 // To avoid spamming the system, we will GC processes one
13991 // at a time, waiting a few seconds between each.
13992 performAppGcLocked(proc);
13993 scheduleAppGcsLocked();
13994 return;
13995 } else {
13996 // It hasn't been long enough since we last GCed this
13997 // process... put it in the list to wait for its time.
13998 addProcessToGcListLocked(proc);
13999 break;
14000 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014001 }
14002 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014003
14004 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014005 }
14006 }
14007
14008 /**
14009 * If all looks good, perform GCs on all processes waiting for them.
14010 */
14011 final void performAppGcsIfAppropriateLocked() {
Josh Bartel7f208742010-02-25 11:01:44 -060014012 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014013 performAppGcsLocked();
14014 return;
14015 }
14016 // Still not idle, wait some more.
14017 scheduleAppGcsLocked();
14018 }
14019
14020 /**
14021 * Schedule the execution of all pending app GCs.
14022 */
14023 final void scheduleAppGcsLocked() {
14024 mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014025
14026 if (mProcessesToGc.size() > 0) {
14027 // Schedule a GC for the time to the next process.
14028 ProcessRecord proc = mProcessesToGc.get(0);
14029 Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG);
14030
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014031 long when = proc.lastRequestedGc + GC_MIN_INTERVAL;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014032 long now = SystemClock.uptimeMillis();
14033 if (when < (now+GC_TIMEOUT)) {
14034 when = now + GC_TIMEOUT;
14035 }
14036 mHandler.sendMessageAtTime(msg, when);
14037 }
14038 }
14039
14040 /**
14041 * Add a process to the array of processes waiting to be GCed. Keeps the
14042 * list in sorted order by the last GC time. The process can't already be
14043 * on the list.
14044 */
14045 final void addProcessToGcListLocked(ProcessRecord proc) {
14046 boolean added = false;
14047 for (int i=mProcessesToGc.size()-1; i>=0; i--) {
14048 if (mProcessesToGc.get(i).lastRequestedGc <
14049 proc.lastRequestedGc) {
14050 added = true;
14051 mProcessesToGc.add(i+1, proc);
14052 break;
14053 }
14054 }
14055 if (!added) {
14056 mProcessesToGc.add(0, proc);
14057 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014058 }
14059
14060 /**
14061 * Set up to ask a process to GC itself. This will either do it
14062 * immediately, or put it on the list of processes to gc the next
14063 * time things are idle.
14064 */
14065 final void scheduleAppGcLocked(ProcessRecord app) {
14066 long now = SystemClock.uptimeMillis();
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014067 if ((app.lastRequestedGc+GC_MIN_INTERVAL) > now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014068 return;
14069 }
14070 if (!mProcessesToGc.contains(app)) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014071 addProcessToGcListLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014072 scheduleAppGcsLocked();
14073 }
14074 }
14075
Dianne Hackborn287952c2010-09-22 22:34:31 -070014076 final void checkExcessivePowerUsageLocked(boolean doKills) {
14077 updateCpuStatsNow();
14078
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014079 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborn287952c2010-09-22 22:34:31 -070014080 boolean doWakeKills = doKills;
14081 boolean doCpuKills = doKills;
14082 if (mLastPowerCheckRealtime == 0) {
14083 doWakeKills = false;
14084 }
14085 if (mLastPowerCheckUptime == 0) {
14086 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014087 }
14088 if (stats.isScreenOn()) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070014089 doWakeKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014090 }
14091 final long curRealtime = SystemClock.elapsedRealtime();
Dianne Hackborn287952c2010-09-22 22:34:31 -070014092 final long realtimeSince = curRealtime - mLastPowerCheckRealtime;
14093 final long curUptime = SystemClock.uptimeMillis();
14094 final long uptimeSince = curUptime - mLastPowerCheckUptime;
14095 mLastPowerCheckRealtime = curRealtime;
14096 mLastPowerCheckUptime = curUptime;
14097 if (realtimeSince < WAKE_LOCK_MIN_CHECK_DURATION) {
14098 doWakeKills = false;
14099 }
14100 if (uptimeSince < CPU_MIN_CHECK_DURATION) {
14101 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014102 }
14103 int i = mLruProcesses.size();
14104 while (i > 0) {
14105 i--;
14106 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn287952c2010-09-22 22:34:31 -070014107 if (!app.keeping) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014108 long wtime;
14109 synchronized (stats) {
14110 wtime = stats.getProcessWakeTime(app.info.uid,
14111 app.pid, curRealtime);
14112 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070014113 long wtimeUsed = wtime - app.lastWakeTime;
14114 long cputimeUsed = app.curCpuTime - app.lastCpuTime;
14115 if (DEBUG_POWER) {
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014116 StringBuilder sb = new StringBuilder(128);
14117 sb.append("Wake for ");
14118 app.toShortString(sb);
14119 sb.append(": over ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070014120 TimeUtils.formatDuration(realtimeSince, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014121 sb.append(" used ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070014122 TimeUtils.formatDuration(wtimeUsed, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014123 sb.append(" (");
Dianne Hackborn287952c2010-09-22 22:34:31 -070014124 sb.append((wtimeUsed*100)/realtimeSince);
14125 sb.append("%)");
14126 Slog.i(TAG, sb.toString());
14127 sb.setLength(0);
14128 sb.append("CPU for ");
14129 app.toShortString(sb);
14130 sb.append(": over ");
14131 TimeUtils.formatDuration(uptimeSince, sb);
14132 sb.append(" used ");
14133 TimeUtils.formatDuration(cputimeUsed, sb);
14134 sb.append(" (");
14135 sb.append((cputimeUsed*100)/uptimeSince);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014136 sb.append("%)");
14137 Slog.i(TAG, sb.toString());
14138 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014139 // If a process has held a wake lock for more
14140 // than 50% of the time during this period,
14141 // that sounds pad. Kill!
Dianne Hackborn287952c2010-09-22 22:34:31 -070014142 if (doWakeKills && realtimeSince > 0
14143 && ((wtimeUsed*100)/realtimeSince) >= 50) {
14144 synchronized (stats) {
14145 stats.reportExcessiveWakeLocked(app.info.uid, app.processName,
14146 realtimeSince, wtimeUsed);
14147 }
14148 Slog.w(TAG, "Excessive wake lock in " + app.processName
14149 + " (pid " + app.pid + "): held " + wtimeUsed
14150 + " during " + realtimeSince);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014151 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14152 app.processName, app.setAdj, "excessive wake lock");
14153 Process.killProcessQuiet(app.pid);
Dianne Hackborn287952c2010-09-22 22:34:31 -070014154 } else if (doCpuKills && uptimeSince > 0
14155 && ((cputimeUsed*100)/uptimeSince) >= 50) {
14156 synchronized (stats) {
14157 stats.reportExcessiveCpuLocked(app.info.uid, app.processName,
14158 uptimeSince, cputimeUsed);
14159 }
14160 Slog.w(TAG, "Excessive CPU in " + app.processName
14161 + " (pid " + app.pid + "): used " + cputimeUsed
14162 + " during " + uptimeSince);
14163 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14164 app.processName, app.setAdj, "excessive cpu");
14165 Process.killProcessQuiet(app.pid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014166 } else {
14167 app.lastWakeTime = wtime;
Dianne Hackborn287952c2010-09-22 22:34:31 -070014168 app.lastCpuTime = app.curCpuTime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014169 }
14170 }
14171 }
14172 }
14173
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014174 private final boolean updateOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014175 ProcessRecord app, int hiddenAdj, ProcessRecord TOP_APP, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014176 app.hiddenAdj = hiddenAdj;
14177
14178 if (app.thread == null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014179 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014180 }
14181
Dianne Hackborn287952c2010-09-22 22:34:31 -070014182 final boolean wasKeeping = app.keeping;
14183
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014184 boolean success = true;
14185
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014186 computeOomAdjLocked(app, hiddenAdj, TOP_APP, false, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014187
Jeff Brown10e89712011-07-08 18:52:57 -070014188 if (app.curRawAdj != app.setRawAdj) {
Dianne Hackborn905577f2011-09-07 18:31:28 -070014189 if (false) {
14190 // Removing for now. Forcing GCs is not so useful anymore
14191 // with Dalvik, and the new memory level hint facility is
14192 // better for what we need to do these days.
14193 if (app.curRawAdj > ProcessList.FOREGROUND_APP_ADJ
14194 && app.setRawAdj <= ProcessList.FOREGROUND_APP_ADJ) {
14195 // If this app is transitioning from foreground to
14196 // non-foreground, have it do a gc.
14197 scheduleAppGcLocked(app);
14198 } else if (app.curRawAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
14199 && app.setRawAdj < ProcessList.HIDDEN_APP_MIN_ADJ) {
14200 // Likewise do a gc when an app is moving in to the
14201 // background (such as a service stopping).
14202 scheduleAppGcLocked(app);
14203 }
Jeff Brown10e89712011-07-08 18:52:57 -070014204 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070014205
Jeff Brown10e89712011-07-08 18:52:57 -070014206 if (wasKeeping && !app.keeping) {
14207 // This app is no longer something we want to keep. Note
14208 // its current wake lock time to later know to kill it if
14209 // it is not behaving well.
14210 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
14211 synchronized (stats) {
14212 app.lastWakeTime = stats.getProcessWakeTime(app.info.uid,
14213 app.pid, SystemClock.elapsedRealtime());
14214 }
14215 app.lastCpuTime = app.curCpuTime;
14216 }
14217
14218 app.setRawAdj = app.curRawAdj;
14219 }
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014220
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014221 if (app.curAdj != app.setAdj) {
14222 if (Process.setOomAdj(app.pid, app.curAdj)) {
Dianne Hackbornbbb09ac2011-11-30 11:31:29 -080014223 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014224 TAG, "Set " + app.pid + " " + app.processName +
14225 " adj " + app.curAdj + ": " + app.adjType);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014226 app.setAdj = app.curAdj;
Jeff Brown10e89712011-07-08 18:52:57 -070014227 } else {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014228 success = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014229 Slog.w(TAG, "Failed setting oom adj of " + app + " to " + app.curAdj);
Jeff Brown10e89712011-07-08 18:52:57 -070014230 }
14231 }
14232 if (app.setSchedGroup != app.curSchedGroup) {
14233 app.setSchedGroup = app.curSchedGroup;
14234 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
14235 "Setting process group of " + app.processName
14236 + " to " + app.curSchedGroup);
14237 if (app.waitingToKill != null &&
14238 app.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
14239 Slog.i(TAG, "Killing " + app.toShortString() + ": " + app.waitingToKill);
14240 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14241 app.processName, app.setAdj, app.waitingToKill);
14242 Process.killProcessQuiet(app.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014243 success = false;
Jeff Brown10e89712011-07-08 18:52:57 -070014244 } else {
14245 if (true) {
14246 long oldId = Binder.clearCallingIdentity();
14247 try {
14248 Process.setProcessGroup(app.pid, app.curSchedGroup);
14249 } catch (Exception e) {
14250 Slog.w(TAG, "Failed setting process group of " + app.pid
14251 + " to " + app.curSchedGroup);
14252 e.printStackTrace();
14253 } finally {
14254 Binder.restoreCallingIdentity(oldId);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014255 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014256 } else {
Jeff Brown10e89712011-07-08 18:52:57 -070014257 if (app.thread != null) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070014258 try {
Jeff Brown10e89712011-07-08 18:52:57 -070014259 app.thread.setSchedulingGroup(app.curSchedGroup);
14260 } catch (RemoteException e) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070014261 }
14262 }
14263 }
14264 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014265 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014266 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014267 }
14268
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014269 private final ActivityRecord resumedAppLocked() {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014270 ActivityRecord resumedActivity = mMainStack.mResumedActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014271 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -080014272 resumedActivity = mMainStack.mPausingActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014273 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014274 resumedActivity = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014275 }
14276 }
14277 return resumedActivity;
14278 }
14279
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014280 private final boolean updateOomAdjLocked(ProcessRecord app) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014281 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014282 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
14283 int curAdj = app.curAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070014284 final boolean wasHidden = curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
14285 && curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014286
14287 mAdjSeq++;
14288
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014289 boolean success = updateOomAdjLocked(app, app.hiddenAdj, TOP_APP, false);
Dianne Hackborn7d608422011-08-07 16:24:18 -070014290 final boolean nowHidden = app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
14291 && app.curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014292 if (nowHidden != wasHidden) {
14293 // Changed to/from hidden state, so apps after it in the LRU
14294 // list may also be changed.
14295 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014296 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014297 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014298 }
14299
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014300 final void updateOomAdjLocked() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014301 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014302 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
14303
14304 if (false) {
14305 RuntimeException e = new RuntimeException();
14306 e.fillInStackTrace();
Joe Onorato8a9b2202010-02-26 18:56:32 -080014307 Slog.i(TAG, "updateOomAdj: top=" + TOP_ACT, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014308 }
14309
14310 mAdjSeq++;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014311 mNewNumServiceProcs = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014312
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014313 // Let's determine how many processes we have running vs.
14314 // how many slots we have for background processes; we may want
14315 // to put multiple processes in a slot of there are enough of
14316 // them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014317 int numSlots = ProcessList.HIDDEN_APP_MAX_ADJ - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014318 int factor = (mLruProcesses.size()-4)/numSlots;
14319 if (factor < 1) factor = 1;
14320 int step = 0;
Dianne Hackborn8633e682010-04-22 16:03:41 -070014321 int numHidden = 0;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014322
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014323 // First update the OOM adjustment for each of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014324 // application processes based on their current state.
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014325 int i = mLruProcesses.size();
Dianne Hackborn7d608422011-08-07 16:24:18 -070014326 int curHiddenAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014327 while (i > 0) {
14328 i--;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014329 ProcessRecord app = mLruProcesses.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080014330 //Slog.i(TAG, "OOM " + app + ": cur hidden=" + curHiddenAdj);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014331 updateOomAdjLocked(app, curHiddenAdj, TOP_APP, true);
14332 if (curHiddenAdj < ProcessList.HIDDEN_APP_MAX_ADJ
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014333 && app.curAdj == curHiddenAdj) {
14334 step++;
14335 if (step >= factor) {
14336 step = 0;
14337 curHiddenAdj++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014338 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014339 }
14340 if (!app.killedBackground) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070014341 if (app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014342 numHidden++;
14343 if (numHidden > mProcessLimit) {
14344 Slog.i(TAG, "No longer want " + app.processName
14345 + " (pid " + app.pid + "): hidden #" + numHidden);
14346 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14347 app.processName, app.setAdj, "too many background");
14348 app.killedBackground = true;
14349 Process.killProcessQuiet(app.pid);
Dianne Hackborn8633e682010-04-22 16:03:41 -070014350 }
14351 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -080014352 if (!app.killedBackground && app.isolated && app.services.size() <= 0) {
14353 // If this is an isolated process, and there are no
14354 // services running in it, then the process is no longer
14355 // needed. We agressively kill these because we can by
14356 // definition not re-use the same process again, and it is
14357 // good to avoid having whatever code was running in them
14358 // left sitting around after no longer needed.
14359 Slog.i(TAG, "Isolated process " + app.processName
14360 + " (pid " + app.pid + ") no longer needed");
14361 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14362 app.processName, app.setAdj, "isolated not needed");
14363 app.killedBackground = true;
14364 Process.killProcessQuiet(app.pid);
14365 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014366 }
14367 }
14368
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014369 mNumServiceProcs = mNewNumServiceProcs;
14370
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014371 // Now determine the memory trimming level of background processes.
14372 // Unfortunately we need to start at the back of the list to do this
14373 // properly. We only do this if the number of background apps we
14374 // are managing to keep around is less than half the maximum we desire;
14375 // if we are keeping a good number around, we'll let them use whatever
14376 // memory they want.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014377 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/2)) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014378 final int N = mLruProcesses.size();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080014379 factor = numHidden/3;
14380 int minFactor = 2;
14381 if (mHomeProcess != null) minFactor++;
14382 if (mPreviousProcess != null) minFactor++;
14383 if (factor < minFactor) factor = minFactor;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014384 step = 0;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014385 int fgTrimLevel;
14386 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/5)) {
14387 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL;
14388 } else if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/3)) {
14389 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW;
14390 } else {
14391 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE;
14392 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014393 int curLevel = ComponentCallbacks2.TRIM_MEMORY_COMPLETE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014394 for (i=0; i<N; i++) {
14395 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080014396 if (app.curAdj >= ProcessList.HOME_APP_ADJ
14397 && app.curAdj != ProcessList.SERVICE_B_ADJ
14398 && !app.killedBackground) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014399 if (app.trimMemoryLevel < curLevel && app.thread != null) {
14400 try {
14401 app.thread.scheduleTrimMemory(curLevel);
14402 } catch (RemoteException e) {
14403 }
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080014404 if (false) {
14405 // For now we won't do this; our memory trimming seems
14406 // to be good enough at this point that destroying
14407 // activities causes more harm than good.
14408 if (curLevel >= ComponentCallbacks2.TRIM_MEMORY_COMPLETE
14409 && app != mHomeProcess && app != mPreviousProcess) {
14410 // For these apps we will also finish their activities
14411 // to help them free memory.
14412 mMainStack.destroyActivitiesLocked(app, false, "trim");
14413 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014414 }
14415 }
14416 app.trimMemoryLevel = curLevel;
14417 step++;
14418 if (step >= factor) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014419 step = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014420 switch (curLevel) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014421 case ComponentCallbacks2.TRIM_MEMORY_COMPLETE:
14422 curLevel = ComponentCallbacks2.TRIM_MEMORY_MODERATE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014423 break;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014424 case ComponentCallbacks2.TRIM_MEMORY_MODERATE:
14425 curLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014426 break;
14427 }
14428 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070014429 } else if (app.curAdj == ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014430 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014431 && app.thread != null) {
14432 try {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014433 app.thread.scheduleTrimMemory(
14434 ComponentCallbacks2.TRIM_MEMORY_BACKGROUND);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014435 } catch (RemoteException e) {
14436 }
14437 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014438 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014439 } else {
14440 if ((app.curAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
14441 && app.pendingUiClean) {
14442 // If this application is now in the background and it
14443 // had done UI, then give it the special trim level to
14444 // have it free UI resources.
14445 final int level = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
14446 if (app.trimMemoryLevel < level && app.thread != null) {
14447 try {
14448 app.thread.scheduleTrimMemory(level);
14449 } catch (RemoteException e) {
14450 }
14451 }
14452 app.pendingUiClean = false;
14453 }
14454 if (app.trimMemoryLevel < fgTrimLevel && app.thread != null) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014455 try {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014456 app.thread.scheduleTrimMemory(fgTrimLevel);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014457 } catch (RemoteException e) {
14458 }
14459 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014460 app.trimMemoryLevel = fgTrimLevel;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014461 }
14462 }
14463 } else {
14464 final int N = mLruProcesses.size();
14465 for (i=0; i<N; i++) {
14466 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -070014467 if ((app.curAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014468 && app.pendingUiClean) {
14469 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
14470 && app.thread != null) {
14471 try {
14472 app.thread.scheduleTrimMemory(
14473 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
14474 } catch (RemoteException e) {
14475 }
14476 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014477 app.pendingUiClean = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014478 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014479 app.trimMemoryLevel = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014480 }
14481 }
14482
14483 if (mAlwaysFinishActivities) {
Dianne Hackborn28695e02011-11-02 21:59:51 -070014484 mMainStack.destroyActivitiesLocked(null, false, "always-finish");
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014485 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014486 }
14487
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014488 final void trimApplications() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014489 synchronized (this) {
14490 int i;
14491
14492 // First remove any unused application processes whose package
14493 // has been removed.
14494 for (i=mRemovedProcesses.size()-1; i>=0; i--) {
14495 final ProcessRecord app = mRemovedProcesses.get(i);
14496 if (app.activities.size() == 0
14497 && app.curReceiver == null && app.services.size() == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080014498 Slog.i(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014499 TAG, "Exiting empty application process "
14500 + app.processName + " ("
14501 + (app.thread != null ? app.thread.asBinder() : null)
14502 + ")\n");
14503 if (app.pid > 0 && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070014504 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14505 app.processName, app.setAdj, "empty");
14506 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014507 } else {
14508 try {
14509 app.thread.scheduleExit();
14510 } catch (Exception e) {
14511 // Ignore exceptions.
14512 }
14513 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070014514 cleanUpApplicationRecordLocked(app, false, true, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014515 mRemovedProcesses.remove(i);
14516
14517 if (app.persistent) {
14518 if (app.persistent) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080014519 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014520 }
14521 }
14522 }
14523 }
14524
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014525 // Now update the oom adj for all processes.
14526 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014527 }
14528 }
14529
14530 /** This method sends the specified signal to each of the persistent apps */
14531 public void signalPersistentProcesses(int sig) throws RemoteException {
14532 if (sig != Process.SIGNAL_USR1) {
14533 throw new SecurityException("Only SIGNAL_USR1 is allowed");
14534 }
14535
14536 synchronized (this) {
14537 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
14538 != PackageManager.PERMISSION_GRANTED) {
14539 throw new SecurityException("Requires permission "
14540 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
14541 }
14542
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014543 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
14544 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014545 if (r.thread != null && r.persistent) {
14546 Process.sendSignal(r.pid, sig);
14547 }
14548 }
14549 }
14550 }
14551
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014552 private void stopProfilerLocked(ProcessRecord proc, String path, int profileType) {
14553 if (proc == null || proc == mProfileProc) {
14554 proc = mProfileProc;
14555 path = mProfileFile;
14556 profileType = mProfileType;
14557 clearProfilerLocked();
14558 }
14559 if (proc == null) {
14560 return;
14561 }
14562 try {
14563 proc.thread.profilerControl(false, path, null, profileType);
14564 } catch (RemoteException e) {
14565 throw new IllegalStateException("Process disappeared");
14566 }
14567 }
14568
14569 private void clearProfilerLocked() {
14570 if (mProfileFd != null) {
14571 try {
14572 mProfileFd.close();
14573 } catch (IOException e) {
14574 }
14575 }
14576 mProfileApp = null;
14577 mProfileProc = null;
14578 mProfileFile = null;
14579 mProfileType = 0;
14580 mAutoStopProfiler = false;
14581 }
14582
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014583 public boolean profileControl(String process, boolean start,
Romain Guy7eabe552011-07-21 14:56:34 -070014584 String path, ParcelFileDescriptor fd, int profileType) throws RemoteException {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014585
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014586 try {
14587 synchronized (this) {
14588 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14589 // its own permission.
14590 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14591 != PackageManager.PERMISSION_GRANTED) {
14592 throw new SecurityException("Requires permission "
14593 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014594 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014595
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014596 if (start && fd == null) {
14597 throw new IllegalArgumentException("null fd");
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014598 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014599
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014600 ProcessRecord proc = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014601 if (process != null) {
14602 try {
14603 int pid = Integer.parseInt(process);
14604 synchronized (mPidsSelfLocked) {
14605 proc = mPidsSelfLocked.get(pid);
14606 }
14607 } catch (NumberFormatException e) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014608 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014609
14610 if (proc == null) {
14611 HashMap<String, SparseArray<ProcessRecord>> all
14612 = mProcessNames.getMap();
14613 SparseArray<ProcessRecord> procs = all.get(process);
14614 if (procs != null && procs.size() > 0) {
14615 proc = procs.valueAt(0);
14616 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014617 }
14618 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014619
14620 if (start && (proc == null || proc.thread == null)) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014621 throw new IllegalArgumentException("Unknown process: " + process);
14622 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014623
14624 if (start) {
14625 stopProfilerLocked(null, null, 0);
14626 setProfileApp(proc.info, proc.processName, path, fd, false);
14627 mProfileProc = proc;
14628 mProfileType = profileType;
14629 try {
14630 fd = fd.dup();
14631 } catch (IOException e) {
14632 fd = null;
14633 }
14634 proc.thread.profilerControl(start, path, fd, profileType);
14635 fd = null;
14636 mProfileFd = null;
14637 } else {
14638 stopProfilerLocked(proc, path, profileType);
14639 if (fd != null) {
14640 try {
14641 fd.close();
14642 } catch (IOException e) {
14643 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014644 }
14645 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014646
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014647 return true;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014648 }
14649 } catch (RemoteException e) {
14650 throw new IllegalStateException("Process disappeared");
14651 } finally {
14652 if (fd != null) {
14653 try {
14654 fd.close();
14655 } catch (IOException e) {
14656 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014657 }
14658 }
14659 }
Andy McFadden824c5102010-07-09 16:26:57 -070014660
14661 public boolean dumpHeap(String process, boolean managed,
14662 String path, ParcelFileDescriptor fd) throws RemoteException {
14663
14664 try {
14665 synchronized (this) {
14666 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14667 // its own permission (same as profileControl).
14668 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14669 != PackageManager.PERMISSION_GRANTED) {
14670 throw new SecurityException("Requires permission "
14671 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
14672 }
14673
14674 if (fd == null) {
14675 throw new IllegalArgumentException("null fd");
14676 }
14677
14678 ProcessRecord proc = null;
14679 try {
14680 int pid = Integer.parseInt(process);
14681 synchronized (mPidsSelfLocked) {
14682 proc = mPidsSelfLocked.get(pid);
14683 }
14684 } catch (NumberFormatException e) {
14685 }
14686
14687 if (proc == null) {
14688 HashMap<String, SparseArray<ProcessRecord>> all
14689 = mProcessNames.getMap();
14690 SparseArray<ProcessRecord> procs = all.get(process);
14691 if (procs != null && procs.size() > 0) {
14692 proc = procs.valueAt(0);
14693 }
14694 }
14695
14696 if (proc == null || proc.thread == null) {
14697 throw new IllegalArgumentException("Unknown process: " + process);
14698 }
14699
Dianne Hackbornf02e57b2011-03-01 22:21:04 -080014700 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
14701 if (!isDebuggable) {
Andy McFadden824c5102010-07-09 16:26:57 -070014702 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
14703 throw new SecurityException("Process not debuggable: " + proc);
14704 }
14705 }
14706
14707 proc.thread.dumpHeap(managed, path, fd);
14708 fd = null;
14709 return true;
14710 }
14711 } catch (RemoteException e) {
14712 throw new IllegalStateException("Process disappeared");
14713 } finally {
14714 if (fd != null) {
14715 try {
14716 fd.close();
14717 } catch (IOException e) {
14718 }
14719 }
14720 }
14721 }
14722
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014723 /** In this method we try to acquire our lock to make sure that we have not deadlocked */
14724 public void monitor() {
14725 synchronized (this) { }
14726 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014727
Dianne Hackborna573f6a2012-02-09 16:12:18 -080014728 void onCoreSettingsChange(Bundle settings) {
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014729 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
14730 ProcessRecord processRecord = mLruProcesses.get(i);
14731 try {
14732 if (processRecord.thread != null) {
14733 processRecord.thread.setCoreSettings(settings);
14734 }
14735 } catch (RemoteException re) {
14736 /* ignore */
14737 }
14738 }
14739 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014740
14741 // Multi-user methods
14742
Amith Yamasani742a6712011-05-04 14:49:28 -070014743 private int mCurrentUserId;
14744 private SparseIntArray mLoggedInUsers = new SparseIntArray(5);
14745
14746 public boolean switchUser(int userId) {
14747 final int callingUid = Binder.getCallingUid();
14748 if (callingUid != 0 && callingUid != Process.myUid()) {
14749 Slog.e(TAG, "Trying to switch user from unauthorized app");
14750 return false;
14751 }
14752 if (mCurrentUserId == userId)
14753 return true;
14754
14755 synchronized (this) {
14756 // Check if user is already logged in, otherwise check if user exists first before
14757 // adding to the list of logged in users.
14758 if (mLoggedInUsers.indexOfKey(userId) < 0) {
14759 if (!userExists(userId)) {
14760 return false;
14761 }
14762 mLoggedInUsers.append(userId, userId);
14763 }
14764
14765 mCurrentUserId = userId;
14766 boolean haveActivities = mMainStack.switchUser(userId);
14767 if (!haveActivities) {
14768 startHomeActivityLocked(userId);
14769 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014770
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014771 }
Amith Yamasani13593602012-03-22 16:16:17 -070014772
14773 // Inform of user switch
14774 Intent addedIntent = new Intent(Intent.ACTION_USER_SWITCHED);
14775 addedIntent.putExtra(Intent.EXTRA_USERID, userId);
14776 mContext.sendBroadcast(addedIntent, android.Manifest.permission.MANAGE_ACCOUNTS);
14777
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014778 return true;
14779 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014780
Amith Yamasani52f1d752012-03-28 18:19:29 -070014781 @Override
14782 public UserInfo getCurrentUser() throws RemoteException {
14783 final int callingUid = Binder.getCallingUid();
14784 if (callingUid != 0 && callingUid != Process.myUid()) {
14785 Slog.e(TAG, "Trying to get user from unauthorized app");
14786 return null;
14787 }
14788 return AppGlobals.getPackageManager().getUser(mCurrentUserId);
14789 }
14790
Amith Yamasani13593602012-03-22 16:16:17 -070014791 private void onUserRemoved(Intent intent) {
14792 int extraUserId = intent.getIntExtra(Intent.EXTRA_USERID, -1);
14793 if (extraUserId < 1) return;
14794
14795 // Kill all the processes for the user
14796 ArrayList<Pair<String, Integer>> pkgAndUids = new ArrayList<Pair<String,Integer>>();
14797 synchronized (this) {
14798 HashMap<String,SparseArray<ProcessRecord>> map = mProcessNames.getMap();
14799 for (Entry<String, SparseArray<ProcessRecord>> uidMap : map.entrySet()) {
14800 SparseArray<ProcessRecord> uids = uidMap.getValue();
14801 for (int i = 0; i < uids.size(); i++) {
14802 if (UserId.getUserId(uids.keyAt(i)) == extraUserId) {
14803 pkgAndUids.add(new Pair<String,Integer>(uidMap.getKey(), uids.keyAt(i)));
14804 }
14805 }
14806 }
14807
14808 for (Pair<String,Integer> pkgAndUid : pkgAndUids) {
14809 forceStopPackageLocked(pkgAndUid.first, pkgAndUid.second,
14810 false, false, true, true, extraUserId);
14811 }
14812 }
14813 }
14814
Amith Yamasani742a6712011-05-04 14:49:28 -070014815 private boolean userExists(int userId) {
14816 try {
Amith Yamasani13593602012-03-22 16:16:17 -070014817 UserInfo user = AppGlobals.getPackageManager().getUser(userId);
14818 return user != null;
Amith Yamasani742a6712011-05-04 14:49:28 -070014819 } catch (RemoteException re) {
14820 // Won't happen, in same process
14821 }
14822
14823 return false;
14824 }
14825
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014826 private void checkValidCaller(int uid, int userId) {
14827 if (UserId.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) return;
14828
14829 throw new SecurityException("Caller uid=" + uid
14830 + " is not privileged to communicate with user=" + userId);
14831 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014832
14833 private int applyUserId(int uid, int userId) {
14834 return UserId.getUid(userId, uid);
14835 }
14836
14837 private ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080014838 if (info == null) return null;
Amith Yamasani742a6712011-05-04 14:49:28 -070014839 ApplicationInfo newInfo = new ApplicationInfo(info);
14840 newInfo.uid = applyUserId(info.uid, userId);
14841 if (newInfo.uid >= Process.FIRST_APPLICATION_UID) {
14842 newInfo.dataDir = USER_DATA_DIR + userId + "/"
14843 + info.packageName;
14844 }
14845 return newInfo;
14846 }
14847
14848 ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080014849 if (aInfo == null || aInfo.applicationInfo.uid < Process.FIRST_APPLICATION_UID
Amith Yamasani742a6712011-05-04 14:49:28 -070014850 || userId < 1) {
14851 return aInfo;
14852 }
14853
14854 ActivityInfo info = new ActivityInfo(aInfo);
14855 info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId);
14856 return info;
14857 }
14858
14859 static class ServiceMap {
14860
14861 private final SparseArray<HashMap<ComponentName, ServiceRecord>> mServicesByNamePerUser
14862 = new SparseArray<HashMap<ComponentName, ServiceRecord>>();
14863 private final SparseArray<HashMap<Intent.FilterComparison, ServiceRecord>>
14864 mServicesByIntentPerUser = new SparseArray<
14865 HashMap<Intent.FilterComparison, ServiceRecord>>();
14866
14867 ServiceRecord getServiceByName(ComponentName name, int callingUser) {
14868 // TODO: Deal with global services
14869 if (DEBUG_MU)
14870 Slog.v(TAG_MU, "getServiceByName(" + name + "), callingUser = " + callingUser);
14871 return getServices(callingUser).get(name);
14872 }
14873
14874 ServiceRecord getServiceByName(ComponentName name) {
14875 return getServiceByName(name, -1);
14876 }
14877
14878 ServiceRecord getServiceByIntent(Intent.FilterComparison filter, int callingUser) {
14879 // TODO: Deal with global services
14880 if (DEBUG_MU)
14881 Slog.v(TAG_MU, "getServiceByIntent(" + filter + "), callingUser = " + callingUser);
14882 return getServicesByIntent(callingUser).get(filter);
14883 }
14884
14885 ServiceRecord getServiceByIntent(Intent.FilterComparison filter) {
14886 return getServiceByIntent(filter, -1);
14887 }
14888
14889 void putServiceByName(ComponentName name, int callingUser, ServiceRecord value) {
14890 // TODO: Deal with global services
14891 getServices(callingUser).put(name, value);
14892 }
14893
14894 void putServiceByIntent(Intent.FilterComparison filter, int callingUser,
14895 ServiceRecord value) {
14896 // TODO: Deal with global services
14897 getServicesByIntent(callingUser).put(filter, value);
14898 }
14899
14900 void removeServiceByName(ComponentName name, int callingUser) {
14901 // TODO: Deal with global services
14902 ServiceRecord removed = getServices(callingUser).remove(name);
14903 if (DEBUG_MU)
14904 Slog.v(TAG, "removeServiceByName user=" + callingUser + " name=" + name
14905 + " removed=" + removed);
14906 }
14907
14908 void removeServiceByIntent(Intent.FilterComparison filter, int callingUser) {
14909 // TODO: Deal with global services
14910 ServiceRecord removed = getServicesByIntent(callingUser).remove(filter);
14911 if (DEBUG_MU)
14912 Slog.v(TAG_MU, "removeServiceByIntent user=" + callingUser + " intent=" + filter
14913 + " removed=" + removed);
14914 }
14915
14916 Collection<ServiceRecord> getAllServices(int callingUser) {
14917 // TODO: Deal with global services
14918 return getServices(callingUser).values();
14919 }
14920
14921 private HashMap<ComponentName, ServiceRecord> getServices(int callingUser) {
14922 HashMap map = mServicesByNamePerUser.get(callingUser);
14923 if (map == null) {
14924 map = new HashMap<ComponentName, ServiceRecord>();
14925 mServicesByNamePerUser.put(callingUser, map);
14926 }
14927 return map;
14928 }
14929
14930 private HashMap<Intent.FilterComparison, ServiceRecord> getServicesByIntent(
14931 int callingUser) {
14932 HashMap map = mServicesByIntentPerUser.get(callingUser);
14933 if (map == null) {
14934 map = new HashMap<Intent.FilterComparison, ServiceRecord>();
14935 mServicesByIntentPerUser.put(callingUser, map);
14936 }
14937 return map;
14938 }
14939 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014940}