blob: 0c2e6acd7ee09d3d5861ab592f38a2ed6111919f [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 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008312
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008313 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 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008355
8356 long origId = Binder.clearCallingIdentity();
8357 boolean more = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008358 // Is the caller requesting to dump a particular piece of data?
8359 if (opti < args.length) {
8360 String cmd = args[opti];
8361 opti++;
8362 if ("activities".equals(cmd) || "a".equals(cmd)) {
8363 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008364 dumpActivitiesLocked(fd, pw, args, opti, true, dumpClient, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008365 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008366 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008367 String[] newArgs;
8368 String name;
8369 if (opti >= args.length) {
8370 name = null;
8371 newArgs = EMPTY_STRING_ARRAY;
8372 } else {
8373 name = args[opti];
8374 opti++;
8375 newArgs = new String[args.length - opti];
8376 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8377 args.length - opti);
8378 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008379 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008380 dumpBroadcastsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008381 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008382 } 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 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008398 } else if ("processes".equals(cmd) || "p".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008399 String[] newArgs;
8400 String name;
8401 if (opti >= args.length) {
8402 name = null;
8403 newArgs = EMPTY_STRING_ARRAY;
8404 } else {
8405 name = args[opti];
8406 opti++;
8407 newArgs = new String[args.length - opti];
8408 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8409 args.length - opti);
8410 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008411 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008412 dumpProcessesLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008413 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008414 } else if ("oom".equals(cmd) || "o".equals(cmd)) {
8415 synchronized (this) {
8416 dumpOomLocked(fd, pw, args, opti, true);
8417 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08008418 } else if ("provider".equals(cmd)) {
8419 String[] newArgs;
8420 String name;
8421 if (opti >= args.length) {
8422 name = null;
8423 newArgs = EMPTY_STRING_ARRAY;
8424 } else {
8425 name = args[opti];
8426 opti++;
8427 newArgs = new String[args.length - opti];
8428 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
8429 }
8430 if (!dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) {
8431 pw.println("No providers match: " + name);
8432 pw.println("Use -h for help.");
8433 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008434 } else if ("providers".equals(cmd) || "prov".equals(cmd)) {
8435 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008436 dumpProvidersLocked(fd, pw, args, opti, true, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008437 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008438 } else if ("service".equals(cmd)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008439 String[] newArgs;
8440 String name;
8441 if (opti >= args.length) {
8442 name = null;
8443 newArgs = EMPTY_STRING_ARRAY;
8444 } else {
8445 name = args[opti];
8446 opti++;
8447 newArgs = new String[args.length - opti];
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008448 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8449 args.length - opti);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008450 }
8451 if (!dumpService(fd, pw, name, newArgs, 0, dumpAll)) {
8452 pw.println("No services match: " + name);
8453 pw.println("Use -h for help.");
8454 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008455 } else if ("package".equals(cmd)) {
8456 String[] newArgs;
8457 if (opti >= args.length) {
8458 pw.println("package: no package name specified");
8459 pw.println("Use -h for help.");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008460 } else {
8461 dumpPackage = args[opti];
8462 opti++;
8463 newArgs = new String[args.length - opti];
8464 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8465 args.length - opti);
8466 args = newArgs;
8467 opti = 0;
Amith Yamasani7463ada2012-04-11 15:02:39 -07008468 more = true;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008469 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008470 } else if ("services".equals(cmd) || "s".equals(cmd)) {
8471 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008472 dumpServicesLocked(fd, pw, args, opti, true, dumpClient, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008473 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07008474 } else {
8475 // Dumping a single activity?
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008476 if (!dumpActivity(fd, pw, cmd, args, opti, dumpAll)) {
8477 pw.println("Bad activity command, or no activities match: " + cmd);
8478 pw.println("Use -h for help.");
Dianne Hackborn625ac272010-09-17 18:29:22 -07008479 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008480 }
8481 if (!more) {
8482 Binder.restoreCallingIdentity(origId);
Dianne Hackborn30d71892010-12-11 10:37:55 -08008483 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008484 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008485 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008486
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008487 // No piece of data specified, dump everything.
8488 synchronized (this) {
8489 boolean needSep;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008490 needSep = dumpPendingIntentsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008491 if (needSep) {
8492 pw.println(" ");
8493 }
8494 if (dumpAll) {
8495 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008496 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008497 needSep = dumpBroadcastsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008498 if (needSep) {
8499 pw.println(" ");
8500 }
8501 if (dumpAll) {
8502 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008503 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008504 needSep = dumpProvidersLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008505 if (needSep) {
8506 pw.println(" ");
8507 }
8508 if (dumpAll) {
8509 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008510 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008511 needSep = dumpServicesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008512 if (needSep) {
8513 pw.println(" ");
8514 }
8515 if (dumpAll) {
8516 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008517 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008518 needSep = dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008519 if (needSep) {
8520 pw.println(" ");
8521 }
8522 if (dumpAll) {
8523 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008524 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008525 dumpProcessesLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008526 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008527 Binder.restoreCallingIdentity(origId);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008528 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008529
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008530 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008531 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008532 pw.println("ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
8533 pw.println(" Main stack:");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008534 dumpHistoryList(fd, pw, mMainStack.mHistory, " ", "Hist", true, !dumpAll, dumpClient,
8535 dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008536 pw.println(" ");
8537 pw.println(" Running activities (most recent first):");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008538 dumpHistoryList(fd, pw, mMainStack.mLRUActivities, " ", "Run", false, !dumpAll, false,
8539 dumpPackage);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008540 if (mMainStack.mWaitingVisibleActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008541 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008542 pw.println(" Activities waiting for another to become visible:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008543 dumpHistoryList(fd, pw, mMainStack.mWaitingVisibleActivities, " ", "Wait", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008544 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008545 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008546 if (mMainStack.mStoppingActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008547 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008548 pw.println(" Activities waiting to stop:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008549 dumpHistoryList(fd, pw, mMainStack.mStoppingActivities, " ", "Stop", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008550 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008551 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008552 if (mMainStack.mGoingToSleepActivities.size() > 0) {
8553 pw.println(" ");
8554 pw.println(" Activities waiting to sleep:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008555 dumpHistoryList(fd, pw, mMainStack.mGoingToSleepActivities, " ", "Sleep", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008556 !dumpAll, false, dumpPackage);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008557 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008558 if (mMainStack.mFinishingActivities.size() > 0) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008559 pw.println(" ");
8560 pw.println(" Activities waiting to finish:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008561 dumpHistoryList(fd, pw, mMainStack.mFinishingActivities, " ", "Fin", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008562 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008563 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008564
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008565 pw.println(" ");
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08008566 if (mMainStack.mPausingActivity != null) {
8567 pw.println(" mPausingActivity: " + mMainStack.mPausingActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008568 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008569 pw.println(" mResumedActivity: " + mMainStack.mResumedActivity);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008570 pw.println(" mFocusedActivity: " + mFocusedActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008571 if (dumpAll) {
8572 pw.println(" mLastPausedActivity: " + mMainStack.mLastPausedActivity);
8573 pw.println(" mSleepTimeout: " + mMainStack.mSleepTimeout);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07008574 pw.println(" mDismissKeyguardOnNextActivity: "
8575 + mMainStack.mDismissKeyguardOnNextActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008576 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008577
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008578 if (mRecentTasks.size() > 0) {
8579 pw.println();
8580 pw.println(" Recent tasks:");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008581
8582 final int N = mRecentTasks.size();
8583 for (int i=0; i<N; i++) {
8584 TaskRecord tr = mRecentTasks.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008585 if (dumpPackage != null) {
8586 if (tr.realActivity == null ||
8587 !dumpPackage.equals(tr.realActivity)) {
8588 continue;
8589 }
8590 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008591 pw.print(" * Recent #"); pw.print(i); pw.print(": ");
8592 pw.println(tr);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008593 if (dumpAll) {
8594 mRecentTasks.get(i).dump(pw, " ");
8595 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008596 }
8597 }
8598
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008599 if (dumpAll) {
8600 pw.println(" ");
8601 pw.println(" mCurTask: " + mCurTask);
8602 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008603
8604 return true;
8605 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008606
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008607 boolean dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008608 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008609 boolean needSep = false;
8610 int numPers = 0;
8611
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008612 pw.println("ACTIVITY MANAGER RUNNING PROCESSES (dumpsys activity processes)");
8613
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008614 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008615 for (SparseArray<ProcessRecord> procs : mProcessNames.getMap().values()) {
8616 final int NA = procs.size();
8617 for (int ia=0; ia<NA; ia++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008618 ProcessRecord r = procs.valueAt(ia);
8619 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8620 continue;
8621 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008622 if (!needSep) {
8623 pw.println(" All known processes:");
8624 needSep = true;
8625 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008626 pw.print(r.persistent ? " *PERS*" : " *APP*");
8627 pw.print(" UID "); pw.print(procs.keyAt(ia));
8628 pw.print(" "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008629 r.dump(pw, " ");
8630 if (r.persistent) {
8631 numPers++;
8632 }
8633 }
8634 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008635 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008636
8637 if (mIsolatedProcesses.size() > 0) {
8638 if (needSep) pw.println(" ");
8639 needSep = true;
8640 pw.println(" Isolated process list (sorted by uid):");
8641 for (int i=0; i<mIsolatedProcesses.size(); i++) {
8642 ProcessRecord r = mIsolatedProcesses.valueAt(i);
8643 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8644 continue;
8645 }
8646 pw.println(String.format("%sIsolated #%2d: %s",
8647 " ", i, r.toString()));
8648 }
8649 }
8650
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008651 if (mLruProcesses.size() > 0) {
8652 if (needSep) pw.println(" ");
8653 needSep = true;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008654 pw.println(" Process LRU list (sorted by oom_adj):");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008655 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008656 "Proc", "PERS", false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008657 needSep = true;
8658 }
8659
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008660 if (dumpAll) {
8661 synchronized (mPidsSelfLocked) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008662 boolean printed = false;
8663 for (int i=0; i<mPidsSelfLocked.size(); i++) {
8664 ProcessRecord r = mPidsSelfLocked.valueAt(i);
8665 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8666 continue;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008667 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008668 if (!printed) {
8669 if (needSep) pw.println(" ");
8670 needSep = true;
8671 pw.println(" PID mappings:");
8672 printed = true;
8673 }
8674 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i));
8675 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008676 }
8677 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008678 }
8679
8680 if (mForegroundProcesses.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008681 synchronized (mPidsSelfLocked) {
8682 boolean printed = false;
8683 for (int i=0; i<mForegroundProcesses.size(); i++) {
8684 ProcessRecord r = mPidsSelfLocked.get(
8685 mForegroundProcesses.valueAt(i).pid);
8686 if (dumpPackage != null && (r == null
8687 || !dumpPackage.equals(r.info.packageName))) {
8688 continue;
8689 }
8690 if (!printed) {
8691 if (needSep) pw.println(" ");
8692 needSep = true;
8693 pw.println(" Foreground Processes:");
8694 printed = true;
8695 }
8696 pw.print(" PID #"); pw.print(mForegroundProcesses.keyAt(i));
8697 pw.print(": "); pw.println(mForegroundProcesses.valueAt(i));
8698 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008699 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008700 }
8701
8702 if (mPersistentStartingProcesses.size() > 0) {
8703 if (needSep) pw.println(" ");
8704 needSep = true;
8705 pw.println(" Persisent processes that are starting:");
8706 dumpProcessList(pw, this, mPersistentStartingProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008707 "Starting Norm", "Restarting PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008708 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008709
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008710 if (mRemovedProcesses.size() > 0) {
8711 if (needSep) pw.println(" ");
8712 needSep = true;
8713 pw.println(" Processes that are being removed:");
8714 dumpProcessList(pw, this, mRemovedProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008715 "Removed Norm", "Removed PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008716 }
8717
8718 if (mProcessesOnHold.size() > 0) {
8719 if (needSep) pw.println(" ");
8720 needSep = true;
8721 pw.println(" Processes that are on old until the system is ready:");
8722 dumpProcessList(pw, this, mProcessesOnHold, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008723 "OnHold Norm", "OnHold PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008724 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008725
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008726 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008727
8728 if (mProcessCrashTimes.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008729 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008730 long now = SystemClock.uptimeMillis();
8731 for (Map.Entry<String, SparseArray<Long>> procs
8732 : mProcessCrashTimes.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008733 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008734 SparseArray<Long> uids = procs.getValue();
8735 final int N = uids.size();
8736 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008737 int puid = uids.keyAt(i);
8738 ProcessRecord r = mProcessNames.get(pname, puid);
8739 if (dumpPackage != null && (r == null
8740 || !dumpPackage.equals(r.info.packageName))) {
8741 continue;
8742 }
8743 if (!printed) {
8744 if (needSep) pw.println(" ");
8745 needSep = true;
8746 pw.println(" Time since processes crashed:");
8747 printed = true;
8748 }
8749 pw.print(" Process "); pw.print(pname);
8750 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008751 pw.print(": last crashed ");
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008752 TimeUtils.formatDuration(now-uids.valueAt(i), pw);
8753 pw.println(" ago");
Dianne Hackbornfd12af42009-08-27 00:44:33 -07008754 }
8755 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008756 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008757
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008758 if (mBadProcesses.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008759 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008760 for (Map.Entry<String, SparseArray<Long>> procs
8761 : mBadProcesses.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008762 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008763 SparseArray<Long> uids = procs.getValue();
8764 final int N = uids.size();
8765 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008766 int puid = uids.keyAt(i);
8767 ProcessRecord r = mProcessNames.get(pname, puid);
8768 if (dumpPackage != null && (r == null
8769 || !dumpPackage.equals(r.info.packageName))) {
8770 continue;
8771 }
8772 if (!printed) {
8773 if (needSep) pw.println(" ");
8774 needSep = true;
8775 pw.println(" Bad processes:");
8776 }
8777 pw.print(" Bad process "); pw.print(pname);
8778 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008779 pw.print(": crashed at time ");
8780 pw.println(uids.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008781 }
8782 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008783 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008784
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008785 pw.println();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008786 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07008787 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn50685602011-12-01 12:23:37 -08008788 if (dumpAll) {
8789 StringBuilder sb = new StringBuilder(128);
8790 sb.append(" mPreviousProcessVisibleTime: ");
8791 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
8792 pw.println(sb);
8793 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07008794 if (mHeavyWeightProcess != null) {
8795 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
8796 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008797 pw.println(" mConfiguration: " + mConfiguration);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008798 if (dumpAll) {
8799 pw.println(" mConfigWillChange: " + mMainStack.mConfigWillChange);
Dianne Hackborn3d0724d2011-05-12 15:39:41 -07008800 if (mCompatModePackages.getPackages().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008801 boolean printed = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07008802 for (Map.Entry<String, Integer> entry
8803 : mCompatModePackages.getPackages().entrySet()) {
8804 String pkg = entry.getKey();
8805 int mode = entry.getValue();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008806 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
8807 continue;
8808 }
8809 if (!printed) {
8810 pw.println(" mScreenCompatPackages:");
8811 printed = true;
8812 }
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07008813 pw.print(" "); pw.print(pkg); pw.print(": ");
8814 pw.print(mode); pw.println();
8815 }
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07008816 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008817 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008818 pw.println(" mSleeping=" + mSleeping + " mShuttingDown=" + mShuttingDown);
8819 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
8820 || mOrigWaitForDebugger) {
8821 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp
8822 + " mDebugTransient=" + mDebugTransient
8823 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger);
8824 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08008825 if (mOpenGlTraceApp != null) {
8826 pw.println(" mOpenGlTraceApp=" + mOpenGlTraceApp);
8827 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07008828 if (mProfileApp != null || mProfileProc != null || mProfileFile != null
8829 || mProfileFd != null) {
8830 pw.println(" mProfileApp=" + mProfileApp + " mProfileProc=" + mProfileProc);
8831 pw.println(" mProfileFile=" + mProfileFile + " mProfileFd=" + mProfileFd);
8832 pw.println(" mProfileType=" + mProfileType + " mAutoStopProfiler="
8833 + mAutoStopProfiler);
8834 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008835 if (mAlwaysFinishActivities || mController != null) {
8836 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities
8837 + " mController=" + mController);
8838 }
8839 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008840 pw.println(" Total persistent processes: " + numPers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008841 pw.println(" mStartRunning=" + mStartRunning
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07008842 + " mProcessesReady=" + mProcessesReady
8843 + " mSystemReady=" + mSystemReady);
8844 pw.println(" mBooting=" + mBooting
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008845 + " mBooted=" + mBooted
8846 + " mFactoryTest=" + mFactoryTest);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008847 pw.print(" mLastPowerCheckRealtime=");
8848 TimeUtils.formatDuration(mLastPowerCheckRealtime, pw);
8849 pw.println("");
8850 pw.print(" mLastPowerCheckUptime=");
8851 TimeUtils.formatDuration(mLastPowerCheckUptime, pw);
8852 pw.println("");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008853 pw.println(" mGoingToSleep=" + mMainStack.mGoingToSleep);
8854 pw.println(" mLaunchingActivity=" + mMainStack.mLaunchingActivity);
Dianne Hackborn906497c2010-05-10 15:57:38 -07008855 pw.println(" mAdjSeq=" + mAdjSeq + " mLruSeq=" + mLruSeq);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008856 pw.println(" mNumServiceProcs=" + mNumServiceProcs
8857 + " mNewNumServiceProcs=" + mNewNumServiceProcs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008858 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008859
8860 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008861 }
8862
Dianne Hackborn287952c2010-09-22 22:34:31 -07008863 boolean dumpProcessesToGc(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008864 int opti, boolean needSep, boolean dumpAll, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07008865 if (mProcessesToGc.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008866 boolean printed = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -07008867 long now = SystemClock.uptimeMillis();
8868 for (int i=0; i<mProcessesToGc.size(); i++) {
8869 ProcessRecord proc = mProcessesToGc.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008870 if (dumpPackage != null && !dumpPackage.equals(proc.info.packageName)) {
8871 continue;
8872 }
8873 if (!printed) {
8874 if (needSep) pw.println(" ");
8875 needSep = true;
8876 pw.println(" Processes that are waiting to GC:");
8877 printed = true;
8878 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008879 pw.print(" Process "); pw.println(proc);
8880 pw.print(" lowMem="); pw.print(proc.reportLowMemory);
8881 pw.print(", last gced=");
8882 pw.print(now-proc.lastRequestedGc);
8883 pw.print(" ms ago, last lowMem=");
8884 pw.print(now-proc.lastLowMemory);
8885 pw.println(" ms ago");
8886
8887 }
8888 }
8889 return needSep;
8890 }
8891
8892 boolean dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args,
8893 int opti, boolean dumpAll) {
8894 boolean needSep = false;
8895
8896 if (mLruProcesses.size() > 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07008897 if (needSep) pw.println(" ");
8898 needSep = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -07008899 pw.println(" OOM levels:");
Dianne Hackborn7d608422011-08-07 16:24:18 -07008900 pw.print(" SYSTEM_ADJ: "); pw.println(ProcessList.SYSTEM_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008901 pw.print(" PERSISTENT_PROC_ADJ: "); pw.println(ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07008902 pw.print(" FOREGROUND_APP_ADJ: "); pw.println(ProcessList.FOREGROUND_APP_ADJ);
8903 pw.print(" VISIBLE_APP_ADJ: "); pw.println(ProcessList.VISIBLE_APP_ADJ);
8904 pw.print(" PERCEPTIBLE_APP_ADJ: "); pw.println(ProcessList.PERCEPTIBLE_APP_ADJ);
8905 pw.print(" HEAVY_WEIGHT_APP_ADJ: "); pw.println(ProcessList.HEAVY_WEIGHT_APP_ADJ);
8906 pw.print(" BACKUP_APP_ADJ: "); pw.println(ProcessList.BACKUP_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008907 pw.print(" SERVICE_ADJ: "); pw.println(ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07008908 pw.print(" HOME_APP_ADJ: "); pw.println(ProcessList.HOME_APP_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07008909 pw.print(" PREVIOUS_APP_ADJ: "); pw.println(ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008910 pw.print(" SERVICE_B_ADJ: "); pw.println(ProcessList.SERVICE_B_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07008911 pw.print(" HIDDEN_APP_MIN_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008912 pw.print(" HIDDEN_APP_MAX_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MAX_ADJ);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07008913
8914 if (needSep) pw.println(" ");
8915 needSep = true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07008916 pw.println(" Process OOM control:");
Dianne Hackborn905577f2011-09-07 18:31:28 -07008917 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008918 "Proc", "PERS", true, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008919 needSep = true;
8920 }
8921
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008922 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008923
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008924 pw.println();
Dianne Hackborn287952c2010-09-22 22:34:31 -07008925 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07008926 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008927 if (mHeavyWeightProcess != null) {
8928 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
8929 }
8930
8931 return true;
8932 }
8933
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008934 /**
8935 * There are three ways to call this:
8936 * - no service specified: dump all the services
8937 * - a flattened component name that matched an existing service was specified as the
8938 * first arg: dump that one service
8939 * - the first arg isn't the flattened component name of an existing service:
8940 * dump all services whose component contains the first arg as a substring
8941 */
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008942 protected boolean dumpService(FileDescriptor fd, PrintWriter pw, String name, String[] args,
8943 int opti, boolean dumpAll) {
8944 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008945
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008946 if ("all".equals(name)) {
Dianne Hackborn14bfa392010-07-24 19:58:06 -07008947 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07008948 try {
8949 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
8950 for (UserInfo user : users) {
8951 for (ServiceRecord r1 : mServiceMap.getAllServices(user.id)) {
8952 services.add(r1);
8953 }
8954 }
8955 } catch (RemoteException re) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008956 }
8957 }
8958 } else {
8959 ComponentName componentName = name != null
8960 ? ComponentName.unflattenFromString(name) : null;
8961 int objectId = 0;
8962 if (componentName == null) {
8963 // Not a '/' separated full component name; maybe an object ID?
8964 try {
8965 objectId = Integer.parseInt(name, 16);
8966 name = null;
8967 componentName = null;
8968 } catch (RuntimeException e) {
8969 }
8970 }
8971
8972 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07008973 try {
8974 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
8975 for (UserInfo user : users) {
8976 for (ServiceRecord r1 : mServiceMap.getAllServices(user.id)) {
8977 if (componentName != null) {
8978 if (r1.name.equals(componentName)) {
8979 services.add(r1);
8980 }
8981 } else if (name != null) {
8982 if (r1.name.flattenToString().contains(name)) {
8983 services.add(r1);
8984 }
8985 } else if (System.identityHashCode(r1) == objectId) {
8986 services.add(r1);
8987 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008988 }
Dianne Hackborn14bfa392010-07-24 19:58:06 -07008989 }
Amith Yamasani742a6712011-05-04 14:49:28 -07008990 } catch (RemoteException re) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008991 }
8992 }
8993 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008994
8995 if (services.size() <= 0) {
8996 return false;
8997 }
8998
8999 boolean needSep = false;
9000 for (int i=0; i<services.size(); i++) {
9001 if (needSep) {
9002 pw.println();
9003 }
9004 needSep = true;
9005 dumpService("", fd, pw, services.get(i), args, dumpAll);
9006 }
9007 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009008 }
9009
9010 /**
9011 * Invokes IApplicationThread.dumpService() on the thread of the specified service if
9012 * there is a thread associated with the service.
9013 */
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009014 private void dumpService(String prefix, FileDescriptor fd, PrintWriter pw,
9015 final ServiceRecord r, String[] args, boolean dumpAll) {
9016 String innerPrefix = prefix + " ";
9017 synchronized (this) {
9018 pw.print(prefix); pw.print("SERVICE ");
9019 pw.print(r.shortName); pw.print(" ");
9020 pw.print(Integer.toHexString(System.identityHashCode(r)));
9021 pw.print(" pid=");
9022 if (r.app != null) pw.println(r.app.pid);
9023 else pw.println("(not running)");
9024 if (dumpAll) {
9025 r.dump(pw, innerPrefix);
9026 }
9027 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009028 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009029 pw.print(prefix); pw.println(" Client:");
9030 pw.flush();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009031 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009032 TransferPipe tp = new TransferPipe();
9033 try {
9034 r.app.thread.dumpService(tp.getWriteFd().getFileDescriptor(), r, args);
9035 tp.setBufferPrefix(prefix + " ");
9036 tp.go(fd);
9037 } finally {
9038 tp.kill();
9039 }
9040 } catch (IOException e) {
9041 pw.println(prefix + " Failure while dumping the service: " + e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009042 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009043 pw.println(prefix + " Got a RemoteException while dumping the service");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009044 }
9045 }
9046 }
9047
Marco Nelissen18cb2872011-11-15 11:19:53 -08009048 /**
9049 * There are three ways to call this:
9050 * - no provider specified: dump all the providers
9051 * - a flattened component name that matched an existing provider was specified as the
9052 * first arg: dump that one provider
9053 * - the first arg isn't the flattened component name of an existing provider:
9054 * dump all providers whose component contains the first arg as a substring
9055 */
9056 protected boolean dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9057 int opti, boolean dumpAll) {
Marco Nelissende7408c2012-02-08 14:57:38 -08009058 return mProviderMap.dumpProvider(fd, pw, name, args, opti, dumpAll);
Marco Nelissen18cb2872011-11-15 11:19:53 -08009059 }
9060
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009061 static class ItemMatcher {
9062 ArrayList<ComponentName> components;
9063 ArrayList<String> strings;
9064 ArrayList<Integer> objects;
9065 boolean all;
9066
9067 ItemMatcher() {
9068 all = true;
9069 }
9070
9071 void build(String name) {
9072 ComponentName componentName = ComponentName.unflattenFromString(name);
9073 if (componentName != null) {
9074 if (components == null) {
9075 components = new ArrayList<ComponentName>();
9076 }
9077 components.add(componentName);
9078 all = false;
9079 } else {
9080 int objectId = 0;
9081 // Not a '/' separated full component name; maybe an object ID?
9082 try {
9083 objectId = Integer.parseInt(name, 16);
9084 if (objects == null) {
9085 objects = new ArrayList<Integer>();
9086 }
9087 objects.add(objectId);
9088 all = false;
9089 } catch (RuntimeException e) {
9090 // Not an integer; just do string match.
9091 if (strings == null) {
9092 strings = new ArrayList<String>();
9093 }
9094 strings.add(name);
9095 all = false;
9096 }
9097 }
9098 }
9099
9100 int build(String[] args, int opti) {
9101 for (; opti<args.length; opti++) {
9102 String name = args[opti];
9103 if ("--".equals(name)) {
9104 return opti+1;
9105 }
9106 build(name);
9107 }
9108 return opti;
9109 }
9110
9111 boolean match(Object object, ComponentName comp) {
9112 if (all) {
9113 return true;
9114 }
9115 if (components != null) {
9116 for (int i=0; i<components.size(); i++) {
9117 if (components.get(i).equals(comp)) {
9118 return true;
9119 }
9120 }
9121 }
9122 if (objects != null) {
9123 for (int i=0; i<objects.size(); i++) {
9124 if (System.identityHashCode(object) == objects.get(i)) {
9125 return true;
9126 }
9127 }
9128 }
9129 if (strings != null) {
9130 String flat = comp.flattenToString();
9131 for (int i=0; i<strings.size(); i++) {
9132 if (flat.contains(strings.get(i))) {
9133 return true;
9134 }
9135 }
9136 }
9137 return false;
9138 }
9139 }
9140
Dianne Hackborn625ac272010-09-17 18:29:22 -07009141 /**
9142 * There are three things that cmd can be:
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009143 * - a flattened component name that matches an existing activity
Dianne Hackborn625ac272010-09-17 18:29:22 -07009144 * - the cmd arg isn't the flattened component name of an existing activity:
9145 * dump all activity whose component contains the cmd as a substring
9146 * - A hex number of the ActivityRecord object instance.
9147 */
9148 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9149 int opti, boolean dumpAll) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009150 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009151
9152 if ("all".equals(name)) {
9153 synchronized (this) {
9154 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009155 activities.add(r1);
9156 }
9157 }
Dianne Hackbornf9302322011-06-14 18:36:14 -07009158 } else if ("top".equals(name)) {
9159 synchronized (this) {
9160 final int N = mMainStack.mHistory.size();
9161 if (N > 0) {
9162 activities.add((ActivityRecord)mMainStack.mHistory.get(N-1));
9163 }
9164 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009165 } else {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009166 ItemMatcher matcher = new ItemMatcher();
9167 matcher.build(name);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009168
9169 synchronized (this) {
9170 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009171 if (matcher.match(r1, r1.intent.getComponent())) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009172 activities.add(r1);
9173 }
9174 }
9175 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009176 }
9177
9178 if (activities.size() <= 0) {
9179 return false;
9180 }
9181
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009182 String[] newArgs = new String[args.length - opti];
9183 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
9184
Dianne Hackborn30d71892010-12-11 10:37:55 -08009185 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009186 boolean needSep = false;
Dianne Hackborn30d71892010-12-11 10:37:55 -08009187 for (int i=activities.size()-1; i>=0; i--) {
9188 ActivityRecord r = (ActivityRecord)activities.get(i);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009189 if (needSep) {
9190 pw.println();
9191 }
9192 needSep = true;
9193 synchronized (this) {
9194 if (lastTask != r.task) {
9195 lastTask = r.task;
9196 pw.print("TASK "); pw.print(lastTask.affinity);
9197 pw.print(" id="); pw.println(lastTask.taskId);
9198 if (dumpAll) {
9199 lastTask.dump(pw, " ");
9200 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08009201 }
9202 }
9203 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009204 }
9205 return true;
9206 }
9207
9208 /**
9209 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
9210 * there is a thread associated with the activity.
9211 */
Dianne Hackborn30d71892010-12-11 10:37:55 -08009212 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009213 final ActivityRecord r, String[] args, boolean dumpAll) {
9214 String innerPrefix = prefix + " ";
Dianne Hackborn30d71892010-12-11 10:37:55 -08009215 synchronized (this) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009216 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
9217 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
9218 pw.print(" pid=");
Dianne Hackborn30d71892010-12-11 10:37:55 -08009219 if (r.app != null) pw.println(r.app.pid);
9220 else pw.println("(not running)");
9221 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009222 r.dump(pw, innerPrefix);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009223 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009224 }
9225 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009226 // flush anything that is already in the PrintWriter since the thread is going
9227 // to write to the file descriptor directly
9228 pw.flush();
Dianne Hackborn625ac272010-09-17 18:29:22 -07009229 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009230 TransferPipe tp = new TransferPipe();
9231 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009232 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9233 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009234 tp.go(fd);
9235 } finally {
9236 tp.kill();
9237 }
9238 } catch (IOException e) {
9239 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009240 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009241 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
Dianne Hackborn625ac272010-09-17 18:29:22 -07009242 }
9243 }
9244 }
9245
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009246 boolean dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009247 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009248 boolean needSep = false;
9249
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009250 pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009251 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009252 if (mRegisteredReceivers.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009253 boolean printed = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009254 Iterator it = mRegisteredReceivers.values().iterator();
9255 while (it.hasNext()) {
9256 ReceiverList r = (ReceiverList)it.next();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009257 if (dumpPackage != null && (r.app == null ||
9258 !dumpPackage.equals(r.app.info.packageName))) {
9259 continue;
9260 }
9261 if (!printed) {
9262 pw.println(" Registered Receivers:");
9263 needSep = true;
9264 printed = true;
9265 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009266 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009267 r.dump(pw, " ");
9268 }
9269 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009270
9271 if (mReceiverResolver.dump(pw, needSep ?
9272 "\n Receiver Resolver Table:" : " Receiver Resolver Table:",
9273 " ", dumpPackage, false)) {
9274 needSep = true;
9275 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009276 }
Christopher Tatef46723b2012-01-26 14:19:24 -08009277
9278 for (BroadcastQueue q : mBroadcastQueues) {
9279 needSep = q.dumpLocked(fd, pw, args, opti, dumpAll, dumpPackage, needSep);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009280 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009281
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009282 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009283
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009284 if (mStickyBroadcasts != null && dumpPackage == null) {
9285 if (needSep) {
9286 pw.println();
9287 }
9288 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009289 pw.println(" Sticky broadcasts:");
9290 StringBuilder sb = new StringBuilder(128);
9291 for (Map.Entry<String, ArrayList<Intent>> ent
9292 : mStickyBroadcasts.entrySet()) {
9293 pw.print(" * Sticky action "); pw.print(ent.getKey());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009294 if (dumpAll) {
9295 pw.println(":");
9296 ArrayList<Intent> intents = ent.getValue();
9297 final int N = intents.size();
9298 for (int i=0; i<N; i++) {
9299 sb.setLength(0);
9300 sb.append(" Intent: ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009301 intents.get(i).toShortString(sb, false, true, false, false);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009302 pw.println(sb.toString());
9303 Bundle bundle = intents.get(i).getExtras();
9304 if (bundle != null) {
9305 pw.print(" ");
9306 pw.println(bundle.toString());
9307 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009308 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009309 } else {
9310 pw.println("");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009311 }
9312 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009313 needSep = true;
9314 }
9315
9316 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009317 pw.println();
Christopher Tatef46723b2012-01-26 14:19:24 -08009318 for (BroadcastQueue queue : mBroadcastQueues) {
9319 pw.println(" mBroadcastsScheduled [" + queue.mQueueName + "]="
9320 + queue.mBroadcastsScheduled);
9321 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009322 pw.println(" mHandler:");
9323 mHandler.dump(new PrintWriterPrinter(pw), " ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009324 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009325 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009326
9327 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009328 }
9329
Marco Nelissen18cb2872011-11-15 11:19:53 -08009330 /**
9331 * Prints a list of ServiceRecords (dumpsys activity services)
9332 */
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009333 boolean dumpServicesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009334 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009335 boolean needSep = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009336
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009337 ItemMatcher matcher = new ItemMatcher();
9338 matcher.build(args, opti);
9339
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009340 pw.println("ACTIVITY MANAGER SERVICES (dumpsys activity services)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009341 try {
9342 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
9343 for (UserInfo user : users) {
9344 if (mServiceMap.getAllServices(user.id).size() > 0) {
9345 boolean printed = false;
9346 long nowReal = SystemClock.elapsedRealtime();
9347 Iterator<ServiceRecord> it = mServiceMap.getAllServices(
9348 user.id).iterator();
9349 needSep = false;
9350 while (it.hasNext()) {
9351 ServiceRecord r = it.next();
9352 if (!matcher.match(r, r.name)) {
9353 continue;
9354 }
9355 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9356 continue;
9357 }
9358 if (!printed) {
9359 pw.println(" Active services:");
9360 printed = true;
9361 }
9362 if (needSep) {
9363 pw.println();
9364 }
9365 pw.print(" * ");
9366 pw.println(r);
9367 if (dumpAll) {
9368 r.dump(pw, " ");
9369 needSep = true;
9370 } else {
9371 pw.print(" app=");
9372 pw.println(r.app);
9373 pw.print(" created=");
9374 TimeUtils.formatDuration(r.createTime, nowReal, pw);
9375 pw.print(" started=");
9376 pw.print(r.startRequested);
9377 pw.print(" connections=");
9378 pw.println(r.connections.size());
9379 if (r.connections.size() > 0) {
9380 pw.println(" Connections:");
9381 for (ArrayList<ConnectionRecord> clist : r.connections.values()) {
9382 for (int i = 0; i < clist.size(); i++) {
9383 ConnectionRecord conn = clist.get(i);
9384 pw.print(" ");
9385 pw.print(conn.binding.intent.intent.getIntent()
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009386 .toShortString(false, false, false, false));
Amith Yamasani742a6712011-05-04 14:49:28 -07009387 pw.print(" -> ");
9388 ProcessRecord proc = conn.binding.client;
9389 pw.println(proc != null ? proc.toShortString() : "null");
9390 }
9391 }
Dianne Hackborn8ec8d412011-11-14 18:27:24 -08009392 }
9393 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009394 if (dumpClient && r.app != null && r.app.thread != null) {
9395 pw.println(" Client:");
9396 pw.flush();
9397 try {
9398 TransferPipe tp = new TransferPipe();
9399 try {
9400 r.app.thread.dumpService(tp.getWriteFd().getFileDescriptor(),
9401 r, args);
9402 tp.setBufferPrefix(" ");
9403 // Short timeout, since blocking here can
9404 // deadlock with the application.
9405 tp.go(fd, 2000);
9406 } finally {
9407 tp.kill();
9408 }
9409 } catch (IOException e) {
9410 pw.println(" Failure while dumping the service: " + e);
9411 } catch (RemoteException e) {
9412 pw.println(" Got a RemoteException while dumping the service");
9413 }
9414 needSep = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009415 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009416 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009417 needSep = printed;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009418 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009419 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009420 } catch (RemoteException re) {
9421
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009422 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009423
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009424 if (mPendingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009425 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009426 for (int i=0; i<mPendingServices.size(); i++) {
9427 ServiceRecord r = mPendingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009428 if (!matcher.match(r, r.name)) {
9429 continue;
9430 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009431 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9432 continue;
9433 }
9434 if (!printed) {
9435 if (needSep) pw.println(" ");
9436 needSep = true;
9437 pw.println(" Pending services:");
9438 printed = true;
9439 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009440 pw.print(" * Pending "); pw.println(r);
9441 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009442 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009443 needSep = true;
9444 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009445
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009446 if (mRestartingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009447 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009448 for (int i=0; i<mRestartingServices.size(); i++) {
9449 ServiceRecord r = mRestartingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009450 if (!matcher.match(r, r.name)) {
9451 continue;
9452 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009453 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9454 continue;
9455 }
9456 if (!printed) {
9457 if (needSep) pw.println(" ");
9458 needSep = true;
9459 pw.println(" Restarting services:");
9460 printed = true;
9461 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009462 pw.print(" * Restarting "); pw.println(r);
9463 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009464 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009465 needSep = true;
9466 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009467
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009468 if (mStoppingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009469 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009470 for (int i=0; i<mStoppingServices.size(); i++) {
9471 ServiceRecord r = mStoppingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009472 if (!matcher.match(r, r.name)) {
9473 continue;
9474 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009475 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9476 continue;
9477 }
9478 if (!printed) {
9479 if (needSep) pw.println(" ");
9480 needSep = true;
9481 pw.println(" Stopping services:");
9482 printed = true;
9483 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009484 pw.print(" * Stopping "); pw.println(r);
9485 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009486 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009487 needSep = true;
9488 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009489
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009490 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009491 if (mServiceConnections.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009492 boolean printed = false;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009493 Iterator<ArrayList<ConnectionRecord>> it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009494 = mServiceConnections.values().iterator();
9495 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009496 ArrayList<ConnectionRecord> r = it.next();
9497 for (int i=0; i<r.size(); i++) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009498 ConnectionRecord cr = r.get(i);
9499 if (!matcher.match(cr.binding.service, cr.binding.service.name)) {
9500 continue;
9501 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009502 if (dumpPackage != null && (cr.binding.client == null
9503 || !dumpPackage.equals(cr.binding.client.info.packageName))) {
9504 continue;
9505 }
9506 if (!printed) {
9507 if (needSep) pw.println(" ");
9508 needSep = true;
9509 pw.println(" Connection bindings to services:");
9510 printed = true;
9511 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009512 pw.print(" * "); pw.println(cr);
9513 cr.dump(pw, " ");
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009514 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009515 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009516 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009517 }
9518 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009519
9520 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009521 }
9522
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009523 boolean dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009524 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07009525 boolean needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009526
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009527 ItemMatcher matcher = new ItemMatcher();
9528 matcher.build(args, opti);
9529
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009530 pw.println("ACTIVITY MANAGER CONTENT PROVIDERS (dumpsys activity providers)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009531
9532 mProviderMap.dumpProvidersLocked(pw, dumpAll);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009533
9534 if (mLaunchingProviders.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009535 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009536 for (int i=mLaunchingProviders.size()-1; i>=0; i--) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009537 ContentProviderRecord r = mLaunchingProviders.get(i);
9538 if (dumpPackage != null && !dumpPackage.equals(r.name.getPackageName())) {
9539 continue;
9540 }
9541 if (!printed) {
9542 if (needSep) pw.println(" ");
9543 needSep = true;
9544 pw.println(" Launching content providers:");
9545 printed = true;
9546 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009547 pw.print(" Launching #"); pw.print(i); pw.print(": ");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009548 pw.println(r);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009549 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009550 }
9551
9552 if (mGrantedUriPermissions.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009553 if (needSep) pw.println();
9554 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009555 pw.println("Granted Uri Permissions:");
9556 for (int i=0; i<mGrantedUriPermissions.size(); i++) {
9557 int uid = mGrantedUriPermissions.keyAt(i);
9558 HashMap<Uri, UriPermission> perms
9559 = mGrantedUriPermissions.valueAt(i);
9560 pw.print(" * UID "); pw.print(uid);
9561 pw.println(" holds:");
9562 for (UriPermission perm : perms.values()) {
9563 pw.print(" "); pw.println(perm);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009564 if (dumpAll) {
9565 perm.dump(pw, " ");
9566 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009567 }
9568 }
9569 needSep = true;
9570 }
9571
9572 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009573 }
9574
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009575 boolean dumpPendingIntentsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009576 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009577 boolean needSep = false;
9578
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009579 if (mIntentSenderRecords.size() > 0) {
9580 boolean printed = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009581 Iterator<WeakReference<PendingIntentRecord>> it
9582 = mIntentSenderRecords.values().iterator();
9583 while (it.hasNext()) {
9584 WeakReference<PendingIntentRecord> ref = it.next();
9585 PendingIntentRecord rec = ref != null ? ref.get(): null;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009586 if (dumpPackage != null && (rec == null
9587 || !dumpPackage.equals(rec.key.packageName))) {
9588 continue;
9589 }
9590 if (!printed) {
9591 pw.println("ACTIVITY MANAGER PENDING INTENTS (dumpsys activity intents)");
9592 printed = true;
9593 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009594 needSep = true;
9595 if (rec != null) {
9596 pw.print(" * "); pw.println(rec);
9597 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009598 rec.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009599 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009600 } else {
9601 pw.print(" * "); pw.println(ref);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009602 }
9603 }
9604 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009605
9606 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009607 }
9608
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009609 private static final void dumpHistoryList(FileDescriptor fd, PrintWriter pw, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009610 String prefix, String label, boolean complete, boolean brief, boolean client,
9611 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009612 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009613 boolean needNL = false;
9614 final String innerPrefix = prefix + " ";
9615 final String[] args = new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009616 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009617 final ActivityRecord r = (ActivityRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009618 if (dumpPackage != null && !dumpPackage.equals(r.packageName)) {
9619 continue;
9620 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07009621 final boolean full = !brief && (complete || !r.isInHistory());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009622 if (needNL) {
9623 pw.println(" ");
9624 needNL = false;
9625 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009626 if (lastTask != r.task) {
9627 lastTask = r.task;
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009628 pw.print(prefix);
9629 pw.print(full ? "* " : " ");
9630 pw.println(lastTask);
9631 if (full) {
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009632 lastTask.dump(pw, prefix + " ");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009633 } else if (complete) {
9634 // Complete + brief == give a summary. Isn't that obvious?!?
9635 if (lastTask.intent != null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009636 pw.print(prefix); pw.print(" ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009637 pw.println(lastTask.intent.toInsecureStringWithClip());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009638 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009639 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009640 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009641 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label);
9642 pw.print(" #"); pw.print(i); pw.print(": ");
9643 pw.println(r);
9644 if (full) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009645 r.dump(pw, innerPrefix);
9646 } else if (complete) {
9647 // Complete + brief == give a summary. Isn't that obvious?!?
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009648 pw.print(innerPrefix); pw.println(r.intent.toInsecureString());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009649 if (r.app != null) {
9650 pw.print(innerPrefix); pw.println(r.app);
9651 }
9652 }
9653 if (client && r.app != null && r.app.thread != null) {
9654 // flush anything that is already in the PrintWriter since the thread is going
9655 // to write to the file descriptor directly
9656 pw.flush();
9657 try {
9658 TransferPipe tp = new TransferPipe();
9659 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009660 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9661 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009662 // Short timeout, since blocking here can
9663 // deadlock with the application.
9664 tp.go(fd, 2000);
9665 } finally {
9666 tp.kill();
9667 }
9668 } catch (IOException e) {
9669 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
9670 } catch (RemoteException e) {
9671 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
9672 }
9673 needNL = true;
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009674 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009675 }
9676 }
9677
Dianne Hackborn09c916b2009-12-08 14:50:51 -08009678 private static String buildOomTag(String prefix, String space, int val, int base) {
9679 if (val == base) {
9680 if (space == null) return prefix;
9681 return prefix + " ";
9682 }
9683 return prefix + "+" + Integer.toString(val-base);
9684 }
9685
9686 private static final int dumpProcessList(PrintWriter pw,
9687 ActivityManagerService service, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009688 String prefix, String normalLabel, String persistentLabel,
9689 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009690 int numPers = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07009691 final int N = list.size()-1;
9692 for (int i=N; i>=0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009693 ProcessRecord r = (ProcessRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009694 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9695 continue;
9696 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009697 pw.println(String.format("%s%s #%2d: %s",
9698 prefix, (r.persistent ? persistentLabel : normalLabel),
9699 i, r.toString()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009700 if (r.persistent) {
9701 numPers++;
9702 }
9703 }
9704 return numPers;
9705 }
9706
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009707 private static final boolean dumpProcessOomList(PrintWriter pw,
Dianne Hackborn905577f2011-09-07 18:31:28 -07009708 ActivityManagerService service, List<ProcessRecord> origList,
Dianne Hackborn287952c2010-09-22 22:34:31 -07009709 String prefix, String normalLabel, String persistentLabel,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009710 boolean inclDetails, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009711
Dianne Hackborn905577f2011-09-07 18:31:28 -07009712 ArrayList<Pair<ProcessRecord, Integer>> list
9713 = new ArrayList<Pair<ProcessRecord, Integer>>(origList.size());
9714 for (int i=0; i<origList.size(); i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009715 ProcessRecord r = origList.get(i);
9716 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9717 continue;
9718 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07009719 list.add(new Pair<ProcessRecord, Integer>(origList.get(i), i));
9720 }
9721
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009722 if (list.size() <= 0) {
9723 return false;
9724 }
9725
Dianne Hackborn905577f2011-09-07 18:31:28 -07009726 Comparator<Pair<ProcessRecord, Integer>> comparator
9727 = new Comparator<Pair<ProcessRecord, Integer>>() {
9728 @Override
9729 public int compare(Pair<ProcessRecord, Integer> object1,
9730 Pair<ProcessRecord, Integer> object2) {
9731 if (object1.first.setAdj != object2.first.setAdj) {
9732 return object1.first.setAdj > object2.first.setAdj ? -1 : 1;
9733 }
9734 if (object1.second.intValue() != object2.second.intValue()) {
9735 return object1.second.intValue() > object2.second.intValue() ? -1 : 1;
9736 }
9737 return 0;
9738 }
9739 };
9740
9741 Collections.sort(list, comparator);
9742
Dianne Hackborn287952c2010-09-22 22:34:31 -07009743 final long curRealtime = SystemClock.elapsedRealtime();
9744 final long realtimeSince = curRealtime - service.mLastPowerCheckRealtime;
9745 final long curUptime = SystemClock.uptimeMillis();
9746 final long uptimeSince = curUptime - service.mLastPowerCheckUptime;
9747
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009748 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07009749 ProcessRecord r = list.get(i).first;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009750 String oomAdj;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009751 if (r.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07009752 oomAdj = buildOomTag("bak", " ", r.setAdj, ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009753 } else if (r.setAdj >= ProcessList.SERVICE_B_ADJ) {
9754 oomAdj = buildOomTag("svcb ", null, r.setAdj, ProcessList.SERVICE_B_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009755 } else if (r.setAdj >= ProcessList.PREVIOUS_APP_ADJ) {
9756 oomAdj = buildOomTag("prev ", null, r.setAdj, ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009757 } else if (r.setAdj >= ProcessList.HOME_APP_ADJ) {
9758 oomAdj = buildOomTag("home ", null, r.setAdj, ProcessList.HOME_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009759 } else if (r.setAdj >= ProcessList.SERVICE_ADJ) {
9760 oomAdj = buildOomTag("svc ", null, r.setAdj, ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009761 } else if (r.setAdj >= ProcessList.BACKUP_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08009762 oomAdj = buildOomTag("bkup ", null, r.setAdj, ProcessList.BACKUP_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009763 } else if (r.setAdj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
9764 oomAdj = buildOomTag("hvy ", null, r.setAdj, ProcessList.HEAVY_WEIGHT_APP_ADJ);
9765 } else if (r.setAdj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
9766 oomAdj = buildOomTag("prcp ", null, r.setAdj, ProcessList.PERCEPTIBLE_APP_ADJ);
9767 } else if (r.setAdj >= ProcessList.VISIBLE_APP_ADJ) {
9768 oomAdj = buildOomTag("vis ", null, r.setAdj, ProcessList.VISIBLE_APP_ADJ);
9769 } else if (r.setAdj >= ProcessList.FOREGROUND_APP_ADJ) {
9770 oomAdj = buildOomTag("fore ", null, r.setAdj, ProcessList.FOREGROUND_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009771 } else if (r.setAdj >= ProcessList.PERSISTENT_PROC_ADJ) {
9772 oomAdj = buildOomTag("pers ", null, r.setAdj, ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009773 } else if (r.setAdj >= ProcessList.SYSTEM_ADJ) {
9774 oomAdj = buildOomTag("sys ", null, r.setAdj, ProcessList.SYSTEM_ADJ);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009775 } else {
9776 oomAdj = Integer.toString(r.setAdj);
9777 }
9778 String schedGroup;
9779 switch (r.setSchedGroup) {
9780 case Process.THREAD_GROUP_BG_NONINTERACTIVE:
9781 schedGroup = "B";
9782 break;
9783 case Process.THREAD_GROUP_DEFAULT:
9784 schedGroup = "F";
9785 break;
9786 default:
9787 schedGroup = Integer.toString(r.setSchedGroup);
9788 break;
9789 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07009790 String foreground;
9791 if (r.foregroundActivities) {
9792 foreground = "A";
9793 } else if (r.foregroundServices) {
9794 foreground = "S";
9795 } else {
9796 foreground = " ";
9797 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07009798 pw.println(String.format("%s%s #%2d: adj=%s/%s%s trm=%2d %s (%s)",
Dianne Hackborn287952c2010-09-22 22:34:31 -07009799 prefix, (r.persistent ? persistentLabel : normalLabel),
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009800 (origList.size()-1)-list.get(i).second, oomAdj, schedGroup,
9801 foreground, r.trimMemoryLevel, r.toShortString(), r.adjType));
Dianne Hackborn287952c2010-09-22 22:34:31 -07009802 if (r.adjSource != null || r.adjTarget != null) {
9803 pw.print(prefix);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009804 pw.print(" ");
Dianne Hackborn287952c2010-09-22 22:34:31 -07009805 if (r.adjTarget instanceof ComponentName) {
9806 pw.print(((ComponentName)r.adjTarget).flattenToShortString());
9807 } else if (r.adjTarget != null) {
9808 pw.print(r.adjTarget.toString());
9809 } else {
9810 pw.print("{null}");
9811 }
9812 pw.print("<=");
9813 if (r.adjSource instanceof ProcessRecord) {
9814 pw.print("Proc{");
9815 pw.print(((ProcessRecord)r.adjSource).toShortString());
9816 pw.println("}");
9817 } else if (r.adjSource != null) {
9818 pw.println(r.adjSource.toString());
9819 } else {
9820 pw.println("{null}");
9821 }
9822 }
9823 if (inclDetails) {
9824 pw.print(prefix);
9825 pw.print(" ");
9826 pw.print("oom: max="); pw.print(r.maxAdj);
9827 pw.print(" hidden="); pw.print(r.hiddenAdj);
9828 pw.print(" curRaw="); pw.print(r.curRawAdj);
9829 pw.print(" setRaw="); pw.print(r.setRawAdj);
9830 pw.print(" cur="); pw.print(r.curAdj);
9831 pw.print(" set="); pw.println(r.setAdj);
9832 pw.print(prefix);
9833 pw.print(" ");
9834 pw.print("keeping="); pw.print(r.keeping);
9835 pw.print(" hidden="); pw.print(r.hidden);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009836 pw.print(" empty="); pw.print(r.empty);
9837 pw.print(" hasAboveClient="); pw.println(r.hasAboveClient);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009838
9839 if (!r.keeping) {
9840 if (r.lastWakeTime != 0) {
9841 long wtime;
9842 BatteryStatsImpl stats = service.mBatteryStatsService.getActiveStatistics();
9843 synchronized (stats) {
9844 wtime = stats.getProcessWakeTime(r.info.uid,
9845 r.pid, curRealtime);
9846 }
9847 long timeUsed = wtime - r.lastWakeTime;
9848 pw.print(prefix);
9849 pw.print(" ");
9850 pw.print("keep awake over ");
9851 TimeUtils.formatDuration(realtimeSince, pw);
9852 pw.print(" used ");
9853 TimeUtils.formatDuration(timeUsed, pw);
9854 pw.print(" (");
9855 pw.print((timeUsed*100)/realtimeSince);
9856 pw.println("%)");
9857 }
9858 if (r.lastCpuTime != 0) {
9859 long timeUsed = r.curCpuTime - r.lastCpuTime;
9860 pw.print(prefix);
9861 pw.print(" ");
9862 pw.print("run cpu over ");
9863 TimeUtils.formatDuration(uptimeSince, pw);
9864 pw.print(" used ");
9865 TimeUtils.formatDuration(timeUsed, pw);
9866 pw.print(" (");
9867 pw.print((timeUsed*100)/uptimeSince);
9868 pw.println("%)");
9869 }
9870 }
9871 }
9872 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009873 return true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009874 }
9875
Dianne Hackbornb437e092011-08-05 17:50:29 -07009876 ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, String[] args) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009877 ArrayList<ProcessRecord> procs;
9878 synchronized (this) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009879 if (args != null && args.length > start
9880 && args[start].charAt(0) != '-') {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009881 procs = new ArrayList<ProcessRecord>();
9882 int pid = -1;
9883 try {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009884 pid = Integer.parseInt(args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009885 } catch (NumberFormatException e) {
9886
9887 }
9888 for (int i=mLruProcesses.size()-1; i>=0; i--) {
9889 ProcessRecord proc = mLruProcesses.get(i);
9890 if (proc.pid == pid) {
9891 procs.add(proc);
Dianne Hackbornb437e092011-08-05 17:50:29 -07009892 } else if (proc.processName.equals(args[start])) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009893 procs.add(proc);
9894 }
9895 }
9896 if (procs.size() <= 0) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009897 pw.println("No process found for: " + args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009898 return null;
9899 }
9900 } else {
9901 procs = new ArrayList<ProcessRecord>(mLruProcesses);
9902 }
9903 }
9904 return procs;
9905 }
9906
9907 final void dumpGraphicsHardwareUsage(FileDescriptor fd,
9908 PrintWriter pw, String[] args) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009909 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009910 if (procs == null) {
9911 return;
9912 }
9913
9914 long uptime = SystemClock.uptimeMillis();
9915 long realtime = SystemClock.elapsedRealtime();
9916 pw.println("Applications Graphics Acceleration Info:");
9917 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
9918
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009919 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
9920 ProcessRecord r = procs.get(i);
Chet Haase9c1e23b2011-03-24 10:51:31 -07009921 if (r.thread != null) {
9922 pw.println("\n** Graphics info for pid " + r.pid + " [" + r.processName + "] **");
9923 pw.flush();
9924 try {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009925 TransferPipe tp = new TransferPipe();
9926 try {
9927 r.thread.dumpGfxInfo(tp.getWriteFd().getFileDescriptor(), args);
9928 tp.go(fd);
9929 } finally {
9930 tp.kill();
9931 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009932 } catch (IOException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009933 pw.println("Failure while dumping the app: " + r);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009934 pw.flush();
Chet Haase9c1e23b2011-03-24 10:51:31 -07009935 } catch (RemoteException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009936 pw.println("Got a RemoteException while dumping the app " + r);
Chet Haase9c1e23b2011-03-24 10:51:31 -07009937 pw.flush();
9938 }
9939 }
9940 }
Chet Haase9c1e23b2011-03-24 10:51:31 -07009941 }
9942
Jeff Brown6754ba22011-12-14 20:20:01 -08009943 final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) {
9944 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
9945 if (procs == null) {
9946 return;
9947 }
9948
9949 pw.println("Applications Database Info:");
9950
9951 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
9952 ProcessRecord r = procs.get(i);
9953 if (r.thread != null) {
9954 pw.println("\n** Database info for pid " + r.pid + " [" + r.processName + "] **");
9955 pw.flush();
9956 try {
9957 TransferPipe tp = new TransferPipe();
9958 try {
9959 r.thread.dumpDbInfo(tp.getWriteFd().getFileDescriptor(), args);
9960 tp.go(fd);
9961 } finally {
9962 tp.kill();
9963 }
9964 } catch (IOException e) {
9965 pw.println("Failure while dumping the app: " + r);
9966 pw.flush();
9967 } catch (RemoteException e) {
9968 pw.println("Got a RemoteException while dumping the app " + r);
9969 pw.flush();
9970 }
9971 }
9972 }
9973 }
9974
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009975 final static class MemItem {
9976 final String label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009977 final String shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009978 final long pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009979 final int id;
Dianne Hackborna4bacb82011-08-24 15:12:38 -07009980 ArrayList<MemItem> subitems;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009981
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009982 public MemItem(String _label, String _shortLabel, long _pss, int _id) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009983 label = _label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009984 shortLabel = _shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009985 pss = _pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009986 id = _id;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009987 }
9988 }
9989
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009990 static final void dumpMemItems(PrintWriter pw, String prefix, ArrayList<MemItem> items,
Dianne Hackbornb437e092011-08-05 17:50:29 -07009991 boolean sort) {
9992 if (sort) {
9993 Collections.sort(items, new Comparator<MemItem>() {
9994 @Override
9995 public int compare(MemItem lhs, MemItem rhs) {
9996 if (lhs.pss < rhs.pss) {
9997 return 1;
9998 } else if (lhs.pss > rhs.pss) {
9999 return -1;
10000 }
10001 return 0;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010002 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010003 });
10004 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010005
10006 for (int i=0; i<items.size(); i++) {
10007 MemItem mi = items.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010008 pw.print(prefix); pw.printf("%7d kB: ", mi.pss); pw.println(mi.label);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010009 if (mi.subitems != null) {
10010 dumpMemItems(pw, prefix + " ", mi.subitems, true);
10011 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010012 }
10013 }
10014
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010015 // These are in KB.
10016 static final long[] DUMP_MEM_BUCKETS = new long[] {
10017 5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024,
10018 120*1024, 160*1024, 200*1024,
10019 250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024,
10020 1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024
10021 };
10022
Dianne Hackborn672342c2011-11-29 11:29:02 -080010023 static final void appendMemBucket(StringBuilder out, long memKB, String label,
10024 boolean stackLike) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010025 int start = label.lastIndexOf('.');
10026 if (start >= 0) start++;
10027 else start = 0;
10028 int end = label.length();
10029 for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) {
10030 if (DUMP_MEM_BUCKETS[i] >= memKB) {
10031 long bucket = DUMP_MEM_BUCKETS[i]/1024;
10032 out.append(bucket);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010033 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010034 out.append(label, start, end);
10035 return;
10036 }
10037 }
10038 out.append(memKB/1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010039 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010040 out.append(label, start, end);
10041 }
10042
10043 static final int[] DUMP_MEM_OOM_ADJ = new int[] {
10044 ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ, ProcessList.FOREGROUND_APP_ADJ,
10045 ProcessList.VISIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ,
10046 ProcessList.BACKUP_APP_ADJ, ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ,
10047 ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.HIDDEN_APP_MAX_ADJ
10048 };
10049 static final String[] DUMP_MEM_OOM_LABEL = new String[] {
10050 "System", "Persistent", "Foreground",
10051 "Visible", "Perceptible", "Heavy Weight",
10052 "Backup", "A Services", "Home", "Previous",
10053 "B Services", "Background"
10054 };
10055
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010056 final void dumpApplicationMemoryUsage(FileDescriptor fd,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010057 PrintWriter pw, String prefix, String[] args, boolean brief,
Dianne Hackborn672342c2011-11-29 11:29:02 -080010058 PrintWriter categoryPw, StringBuilder outTag, StringBuilder outStack) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010059 boolean dumpAll = false;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010060 boolean oomOnly = false;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010061
10062 int opti = 0;
10063 while (opti < args.length) {
10064 String opt = args[opti];
10065 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
10066 break;
10067 }
10068 opti++;
10069 if ("-a".equals(opt)) {
10070 dumpAll = true;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010071 } else if ("--oom".equals(opt)) {
10072 oomOnly = true;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010073 } else if ("-h".equals(opt)) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010074 pw.println("meminfo dump options: [-a] [--oom] [process]");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010075 pw.println(" -a: include all available information for each process.");
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010076 pw.println(" --oom: only show processes organized by oom adj.");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010077 pw.println("If [process] is specified it can be the name or ");
10078 pw.println("pid of a specific process to dump.");
10079 return;
10080 } else {
10081 pw.println("Unknown argument: " + opt + "; use -h for help");
10082 }
10083 }
10084
10085 ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010086 if (procs == null) {
10087 return;
10088 }
10089
Dianne Hackborn6447ca32009-04-07 19:50:08 -070010090 final boolean isCheckinRequest = scanArgs(args, "--checkin");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010091 long uptime = SystemClock.uptimeMillis();
10092 long realtime = SystemClock.elapsedRealtime();
Dianne Hackbornb437e092011-08-05 17:50:29 -070010093
10094 if (procs.size() == 1 || isCheckinRequest) {
10095 dumpAll = true;
10096 }
10097
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010098 if (isCheckinRequest) {
10099 // short checkin version
10100 pw.println(uptime + "," + realtime);
10101 pw.flush();
10102 } else {
10103 pw.println("Applications Memory Usage (kB):");
10104 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10105 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010106
Dianne Hackbornb437e092011-08-05 17:50:29 -070010107 String[] innerArgs = new String[args.length-opti];
10108 System.arraycopy(args, opti, innerArgs, 0, args.length-opti);
10109
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010110 ArrayList<MemItem> procMems = new ArrayList<MemItem>();
10111 long nativePss=0, dalvikPss=0, otherPss=0;
10112 long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
10113
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010114 long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length];
10115 ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[])
10116 new ArrayList[DUMP_MEM_OOM_LABEL.length];
Dianne Hackbornb437e092011-08-05 17:50:29 -070010117
10118 long totalPss = 0;
10119
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010120 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10121 ProcessRecord r = procs.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010122 if (r.thread != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010123 if (!isCheckinRequest && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010124 pw.println("\n** MEMINFO in pid " + r.pid + " [" + r.processName + "] **");
10125 pw.flush();
10126 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010127 Debug.MemoryInfo mi = null;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010128 if (dumpAll) {
10129 try {
10130 mi = r.thread.dumpMemInfo(fd, isCheckinRequest, dumpAll, innerArgs);
10131 } catch (RemoteException e) {
10132 if (!isCheckinRequest) {
10133 pw.println("Got RemoteException!");
10134 pw.flush();
10135 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010136 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010137 } else {
10138 mi = new Debug.MemoryInfo();
10139 Debug.getMemoryInfo(r.pid, mi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010140 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010141
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010142 if (!isCheckinRequest && mi != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010143 long myTotalPss = mi.getTotalPss();
10144 totalPss += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010145 MemItem pssItem = new MemItem(r.processName + " (pid " + r.pid + ")",
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010146 r.processName, myTotalPss, 0);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010147 procMems.add(pssItem);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010148
10149 nativePss += mi.nativePss;
10150 dalvikPss += mi.dalvikPss;
10151 otherPss += mi.otherPss;
10152 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
10153 long mem = mi.getOtherPss(j);
10154 miscPss[j] += mem;
10155 otherPss -= mem;
10156 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010157
10158 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010159 if (r.setAdj <= DUMP_MEM_OOM_ADJ[oomIndex]
10160 || oomIndex == (oomPss.length-1)) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010161 oomPss[oomIndex] += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010162 if (oomProcs[oomIndex] == null) {
10163 oomProcs[oomIndex] = new ArrayList<MemItem>();
10164 }
10165 oomProcs[oomIndex].add(pssItem);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010166 break;
10167 }
10168 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010169 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010170 }
10171 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010172
10173 if (!isCheckinRequest && procs.size() > 1) {
10174 ArrayList<MemItem> catMems = new ArrayList<MemItem>();
10175
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010176 catMems.add(new MemItem("Native", "Native", nativePss, -1));
10177 catMems.add(new MemItem("Dalvik", "Dalvik", dalvikPss, -2));
10178 catMems.add(new MemItem("Unknown", "Unknown", otherPss, -3));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010179 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010180 String label = Debug.MemoryInfo.getOtherLabel(j);
10181 catMems.add(new MemItem(label, label, miscPss[j], j));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010182 }
10183
Dianne Hackbornb437e092011-08-05 17:50:29 -070010184 ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
10185 for (int j=0; j<oomPss.length; j++) {
10186 if (oomPss[j] != 0) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010187 String label = DUMP_MEM_OOM_LABEL[j];
10188 MemItem item = new MemItem(label, label, oomPss[j],
10189 DUMP_MEM_OOM_ADJ[j]);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010190 item.subitems = oomProcs[j];
10191 oomMems.add(item);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010192 }
10193 }
10194
Dianne Hackborn672342c2011-11-29 11:29:02 -080010195 if (outTag != null || outStack != null) {
10196 if (outTag != null) {
10197 appendMemBucket(outTag, totalPss, "total", false);
10198 }
10199 if (outStack != null) {
10200 appendMemBucket(outStack, totalPss, "total", true);
10201 }
10202 boolean firstLine = true;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010203 for (int i=0; i<oomMems.size(); i++) {
10204 MemItem miCat = oomMems.get(i);
10205 if (miCat.subitems == null || miCat.subitems.size() < 1) {
10206 continue;
10207 }
10208 if (miCat.id < ProcessList.SERVICE_ADJ
10209 || miCat.id == ProcessList.HOME_APP_ADJ
10210 || miCat.id == ProcessList.PREVIOUS_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010211 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10212 outTag.append(" / ");
10213 }
10214 if (outStack != null) {
10215 if (miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10216 if (firstLine) {
10217 outStack.append(":");
10218 firstLine = false;
10219 }
10220 outStack.append("\n\t at ");
10221 } else {
10222 outStack.append("$");
10223 }
10224 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010225 for (int j=0; j<miCat.subitems.size(); j++) {
10226 MemItem mi = miCat.subitems.get(j);
10227 if (j > 0) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010228 if (outTag != null) {
10229 outTag.append(" ");
10230 }
10231 if (outStack != null) {
10232 outStack.append("$");
10233 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010234 }
Dianne Hackborn672342c2011-11-29 11:29:02 -080010235 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10236 appendMemBucket(outTag, mi.pss, mi.shortLabel, false);
10237 }
10238 if (outStack != null) {
10239 appendMemBucket(outStack, mi.pss, mi.shortLabel, true);
10240 }
10241 }
10242 if (outStack != null && miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10243 outStack.append("(");
10244 for (int k=0; k<DUMP_MEM_OOM_ADJ.length; k++) {
10245 if (DUMP_MEM_OOM_ADJ[k] == miCat.id) {
10246 outStack.append(DUMP_MEM_OOM_LABEL[k]);
10247 outStack.append(":");
10248 outStack.append(DUMP_MEM_OOM_ADJ[k]);
10249 }
10250 }
10251 outStack.append(")");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010252 }
10253 }
10254 }
10255 }
10256
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010257 if (!brief && !oomOnly) {
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010258 pw.println();
10259 pw.println("Total PSS by process:");
10260 dumpMemItems(pw, " ", procMems, true);
10261 pw.println();
10262 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010263 pw.println("Total PSS by OOM adjustment:");
10264 dumpMemItems(pw, " ", oomMems, false);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010265 if (!oomOnly) {
10266 PrintWriter out = categoryPw != null ? categoryPw : pw;
10267 out.println();
10268 out.println("Total PSS by category:");
10269 dumpMemItems(out, " ", catMems, true);
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010270 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010271 pw.println();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010272 pw.print("Total PSS: "); pw.print(totalPss); pw.println(" kB");
Dianne Hackbornd3e677b2012-04-05 14:58:18 -070010273 final int[] SINGLE_LONG_FORMAT = new int[] {
10274 Process.PROC_SPACE_TERM|Process.PROC_OUT_LONG
10275 };
10276 long[] longOut = new long[1];
10277 Process.readProcFile("/sys/kernel/mm/ksm/pages_shared",
10278 SINGLE_LONG_FORMAT, null, longOut, null);
10279 long shared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10280 longOut[0] = 0;
10281 Process.readProcFile("/sys/kernel/mm/ksm/pages_sharing",
10282 SINGLE_LONG_FORMAT, null, longOut, null);
10283 long sharing = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10284 longOut[0] = 0;
10285 Process.readProcFile("/sys/kernel/mm/ksm/pages_unshared",
10286 SINGLE_LONG_FORMAT, null, longOut, null);
10287 long unshared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10288 longOut[0] = 0;
10289 Process.readProcFile("/sys/kernel/mm/ksm/pages_volatile",
10290 SINGLE_LONG_FORMAT, null, longOut, null);
10291 long voltile = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10292 pw.print(" KSM: "); pw.print(sharing); pw.print(" kB saved from shared ");
10293 pw.print(shared); pw.println(" kB");
10294 pw.print(" "); pw.print(unshared); pw.print(" kB unshared; ");
10295 pw.print(voltile); pw.println(" kB volatile");
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010296 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010297 }
10298
10299 /**
10300 * Searches array of arguments for the specified string
10301 * @param args array of argument strings
10302 * @param value value to search for
10303 * @return true if the value is contained in the array
10304 */
10305 private static boolean scanArgs(String[] args, String value) {
10306 if (args != null) {
10307 for (String arg : args) {
10308 if (value.equals(arg)) {
10309 return true;
10310 }
10311 }
10312 }
10313 return false;
10314 }
10315
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010316 private final void killServicesLocked(ProcessRecord app,
10317 boolean allowRestart) {
10318 // Report disconnected services.
10319 if (false) {
10320 // XXX we are letting the client link to the service for
10321 // death notifications.
10322 if (app.services.size() > 0) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010323 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010324 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010325 ServiceRecord r = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010326 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010327 Iterator<ArrayList<ConnectionRecord>> jt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010328 = r.connections.values().iterator();
10329 while (jt.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010330 ArrayList<ConnectionRecord> cl = jt.next();
10331 for (int i=0; i<cl.size(); i++) {
10332 ConnectionRecord c = cl.get(i);
10333 if (c.binding.client != app) {
10334 try {
10335 //c.conn.connected(r.className, null);
10336 } catch (Exception e) {
10337 // todo: this should be asynchronous!
10338 Slog.w(TAG, "Exception thrown disconnected servce "
10339 + r.shortName
10340 + " from app " + app.processName, e);
10341 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010342 }
10343 }
10344 }
10345 }
10346 }
10347 }
10348 }
10349
10350 // Clean up any connections this application has to other services.
10351 if (app.connections.size() > 0) {
10352 Iterator<ConnectionRecord> it = app.connections.iterator();
10353 while (it.hasNext()) {
10354 ConnectionRecord r = it.next();
10355 removeConnectionLocked(r, app, null);
10356 }
10357 }
10358 app.connections.clear();
10359
10360 if (app.services.size() != 0) {
10361 // Any services running in the application need to be placed
10362 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -070010363 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010364 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010365 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010366 synchronized (sr.stats.getBatteryStats()) {
10367 sr.stats.stopLaunchedLocked();
10368 }
10369 sr.app = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010370 sr.isolatedProc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010371 sr.executeNesting = 0;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010372 if (mStoppingServices.remove(sr)) {
10373 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
10374 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010375
10376 boolean hasClients = sr.bindings.size() > 0;
10377 if (hasClients) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010378 Iterator<IntentBindRecord> bindings
10379 = sr.bindings.values().iterator();
10380 while (bindings.hasNext()) {
10381 IntentBindRecord b = bindings.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -080010382 if (DEBUG_SERVICE) Slog.v(TAG, "Killing binding " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010383 + ": shouldUnbind=" + b.hasBound);
10384 b.binder = null;
10385 b.requested = b.received = b.hasBound = false;
10386 }
10387 }
10388
Dianne Hackborn070783f2010-12-29 16:46:28 -080010389 if (sr.crashCount >= 2 && (sr.serviceInfo.applicationInfo.flags
10390 &ApplicationInfo.FLAG_PERSISTENT) == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010391 Slog.w(TAG, "Service crashed " + sr.crashCount
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010392 + " times, stopping: " + sr);
Doug Zongker2bec3d42009-12-04 12:52:44 -080010393 EventLog.writeEvent(EventLogTags.AM_SERVICE_CRASHED_TOO_MUCH,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010394 sr.crashCount, sr.shortName, app.pid);
10395 bringDownServiceLocked(sr, true);
10396 } else if (!allowRestart) {
10397 bringDownServiceLocked(sr, true);
10398 } else {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010399 boolean canceled = scheduleServiceRestartLocked(sr, true);
10400
10401 // Should the service remain running? Note that in the
10402 // extreme case of so many attempts to deliver a command
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010403 // that it failed we also will stop it here.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010404 if (sr.startRequested && (sr.stopIfKilled || canceled)) {
10405 if (sr.pendingStarts.size() == 0) {
10406 sr.startRequested = false;
10407 if (!hasClients) {
10408 // Whoops, no reason to restart!
10409 bringDownServiceLocked(sr, true);
10410 }
10411 }
10412 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010413 }
10414 }
10415
10416 if (!allowRestart) {
10417 app.services.clear();
10418 }
10419 }
10420
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010421 // Make sure we have no more records on the stopping list.
10422 int i = mStoppingServices.size();
10423 while (i > 0) {
10424 i--;
10425 ServiceRecord sr = mStoppingServices.get(i);
10426 if (sr.app == app) {
10427 mStoppingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010428 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010429 }
10430 }
10431
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010432 app.executingServices.clear();
10433 }
10434
10435 private final void removeDyingProviderLocked(ProcessRecord proc,
10436 ContentProviderRecord cpr) {
10437 synchronized (cpr) {
10438 cpr.launchingApp = null;
10439 cpr.notifyAll();
10440 }
10441
Amith Yamasani742a6712011-05-04 14:49:28 -070010442 mProviderMap.removeProviderByClass(cpr.name, UserId.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010443 String names[] = cpr.info.authority.split(";");
10444 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010445 mProviderMap.removeProviderByName(names[j], UserId.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010446 }
10447
10448 Iterator<ProcessRecord> cit = cpr.clients.iterator();
10449 while (cit.hasNext()) {
10450 ProcessRecord capp = cit.next();
10451 if (!capp.persistent && capp.thread != null
10452 && capp.pid != 0
10453 && capp.pid != MY_PID) {
Dianne Hackborn8633e682010-04-22 16:03:41 -070010454 Slog.i(TAG, "Kill " + capp.processName
10455 + " (pid " + capp.pid + "): provider " + cpr.info.name
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010456 + " in dying process " + (proc != null ? proc.processName : "??"));
Dianne Hackborn8633e682010-04-22 16:03:41 -070010457 EventLog.writeEvent(EventLogTags.AM_KILL, capp.pid,
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010458 capp.processName, capp.setAdj, "dying provider "
10459 + cpr.name.toShortString());
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070010460 Process.killProcessQuiet(capp.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010461 }
10462 }
10463
10464 mLaunchingProviders.remove(cpr);
10465 }
10466
10467 /**
10468 * Main code for cleaning up a process when it has gone away. This is
10469 * called both as a result of the process dying, or directly when stopping
10470 * a process when running in single process mode.
10471 */
10472 private final void cleanUpApplicationRecordLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010473 boolean restarting, boolean allowRestart, int index) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010474 if (index >= 0) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010475 mLruProcesses.remove(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010476 }
10477
Dianne Hackborn36124872009-10-08 16:22:03 -070010478 mProcessesToGc.remove(app);
10479
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010480 // Dismiss any open dialogs.
10481 if (app.crashDialog != null) {
10482 app.crashDialog.dismiss();
10483 app.crashDialog = null;
10484 }
10485 if (app.anrDialog != null) {
10486 app.anrDialog.dismiss();
10487 app.anrDialog = null;
10488 }
10489 if (app.waitDialog != null) {
10490 app.waitDialog.dismiss();
10491 app.waitDialog = null;
10492 }
10493
10494 app.crashing = false;
10495 app.notResponding = false;
10496
10497 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -070010498 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010499 app.thread = null;
10500 app.forcingToForeground = null;
10501 app.foregroundServices = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010502 app.foregroundActivities = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070010503 app.hasShownUi = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010504 app.hasAboveClient = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010505
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010506 killServicesLocked(app, allowRestart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010507
10508 boolean restart = false;
10509
10510 int NL = mLaunchingProviders.size();
10511
10512 // Remove published content providers.
10513 if (!app.pubProviders.isEmpty()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010514 Iterator<ContentProviderRecord> it = app.pubProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010515 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010516 ContentProviderRecord cpr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010517 cpr.provider = null;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010518 cpr.proc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010519
10520 // See if someone is waiting for this provider... in which
10521 // case we don't remove it, but just let it restart.
10522 int i = 0;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010523 if (!app.bad && allowRestart) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010524 for (; i<NL; i++) {
10525 if (mLaunchingProviders.get(i) == cpr) {
10526 restart = true;
10527 break;
10528 }
10529 }
10530 } else {
10531 i = NL;
10532 }
10533
10534 if (i >= NL) {
10535 removeDyingProviderLocked(app, cpr);
10536 NL = mLaunchingProviders.size();
10537 }
10538 }
10539 app.pubProviders.clear();
10540 }
10541
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010542 // Take care of any launching providers waiting for this process.
10543 if (checkAppInLaunchingProvidersLocked(app, false)) {
10544 restart = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010545 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010546
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010547 // Unregister from connected content providers.
10548 if (!app.conProviders.isEmpty()) {
Dianne Hackborn0c3154d2009-10-06 17:18:05 -070010549 Iterator it = app.conProviders.keySet().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010550 while (it.hasNext()) {
10551 ContentProviderRecord cpr = (ContentProviderRecord)it.next();
10552 cpr.clients.remove(app);
10553 }
10554 app.conProviders.clear();
10555 }
10556
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010557 // At this point there may be remaining entries in mLaunchingProviders
10558 // where we were the only one waiting, so they are no longer of use.
10559 // Look for these and clean up if found.
10560 // XXX Commented out for now. Trying to figure out a way to reproduce
10561 // the actual situation to identify what is actually going on.
10562 if (false) {
10563 for (int i=0; i<NL; i++) {
10564 ContentProviderRecord cpr = (ContentProviderRecord)
10565 mLaunchingProviders.get(i);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080010566 if (cpr.clients.size() <= 0 && !cpr.hasExternalProcessHandles()) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010567 synchronized (cpr) {
10568 cpr.launchingApp = null;
10569 cpr.notifyAll();
10570 }
10571 }
10572 }
10573 }
10574
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010575 skipCurrentReceiverLocked(app);
10576
10577 // Unregister any receivers.
10578 if (app.receivers.size() > 0) {
10579 Iterator<ReceiverList> it = app.receivers.iterator();
10580 while (it.hasNext()) {
10581 removeReceiverLocked(it.next());
10582 }
10583 app.receivers.clear();
10584 }
10585
Christopher Tate181fafa2009-05-14 11:12:14 -070010586 // If the app is undergoing backup, tell the backup manager about it
10587 if (mBackupTarget != null && app.pid == mBackupTarget.app.pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010588 if (DEBUG_BACKUP) Slog.d(TAG, "App " + mBackupTarget.appInfo + " died during backup");
Christopher Tate181fafa2009-05-14 11:12:14 -070010589 try {
10590 IBackupManager bm = IBackupManager.Stub.asInterface(
10591 ServiceManager.getService(Context.BACKUP_SERVICE));
10592 bm.agentDisconnected(app.info.packageName);
10593 } catch (RemoteException e) {
10594 // can't happen; backup manager is local
10595 }
10596 }
10597
Jeff Sharkey287bd832011-05-28 19:36:26 -070010598 mHandler.obtainMessage(DISPATCH_PROCESS_DIED, app.pid, app.info.uid, null).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010599
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010600 // If the caller is restarting this app, then leave it in its
10601 // current lists and let the caller take care of it.
10602 if (restarting) {
10603 return;
10604 }
10605
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010606 if (!app.persistent || app.isolated) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010607 if (DEBUG_PROCESSES) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010608 "Removing non-persistent process during cleanup: " + app);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010609 mProcessNames.remove(app.processName, app.uid);
10610 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -070010611 if (mHeavyWeightProcess == app) {
10612 mHeavyWeightProcess = null;
10613 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
10614 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010615 } else if (!app.removed) {
10616 // This app is persistent, so we need to keep its record around.
10617 // If it is not already on the pending app list, add it there
10618 // and start a new process for it.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010619 if (mPersistentStartingProcesses.indexOf(app) < 0) {
10620 mPersistentStartingProcesses.add(app);
10621 restart = true;
10622 }
10623 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070010624 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
10625 "Clean-up removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010626 mProcessesOnHold.remove(app);
10627
The Android Open Source Project4df24232009-03-05 14:34:35 -080010628 if (app == mHomeProcess) {
10629 mHomeProcess = null;
10630 }
Dianne Hackbornf35fe232011-11-01 19:25:20 -070010631 if (app == mPreviousProcess) {
10632 mPreviousProcess = null;
10633 }
10634
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010635 if (restart && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010636 // We have components that still need to be running in the
10637 // process, so re-launch it.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010638 mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010639 startProcessLocked(app, "restart", app.processName);
10640 } else if (app.pid > 0 && app.pid != MY_PID) {
10641 // Goodbye!
10642 synchronized (mPidsSelfLocked) {
10643 mPidsSelfLocked.remove(app.pid);
10644 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
10645 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010646 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010647 }
10648 }
10649
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010650 boolean checkAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) {
10651 // Look through the content providers we are waiting to have launched,
10652 // and if any run in this process then either schedule a restart of
10653 // the process or kill the client waiting for it if this process has
10654 // gone bad.
10655 int NL = mLaunchingProviders.size();
10656 boolean restart = false;
10657 for (int i=0; i<NL; i++) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010658 ContentProviderRecord cpr = mLaunchingProviders.get(i);
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010659 if (cpr.launchingApp == app) {
10660 if (!alwaysBad && !app.bad) {
10661 restart = true;
10662 } else {
10663 removeDyingProviderLocked(app, cpr);
10664 NL = mLaunchingProviders.size();
10665 }
10666 }
10667 }
10668 return restart;
10669 }
10670
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010671 // =========================================================
10672 // SERVICES
10673 // =========================================================
10674
10675 ActivityManager.RunningServiceInfo makeRunningServiceInfoLocked(ServiceRecord r) {
10676 ActivityManager.RunningServiceInfo info =
10677 new ActivityManager.RunningServiceInfo();
10678 info.service = r.name;
10679 if (r.app != null) {
10680 info.pid = r.app.pid;
10681 }
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010682 info.uid = r.appInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010683 info.process = r.processName;
10684 info.foreground = r.isForeground;
10685 info.activeSince = r.createTime;
10686 info.started = r.startRequested;
10687 info.clientCount = r.connections.size();
10688 info.crashCount = r.crashCount;
10689 info.lastActivityTime = r.lastActivity;
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010690 if (r.isForeground) {
10691 info.flags |= ActivityManager.RunningServiceInfo.FLAG_FOREGROUND;
10692 }
10693 if (r.startRequested) {
10694 info.flags |= ActivityManager.RunningServiceInfo.FLAG_STARTED;
10695 }
Dan Egnor42471dd2010-01-07 17:25:22 -080010696 if (r.app != null && r.app.pid == MY_PID) {
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010697 info.flags |= ActivityManager.RunningServiceInfo.FLAG_SYSTEM_PROCESS;
10698 }
10699 if (r.app != null && r.app.persistent) {
10700 info.flags |= ActivityManager.RunningServiceInfo.FLAG_PERSISTENT_PROCESS;
10701 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010702
10703 for (ArrayList<ConnectionRecord> connl : r.connections.values()) {
10704 for (int i=0; i<connl.size(); i++) {
10705 ConnectionRecord conn = connl.get(i);
10706 if (conn.clientLabel != 0) {
10707 info.clientPackage = conn.binding.client.info.packageName;
10708 info.clientLabel = conn.clientLabel;
10709 return info;
10710 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010711 }
10712 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010713 return info;
10714 }
10715
10716 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum,
10717 int flags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010718 enforceNotIsolatedCaller("getServices");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010719 synchronized (this) {
10720 ArrayList<ActivityManager.RunningServiceInfo> res
10721 = new ArrayList<ActivityManager.RunningServiceInfo>();
10722
Amith Yamasani742a6712011-05-04 14:49:28 -070010723 int userId = UserId.getUserId(Binder.getCallingUid());
10724 if (mServiceMap.getAllServices(userId).size() > 0) {
10725 Iterator<ServiceRecord> it
10726 = mServiceMap.getAllServices(userId).iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010727 while (it.hasNext() && res.size() < maxNum) {
10728 res.add(makeRunningServiceInfoLocked(it.next()));
10729 }
10730 }
10731
10732 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
10733 ServiceRecord r = mRestartingServices.get(i);
10734 ActivityManager.RunningServiceInfo info =
10735 makeRunningServiceInfoLocked(r);
10736 info.restarting = r.nextRestartTime;
10737 res.add(info);
10738 }
10739
10740 return res;
10741 }
10742 }
10743
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010744 public PendingIntent getRunningServiceControlPanel(ComponentName name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010745 enforceNotIsolatedCaller("getRunningServiceControlPanel");
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010746 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010747 int userId = UserId.getUserId(Binder.getCallingUid());
10748 ServiceRecord r = mServiceMap.getServiceByName(name, userId);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010749 if (r != null) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010750 for (ArrayList<ConnectionRecord> conn : r.connections.values()) {
10751 for (int i=0; i<conn.size(); i++) {
10752 if (conn.get(i).clientIntent != null) {
10753 return conn.get(i).clientIntent;
10754 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010755 }
10756 }
10757 }
10758 }
10759 return null;
10760 }
10761
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010762 private final ServiceRecord findServiceLocked(ComponentName name,
10763 IBinder token) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010764 ServiceRecord r = mServiceMap.getServiceByName(name, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010765 return r == token ? r : null;
10766 }
10767
10768 private final class ServiceLookupResult {
10769 final ServiceRecord record;
10770 final String permission;
10771
10772 ServiceLookupResult(ServiceRecord _record, String _permission) {
10773 record = _record;
10774 permission = _permission;
10775 }
10776 };
10777
10778 private ServiceLookupResult findServiceLocked(Intent service,
Amith Yamasani483f3b02012-03-13 16:08:00 -070010779 String resolvedType, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010780 ServiceRecord r = null;
10781 if (service.getComponent() != null) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070010782 r = mServiceMap.getServiceByName(service.getComponent(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010783 }
10784 if (r == null) {
10785 Intent.FilterComparison filter = new Intent.FilterComparison(service);
Amith Yamasani483f3b02012-03-13 16:08:00 -070010786 r = mServiceMap.getServiceByIntent(filter, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010787 }
10788
10789 if (r == null) {
10790 try {
10791 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070010792 AppGlobals.getPackageManager().resolveService(
Amith Yamasani483f3b02012-03-13 16:08:00 -070010793 service, resolvedType, 0, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010794 ServiceInfo sInfo =
10795 rInfo != null ? rInfo.serviceInfo : null;
10796 if (sInfo == null) {
10797 return null;
10798 }
10799
10800 ComponentName name = new ComponentName(
10801 sInfo.applicationInfo.packageName, sInfo.name);
Amith Yamasani742a6712011-05-04 14:49:28 -070010802 r = mServiceMap.getServiceByName(name, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010803 } catch (RemoteException ex) {
10804 // pm is in same process, this will never happen.
10805 }
10806 }
10807 if (r != null) {
10808 int callingPid = Binder.getCallingPid();
10809 int callingUid = Binder.getCallingUid();
10810 if (checkComponentPermission(r.permission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010811 callingPid, callingUid, r.appInfo.uid, r.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010812 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010813 if (!r.exported) {
10814 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
10815 + " from pid=" + callingPid
10816 + ", uid=" + callingUid
10817 + " that is not exported from uid " + r.appInfo.uid);
10818 return new ServiceLookupResult(null, "not exported from uid "
10819 + r.appInfo.uid);
10820 }
Joe Onorato8a9b2202010-02-26 18:56:32 -080010821 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010822 + " from pid=" + callingPid
10823 + ", uid=" + callingUid
10824 + " requires " + r.permission);
10825 return new ServiceLookupResult(null, r.permission);
10826 }
10827 return new ServiceLookupResult(r, null);
10828 }
10829 return null;
10830 }
10831
10832 private class ServiceRestarter implements Runnable {
10833 private ServiceRecord mService;
10834
10835 void setService(ServiceRecord service) {
10836 mService = service;
10837 }
10838
10839 public void run() {
10840 synchronized(ActivityManagerService.this) {
10841 performServiceRestartLocked(mService);
10842 }
10843 }
10844 }
10845
10846 private ServiceLookupResult retrieveServiceLocked(Intent service,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010847 String resolvedType, int callingPid, int callingUid, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010848 ServiceRecord r = null;
Amith Yamasani742a6712011-05-04 14:49:28 -070010849 if (DEBUG_SERVICE)
10850 Slog.v(TAG, "retrieveServiceLocked: " + service + " type=" + resolvedType
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010851 + " callingUid=" + callingUid);
Amith Yamasani742a6712011-05-04 14:49:28 -070010852
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010853 if (service.getComponent() != null) {
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010854 r = mServiceMap.getServiceByName(service.getComponent(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010855 }
Amith Yamasani742a6712011-05-04 14:49:28 -070010856 if (r == null) {
10857 Intent.FilterComparison filter = new Intent.FilterComparison(service);
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010858 r = mServiceMap.getServiceByIntent(filter, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -070010859 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010860 if (r == null) {
10861 try {
10862 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070010863 AppGlobals.getPackageManager().resolveService(
Amith Yamasani483f3b02012-03-13 16:08:00 -070010864 service, resolvedType, STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010865 ServiceInfo sInfo =
10866 rInfo != null ? rInfo.serviceInfo : null;
10867 if (sInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010868 Slog.w(TAG, "Unable to start service " + service +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010869 ": not found");
10870 return null;
10871 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010872 if (userId > 0) {
10873 sInfo.applicationInfo = getAppInfoForUser(sInfo.applicationInfo, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -070010874 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010875 ComponentName name = new ComponentName(
10876 sInfo.applicationInfo.packageName, sInfo.name);
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010877 r = mServiceMap.getServiceByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010878 if (r == null) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010879 Intent.FilterComparison filter = new Intent.FilterComparison(
10880 service.cloneFilter());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010881 ServiceRestarter res = new ServiceRestarter();
10882 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
10883 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
10884 synchronized (stats) {
10885 ss = stats.getServiceStatsLocked(
10886 sInfo.applicationInfo.uid, sInfo.packageName,
10887 sInfo.name);
10888 }
Dianne Hackbornb1c4a2a2010-01-19 15:36:42 -080010889 r = new ServiceRecord(this, ss, name, filter, sInfo, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010890 res.setService(r);
Amith Yamasani742a6712011-05-04 14:49:28 -070010891 mServiceMap.putServiceByName(name, UserId.getUserId(r.appInfo.uid), r);
10892 mServiceMap.putServiceByIntent(filter, UserId.getUserId(r.appInfo.uid), r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010893
10894 // Make sure this component isn't in the pending list.
10895 int N = mPendingServices.size();
10896 for (int i=0; i<N; i++) {
10897 ServiceRecord pr = mPendingServices.get(i);
10898 if (pr.name.equals(name)) {
10899 mPendingServices.remove(i);
10900 i--;
10901 N--;
10902 }
10903 }
10904 }
10905 } catch (RemoteException ex) {
10906 // pm is in same process, this will never happen.
10907 }
10908 }
10909 if (r != null) {
10910 if (checkComponentPermission(r.permission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010911 callingPid, callingUid, r.appInfo.uid, r.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010912 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010913 if (!r.exported) {
10914 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
10915 + " from pid=" + callingPid
10916 + ", uid=" + callingUid
10917 + " that is not exported from uid " + r.appInfo.uid);
10918 return new ServiceLookupResult(null, "not exported from uid "
10919 + r.appInfo.uid);
10920 }
Joe Onorato8a9b2202010-02-26 18:56:32 -080010921 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010922 + " from pid=" + callingPid
10923 + ", uid=" + callingUid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010924 + " requires " + r.permission);
10925 return new ServiceLookupResult(null, r.permission);
10926 }
10927 return new ServiceLookupResult(r, null);
10928 }
10929 return null;
10930 }
10931
Dianne Hackborn287952c2010-09-22 22:34:31 -070010932 private final void bumpServiceExecutingLocked(ServiceRecord r, String why) {
10933 if (DEBUG_SERVICE) Log.v(TAG, ">>> EXECUTING "
10934 + why + " of " + r + " in app " + r.app);
10935 else if (DEBUG_SERVICE_EXECUTING) Log.v(TAG, ">>> EXECUTING "
10936 + why + " of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010937 long now = SystemClock.uptimeMillis();
10938 if (r.executeNesting == 0 && r.app != null) {
10939 if (r.app.executingServices.size() == 0) {
10940 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
10941 msg.obj = r.app;
10942 mHandler.sendMessageAtTime(msg, now+SERVICE_TIMEOUT);
10943 }
10944 r.app.executingServices.add(r);
10945 }
10946 r.executeNesting++;
10947 r.executingStart = now;
10948 }
10949
10950 private final void sendServiceArgsLocked(ServiceRecord r,
10951 boolean oomAdjusted) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010952 final int N = r.pendingStarts.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010953 if (N == 0) {
10954 return;
10955 }
10956
Dianne Hackborn39792d22010-08-19 18:01:52 -070010957 while (r.pendingStarts.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010958 try {
Dianne Hackborn39792d22010-08-19 18:01:52 -070010959 ServiceRecord.StartItem si = r.pendingStarts.remove(0);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010960 if (DEBUG_SERVICE) Slog.v(TAG, "Sending arguments to: "
10961 + r + " " + r.intent + " args=" + si.intent);
Dianne Hackborn3a28f222011-03-01 12:25:54 -080010962 if (si.intent == null && N > 1) {
10963 // If somehow we got a dummy null intent in the middle,
10964 // then skip it. DO NOT skip a null intent when it is
10965 // the only one in the list -- this is to support the
10966 // onStartCommand(null) case.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010967 continue;
10968 }
Dianne Hackborn39792d22010-08-19 18:01:52 -070010969 si.deliveredTime = SystemClock.uptimeMillis();
10970 r.deliveredStarts.add(si);
10971 si.deliveryCount++;
Dianne Hackborn21c241e2012-03-08 13:57:23 -080010972 if (si.neededGrants != null) {
10973 grantUriPermissionUncheckedFromIntentLocked(si.neededGrants,
10974 si.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -070010975 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070010976 bumpServiceExecutingLocked(r, "start");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010977 if (!oomAdjusted) {
10978 oomAdjusted = true;
10979 updateOomAdjLocked(r.app);
10980 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010981 int flags = 0;
10982 if (si.deliveryCount > 0) {
10983 flags |= Service.START_FLAG_RETRY;
10984 }
10985 if (si.doneExecutingCount > 0) {
10986 flags |= Service.START_FLAG_REDELIVERY;
10987 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070010988 r.app.thread.scheduleServiceArgs(r, si.taskRemoved, si.id, flags, si.intent);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010989 } catch (RemoteException e) {
10990 // Remote process gone... we'll let the normal cleanup take
10991 // care of this.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010992 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while scheduling start: " + r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010993 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010994 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010995 Slog.w(TAG, "Unexpected exception", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010996 break;
10997 }
10998 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010999 }
11000
11001 private final boolean requestServiceBindingLocked(ServiceRecord r,
11002 IntentBindRecord i, boolean rebind) {
11003 if (r.app == null || r.app.thread == null) {
11004 // If service is not currently running, can't yet bind.
11005 return false;
11006 }
11007 if ((!i.requested || rebind) && i.apps.size() > 0) {
11008 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011009 bumpServiceExecutingLocked(r, "bind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011010 r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind);
11011 if (!rebind) {
11012 i.requested = true;
11013 }
11014 i.hasBound = true;
11015 i.doRebind = false;
11016 } catch (RemoteException e) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011017 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while binding " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011018 return false;
11019 }
11020 }
11021 return true;
11022 }
11023
11024 private final void requestServiceBindingsLocked(ServiceRecord r) {
11025 Iterator<IntentBindRecord> bindings = r.bindings.values().iterator();
11026 while (bindings.hasNext()) {
11027 IntentBindRecord i = bindings.next();
11028 if (!requestServiceBindingLocked(r, i, false)) {
11029 break;
11030 }
11031 }
11032 }
11033
11034 private final void realStartServiceLocked(ServiceRecord r,
11035 ProcessRecord app) throws RemoteException {
11036 if (app.thread == null) {
11037 throw new RemoteException();
11038 }
Amith Yamasani742a6712011-05-04 14:49:28 -070011039 if (DEBUG_MU)
11040 Slog.v(TAG_MU, "realStartServiceLocked, ServiceRecord.uid = " + r.appInfo.uid
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011041 + ", ProcessRecord.uid = " + app.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011042 r.app = app;
The Android Open Source Project10592532009-03-18 17:39:46 -070011043 r.restartTime = r.lastActivity = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011044
11045 app.services.add(r);
Dianne Hackborn287952c2010-09-22 22:34:31 -070011046 bumpServiceExecutingLocked(r, "create");
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011047 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011048
11049 boolean created = false;
11050 try {
Dianne Hackborna33e3f72009-09-29 17:28:24 -070011051 mStringBuilder.setLength(0);
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011052 r.intent.getIntent().toShortString(mStringBuilder, true, false, true, false);
Doug Zongker2bec3d42009-12-04 12:52:44 -080011053 EventLog.writeEvent(EventLogTags.AM_CREATE_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011054 System.identityHashCode(r), r.shortName,
Dianne Hackborna33e3f72009-09-29 17:28:24 -070011055 mStringBuilder.toString(), r.app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011056 synchronized (r.stats.getBatteryStats()) {
11057 r.stats.startLaunchedLocked();
11058 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -070011059 ensurePackageDexOpt(r.serviceInfo.packageName);
Dianne Hackborne2515ee2011-04-27 18:52:56 -040011060 app.thread.scheduleCreateService(r, r.serviceInfo,
11061 compatibilityInfoForPackageLocked(r.serviceInfo.applicationInfo));
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011062 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011063 created = true;
11064 } finally {
11065 if (!created) {
11066 app.services.remove(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011067 scheduleServiceRestartLocked(r, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011068 }
11069 }
11070
11071 requestServiceBindingsLocked(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011072
11073 // If the service is in the started state, and there are no
11074 // pending arguments, then fake up one so its onStartCommand() will
11075 // be called.
11076 if (r.startRequested && r.callStart && r.pendingStarts.size() == 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011077 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011078 null, null));
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011079 }
11080
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011081 sendServiceArgsLocked(r, true);
11082 }
11083
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011084 private final boolean scheduleServiceRestartLocked(ServiceRecord r,
11085 boolean allowCancel) {
11086 boolean canceled = false;
11087
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011088 final long now = SystemClock.uptimeMillis();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011089 long minDuration = SERVICE_RESTART_DURATION;
Dianne Hackborn6ccd2af2009-08-27 12:26:44 -070011090 long resetTime = SERVICE_RESET_RUN_DURATION;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011091
Dianne Hackborn070783f2010-12-29 16:46:28 -080011092 if ((r.serviceInfo.applicationInfo.flags
11093 &ApplicationInfo.FLAG_PERSISTENT) != 0) {
11094 minDuration /= 4;
11095 }
11096
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011097 // Any delivered but not yet finished starts should be put back
11098 // on the pending list.
11099 final int N = r.deliveredStarts.size();
11100 if (N > 0) {
11101 for (int i=N-1; i>=0; i--) {
11102 ServiceRecord.StartItem si = r.deliveredStarts.get(i);
Dianne Hackborn39792d22010-08-19 18:01:52 -070011103 si.removeUriPermissionsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011104 if (si.intent == null) {
11105 // We'll generate this again if needed.
11106 } else if (!allowCancel || (si.deliveryCount < ServiceRecord.MAX_DELIVERY_COUNT
11107 && si.doneExecutingCount < ServiceRecord.MAX_DONE_EXECUTING_COUNT)) {
11108 r.pendingStarts.add(0, si);
11109 long dur = SystemClock.uptimeMillis() - si.deliveredTime;
11110 dur *= 2;
11111 if (minDuration < dur) minDuration = dur;
11112 if (resetTime < dur) resetTime = dur;
11113 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011114 Slog.w(TAG, "Canceling start item " + si.intent + " in service "
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011115 + r.name);
11116 canceled = true;
11117 }
11118 }
11119 r.deliveredStarts.clear();
11120 }
11121
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011122 r.totalRestartCount++;
11123 if (r.restartDelay == 0) {
11124 r.restartCount++;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011125 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011126 } else {
11127 // If it has been a "reasonably long time" since the service
11128 // was started, then reset our restart duration back to
11129 // the beginning, so we don't infinitely increase the duration
11130 // on a service that just occasionally gets killed (which is
11131 // a normal case, due to process being killed to reclaim memory).
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011132 if (now > (r.restartTime+resetTime)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011133 r.restartCount = 1;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011134 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011135 } else {
Dianne Hackborn070783f2010-12-29 16:46:28 -080011136 if ((r.serviceInfo.applicationInfo.flags
11137 &ApplicationInfo.FLAG_PERSISTENT) != 0) {
11138 // Services in peristent processes will restart much more
11139 // quickly, since they are pretty important. (Think SystemUI).
11140 r.restartDelay += minDuration/2;
11141 } else {
11142 r.restartDelay *= SERVICE_RESTART_DURATION_FACTOR;
11143 if (r.restartDelay < minDuration) {
11144 r.restartDelay = minDuration;
11145 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011146 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011147 }
11148 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011149
11150 r.nextRestartTime = now + r.restartDelay;
11151
11152 // Make sure that we don't end up restarting a bunch of services
11153 // all at the same time.
11154 boolean repeat;
11155 do {
11156 repeat = false;
11157 for (int i=mRestartingServices.size()-1; i>=0; i--) {
11158 ServiceRecord r2 = mRestartingServices.get(i);
11159 if (r2 != r && r.nextRestartTime
11160 >= (r2.nextRestartTime-SERVICE_MIN_RESTART_TIME_BETWEEN)
11161 && r.nextRestartTime
11162 < (r2.nextRestartTime+SERVICE_MIN_RESTART_TIME_BETWEEN)) {
11163 r.nextRestartTime = r2.nextRestartTime + SERVICE_MIN_RESTART_TIME_BETWEEN;
11164 r.restartDelay = r.nextRestartTime - now;
11165 repeat = true;
11166 break;
11167 }
11168 }
11169 } while (repeat);
11170
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011171 if (!mRestartingServices.contains(r)) {
11172 mRestartingServices.add(r);
11173 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011174
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011175 r.cancelNotification();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011176
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011177 mHandler.removeCallbacks(r.restarter);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011178 mHandler.postAtTime(r.restarter, r.nextRestartTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011179 r.nextRestartTime = SystemClock.uptimeMillis() + r.restartDelay;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011180 Slog.w(TAG, "Scheduling restart of crashed service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011181 + r.shortName + " in " + r.restartDelay + "ms");
Doug Zongker2bec3d42009-12-04 12:52:44 -080011182 EventLog.writeEvent(EventLogTags.AM_SCHEDULE_SERVICE_RESTART,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011183 r.shortName, r.restartDelay);
11184
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011185 return canceled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011186 }
11187
11188 final void performServiceRestartLocked(ServiceRecord r) {
11189 if (!mRestartingServices.contains(r)) {
11190 return;
11191 }
11192 bringUpServiceLocked(r, r.intent.getIntent().getFlags(), true);
11193 }
11194
11195 private final boolean unscheduleServiceRestartLocked(ServiceRecord r) {
11196 if (r.restartDelay == 0) {
11197 return false;
11198 }
11199 r.resetRestartCounter();
11200 mRestartingServices.remove(r);
11201 mHandler.removeCallbacks(r.restarter);
11202 return true;
11203 }
11204
11205 private final boolean bringUpServiceLocked(ServiceRecord r,
11206 int intentFlags, boolean whileRestarting) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011207 //Slog.i(TAG, "Bring up service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011208 //r.dump(" ");
11209
Dianne Hackborn36124872009-10-08 16:22:03 -070011210 if (r.app != null && r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011211 sendServiceArgsLocked(r, false);
11212 return true;
11213 }
11214
11215 if (!whileRestarting && r.restartDelay > 0) {
11216 // If waiting for a restart, then do nothing.
11217 return true;
11218 }
11219
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011220 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing up " + r + " " + r.intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011221
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011222 // We are now bringing the service up, so no longer in the
11223 // restarting state.
11224 mRestartingServices.remove(r);
11225
Dianne Hackborne7f97212011-02-24 14:40:20 -080011226 // Service is now being launched, its package can't be stopped.
11227 try {
11228 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -070011229 r.packageName, false, r.userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -080011230 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080011231 } catch (IllegalArgumentException e) {
11232 Slog.w(TAG, "Failed trying to unstop package "
11233 + r.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080011234 }
11235
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011236 final boolean isolated = (r.serviceInfo.flags&ServiceInfo.FLAG_ISOLATED_PROCESS) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011237 final String appName = r.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011238 ProcessRecord app;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011239
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011240 if (!isolated) {
11241 app = getProcessRecordLocked(appName, r.appInfo.uid);
11242 if (DEBUG_MU)
11243 Slog.v(TAG_MU, "bringUpServiceLocked: appInfo.uid=" + r.appInfo.uid + " app=" + app);
11244 if (app != null && app.thread != null) {
11245 try {
11246 app.addPackage(r.appInfo.packageName);
11247 realStartServiceLocked(r, app);
11248 return true;
11249 } catch (RemoteException e) {
11250 Slog.w(TAG, "Exception when starting service " + r.shortName, e);
11251 }
11252
11253 // If a dead object exception was thrown -- fall through to
11254 // restart the application.
11255 }
11256 } else {
11257 // If this service runs in an isolated process, then each time
11258 // we call startProcessLocked() we will get a new isolated
11259 // process, starting another process if we are currently waiting
11260 // for a previous process to come up. To deal with this, we store
11261 // in the service any current isolated process it is running in or
11262 // waiting to have come up.
11263 app = r.isolatedProc;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011264 }
11265
Dianne Hackborn36124872009-10-08 16:22:03 -070011266 // Not running -- get it started, and enqueue this service record
11267 // to be executed when the app comes up.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011268 if (app == null) {
11269 if ((app=startProcessLocked(appName, r.appInfo, true, intentFlags,
11270 "service", r.name, false, isolated)) == null) {
11271 Slog.w(TAG, "Unable to launch app "
11272 + r.appInfo.packageName + "/"
11273 + r.appInfo.uid + " for service "
11274 + r.intent.getIntent() + ": process is bad");
11275 bringDownServiceLocked(r, true);
11276 return false;
11277 }
11278 if (isolated) {
11279 r.isolatedProc = app;
11280 }
Dianne Hackborn36124872009-10-08 16:22:03 -070011281 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011282
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011283 if (!mPendingServices.contains(r)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011284 mPendingServices.add(r);
11285 }
Dianne Hackborn36124872009-10-08 16:22:03 -070011286
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011287 return true;
11288 }
11289
11290 private final void bringDownServiceLocked(ServiceRecord r, boolean force) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011291 //Slog.i(TAG, "Bring down service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011292 //r.dump(" ");
11293
11294 // Does it still need to run?
11295 if (!force && r.startRequested) {
11296 return;
11297 }
11298 if (r.connections.size() > 0) {
11299 if (!force) {
11300 // XXX should probably keep a count of the number of auto-create
11301 // connections directly in the service.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011302 Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011303 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011304 ArrayList<ConnectionRecord> cr = it.next();
11305 for (int i=0; i<cr.size(); i++) {
11306 if ((cr.get(i).flags&Context.BIND_AUTO_CREATE) != 0) {
11307 return;
11308 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011309 }
11310 }
11311 }
11312
11313 // Report to all of the connections that the service is no longer
11314 // available.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011315 Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011316 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011317 ArrayList<ConnectionRecord> c = it.next();
11318 for (int i=0; i<c.size(); i++) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011319 ConnectionRecord cr = c.get(i);
11320 // There is still a connection to the service that is
11321 // being brought down. Mark it as dead.
11322 cr.serviceDead = true;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011323 try {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011324 cr.conn.connected(r.name, null);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011325 } catch (Exception e) {
11326 Slog.w(TAG, "Failure disconnecting service " + r.name +
11327 " to connection " + c.get(i).conn.asBinder() +
11328 " (in " + c.get(i).binding.client.processName + ")", e);
11329 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011330 }
11331 }
11332 }
11333
11334 // Tell the service that it has been unbound.
11335 if (r.bindings.size() > 0 && r.app != null && r.app.thread != null) {
11336 Iterator<IntentBindRecord> it = r.bindings.values().iterator();
11337 while (it.hasNext()) {
11338 IntentBindRecord ibr = it.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -080011339 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down binding " + ibr
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011340 + ": hasBound=" + ibr.hasBound);
11341 if (r.app != null && r.app.thread != null && ibr.hasBound) {
11342 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011343 bumpServiceExecutingLocked(r, "bring down unbind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011344 updateOomAdjLocked(r.app);
11345 ibr.hasBound = false;
11346 r.app.thread.scheduleUnbindService(r,
11347 ibr.intent.getIntent());
11348 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011349 Slog.w(TAG, "Exception when unbinding service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011350 + r.shortName, e);
11351 serviceDoneExecutingLocked(r, true);
11352 }
11353 }
11354 }
11355 }
11356
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011357 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down " + r + " " + r.intent);
Doug Zongker2bec3d42009-12-04 12:52:44 -080011358 EventLog.writeEvent(EventLogTags.AM_DESTROY_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011359 System.identityHashCode(r), r.shortName,
11360 (r.app != null) ? r.app.pid : -1);
11361
Amith Yamasani742a6712011-05-04 14:49:28 -070011362 mServiceMap.removeServiceByName(r.name, r.userId);
11363 mServiceMap.removeServiceByIntent(r.intent, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011364 r.totalRestartCount = 0;
11365 unscheduleServiceRestartLocked(r);
11366
11367 // Also make sure it is not on the pending list.
11368 int N = mPendingServices.size();
11369 for (int i=0; i<N; i++) {
11370 if (mPendingServices.get(i) == r) {
11371 mPendingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011372 if (DEBUG_SERVICE) Slog.v(TAG, "Removed pending: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011373 i--;
11374 N--;
11375 }
11376 }
11377
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011378 r.cancelNotification();
11379 r.isForeground = false;
11380 r.foregroundId = 0;
11381 r.foregroundNoti = null;
11382
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011383 // Clear start entries.
Dianne Hackborn39792d22010-08-19 18:01:52 -070011384 r.clearDeliveredStartsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011385 r.pendingStarts.clear();
11386
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011387 if (r.app != null) {
11388 synchronized (r.stats.getBatteryStats()) {
11389 r.stats.stopLaunchedLocked();
11390 }
11391 r.app.services.remove(r);
11392 if (r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011393 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011394 bumpServiceExecutingLocked(r, "stop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011395 mStoppingServices.add(r);
11396 updateOomAdjLocked(r.app);
11397 r.app.thread.scheduleStopService(r);
11398 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011399 Slog.w(TAG, "Exception when stopping service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011400 + r.shortName, e);
11401 serviceDoneExecutingLocked(r, true);
11402 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011403 updateServiceForegroundLocked(r.app, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011404 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011405 if (DEBUG_SERVICE) Slog.v(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011406 TAG, "Removed service that has no process: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011407 }
11408 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011409 if (DEBUG_SERVICE) Slog.v(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011410 TAG, "Removed service that is not running: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011411 }
Vairavan Srinivasana207ce22010-12-23 13:51:48 -080011412
11413 if (r.bindings.size() > 0) {
11414 r.bindings.clear();
11415 }
11416
11417 if (r.restarter instanceof ServiceRestarter) {
11418 ((ServiceRestarter)r.restarter).setService(null);
11419 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011420 }
11421
11422 ComponentName startServiceLocked(IApplicationThread caller,
11423 Intent service, String resolvedType,
11424 int callingPid, int callingUid) {
11425 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011426 if (DEBUG_SERVICE) Slog.v(TAG, "startService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011427 + " type=" + resolvedType + " args=" + service.getExtras());
11428
11429 if (caller != null) {
11430 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11431 if (callerApp == null) {
11432 throw new SecurityException(
11433 "Unable to find app for caller " + caller
11434 + " (pid=" + Binder.getCallingPid()
11435 + ") when starting service " + service);
11436 }
11437 }
11438
11439 ServiceLookupResult res =
11440 retrieveServiceLocked(service, resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011441 callingPid, callingUid, UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011442 if (res == null) {
11443 return null;
11444 }
11445 if (res.record == null) {
11446 return new ComponentName("!", res.permission != null
11447 ? res.permission : "private to package");
11448 }
11449 ServiceRecord r = res.record;
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011450 NeededUriGrants neededGrants = checkGrantUriPermissionFromIntentLocked(
11451 callingUid, r.packageName, service, service.getFlags(), null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011452 if (unscheduleServiceRestartLocked(r)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011453 if (DEBUG_SERVICE) Slog.v(TAG, "START SERVICE WHILE RESTART PENDING: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011454 }
11455 r.startRequested = true;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011456 r.callStart = false;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011457 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011458 service, neededGrants));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011459 r.lastActivity = SystemClock.uptimeMillis();
11460 synchronized (r.stats.getBatteryStats()) {
11461 r.stats.startRunningLocked();
11462 }
11463 if (!bringUpServiceLocked(r, service.getFlags(), false)) {
11464 return new ComponentName("!", "Service process is bad");
11465 }
11466 return r.name;
11467 }
11468 }
11469
11470 public ComponentName startService(IApplicationThread caller, Intent service,
11471 String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011472 enforceNotIsolatedCaller("startService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011473 // Refuse possible leaked file descriptors
11474 if (service != null && service.hasFileDescriptors() == true) {
11475 throw new IllegalArgumentException("File descriptors passed in Intent");
11476 }
11477
Amith Yamasani742a6712011-05-04 14:49:28 -070011478 if (DEBUG_SERVICE)
11479 Slog.v(TAG, "startService: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011480 synchronized(this) {
11481 final int callingPid = Binder.getCallingPid();
11482 final int callingUid = Binder.getCallingUid();
11483 final long origId = Binder.clearCallingIdentity();
11484 ComponentName res = startServiceLocked(caller, service,
11485 resolvedType, callingPid, callingUid);
11486 Binder.restoreCallingIdentity(origId);
11487 return res;
11488 }
11489 }
11490
11491 ComponentName startServiceInPackage(int uid,
11492 Intent service, String resolvedType) {
11493 synchronized(this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070011494 if (DEBUG_SERVICE)
11495 Slog.v(TAG, "startServiceInPackage: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011496 final long origId = Binder.clearCallingIdentity();
11497 ComponentName res = startServiceLocked(null, service,
11498 resolvedType, -1, uid);
11499 Binder.restoreCallingIdentity(origId);
11500 return res;
11501 }
11502 }
11503
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011504 private void stopServiceLocked(ServiceRecord service) {
11505 synchronized (service.stats.getBatteryStats()) {
11506 service.stats.stopRunningLocked();
11507 }
11508 service.startRequested = false;
11509 service.callStart = false;
11510 bringDownServiceLocked(service, false);
11511 }
11512
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011513 public int stopService(IApplicationThread caller, Intent service,
11514 String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011515 enforceNotIsolatedCaller("stopService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011516 // Refuse possible leaked file descriptors
11517 if (service != null && service.hasFileDescriptors() == true) {
11518 throw new IllegalArgumentException("File descriptors passed in Intent");
11519 }
11520
11521 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011522 if (DEBUG_SERVICE) Slog.v(TAG, "stopService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011523 + " type=" + resolvedType);
11524
11525 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11526 if (caller != null && callerApp == null) {
11527 throw new SecurityException(
11528 "Unable to find app for caller " + caller
11529 + " (pid=" + Binder.getCallingPid()
11530 + ") when stopping service " + service);
11531 }
11532
11533 // If this service is active, make sure it is stopped.
Amith Yamasani483f3b02012-03-13 16:08:00 -070011534 ServiceLookupResult r = findServiceLocked(service, resolvedType,
11535 callerApp == null ? UserId.getCallingUserId() : callerApp.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011536 if (r != null) {
11537 if (r.record != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011538 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011539 try {
11540 stopServiceLocked(r.record);
11541 } finally {
11542 Binder.restoreCallingIdentity(origId);
11543 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011544 return 1;
11545 }
11546 return -1;
11547 }
11548 }
11549
11550 return 0;
11551 }
11552
11553 public IBinder peekService(Intent service, String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011554 enforceNotIsolatedCaller("peekService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011555 // Refuse possible leaked file descriptors
11556 if (service != null && service.hasFileDescriptors() == true) {
11557 throw new IllegalArgumentException("File descriptors passed in Intent");
11558 }
11559
11560 IBinder ret = null;
11561
11562 synchronized(this) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070011563 ServiceLookupResult r = findServiceLocked(service, resolvedType,
11564 UserId.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011565
11566 if (r != null) {
11567 // r.record is null if findServiceLocked() failed the caller permission check
11568 if (r.record == null) {
11569 throw new SecurityException(
11570 "Permission Denial: Accessing service " + r.record.name
11571 + " from pid=" + Binder.getCallingPid()
11572 + ", uid=" + Binder.getCallingUid()
11573 + " requires " + r.permission);
11574 }
11575 IntentBindRecord ib = r.record.bindings.get(r.record.intent);
11576 if (ib != null) {
11577 ret = ib.binder;
11578 }
11579 }
11580 }
11581
11582 return ret;
11583 }
11584
11585 public boolean stopServiceToken(ComponentName className, IBinder token,
11586 int startId) {
11587 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011588 if (DEBUG_SERVICE) Slog.v(TAG, "stopServiceToken: " + className
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011589 + " " + token + " startId=" + startId);
11590 ServiceRecord r = findServiceLocked(className, token);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011591 if (r != null) {
11592 if (startId >= 0) {
11593 // Asked to only stop if done with all work. Note that
11594 // to avoid leaks, we will take this as dropping all
11595 // start items up to and including this one.
11596 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
11597 if (si != null) {
11598 while (r.deliveredStarts.size() > 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -070011599 ServiceRecord.StartItem cur = r.deliveredStarts.remove(0);
11600 cur.removeUriPermissionsLocked();
11601 if (cur == si) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011602 break;
11603 }
11604 }
11605 }
11606
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011607 if (r.getLastStartId() != startId) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011608 return false;
11609 }
11610
11611 if (r.deliveredStarts.size() > 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011612 Slog.w(TAG, "stopServiceToken startId " + startId
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011613 + " is last, but have " + r.deliveredStarts.size()
11614 + " remaining args");
11615 }
11616 }
11617
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011618 synchronized (r.stats.getBatteryStats()) {
11619 r.stats.stopRunningLocked();
11620 r.startRequested = false;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011621 r.callStart = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011622 }
11623 final long origId = Binder.clearCallingIdentity();
11624 bringDownServiceLocked(r, false);
11625 Binder.restoreCallingIdentity(origId);
11626 return true;
11627 }
11628 }
11629 return false;
11630 }
11631
11632 public void setServiceForeground(ComponentName className, IBinder token,
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011633 int id, Notification notification, boolean removeNotification) {
11634 final long origId = Binder.clearCallingIdentity();
11635 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011636 synchronized(this) {
11637 ServiceRecord r = findServiceLocked(className, token);
11638 if (r != null) {
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011639 if (id != 0) {
11640 if (notification == null) {
11641 throw new IllegalArgumentException("null notification");
11642 }
11643 if (r.foregroundId != id) {
11644 r.cancelNotification();
11645 r.foregroundId = id;
11646 }
11647 notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
11648 r.foregroundNoti = notification;
11649 r.isForeground = true;
11650 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011651 if (r.app != null) {
11652 updateServiceForegroundLocked(r.app, true);
11653 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011654 } else {
11655 if (r.isForeground) {
11656 r.isForeground = false;
11657 if (r.app != null) {
Dianne Hackborn8633e682010-04-22 16:03:41 -070011658 updateLruProcessLocked(r.app, false, true);
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011659 updateServiceForegroundLocked(r.app, true);
11660 }
11661 }
11662 if (removeNotification) {
11663 r.cancelNotification();
11664 r.foregroundId = 0;
11665 r.foregroundNoti = null;
11666 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011667 }
11668 }
11669 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011670 } finally {
11671 Binder.restoreCallingIdentity(origId);
11672 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011673 }
11674
11675 public void updateServiceForegroundLocked(ProcessRecord proc, boolean oomAdj) {
11676 boolean anyForeground = false;
Dianne Hackborn860755f2010-06-03 18:47:52 -070011677 for (ServiceRecord sr : proc.services) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011678 if (sr.isForeground) {
11679 anyForeground = true;
11680 break;
11681 }
11682 }
11683 if (anyForeground != proc.foregroundServices) {
11684 proc.foregroundServices = anyForeground;
11685 if (oomAdj) {
11686 updateOomAdjLocked();
11687 }
11688 }
11689 }
11690
11691 public int bindService(IApplicationThread caller, IBinder token,
11692 Intent service, String resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011693 IServiceConnection connection, int flags, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011694 enforceNotIsolatedCaller("bindService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011695 // Refuse possible leaked file descriptors
11696 if (service != null && service.hasFileDescriptors() == true) {
11697 throw new IllegalArgumentException("File descriptors passed in Intent");
11698 }
11699
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011700 checkValidCaller(Binder.getCallingUid(), userId);
11701
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011702 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011703 if (DEBUG_SERVICE) Slog.v(TAG, "bindService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011704 + " type=" + resolvedType + " conn=" + connection.asBinder()
11705 + " flags=0x" + Integer.toHexString(flags));
Amith Yamasani742a6712011-05-04 14:49:28 -070011706 if (DEBUG_MU)
11707 Slog.i(TAG_MU, "bindService uid=" + Binder.getCallingUid() + " origUid="
11708 + Binder.getOrigCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011709 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11710 if (callerApp == null) {
11711 throw new SecurityException(
11712 "Unable to find app for caller " + caller
11713 + " (pid=" + Binder.getCallingPid()
11714 + ") when binding service " + service);
11715 }
11716
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011717 ActivityRecord activity = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011718 if (token != null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070011719 activity = mMainStack.isInStackLocked(token);
11720 if (activity == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011721 Slog.w(TAG, "Binding with unknown activity: " + token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011722 return 0;
11723 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011724 }
11725
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011726 int clientLabel = 0;
11727 PendingIntent clientIntent = null;
11728
11729 if (callerApp.info.uid == Process.SYSTEM_UID) {
11730 // Hacky kind of thing -- allow system stuff to tell us
11731 // what they are, so we can report this elsewhere for
11732 // others to know why certain services are running.
11733 try {
11734 clientIntent = (PendingIntent)service.getParcelableExtra(
11735 Intent.EXTRA_CLIENT_INTENT);
11736 } catch (RuntimeException e) {
11737 }
11738 if (clientIntent != null) {
11739 clientLabel = service.getIntExtra(Intent.EXTRA_CLIENT_LABEL, 0);
11740 if (clientLabel != 0) {
11741 // There are no useful extras in the intent, trash them.
11742 // System code calling with this stuff just needs to know
11743 // this will happen.
11744 service = service.cloneFilter();
11745 }
11746 }
11747 }
11748
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011749 ServiceLookupResult res =
11750 retrieveServiceLocked(service, resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011751 Binder.getCallingPid(), Binder.getCallingUid(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011752 if (res == null) {
11753 return 0;
11754 }
11755 if (res.record == null) {
11756 return -1;
11757 }
11758 ServiceRecord s = res.record;
11759
11760 final long origId = Binder.clearCallingIdentity();
11761
11762 if (unscheduleServiceRestartLocked(s)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011763 if (DEBUG_SERVICE) Slog.v(TAG, "BIND SERVICE WHILE RESTART PENDING: "
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011764 + s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011765 }
11766
11767 AppBindRecord b = s.retrieveAppBindingLocked(service, callerApp);
11768 ConnectionRecord c = new ConnectionRecord(b, activity,
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011769 connection, flags, clientLabel, clientIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011770
11771 IBinder binder = connection.asBinder();
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011772 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
11773 if (clist == null) {
11774 clist = new ArrayList<ConnectionRecord>();
11775 s.connections.put(binder, clist);
11776 }
11777 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011778 b.connections.add(c);
11779 if (activity != null) {
11780 if (activity.connections == null) {
11781 activity.connections = new HashSet<ConnectionRecord>();
11782 }
11783 activity.connections.add(c);
11784 }
11785 b.client.connections.add(c);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070011786 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
11787 b.client.hasAboveClient = true;
11788 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011789 clist = mServiceConnections.get(binder);
11790 if (clist == null) {
11791 clist = new ArrayList<ConnectionRecord>();
11792 mServiceConnections.put(binder, clist);
11793 }
11794 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011795
11796 if ((flags&Context.BIND_AUTO_CREATE) != 0) {
11797 s.lastActivity = SystemClock.uptimeMillis();
11798 if (!bringUpServiceLocked(s, service.getFlags(), false)) {
11799 return 0;
11800 }
11801 }
11802
11803 if (s.app != null) {
11804 // This could have made the service more important.
11805 updateOomAdjLocked(s.app);
11806 }
11807
Joe Onorato8a9b2202010-02-26 18:56:32 -080011808 if (DEBUG_SERVICE) Slog.v(TAG, "Bind " + s + " with " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011809 + ": received=" + b.intent.received
11810 + " apps=" + b.intent.apps.size()
11811 + " doRebind=" + b.intent.doRebind);
11812
11813 if (s.app != null && b.intent.received) {
11814 // Service is already running, so we can immediately
11815 // publish the connection.
11816 try {
11817 c.conn.connected(s.name, b.intent.binder);
11818 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011819 Slog.w(TAG, "Failure sending service " + s.shortName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011820 + " to connection " + c.conn.asBinder()
11821 + " (in " + c.binding.client.processName + ")", e);
11822 }
11823
11824 // If this is the first app connected back to this binding,
11825 // and the service had previously asked to be told when
11826 // rebound, then do so.
11827 if (b.intent.apps.size() == 1 && b.intent.doRebind) {
11828 requestServiceBindingLocked(s, b.intent, true);
11829 }
11830 } else if (!b.intent.requested) {
11831 requestServiceBindingLocked(s, b.intent, false);
11832 }
11833
11834 Binder.restoreCallingIdentity(origId);
11835 }
11836
11837 return 1;
11838 }
11839
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070011840 void removeConnectionLocked(
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011841 ConnectionRecord c, ProcessRecord skipApp, ActivityRecord skipAct) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011842 IBinder binder = c.conn.asBinder();
11843 AppBindRecord b = c.binding;
11844 ServiceRecord s = b.service;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011845 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
11846 if (clist != null) {
11847 clist.remove(c);
11848 if (clist.size() == 0) {
11849 s.connections.remove(binder);
11850 }
11851 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011852 b.connections.remove(c);
11853 if (c.activity != null && c.activity != skipAct) {
11854 if (c.activity.connections != null) {
11855 c.activity.connections.remove(c);
11856 }
11857 }
11858 if (b.client != skipApp) {
11859 b.client.connections.remove(c);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070011860 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
11861 b.client.updateHasAboveClientLocked();
11862 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011863 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011864 clist = mServiceConnections.get(binder);
11865 if (clist != null) {
11866 clist.remove(c);
11867 if (clist.size() == 0) {
11868 mServiceConnections.remove(binder);
11869 }
11870 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011871
11872 if (b.connections.size() == 0) {
11873 b.intent.apps.remove(b.client);
11874 }
11875
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011876 if (!c.serviceDead) {
11877 if (DEBUG_SERVICE) Slog.v(TAG, "Disconnecting binding " + b.intent
11878 + ": shouldUnbind=" + b.intent.hasBound);
11879 if (s.app != null && s.app.thread != null && b.intent.apps.size() == 0
11880 && b.intent.hasBound) {
11881 try {
11882 bumpServiceExecutingLocked(s, "unbind");
11883 updateOomAdjLocked(s.app);
11884 b.intent.hasBound = false;
11885 // Assume the client doesn't want to know about a rebind;
11886 // we will deal with that later if it asks for one.
11887 b.intent.doRebind = false;
11888 s.app.thread.scheduleUnbindService(s, b.intent.intent.getIntent());
11889 } catch (Exception e) {
11890 Slog.w(TAG, "Exception when unbinding service " + s.shortName, e);
11891 serviceDoneExecutingLocked(s, true);
11892 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011893 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011894
11895 if ((c.flags&Context.BIND_AUTO_CREATE) != 0) {
11896 bringDownServiceLocked(s, false);
11897 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011898 }
11899 }
11900
11901 public boolean unbindService(IServiceConnection connection) {
11902 synchronized (this) {
11903 IBinder binder = connection.asBinder();
Joe Onorato8a9b2202010-02-26 18:56:32 -080011904 if (DEBUG_SERVICE) Slog.v(TAG, "unbindService: conn=" + binder);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011905 ArrayList<ConnectionRecord> clist = mServiceConnections.get(binder);
11906 if (clist == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011907 Slog.w(TAG, "Unbind failed: could not find connection for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011908 + connection.asBinder());
11909 return false;
11910 }
11911
11912 final long origId = Binder.clearCallingIdentity();
11913
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011914 while (clist.size() > 0) {
11915 ConnectionRecord r = clist.get(0);
11916 removeConnectionLocked(r, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011917
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011918 if (r.binding.service.app != null) {
11919 // This could have made the service less important.
11920 updateOomAdjLocked(r.binding.service.app);
11921 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011922 }
11923
11924 Binder.restoreCallingIdentity(origId);
11925 }
11926
11927 return true;
11928 }
11929
11930 public void publishService(IBinder token, Intent intent, IBinder service) {
11931 // Refuse possible leaked file descriptors
11932 if (intent != null && intent.hasFileDescriptors() == true) {
11933 throw new IllegalArgumentException("File descriptors passed in Intent");
11934 }
11935
11936 synchronized(this) {
11937 if (!(token instanceof ServiceRecord)) {
11938 throw new IllegalArgumentException("Invalid service token");
11939 }
11940 ServiceRecord r = (ServiceRecord)token;
11941
11942 final long origId = Binder.clearCallingIdentity();
11943
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011944 if (DEBUG_SERVICE) Slog.v(TAG, "PUBLISHING " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011945 + " " + intent + ": " + service);
11946 if (r != null) {
11947 Intent.FilterComparison filter
11948 = new Intent.FilterComparison(intent);
11949 IntentBindRecord b = r.bindings.get(filter);
11950 if (b != null && !b.received) {
11951 b.binder = service;
11952 b.requested = true;
11953 b.received = true;
11954 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011955 Iterator<ArrayList<ConnectionRecord>> it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011956 = r.connections.values().iterator();
11957 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011958 ArrayList<ConnectionRecord> clist = it.next();
11959 for (int i=0; i<clist.size(); i++) {
11960 ConnectionRecord c = clist.get(i);
11961 if (!filter.equals(c.binding.intent.intent)) {
11962 if (DEBUG_SERVICE) Slog.v(
11963 TAG, "Not publishing to: " + c);
11964 if (DEBUG_SERVICE) Slog.v(
11965 TAG, "Bound intent: " + c.binding.intent.intent);
11966 if (DEBUG_SERVICE) Slog.v(
11967 TAG, "Published intent: " + intent);
11968 continue;
11969 }
11970 if (DEBUG_SERVICE) Slog.v(TAG, "Publishing to: " + c);
11971 try {
11972 c.conn.connected(r.name, service);
11973 } catch (Exception e) {
11974 Slog.w(TAG, "Failure sending service " + r.name +
11975 " to connection " + c.conn.asBinder() +
11976 " (in " + c.binding.client.processName + ")", e);
11977 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011978 }
11979 }
11980 }
11981 }
11982
11983 serviceDoneExecutingLocked(r, mStoppingServices.contains(r));
11984
11985 Binder.restoreCallingIdentity(origId);
11986 }
11987 }
11988 }
11989
11990 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
11991 // Refuse possible leaked file descriptors
11992 if (intent != null && intent.hasFileDescriptors() == true) {
11993 throw new IllegalArgumentException("File descriptors passed in Intent");
11994 }
11995
11996 synchronized(this) {
11997 if (!(token instanceof ServiceRecord)) {
11998 throw new IllegalArgumentException("Invalid service token");
11999 }
12000 ServiceRecord r = (ServiceRecord)token;
12001
12002 final long origId = Binder.clearCallingIdentity();
12003
12004 if (r != null) {
12005 Intent.FilterComparison filter
12006 = new Intent.FilterComparison(intent);
12007 IntentBindRecord b = r.bindings.get(filter);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012008 if (DEBUG_SERVICE) Slog.v(TAG, "unbindFinished in " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012009 + " at " + b + ": apps="
12010 + (b != null ? b.apps.size() : 0));
Per Edelberg78f9fff2010-08-30 20:01:35 +020012011
12012 boolean inStopping = mStoppingServices.contains(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012013 if (b != null) {
Per Edelberg78f9fff2010-08-30 20:01:35 +020012014 if (b.apps.size() > 0 && !inStopping) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012015 // Applications have already bound since the last
12016 // unbind, so just rebind right here.
12017 requestServiceBindingLocked(r, b, true);
12018 } else {
12019 // Note to tell the service the next time there is
12020 // a new client.
12021 b.doRebind = true;
12022 }
12023 }
12024
Per Edelberg78f9fff2010-08-30 20:01:35 +020012025 serviceDoneExecutingLocked(r, inStopping);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012026
12027 Binder.restoreCallingIdentity(origId);
12028 }
12029 }
12030 }
12031
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012032 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012033 synchronized(this) {
12034 if (!(token instanceof ServiceRecord)) {
12035 throw new IllegalArgumentException("Invalid service token");
12036 }
12037 ServiceRecord r = (ServiceRecord)token;
12038 boolean inStopping = mStoppingServices.contains(token);
12039 if (r != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012040 if (r != token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012041 Slog.w(TAG, "Done executing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012042 + " with incorrect token: given " + token
12043 + ", expected " + r);
12044 return;
12045 }
12046
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012047 if (type == 1) {
12048 // This is a call from a service start... take care of
12049 // book-keeping.
12050 r.callStart = true;
12051 switch (res) {
12052 case Service.START_STICKY_COMPATIBILITY:
12053 case Service.START_STICKY: {
12054 // We are done with the associated start arguments.
12055 r.findDeliveredStart(startId, true);
12056 // Don't stop if killed.
12057 r.stopIfKilled = false;
12058 break;
12059 }
12060 case Service.START_NOT_STICKY: {
12061 // We are done with the associated start arguments.
12062 r.findDeliveredStart(startId, true);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070012063 if (r.getLastStartId() == startId) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012064 // There is no more work, and this service
12065 // doesn't want to hang around if killed.
12066 r.stopIfKilled = true;
12067 }
12068 break;
12069 }
12070 case Service.START_REDELIVER_INTENT: {
12071 // We'll keep this item until they explicitly
12072 // call stop for it, but keep track of the fact
12073 // that it was delivered.
12074 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
12075 if (si != null) {
12076 si.deliveryCount = 0;
12077 si.doneExecutingCount++;
12078 // Don't stop if killed.
12079 r.stopIfKilled = true;
12080 }
12081 break;
12082 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070012083 case Service.START_TASK_REMOVED_COMPLETE: {
12084 // Special processing for onTaskRemoved(). Don't
12085 // impact normal onStartCommand() processing.
12086 r.findDeliveredStart(startId, true);
12087 break;
12088 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012089 default:
12090 throw new IllegalArgumentException(
12091 "Unknown service start result: " + res);
12092 }
12093 if (res == Service.START_STICKY_COMPATIBILITY) {
12094 r.callStart = false;
12095 }
12096 }
Amith Yamasani742a6712011-05-04 14:49:28 -070012097 if (DEBUG_MU)
12098 Slog.v(TAG_MU, "before serviceDontExecutingLocked, uid="
12099 + Binder.getOrigCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012100 final long origId = Binder.clearCallingIdentity();
12101 serviceDoneExecutingLocked(r, inStopping);
12102 Binder.restoreCallingIdentity(origId);
12103 } else {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012104 Slog.w(TAG, "Done executing unknown service from pid "
12105 + Binder.getCallingPid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012106 }
12107 }
12108 }
12109
12110 public void serviceDoneExecutingLocked(ServiceRecord r, boolean inStopping) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012111 if (DEBUG_SERVICE) Slog.v(TAG, "<<< DONE EXECUTING " + r
12112 + ": nesting=" + r.executeNesting
12113 + ", inStopping=" + inStopping + ", app=" + r.app);
Dianne Hackborn287952c2010-09-22 22:34:31 -070012114 else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG, "<<< DONE EXECUTING " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012115 r.executeNesting--;
12116 if (r.executeNesting <= 0 && r.app != null) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012117 if (DEBUG_SERVICE) Slog.v(TAG,
12118 "Nesting at 0 of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012119 r.app.executingServices.remove(r);
12120 if (r.app.executingServices.size() == 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012121 if (DEBUG_SERVICE || DEBUG_SERVICE_EXECUTING) Slog.v(TAG,
12122 "No more executingServices of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012123 mHandler.removeMessages(SERVICE_TIMEOUT_MSG, r.app);
12124 }
12125 if (inStopping) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012126 if (DEBUG_SERVICE) Slog.v(TAG,
12127 "doneExecuting remove stopping " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012128 mStoppingServices.remove(r);
Mattias Petersson3996b412010-10-27 09:32:51 +020012129 r.bindings.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012130 }
12131 updateOomAdjLocked(r.app);
12132 }
12133 }
12134
12135 void serviceTimeout(ProcessRecord proc) {
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012136 String anrMessage = null;
12137
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012138 synchronized(this) {
12139 if (proc.executingServices.size() == 0 || proc.thread == null) {
12140 return;
12141 }
12142 long maxTime = SystemClock.uptimeMillis() - SERVICE_TIMEOUT;
12143 Iterator<ServiceRecord> it = proc.executingServices.iterator();
12144 ServiceRecord timeout = null;
12145 long nextTime = 0;
12146 while (it.hasNext()) {
12147 ServiceRecord sr = it.next();
12148 if (sr.executingStart < maxTime) {
12149 timeout = sr;
12150 break;
12151 }
12152 if (sr.executingStart > nextTime) {
12153 nextTime = sr.executingStart;
12154 }
12155 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012156 if (timeout != null && mLruProcesses.contains(proc)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012157 Slog.w(TAG, "Timeout executing service: " + timeout);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012158 anrMessage = "Executing service " + timeout.shortName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012159 } else {
12160 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
12161 msg.obj = proc;
12162 mHandler.sendMessageAtTime(msg, nextTime+SERVICE_TIMEOUT);
12163 }
12164 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012165
12166 if (anrMessage != null) {
12167 appNotResponding(proc, null, null, anrMessage);
12168 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012169 }
12170
12171 // =========================================================
Christopher Tate181fafa2009-05-14 11:12:14 -070012172 // BACKUP AND RESTORE
12173 // =========================================================
12174
12175 // Cause the target app to be launched if necessary and its backup agent
12176 // instantiated. The backup agent will invoke backupAgentCreated() on the
12177 // activity manager to announce its creation.
12178 public boolean bindBackupAgent(ApplicationInfo app, int backupMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012179 if (DEBUG_BACKUP) Slog.v(TAG, "startBackupAgent: app=" + app + " mode=" + backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070012180 enforceCallingPermission("android.permission.BACKUP", "startBackupAgent");
12181
12182 synchronized(this) {
12183 // !!! TODO: currently no check here that we're already bound
12184 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
12185 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
12186 synchronized (stats) {
12187 ss = stats.getServiceStatsLocked(app.uid, app.packageName, app.name);
12188 }
12189
Dianne Hackborne7f97212011-02-24 14:40:20 -080012190 // Backup agent is now in use, its package can't be stopped.
12191 try {
12192 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -070012193 app.packageName, false, UserId.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -080012194 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080012195 } catch (IllegalArgumentException e) {
12196 Slog.w(TAG, "Failed trying to unstop package "
12197 + app.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080012198 }
12199
Christopher Tate181fafa2009-05-14 11:12:14 -070012200 BackupRecord r = new BackupRecord(ss, app, backupMode);
Christopher Tate4a627c72011-04-01 14:43:32 -070012201 ComponentName hostingName = (backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL)
12202 ? new ComponentName(app.packageName, app.backupAgentName)
12203 : new ComponentName("android", "FullBackupAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -070012204 // startProcessLocked() returns existing proc's record if it's already running
12205 ProcessRecord proc = startProcessLocked(app.processName, app,
Dianne Hackborna0c283e2012-02-09 10:47:01 -080012206 false, 0, "backup", hostingName, false, false);
Christopher Tate181fafa2009-05-14 11:12:14 -070012207 if (proc == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012208 Slog.e(TAG, "Unable to start backup agent process " + r);
Christopher Tate181fafa2009-05-14 11:12:14 -070012209 return false;
12210 }
12211
12212 r.app = proc;
12213 mBackupTarget = r;
12214 mBackupAppName = app.packageName;
12215
Christopher Tate6fa95972009-06-05 18:43:55 -070012216 // Try not to kill the process during backup
12217 updateOomAdjLocked(proc);
12218
Christopher Tate181fafa2009-05-14 11:12:14 -070012219 // If the process is already attached, schedule the creation of the backup agent now.
12220 // If it is not yet live, this will be done when it attaches to the framework.
12221 if (proc.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012222 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc already running: " + proc);
Christopher Tate181fafa2009-05-14 11:12:14 -070012223 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040012224 proc.thread.scheduleCreateBackupAgent(app,
12225 compatibilityInfoForPackageLocked(app), backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070012226 } catch (RemoteException e) {
Christopher Tate436344a2009-09-30 16:17:37 -070012227 // Will time out on the backup manager side
Christopher Tate181fafa2009-05-14 11:12:14 -070012228 }
12229 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012230 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc not running, waiting for attach");
Christopher Tate181fafa2009-05-14 11:12:14 -070012231 }
12232 // Invariants: at this point, the target app process exists and the application
12233 // is either already running or in the process of coming up. mBackupTarget and
12234 // mBackupAppName describe the app, so that when it binds back to the AM we
12235 // know that it's scheduled for a backup-agent operation.
12236 }
12237
12238 return true;
12239 }
12240
12241 // A backup agent has just come up
12242 public void backupAgentCreated(String agentPackageName, IBinder agent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012243 if (DEBUG_BACKUP) Slog.v(TAG, "backupAgentCreated: " + agentPackageName
Christopher Tate181fafa2009-05-14 11:12:14 -070012244 + " = " + agent);
12245
12246 synchronized(this) {
12247 if (!agentPackageName.equals(mBackupAppName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012248 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
Christopher Tate181fafa2009-05-14 11:12:14 -070012249 return;
12250 }
Dianne Hackborn06740692010-09-22 22:46:21 -070012251 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012252
Dianne Hackborn06740692010-09-22 22:46:21 -070012253 long oldIdent = Binder.clearCallingIdentity();
12254 try {
12255 IBackupManager bm = IBackupManager.Stub.asInterface(
12256 ServiceManager.getService(Context.BACKUP_SERVICE));
12257 bm.agentConnected(agentPackageName, agent);
12258 } catch (RemoteException e) {
12259 // can't happen; the backup manager service is local
12260 } catch (Exception e) {
12261 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: ");
12262 e.printStackTrace();
12263 } finally {
12264 Binder.restoreCallingIdentity(oldIdent);
Christopher Tate181fafa2009-05-14 11:12:14 -070012265 }
12266 }
12267
12268 // done with this agent
12269 public void unbindBackupAgent(ApplicationInfo appInfo) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012270 if (DEBUG_BACKUP) Slog.v(TAG, "unbindBackupAgent: " + appInfo);
Christopher Tate8a27f922009-06-26 11:49:18 -070012271 if (appInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012272 Slog.w(TAG, "unbind backup agent for null app");
Christopher Tate8a27f922009-06-26 11:49:18 -070012273 return;
12274 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012275
12276 synchronized(this) {
Christopher Tate8a27f922009-06-26 11:49:18 -070012277 if (mBackupAppName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012278 Slog.w(TAG, "Unbinding backup agent with no active backup");
Christopher Tate8a27f922009-06-26 11:49:18 -070012279 return;
12280 }
12281
Christopher Tate181fafa2009-05-14 11:12:14 -070012282 if (!mBackupAppName.equals(appInfo.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012283 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
Christopher Tate181fafa2009-05-14 11:12:14 -070012284 return;
12285 }
12286
Christopher Tate6fa95972009-06-05 18:43:55 -070012287 ProcessRecord proc = mBackupTarget.app;
12288 mBackupTarget = null;
12289 mBackupAppName = null;
12290
12291 // Not backing this app up any more; reset its OOM adjustment
12292 updateOomAdjLocked(proc);
12293
Christopher Tatec7b31e32009-06-10 15:49:30 -070012294 // If the app crashed during backup, 'thread' will be null here
12295 if (proc.thread != null) {
12296 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040012297 proc.thread.scheduleDestroyBackupAgent(appInfo,
12298 compatibilityInfoForPackageLocked(appInfo));
Christopher Tatec7b31e32009-06-10 15:49:30 -070012299 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012300 Slog.e(TAG, "Exception when unbinding backup agent:");
Christopher Tatec7b31e32009-06-10 15:49:30 -070012301 e.printStackTrace();
12302 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012303 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012304 }
12305 }
12306 // =========================================================
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012307 // BROADCASTS
12308 // =========================================================
12309
Josh Bartel7f208742010-02-25 11:01:44 -060012310 private final List getStickiesLocked(String action, IntentFilter filter,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012311 List cur) {
12312 final ContentResolver resolver = mContext.getContentResolver();
12313 final ArrayList<Intent> list = mStickyBroadcasts.get(action);
12314 if (list == null) {
12315 return cur;
12316 }
12317 int N = list.size();
12318 for (int i=0; i<N; i++) {
12319 Intent intent = list.get(i);
12320 if (filter.match(resolver, intent, true, TAG) >= 0) {
12321 if (cur == null) {
12322 cur = new ArrayList<Intent>();
12323 }
12324 cur.add(intent);
12325 }
12326 }
12327 return cur;
12328 }
12329
Christopher Tatef46723b2012-01-26 14:19:24 -080012330 boolean isPendingBroadcastProcessLocked(int pid) {
12331 return mFgBroadcastQueue.isPendingBroadcastProcessLocked(pid)
12332 || mBgBroadcastQueue.isPendingBroadcastProcessLocked(pid);
12333 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012334
Christopher Tatef46723b2012-01-26 14:19:24 -080012335 void skipPendingBroadcastLocked(int pid) {
12336 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
12337 for (BroadcastQueue queue : mBroadcastQueues) {
12338 queue.skipPendingBroadcastLocked(pid);
12339 }
12340 }
12341
12342 // The app just attached; send any pending broadcasts that it should receive
12343 boolean sendPendingBroadcastsLocked(ProcessRecord app) {
12344 boolean didSomething = false;
12345 for (BroadcastQueue queue : mBroadcastQueues) {
12346 didSomething |= queue.sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012347 }
Christopher Tatef46723b2012-01-26 14:19:24 -080012348 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012349 }
12350
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012351 public Intent registerReceiver(IApplicationThread caller, String callerPackage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012352 IIntentReceiver receiver, IntentFilter filter, String permission) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012353 enforceNotIsolatedCaller("registerReceiver");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012354 synchronized(this) {
12355 ProcessRecord callerApp = null;
12356 if (caller != null) {
12357 callerApp = getRecordForAppLocked(caller);
12358 if (callerApp == null) {
12359 throw new SecurityException(
12360 "Unable to find app for caller " + caller
12361 + " (pid=" + Binder.getCallingPid()
12362 + ") when registering receiver " + receiver);
12363 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012364 if (callerApp.info.uid != Process.SYSTEM_UID &&
12365 !callerApp.pkgList.contains(callerPackage)) {
12366 throw new SecurityException("Given caller package " + callerPackage
12367 + " is not running in process " + callerApp);
12368 }
12369 } else {
12370 callerPackage = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012371 }
12372
12373 List allSticky = null;
12374
12375 // Look for any matching sticky broadcasts...
12376 Iterator actions = filter.actionsIterator();
12377 if (actions != null) {
12378 while (actions.hasNext()) {
12379 String action = (String)actions.next();
Josh Bartel7f208742010-02-25 11:01:44 -060012380 allSticky = getStickiesLocked(action, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012381 }
12382 } else {
Josh Bartel7f208742010-02-25 11:01:44 -060012383 allSticky = getStickiesLocked(null, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012384 }
12385
12386 // The first sticky in the list is returned directly back to
12387 // the client.
12388 Intent sticky = allSticky != null ? (Intent)allSticky.get(0) : null;
12389
Joe Onorato8a9b2202010-02-26 18:56:32 -080012390 if (DEBUG_BROADCAST) Slog.v(TAG, "Register receiver " + filter
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012391 + ": " + sticky);
12392
12393 if (receiver == null) {
12394 return sticky;
12395 }
12396
12397 ReceiverList rl
12398 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
12399 if (rl == null) {
12400 rl = new ReceiverList(this, callerApp,
12401 Binder.getCallingPid(),
12402 Binder.getCallingUid(), receiver);
12403 if (rl.app != null) {
12404 rl.app.receivers.add(rl);
12405 } else {
12406 try {
12407 receiver.asBinder().linkToDeath(rl, 0);
12408 } catch (RemoteException e) {
12409 return sticky;
12410 }
12411 rl.linkedToDeath = true;
12412 }
12413 mRegisteredReceivers.put(receiver.asBinder(), rl);
12414 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012415 BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage, permission);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012416 rl.add(bf);
12417 if (!bf.debugCheck()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012418 Slog.w(TAG, "==> For Dynamic broadast");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012419 }
12420 mReceiverResolver.addFilter(bf);
12421
12422 // Enqueue broadcasts for all existing stickies that match
12423 // this filter.
12424 if (allSticky != null) {
12425 ArrayList receivers = new ArrayList();
12426 receivers.add(bf);
12427
12428 int N = allSticky.size();
12429 for (int i=0; i<N; i++) {
12430 Intent intent = (Intent)allSticky.get(i);
Christopher Tatef46723b2012-01-26 14:19:24 -080012431 BroadcastQueue queue = broadcastQueueForIntent(intent);
12432 BroadcastRecord r = new BroadcastRecord(queue, intent, null,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012433 null, -1, -1, null, receivers, null, 0, null, null,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012434 false, true, true);
Christopher Tatef46723b2012-01-26 14:19:24 -080012435 queue.enqueueParallelBroadcastLocked(r);
12436 queue.scheduleBroadcastsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012437 }
12438 }
12439
12440 return sticky;
12441 }
12442 }
12443
12444 public void unregisterReceiver(IIntentReceiver receiver) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012445 if (DEBUG_BROADCAST) Slog.v(TAG, "Unregister receiver: " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012446
Christopher Tatef46723b2012-01-26 14:19:24 -080012447 final long origId = Binder.clearCallingIdentity();
12448 try {
12449 boolean doTrim = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012450
Christopher Tatef46723b2012-01-26 14:19:24 -080012451 synchronized(this) {
12452 ReceiverList rl
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012453 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
Christopher Tatef46723b2012-01-26 14:19:24 -080012454 if (rl != null) {
12455 if (rl.curBroadcast != null) {
12456 BroadcastRecord r = rl.curBroadcast;
12457 final boolean doNext = finishReceiverLocked(
12458 receiver.asBinder(), r.resultCode, r.resultData,
12459 r.resultExtras, r.resultAbort, true);
12460 if (doNext) {
12461 doTrim = true;
12462 r.queue.processNextBroadcast(false);
12463 }
12464 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012465
Christopher Tatef46723b2012-01-26 14:19:24 -080012466 if (rl.app != null) {
12467 rl.app.receivers.remove(rl);
12468 }
12469 removeReceiverLocked(rl);
12470 if (rl.linkedToDeath) {
12471 rl.linkedToDeath = false;
12472 rl.receiver.asBinder().unlinkToDeath(rl, 0);
12473 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012474 }
12475 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012476
Christopher Tatef46723b2012-01-26 14:19:24 -080012477 // If we actually concluded any broadcasts, we might now be able
12478 // to trim the recipients' apps from our working set
12479 if (doTrim) {
12480 trimApplications();
12481 return;
12482 }
12483
12484 } finally {
12485 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012486 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012487 }
12488
12489 void removeReceiverLocked(ReceiverList rl) {
12490 mRegisteredReceivers.remove(rl.receiver.asBinder());
12491 int N = rl.size();
12492 for (int i=0; i<N; i++) {
12493 mReceiverResolver.removeFilter(rl.get(i));
12494 }
12495 }
12496
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012497 private final void sendPackageBroadcastLocked(int cmd, String[] packages) {
12498 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
12499 ProcessRecord r = mLruProcesses.get(i);
12500 if (r.thread != null) {
12501 try {
12502 r.thread.dispatchPackageBroadcast(cmd, packages);
12503 } catch (RemoteException ex) {
12504 }
12505 }
12506 }
12507 }
12508
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012509 private final int broadcastIntentLocked(ProcessRecord callerApp,
12510 String callerPackage, Intent intent, String resolvedType,
12511 IIntentReceiver resultTo, int resultCode, String resultData,
12512 Bundle map, String requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070012513 boolean ordered, boolean sticky, int callingPid, int callingUid,
12514 int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012515 intent = new Intent(intent);
12516
Dianne Hackborne7f97212011-02-24 14:40:20 -080012517 // By default broadcasts do not go to stopped apps.
12518 intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
12519
Joe Onorato8a9b2202010-02-26 18:56:32 -080012520 if (DEBUG_BROADCAST_LIGHT) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012521 TAG, (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
Amith Yamasani13593602012-03-22 16:16:17 -070012522 + " ordered=" + ordered + " userid=" + userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012523 if ((resultTo != null) && !ordered) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012524 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012525 }
12526
12527 // Handle special intents: if this broadcast is from the package
12528 // manager about a package being removed, we need to remove all of
12529 // its activities from the history stack.
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012530 final boolean uidRemoved = Intent.ACTION_UID_REMOVED.equals(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012531 intent.getAction());
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012532 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())
12533 || Intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction())
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080012534 || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012535 || uidRemoved) {
12536 if (checkComponentPermission(
12537 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080012538 callingPid, callingUid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012539 == PackageManager.PERMISSION_GRANTED) {
12540 if (uidRemoved) {
12541 final Bundle intentExtras = intent.getExtras();
12542 final int uid = intentExtras != null
12543 ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
12544 if (uid >= 0) {
12545 BatteryStatsImpl bs = mBatteryStatsService.getActiveStatistics();
12546 synchronized (bs) {
12547 bs.removeUidStatsLocked(uid);
12548 }
12549 }
12550 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012551 // If resources are unvailble just force stop all
12552 // those packages and flush the attribute cache as well.
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080012553 if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012554 String list[] = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
12555 if (list != null && (list.length > 0)) {
12556 for (String pkg : list) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070012557 forceStopPackageLocked(pkg, -1, false, true, true, false, userId);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012558 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012559 sendPackageBroadcastLocked(
12560 IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE, list);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012561 }
12562 } else {
12563 Uri data = intent.getData();
12564 String ssp;
12565 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
12566 if (!intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false)) {
12567 forceStopPackageLocked(ssp,
Amith Yamasani483f3b02012-03-13 16:08:00 -070012568 intent.getIntExtra(Intent.EXTRA_UID, -1), false, true, true,
12569 false, userId);
Dianne Hackbornde7faf62009-06-30 13:27:30 -070012570 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012571 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012572 sendPackageBroadcastLocked(IApplicationThread.PACKAGE_REMOVED,
12573 new String[] {ssp});
12574 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012575 }
12576 }
12577 }
12578 } else {
12579 String msg = "Permission Denial: " + intent.getAction()
12580 + " broadcast from " + callerPackage + " (pid=" + callingPid
12581 + ", uid=" + callingUid + ")"
12582 + " requires "
12583 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012584 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012585 throw new SecurityException(msg);
12586 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012587
12588 // Special case for adding a package: by default turn on compatibility
12589 // mode.
12590 } else if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -070012591 Uri data = intent.getData();
12592 String ssp;
12593 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
12594 mCompatModePackages.handlePackageAddedLocked(ssp,
12595 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false));
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012596 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012597 }
12598
12599 /*
12600 * If this is the time zone changed action, queue up a message that will reset the timezone
12601 * of all currently running processes. This message will get queued up before the broadcast
12602 * happens.
12603 */
12604 if (intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) {
12605 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
12606 }
12607
Robert Greenwalt03595d02010-11-02 14:08:23 -070012608 if (intent.ACTION_CLEAR_DNS_CACHE.equals(intent.getAction())) {
12609 mHandler.sendEmptyMessage(CLEAR_DNS_CACHE);
12610 }
12611
Robert Greenwalt434203a2010-10-11 16:00:27 -070012612 if (Proxy.PROXY_CHANGE_ACTION.equals(intent.getAction())) {
12613 ProxyProperties proxy = intent.getParcelableExtra("proxy");
12614 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY, proxy));
12615 }
12616
Dianne Hackborn854060af2009-07-09 18:14:31 -070012617 /*
12618 * Prevent non-system code (defined here to be non-persistent
12619 * processes) from sending protected broadcasts.
12620 */
12621 if (callingUid == Process.SYSTEM_UID || callingUid == Process.PHONE_UID
12622 || callingUid == Process.SHELL_UID || callingUid == 0) {
12623 // Always okay.
12624 } else if (callerApp == null || !callerApp.persistent) {
12625 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012626 if (AppGlobals.getPackageManager().isProtectedBroadcast(
Dianne Hackborn854060af2009-07-09 18:14:31 -070012627 intent.getAction())) {
12628 String msg = "Permission Denial: not allowed to send broadcast "
12629 + intent.getAction() + " from pid="
12630 + callingPid + ", uid=" + callingUid;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012631 Slog.w(TAG, msg);
Dianne Hackborn854060af2009-07-09 18:14:31 -070012632 throw new SecurityException(msg);
12633 }
12634 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012635 Slog.w(TAG, "Remote exception", e);
Dianne Hackborna4972e92012-03-14 10:38:05 -070012636 return ActivityManager.BROADCAST_SUCCESS;
Dianne Hackborn854060af2009-07-09 18:14:31 -070012637 }
12638 }
12639
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012640 // Add to the sticky list if requested.
12641 if (sticky) {
12642 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
12643 callingPid, callingUid)
12644 != PackageManager.PERMISSION_GRANTED) {
12645 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
12646 + callingPid + ", uid=" + callingUid
12647 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012648 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012649 throw new SecurityException(msg);
12650 }
12651 if (requiredPermission != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012652 Slog.w(TAG, "Can't broadcast sticky intent " + intent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012653 + " and enforce permission " + requiredPermission);
Dianne Hackborna4972e92012-03-14 10:38:05 -070012654 return ActivityManager.BROADCAST_STICKY_CANT_HAVE_PERMISSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012655 }
12656 if (intent.getComponent() != null) {
12657 throw new SecurityException(
12658 "Sticky broadcasts can't target a specific component");
12659 }
12660 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
12661 if (list == null) {
12662 list = new ArrayList<Intent>();
12663 mStickyBroadcasts.put(intent.getAction(), list);
12664 }
12665 int N = list.size();
12666 int i;
12667 for (i=0; i<N; i++) {
12668 if (intent.filterEquals(list.get(i))) {
12669 // This sticky already exists, replace it.
12670 list.set(i, new Intent(intent));
12671 break;
12672 }
12673 }
12674 if (i >= N) {
12675 list.add(new Intent(intent));
12676 }
12677 }
12678
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012679 // Figure out who all will receive this broadcast.
12680 List receivers = null;
12681 List<BroadcastFilter> registeredReceivers = null;
12682 try {
12683 if (intent.getComponent() != null) {
12684 // Broadcast is going to one specific receiver class...
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012685 ActivityInfo ai = AppGlobals.getPackageManager().
Amith Yamasani483f3b02012-03-13 16:08:00 -070012686 getReceiverInfo(intent.getComponent(), STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012687 if (ai != null) {
12688 receivers = new ArrayList();
12689 ResolveInfo ri = new ResolveInfo();
Amith Yamasani742a6712011-05-04 14:49:28 -070012690 ri.activityInfo = getActivityInfoForUser(ai, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012691 receivers.add(ri);
12692 }
12693 } else {
12694 // Need to resolve the intent to interested receivers...
12695 if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
12696 == 0) {
12697 receivers =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012698 AppGlobals.getPackageManager().queryIntentReceivers(
Amith Yamasani483f3b02012-03-13 16:08:00 -070012699 intent, resolvedType, STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012700 }
Amith Yamasani483f3b02012-03-13 16:08:00 -070012701 registeredReceivers = mReceiverResolver.queryIntent(intent, resolvedType, false,
12702 userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012703 }
12704 } catch (RemoteException ex) {
12705 // pm is in same process, this will never happen.
12706 }
12707
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012708 final boolean replacePending =
12709 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
12710
Joe Onorato8a9b2202010-02-26 18:56:32 -080012711 if (DEBUG_BROADCAST) Slog.v(TAG, "Enqueing broadcast: " + intent.getAction()
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012712 + " replacePending=" + replacePending);
12713
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012714 int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
12715 if (!ordered && NR > 0) {
12716 // If we are not serializing this broadcast, then send the
12717 // registered receivers separately so they don't wait for the
12718 // components to be launched.
Christopher Tatef46723b2012-01-26 14:19:24 -080012719 final BroadcastQueue queue = broadcastQueueForIntent(intent);
12720 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012721 callerPackage, callingPid, callingUid, requiredPermission,
12722 registeredReceivers, resultTo, resultCode, resultData, map,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012723 ordered, sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012724 if (DEBUG_BROADCAST) Slog.v(
Christopher Tatef46723b2012-01-26 14:19:24 -080012725 TAG, "Enqueueing parallel broadcast " + r);
12726 final boolean replaced = replacePending && queue.replaceParallelBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012727 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012728 queue.enqueueParallelBroadcastLocked(r);
12729 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012730 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012731 registeredReceivers = null;
12732 NR = 0;
12733 }
12734
12735 // Merge into one list.
12736 int ir = 0;
12737 if (receivers != null) {
12738 // A special case for PACKAGE_ADDED: do not allow the package
12739 // being added to see this broadcast. This prevents them from
12740 // using this as a back door to get run as soon as they are
12741 // installed. Maybe in the future we want to have a special install
12742 // broadcast or such for apps, but we'd like to deliberately make
12743 // this decision.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012744 String skipPackages[] = null;
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012745 if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
12746 || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
12747 || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012748 Uri data = intent.getData();
12749 if (data != null) {
12750 String pkgName = data.getSchemeSpecificPart();
12751 if (pkgName != null) {
12752 skipPackages = new String[] { pkgName };
12753 }
12754 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012755 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012756 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
The Android Open Source Project10592532009-03-18 17:39:46 -070012757 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012758 if (skipPackages != null && (skipPackages.length > 0)) {
12759 for (String skipPackage : skipPackages) {
12760 if (skipPackage != null) {
12761 int NT = receivers.size();
12762 for (int it=0; it<NT; it++) {
12763 ResolveInfo curt = (ResolveInfo)receivers.get(it);
12764 if (curt.activityInfo.packageName.equals(skipPackage)) {
12765 receivers.remove(it);
12766 it--;
12767 NT--;
12768 }
12769 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012770 }
12771 }
12772 }
12773
12774 int NT = receivers != null ? receivers.size() : 0;
12775 int it = 0;
12776 ResolveInfo curt = null;
12777 BroadcastFilter curr = null;
12778 while (it < NT && ir < NR) {
12779 if (curt == null) {
12780 curt = (ResolveInfo)receivers.get(it);
12781 }
12782 if (curr == null) {
12783 curr = registeredReceivers.get(ir);
12784 }
12785 if (curr.getPriority() >= curt.priority) {
12786 // Insert this broadcast record into the final list.
12787 receivers.add(it, curr);
12788 ir++;
12789 curr = null;
12790 it++;
12791 NT++;
12792 } else {
12793 // Skip to the next ResolveInfo in the final list.
12794 it++;
12795 curt = null;
12796 }
12797 }
12798 }
12799 while (ir < NR) {
12800 if (receivers == null) {
12801 receivers = new ArrayList();
12802 }
12803 receivers.add(registeredReceivers.get(ir));
12804 ir++;
12805 }
12806
12807 if ((receivers != null && receivers.size() > 0)
12808 || resultTo != null) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012809 BroadcastQueue queue = broadcastQueueForIntent(intent);
12810 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012811 callerPackage, callingPid, callingUid, requiredPermission,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012812 receivers, resultTo, resultCode, resultData, map, ordered,
12813 sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012814 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012815 TAG, "Enqueueing ordered broadcast " + r
Christopher Tatef46723b2012-01-26 14:19:24 -080012816 + ": prev had " + queue.mOrderedBroadcasts.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012817 if (DEBUG_BROADCAST) {
12818 int seq = r.intent.getIntExtra("seq", -1);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012819 Slog.i(TAG, "Enqueueing broadcast " + r.intent.getAction() + " seq=" + seq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012820 }
Christopher Tatef46723b2012-01-26 14:19:24 -080012821 boolean replaced = replacePending && queue.replaceOrderedBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012822 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012823 queue.enqueueOrderedBroadcastLocked(r);
12824 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012825 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012826 }
12827
Dianne Hackborna4972e92012-03-14 10:38:05 -070012828 return ActivityManager.BROADCAST_SUCCESS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012829 }
12830
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012831 final Intent verifyBroadcastLocked(Intent intent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012832 // Refuse possible leaked file descriptors
12833 if (intent != null && intent.hasFileDescriptors() == true) {
12834 throw new IllegalArgumentException("File descriptors passed in Intent");
12835 }
12836
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012837 int flags = intent.getFlags();
12838
12839 if (!mProcessesReady) {
12840 // if the caller really truly claims to know what they're doing, go
12841 // ahead and allow the broadcast without launching any receivers
12842 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
12843 intent = new Intent(intent);
12844 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
12845 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
12846 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
12847 + " before boot completion");
12848 throw new IllegalStateException("Cannot broadcast before boot completed");
12849 }
12850 }
12851
12852 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
12853 throw new IllegalArgumentException(
12854 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
12855 }
12856
12857 return intent;
12858 }
12859
12860 public final int broadcastIntent(IApplicationThread caller,
12861 Intent intent, String resolvedType, IIntentReceiver resultTo,
12862 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070012863 String requiredPermission, boolean serialized, boolean sticky, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012864 enforceNotIsolatedCaller("broadcastIntent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012865 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012866 intent = verifyBroadcastLocked(intent);
Dianne Hackborn9acc0302009-08-25 00:27:12 -070012867
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012868 final ProcessRecord callerApp = getRecordForAppLocked(caller);
12869 final int callingPid = Binder.getCallingPid();
12870 final int callingUid = Binder.getCallingUid();
12871 final long origId = Binder.clearCallingIdentity();
12872 int res = broadcastIntentLocked(callerApp,
12873 callerApp != null ? callerApp.info.packageName : null,
12874 intent, resolvedType, resultTo,
Amith Yamasani742a6712011-05-04 14:49:28 -070012875 resultCode, resultData, map, requiredPermission, serialized, sticky,
12876 callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012877 Binder.restoreCallingIdentity(origId);
12878 return res;
12879 }
12880 }
12881
12882 int broadcastIntentInPackage(String packageName, int uid,
12883 Intent intent, String resolvedType, IIntentReceiver resultTo,
12884 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070012885 String requiredPermission, boolean serialized, boolean sticky, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012886 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012887 intent = verifyBroadcastLocked(intent);
12888
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012889 final long origId = Binder.clearCallingIdentity();
12890 int res = broadcastIntentLocked(null, packageName, intent, resolvedType,
12891 resultTo, resultCode, resultData, map, requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070012892 serialized, sticky, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012893 Binder.restoreCallingIdentity(origId);
12894 return res;
12895 }
12896 }
12897
Amith Yamasani742a6712011-05-04 14:49:28 -070012898 // TODO: Use the userId; maybe mStickyBroadcasts need to be tied to the user.
12899 public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012900 // Refuse possible leaked file descriptors
12901 if (intent != null && intent.hasFileDescriptors() == true) {
12902 throw new IllegalArgumentException("File descriptors passed in Intent");
12903 }
12904
12905 synchronized(this) {
12906 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
12907 != PackageManager.PERMISSION_GRANTED) {
12908 String msg = "Permission Denial: unbroadcastIntent() from pid="
12909 + Binder.getCallingPid()
12910 + ", uid=" + Binder.getCallingUid()
12911 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012912 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012913 throw new SecurityException(msg);
12914 }
12915 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
12916 if (list != null) {
12917 int N = list.size();
12918 int i;
12919 for (i=0; i<N; i++) {
12920 if (intent.filterEquals(list.get(i))) {
12921 list.remove(i);
12922 break;
12923 }
12924 }
12925 }
12926 }
12927 }
12928
12929 private final boolean finishReceiverLocked(IBinder receiver, int resultCode,
12930 String resultData, Bundle resultExtras, boolean resultAbort,
12931 boolean explicit) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012932 final BroadcastRecord r = broadcastRecordForReceiverLocked(receiver);
12933 if (r == null) {
12934 Slog.w(TAG, "finishReceiver called but not found on queue");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012935 return false;
12936 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012937
Christopher Tatef46723b2012-01-26 14:19:24 -080012938 return r.queue.finishReceiverLocked(r, resultCode, resultData, resultExtras, resultAbort,
12939 explicit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012940 }
12941
12942 public void finishReceiver(IBinder who, int resultCode, String resultData,
12943 Bundle resultExtras, boolean resultAbort) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012944 if (DEBUG_BROADCAST) Slog.v(TAG, "Finish receiver: " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012945
12946 // Refuse possible leaked file descriptors
12947 if (resultExtras != null && resultExtras.hasFileDescriptors()) {
12948 throw new IllegalArgumentException("File descriptors passed in Bundle");
12949 }
12950
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012951 final long origId = Binder.clearCallingIdentity();
Christopher Tatef46723b2012-01-26 14:19:24 -080012952 try {
12953 boolean doNext = false;
12954 BroadcastRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012955
Christopher Tatef46723b2012-01-26 14:19:24 -080012956 synchronized(this) {
12957 r = broadcastRecordForReceiverLocked(who);
12958 if (r != null) {
12959 doNext = r.queue.finishReceiverLocked(r, resultCode,
12960 resultData, resultExtras, resultAbort, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012961 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012962 }
Jeff Brown4d94a762010-09-23 11:33:28 -070012963
Christopher Tatef46723b2012-01-26 14:19:24 -080012964 if (doNext) {
12965 r.queue.processNextBroadcast(false);
12966 }
12967 trimApplications();
12968 } finally {
12969 Binder.restoreCallingIdentity(origId);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012970 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012971 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012972
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012973 // =========================================================
12974 // INSTRUMENTATION
12975 // =========================================================
12976
12977 public boolean startInstrumentation(ComponentName className,
12978 String profileFile, int flags, Bundle arguments,
12979 IInstrumentationWatcher watcher) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012980 enforceNotIsolatedCaller("startInstrumentation");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012981 // Refuse possible leaked file descriptors
12982 if (arguments != null && arguments.hasFileDescriptors()) {
12983 throw new IllegalArgumentException("File descriptors passed in Bundle");
12984 }
12985
12986 synchronized(this) {
12987 InstrumentationInfo ii = null;
12988 ApplicationInfo ai = null;
12989 try {
12990 ii = mContext.getPackageManager().getInstrumentationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070012991 className, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012992 ai = mContext.getPackageManager().getApplicationInfo(
Amith Yamasani483f3b02012-03-13 16:08:00 -070012993 ii.targetPackage, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012994 } catch (PackageManager.NameNotFoundException e) {
12995 }
12996 if (ii == null) {
12997 reportStartInstrumentationFailure(watcher, className,
12998 "Unable to find instrumentation info for: " + className);
12999 return false;
13000 }
13001 if (ai == null) {
13002 reportStartInstrumentationFailure(watcher, className,
13003 "Unable to find instrumentation target package: " + ii.targetPackage);
13004 return false;
13005 }
13006
13007 int match = mContext.getPackageManager().checkSignatures(
13008 ii.targetPackage, ii.packageName);
13009 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
13010 String msg = "Permission Denial: starting instrumentation "
13011 + className + " from pid="
13012 + Binder.getCallingPid()
13013 + ", uid=" + Binder.getCallingPid()
13014 + " not allowed because package " + ii.packageName
13015 + " does not have a signature matching the target "
13016 + ii.targetPackage;
13017 reportStartInstrumentationFailure(watcher, className, msg);
13018 throw new SecurityException(msg);
13019 }
13020
Amith Yamasani483f3b02012-03-13 16:08:00 -070013021 int userId = UserId.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013022 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -070013023 // Instrumentation can kill and relaunch even persistent processes
Amith Yamasani483f3b02012-03-13 16:08:00 -070013024 forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true, userId);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013025 ProcessRecord app = addAppLocked(ai, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013026 app.instrumentationClass = className;
Dianne Hackborn1655be42009-05-08 14:29:01 -070013027 app.instrumentationInfo = ai;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013028 app.instrumentationProfileFile = profileFile;
13029 app.instrumentationArguments = arguments;
13030 app.instrumentationWatcher = watcher;
13031 app.instrumentationResultClass = className;
13032 Binder.restoreCallingIdentity(origId);
13033 }
13034
13035 return true;
13036 }
13037
13038 /**
13039 * Report errors that occur while attempting to start Instrumentation. Always writes the
13040 * error to the logs, but if somebody is watching, send the report there too. This enables
13041 * the "am" command to report errors with more information.
13042 *
13043 * @param watcher The IInstrumentationWatcher. Null if there isn't one.
13044 * @param cn The component name of the instrumentation.
13045 * @param report The error report.
13046 */
13047 private void reportStartInstrumentationFailure(IInstrumentationWatcher watcher,
13048 ComponentName cn, String report) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013049 Slog.w(TAG, report);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013050 try {
13051 if (watcher != null) {
13052 Bundle results = new Bundle();
13053 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
13054 results.putString("Error", report);
13055 watcher.instrumentationStatus(cn, -1, results);
13056 }
13057 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013058 Slog.w(TAG, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013059 }
13060 }
13061
13062 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
13063 if (app.instrumentationWatcher != null) {
13064 try {
13065 // NOTE: IInstrumentationWatcher *must* be oneway here
13066 app.instrumentationWatcher.instrumentationFinished(
13067 app.instrumentationClass,
13068 resultCode,
13069 results);
13070 } catch (RemoteException e) {
13071 }
13072 }
13073 app.instrumentationWatcher = null;
13074 app.instrumentationClass = null;
Dianne Hackborn1655be42009-05-08 14:29:01 -070013075 app.instrumentationInfo = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013076 app.instrumentationProfileFile = null;
13077 app.instrumentationArguments = null;
13078
Amith Yamasani483f3b02012-03-13 16:08:00 -070013079 forceStopPackageLocked(app.processName, -1, false, false, true, true, app.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013080 }
13081
13082 public void finishInstrumentation(IApplicationThread target,
13083 int resultCode, Bundle results) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070013084 int userId = UserId.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013085 // Refuse possible leaked file descriptors
13086 if (results != null && results.hasFileDescriptors()) {
13087 throw new IllegalArgumentException("File descriptors passed in Intent");
13088 }
13089
13090 synchronized(this) {
13091 ProcessRecord app = getRecordForAppLocked(target);
13092 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013093 Slog.w(TAG, "finishInstrumentation: no app for " + target);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013094 return;
13095 }
13096 final long origId = Binder.clearCallingIdentity();
13097 finishInstrumentationLocked(app, resultCode, results);
13098 Binder.restoreCallingIdentity(origId);
13099 }
13100 }
13101
13102 // =========================================================
13103 // CONFIGURATION
13104 // =========================================================
13105
13106 public ConfigurationInfo getDeviceConfigurationInfo() {
13107 ConfigurationInfo config = new ConfigurationInfo();
13108 synchronized (this) {
13109 config.reqTouchScreen = mConfiguration.touchscreen;
13110 config.reqKeyboardType = mConfiguration.keyboard;
13111 config.reqNavigation = mConfiguration.navigation;
Dianne Hackbornfae76f52009-07-16 13:41:23 -070013112 if (mConfiguration.navigation == Configuration.NAVIGATION_DPAD
13113 || mConfiguration.navigation == Configuration.NAVIGATION_TRACKBALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013114 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
13115 }
Dianne Hackbornfae76f52009-07-16 13:41:23 -070013116 if (mConfiguration.keyboard != Configuration.KEYBOARD_UNDEFINED
13117 && mConfiguration.keyboard != Configuration.KEYBOARD_NOKEYS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013118 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
13119 }
Jack Palevichb90d28c2009-07-22 15:35:24 -070013120 config.reqGlEsVersion = GL_ES_VERSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013121 }
13122 return config;
13123 }
13124
13125 public Configuration getConfiguration() {
13126 Configuration ci;
13127 synchronized(this) {
13128 ci = new Configuration(mConfiguration);
13129 }
13130 return ci;
13131 }
13132
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013133 public void updatePersistentConfiguration(Configuration values) {
13134 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
13135 "updateConfiguration()");
13136 enforceCallingPermission(android.Manifest.permission.WRITE_SETTINGS,
13137 "updateConfiguration()");
13138 if (values == null) {
13139 throw new NullPointerException("Configuration must not be null");
13140 }
13141
13142 synchronized(this) {
13143 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn813075a62011-11-14 17:45:19 -080013144 updateConfigurationLocked(values, null, true, false);
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013145 Binder.restoreCallingIdentity(origId);
13146 }
13147 }
13148
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013149 public void updateConfiguration(Configuration values) {
13150 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
13151 "updateConfiguration()");
13152
13153 synchronized(this) {
13154 if (values == null && mWindowManager != null) {
13155 // sentinel: fetch the current configuration from the window manager
13156 values = mWindowManager.computeNewConfiguration();
13157 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013158
13159 if (mWindowManager != null) {
13160 mProcessList.applyDisplaySize(mWindowManager);
13161 }
13162
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013163 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013164 if (values != null) {
13165 Settings.System.clearConfiguration(values);
13166 }
Dianne Hackborn813075a62011-11-14 17:45:19 -080013167 updateConfigurationLocked(values, null, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013168 Binder.restoreCallingIdentity(origId);
13169 }
13170 }
13171
13172 /**
13173 * Do either or both things: (1) change the current configuration, and (2)
13174 * make sure the given activity is running with the (now) current
13175 * configuration. Returns true if the activity has been left running, or
13176 * false if <var>starting</var> is being destroyed to match the new
13177 * configuration.
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013178 * @param persistent TODO
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013179 */
Dianne Hackborna573f6a2012-02-09 16:12:18 -080013180 boolean updateConfigurationLocked(Configuration values,
Dianne Hackborn813075a62011-11-14 17:45:19 -080013181 ActivityRecord starting, boolean persistent, boolean initLocale) {
Mike Lockwood3a74bd32011-08-12 13:55:22 -070013182 // do nothing if we are headless
13183 if (mHeadless) return true;
13184
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013185 int changes = 0;
13186
13187 boolean kept = true;
13188
13189 if (values != null) {
13190 Configuration newConfig = new Configuration(mConfiguration);
13191 changes = newConfig.updateFrom(values);
13192 if (changes != 0) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013193 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013194 Slog.i(TAG, "Updating configuration to: " + values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013195 }
13196
Doug Zongker2bec3d42009-12-04 12:52:44 -080013197 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013198
Dianne Hackborn813075a62011-11-14 17:45:19 -080013199 if (values.locale != null && !initLocale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013200 saveLocaleLocked(values.locale,
13201 !values.locale.equals(mConfiguration.locale),
13202 values.userSetLocale);
13203 }
13204
Dianne Hackborne36d6e22010-02-17 19:46:25 -080013205 mConfigurationSeq++;
13206 if (mConfigurationSeq <= 0) {
13207 mConfigurationSeq = 1;
13208 }
13209 newConfig.seq = mConfigurationSeq;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013210 mConfiguration = newConfig;
Joe Onorato8a9b2202010-02-26 18:56:32 -080013211 Slog.i(TAG, "Config changed: " + newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013212
13213 final Configuration configCopy = new Configuration(mConfiguration);
Joe Onorato54a4a412011-11-02 20:50:08 -070013214
13215 // TODO: If our config changes, should we auto dismiss any currently
13216 // showing dialogs?
13217 mShowDialogs = shouldShowDialogs(newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013218
Dianne Hackborn826d17c2009-11-12 12:55:51 -080013219 AttributeCache ac = AttributeCache.instance();
13220 if (ac != null) {
Dianne Hackborn813075a62011-11-14 17:45:19 -080013221 ac.updateConfiguration(configCopy);
Dianne Hackborn826d17c2009-11-12 12:55:51 -080013222 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013223
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070013224 // Make sure all resources in our process are updated
13225 // right now, so that anyone who is going to retrieve
13226 // resource values after we return will be sure to get
13227 // the new ones. This is especially important during
13228 // boot, where the first config change needs to guarantee
13229 // all resources have that config before following boot
13230 // code is executed.
Dianne Hackborn813075a62011-11-14 17:45:19 -080013231 mSystemThread.applyConfigurationToResources(configCopy);
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070013232
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013233 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080013234 Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013235 msg.obj = new Configuration(configCopy);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080013236 mHandler.sendMessage(msg);
13237 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013238
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013239 for (int i=mLruProcesses.size()-1; i>=0; i--) {
13240 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013241 try {
13242 if (app.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013243 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending to proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013244 + app.processName + " new config " + mConfiguration);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013245 app.thread.scheduleConfigurationChanged(configCopy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013246 }
13247 } catch (Exception e) {
13248 }
13249 }
13250 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080013251 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
13252 | Intent.FLAG_RECEIVER_REPLACE_PENDING);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013253 broadcastIntentLocked(null, null, intent, null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070013254 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080013255 if ((changes&ActivityInfo.CONFIG_LOCALE) != 0) {
13256 broadcastIntentLocked(null, null,
13257 new Intent(Intent.ACTION_LOCALE_CHANGED),
13258 null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070013259 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080013260 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013261 }
13262 }
13263
13264 if (changes != 0 && starting == null) {
13265 // If the configuration changed, and the caller is not already
13266 // in the process of starting an activity, then find the top
13267 // activity to check if its configuration needs to change.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013268 starting = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013269 }
13270
13271 if (starting != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013272 kept = mMainStack.ensureActivityConfigurationLocked(starting, changes);
Dianne Hackborn5f4d6432010-12-21 20:40:11 -080013273 // And we need to make sure at this point that all other activities
13274 // are made visible with the correct configuration.
13275 mMainStack.ensureActivitiesVisibleLocked(starting, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013276 }
13277
Dianne Hackborne36d6e22010-02-17 19:46:25 -080013278 if (values != null && mWindowManager != null) {
13279 mWindowManager.setNewConfiguration(mConfiguration);
13280 }
13281
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013282 return kept;
13283 }
Joe Onorato54a4a412011-11-02 20:50:08 -070013284
13285 /**
13286 * Decide based on the configuration whether we should shouw the ANR,
13287 * crash, etc dialogs. The idea is that if there is no affordnace to
13288 * press the on-screen buttons, we shouldn't show the dialog.
13289 *
13290 * A thought: SystemUI might also want to get told about this, the Power
13291 * dialog / global actions also might want different behaviors.
13292 */
13293 private static final boolean shouldShowDialogs(Configuration config) {
13294 return !(config.keyboard == Configuration.KEYBOARD_NOKEYS
13295 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH);
13296 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013297
13298 /**
13299 * Save the locale. You must be inside a synchronized (this) block.
13300 */
13301 private void saveLocaleLocked(Locale l, boolean isDiff, boolean isPersist) {
13302 if(isDiff) {
13303 SystemProperties.set("user.language", l.getLanguage());
13304 SystemProperties.set("user.region", l.getCountry());
13305 }
13306
13307 if(isPersist) {
13308 SystemProperties.set("persist.sys.language", l.getLanguage());
13309 SystemProperties.set("persist.sys.country", l.getCountry());
13310 SystemProperties.set("persist.sys.localevar", l.getVariant());
13311 }
13312 }
13313
Adam Powelldd8fab22012-03-22 17:47:27 -070013314 @Override
13315 public boolean targetTaskAffinityMatchesActivity(IBinder token, String destAffinity) {
13316 ActivityRecord srec = ActivityRecord.forToken(token);
13317 return srec.task.affinity != null && srec.task.affinity.equals(destAffinity);
13318 }
13319
13320 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
13321 Intent resultData) {
13322 ComponentName dest = destIntent.getComponent();
13323
13324 synchronized (this) {
13325 ActivityRecord srec = ActivityRecord.forToken(token);
13326 ArrayList<ActivityRecord> history = srec.stack.mHistory;
13327 final int start = history.indexOf(srec);
13328 if (start < 0) {
13329 // Current activity is not in history stack; do nothing.
13330 return false;
13331 }
13332 int finishTo = start - 1;
13333 ActivityRecord parent = null;
13334 boolean foundParentInTask = false;
13335 if (dest != null) {
13336 TaskRecord tr = srec.task;
13337 for (int i = start - 1; i >= 0; i--) {
13338 ActivityRecord r = history.get(i);
13339 if (tr != r.task) {
13340 // Couldn't find parent in the same task; stop at the one above this.
13341 // (Root of current task; in-app "home" behavior)
13342 // Always at least finish the current activity.
13343 finishTo = Math.min(start - 1, i + 1);
13344 parent = history.get(finishTo);
13345 break;
13346 } else if (r.info.packageName.equals(dest.getPackageName()) &&
13347 r.info.name.equals(dest.getClassName())) {
13348 finishTo = i;
13349 parent = r;
13350 foundParentInTask = true;
13351 break;
13352 }
13353 }
13354 }
13355
13356 if (mController != null) {
13357 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
13358 if (next != null) {
13359 // ask watcher if this is allowed
13360 boolean resumeOK = true;
13361 try {
13362 resumeOK = mController.activityResuming(next.packageName);
13363 } catch (RemoteException e) {
13364 mController = null;
13365 }
13366
13367 if (!resumeOK) {
13368 return false;
13369 }
13370 }
13371 }
13372 final long origId = Binder.clearCallingIdentity();
13373 for (int i = start; i > finishTo; i--) {
13374 ActivityRecord r = history.get(i);
13375 mMainStack.requestFinishActivityLocked(r.appToken, resultCode, resultData,
13376 "navigate-up");
13377 // Only return the supplied result for the first activity finished
13378 resultCode = Activity.RESULT_CANCELED;
13379 resultData = null;
13380 }
13381
13382 if (parent != null && foundParentInTask) {
13383 final int parentLaunchMode = parent.info.launchMode;
13384 final int destIntentFlags = destIntent.getFlags();
13385 if (parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE ||
13386 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TASK ||
13387 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TOP ||
13388 (destIntentFlags & Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
13389 parent.deliverNewIntentLocked(srec.app.uid, destIntent);
13390 } else {
13391 try {
13392 ActivityInfo aInfo = AppGlobals.getPackageManager().getActivityInfo(
13393 destIntent.getComponent(), 0, UserId.getCallingUserId());
13394 int res = mMainStack.startActivityLocked(srec.app.thread, destIntent,
13395 null, aInfo, parent.appToken, null,
13396 0, -1, parent.launchedFromUid, 0, null, true, null);
13397 foundParentInTask = res == ActivityManager.START_SUCCESS;
13398 } catch (RemoteException e) {
13399 foundParentInTask = false;
13400 }
13401 mMainStack.requestFinishActivityLocked(parent.appToken, resultCode,
13402 resultData, "navigate-up");
13403 }
13404 }
13405 Binder.restoreCallingIdentity(origId);
13406 return foundParentInTask;
13407 }
13408 }
13409
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013410 // =========================================================
13411 // LIFETIME MANAGEMENT
13412 // =========================================================
13413
Christopher Tatef46723b2012-01-26 14:19:24 -080013414 // Returns which broadcast queue the app is the current [or imminent] receiver
13415 // on, or 'null' if the app is not an active broadcast recipient.
13416 private BroadcastQueue isReceivingBroadcast(ProcessRecord app) {
13417 BroadcastRecord r = app.curReceiver;
13418 if (r != null) {
13419 return r.queue;
13420 }
13421
13422 // It's not the current receiver, but it might be starting up to become one
13423 synchronized (this) {
13424 for (BroadcastQueue queue : mBroadcastQueues) {
13425 r = queue.mPendingBroadcast;
13426 if (r != null && r.curApp == app) {
13427 // found it; report which queue it's in
13428 return queue;
13429 }
13430 }
13431 }
13432
13433 return null;
13434 }
13435
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013436 private final int computeOomAdjLocked(ProcessRecord app, int hiddenAdj,
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013437 ProcessRecord TOP_APP, boolean recursed, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013438 if (mAdjSeq == app.adjSeq) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013439 // This adjustment has already been computed. If we are calling
13440 // from the top, we may have already computed our adjustment with
13441 // an earlier hidden adjustment that isn't really for us... if
13442 // so, use the new hidden adjustment.
13443 if (!recursed && app.hidden) {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013444 app.curAdj = app.curRawAdj = app.nonStoppingAdj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013445 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013446 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013447 }
13448
13449 if (app.thread == null) {
13450 app.adjSeq = mAdjSeq;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013451 app.curSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013452 return (app.curAdj=ProcessList.HIDDEN_APP_MAX_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013453 }
13454
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013455 app.adjTypeCode = ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN;
13456 app.adjSource = null;
13457 app.adjTarget = null;
13458 app.empty = false;
13459 app.hidden = false;
13460
13461 final int activitiesSize = app.activities.size();
13462
Dianne Hackborn7d608422011-08-07 16:24:18 -070013463 if (app.maxAdj <= ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013464 // The max adjustment doesn't allow this app to be anything
13465 // below foreground, so it is not worth doing work for it.
13466 app.adjType = "fixed";
13467 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013468 app.curRawAdj = app.nonStoppingAdj = app.maxAdj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013469 app.foregroundActivities = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013470 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013471 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013472 // System process can do UI, and when they do we want to have
13473 // them trim their memory after the user leaves the UI. To
13474 // facilitate this, here we need to determine whether or not it
13475 // is currently showing UI.
13476 app.systemNoUi = true;
13477 if (app == TOP_APP) {
13478 app.systemNoUi = false;
13479 } else if (activitiesSize > 0) {
13480 for (int j = 0; j < activitiesSize; j++) {
13481 final ActivityRecord r = app.activities.get(j);
13482 if (r.visible) {
13483 app.systemNoUi = false;
13484 break;
13485 }
13486 }
13487 }
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013488 return (app.curAdj=app.maxAdj);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013489 }
13490
13491 final boolean hadForegroundActivities = app.foregroundActivities;
13492
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013493 app.foregroundActivities = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013494 app.keeping = false;
13495 app.systemNoUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013496
The Android Open Source Project4df24232009-03-05 14:34:35 -080013497 // Determine the importance of the process, starting with most
13498 // important to least, and assign an appropriate OOM adjustment.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013499 int adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013500 int schedGroup;
Christopher Tatef46723b2012-01-26 14:19:24 -080013501 BroadcastQueue queue;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013502 if (app == TOP_APP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013503 // The last app on the list is the foreground app.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013504 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013505 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013506 app.adjType = "top-activity";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013507 app.foregroundActivities = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013508 } else if (app.instrumentationClass != null) {
13509 // Don't want to kill running instrumentation.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013510 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013511 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013512 app.adjType = "instrumentation";
Christopher Tatef46723b2012-01-26 14:19:24 -080013513 } else if ((queue = isReceivingBroadcast(app)) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013514 // An app that is currently receiving a broadcast also
Christopher Tatef46723b2012-01-26 14:19:24 -080013515 // counts as being in the foreground for OOM killer purposes.
13516 // It's placed in a sched group based on the nature of the
13517 // broadcast as reflected by which queue it's active in.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013518 adj = ProcessList.FOREGROUND_APP_ADJ;
Christopher Tatef46723b2012-01-26 14:19:24 -080013519 schedGroup = (queue == mFgBroadcastQueue)
13520 ? Process.THREAD_GROUP_DEFAULT : Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013521 app.adjType = "broadcast";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013522 } else if (app.executingServices.size() > 0) {
13523 // An app that is currently executing a service callback also
13524 // counts as being in the foreground.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013525 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013526 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013527 app.adjType = "exec-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013528 } else if (activitiesSize > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013529 // This app is in the background with paused activities.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013530 // We inspect activities to potentially upgrade adjustment further below.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013531 adj = hiddenAdj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013532 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013533 app.hidden = true;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013534 app.adjType = "bg-activities";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013535 } else {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013536 // A very not-needed process. If this is lower in the lru list,
13537 // we will push it in to the empty bucket.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013538 adj = hiddenAdj;
13539 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013540 app.hidden = true;
13541 app.empty = true;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013542 app.adjType = "bg-empty";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013543 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013544
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013545 boolean hasStoppingActivities = false;
13546
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013547 // Examine all activities if not already foreground.
13548 if (!app.foregroundActivities && activitiesSize > 0) {
13549 for (int j = 0; j < activitiesSize; j++) {
13550 final ActivityRecord r = app.activities.get(j);
13551 if (r.visible) {
13552 // App has a visible activity; only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013553 if (adj > ProcessList.VISIBLE_APP_ADJ) {
13554 adj = ProcessList.VISIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013555 app.adjType = "visible";
13556 }
13557 schedGroup = Process.THREAD_GROUP_DEFAULT;
13558 app.hidden = false;
13559 app.foregroundActivities = true;
13560 break;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013561 } else if (r.state == ActivityState.PAUSING || r.state == ActivityState.PAUSED) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013562 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13563 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013564 app.adjType = "pausing";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013565 }
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -080013566 app.hidden = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013567 app.foregroundActivities = true;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013568 } else if (r.state == ActivityState.STOPPING) {
13569 // We will apply the actual adjustment later, because
13570 // we want to allow this process to immediately go through
13571 // any memory trimming that is in effect.
13572 app.hidden = false;
13573 app.foregroundActivities = true;
13574 hasStoppingActivities = true;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013575 }
13576 }
13577 }
13578
Dianne Hackborn7d608422011-08-07 16:24:18 -070013579 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013580 if (app.foregroundServices) {
13581 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013582 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013583 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013584 app.adjType = "foreground-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013585 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013586 } else if (app.forcingToForeground != null) {
13587 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013588 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013589 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013590 app.adjType = "force-foreground";
13591 app.adjSource = app.forcingToForeground;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013592 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013593 }
13594 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013595
Dianne Hackborn7d608422011-08-07 16:24:18 -070013596 if (adj > ProcessList.HEAVY_WEIGHT_APP_ADJ && app == mHeavyWeightProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013597 // We don't want to kill the current heavy-weight process.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013598 adj = ProcessList.HEAVY_WEIGHT_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013599 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013600 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013601 app.adjType = "heavy";
13602 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013603
Dianne Hackborn7d608422011-08-07 16:24:18 -070013604 if (adj > ProcessList.HOME_APP_ADJ && app == mHomeProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013605 // This process is hosting what we currently consider to be the
13606 // home app, so we don't want to let it go into the background.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013607 adj = ProcessList.HOME_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013608 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013609 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013610 app.adjType = "home";
13611 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013612
Dianne Hackbornf35fe232011-11-01 19:25:20 -070013613 if (adj > ProcessList.PREVIOUS_APP_ADJ && app == mPreviousProcess
13614 && app.activities.size() > 0) {
13615 // This was the previous process that showed UI to the user.
13616 // We want to try to keep it around more aggressively, to give
13617 // a good experience around switching between two apps.
13618 adj = ProcessList.PREVIOUS_APP_ADJ;
13619 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
13620 app.hidden = false;
13621 app.adjType = "previous";
13622 }
13623
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013624 if (false) Slog.i(TAG, "OOM " + app + ": initial adj=" + adj
13625 + " reason=" + app.adjType);
13626
The Android Open Source Project4df24232009-03-05 14:34:35 -080013627 // By default, we use the computed adjustment. It may be changed if
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013628 // there are applications dependent on our services or providers, but
13629 // this gives us a baseline and makes sure we don't get into an
13630 // infinite recursion.
13631 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013632 app.curRawAdj = app.nonStoppingAdj = adj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013633
Christopher Tate6fa95972009-06-05 18:43:55 -070013634 if (mBackupTarget != null && app == mBackupTarget.app) {
13635 // If possible we want to avoid killing apps while they're being backed up
Dianne Hackborn7d608422011-08-07 16:24:18 -070013636 if (adj > ProcessList.BACKUP_APP_ADJ) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013637 if (DEBUG_BACKUP) Slog.v(TAG, "oom BACKUP_APP_ADJ for " + app);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013638 adj = ProcessList.BACKUP_APP_ADJ;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013639 app.adjType = "backup";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013640 app.hidden = false;
Christopher Tate6fa95972009-06-05 18:43:55 -070013641 }
13642 }
13643
Dianne Hackborn7d608422011-08-07 16:24:18 -070013644 if (app.services.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013645 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013646 final long now = SystemClock.uptimeMillis();
13647 // This process is more important if the top activity is
13648 // bound to the service.
Dianne Hackborn860755f2010-06-03 18:47:52 -070013649 Iterator<ServiceRecord> jt = app.services.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013650 while (jt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013651 ServiceRecord s = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013652 if (s.startRequested) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013653 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013654 // If this process has shown some UI, let it immediately
13655 // go to the LRU list because it may be pretty heavy with
13656 // UI stuff. We'll tag it with a label just to help
13657 // debug and understand what is going on.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013658 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013659 app.adjType = "started-bg-ui-services";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013660 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013661 } else {
13662 if (now < (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
13663 // This service has seen some activity within
13664 // recent memory, so we will keep its process ahead
13665 // of the background processes.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013666 if (adj > ProcessList.SERVICE_ADJ) {
13667 adj = ProcessList.SERVICE_ADJ;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013668 app.adjType = "started-services";
13669 app.hidden = false;
13670 }
13671 }
13672 // If we have let the service slide into the background
13673 // state, still have some text describing what it is doing
13674 // even though the service no longer has an impact.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013675 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013676 app.adjType = "started-bg-services";
13677 }
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080013678 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013679 // Don't kill this process because it is doing work; it
13680 // has said it is doing work.
13681 app.keeping = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013682 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013683 if (s.connections.size() > 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013684 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013685 Iterator<ArrayList<ConnectionRecord>> kt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013686 = s.connections.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013687 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013688 ArrayList<ConnectionRecord> clist = kt.next();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013689 for (int i=0; i<clist.size() && adj > ProcessList.FOREGROUND_APP_ADJ; i++) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013690 // XXX should compute this based on the max of
13691 // all connected clients.
13692 ConnectionRecord cr = clist.get(i);
13693 if (cr.binding.client == app) {
13694 // Binding to ourself is not interesting.
13695 continue;
13696 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013697 if ((cr.flags&Context.BIND_WAIVE_PRIORITY) == 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013698 ProcessRecord client = cr.binding.client;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013699 int clientAdj = adj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013700 int myHiddenAdj = hiddenAdj;
13701 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013702 if (client.hiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013703 myHiddenAdj = client.hiddenAdj;
13704 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013705 myHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013706 }
13707 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013708 clientAdj = computeOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013709 client, myHiddenAdj, TOP_APP, true, doingAll);
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013710 String adjType = null;
13711 if ((cr.flags&Context.BIND_ALLOW_OOM_MANAGEMENT) != 0) {
13712 // Not doing bind OOM management, so treat
13713 // this guy more like a started service.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013714 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013715 // If this process has shown some UI, let it immediately
13716 // go to the LRU list because it may be pretty heavy with
13717 // UI stuff. We'll tag it with a label just to help
13718 // debug and understand what is going on.
13719 if (adj > clientAdj) {
13720 adjType = "bound-bg-ui-services";
13721 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013722 app.hidden = false;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013723 clientAdj = adj;
13724 } else {
13725 if (now >= (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
13726 // This service has not seen activity within
13727 // recent memory, so allow it to drop to the
13728 // LRU list if there is no other reason to keep
13729 // it around. We'll also tag it with a label just
13730 // to help debug and undertand what is going on.
13731 if (adj > clientAdj) {
13732 adjType = "bound-bg-services";
13733 }
13734 clientAdj = adj;
13735 }
13736 }
13737 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013738 if (adj > clientAdj) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013739 // If this process has recently shown UI, and
13740 // the process that is binding to it is less
13741 // important than being visible, then we don't
13742 // care about the binding as much as we care
13743 // about letting this process get into the LRU
13744 // list to be killed and restarted if needed for
13745 // memory.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013746 if (app.hasShownUi && app != mHomeProcess
13747 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013748 adjType = "bound-bg-ui-services";
13749 } else {
13750 if ((cr.flags&(Context.BIND_ABOVE_CLIENT
13751 |Context.BIND_IMPORTANT)) != 0) {
13752 adj = clientAdj;
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070013753 } else if ((cr.flags&Context.BIND_NOT_VISIBLE) != 0
13754 && clientAdj < ProcessList.PERCEPTIBLE_APP_ADJ
13755 && adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13756 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13757 } else if (clientAdj > ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013758 adj = clientAdj;
13759 } else {
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070013760 app.pendingUiClean = true;
13761 if (adj > ProcessList.VISIBLE_APP_ADJ) {
13762 adj = ProcessList.VISIBLE_APP_ADJ;
13763 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013764 }
13765 if (!client.hidden) {
13766 app.hidden = false;
13767 }
13768 if (client.keeping) {
13769 app.keeping = true;
13770 }
13771 adjType = "service";
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013772 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013773 }
13774 if (adjType != null) {
13775 app.adjType = adjType;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013776 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13777 .REASON_SERVICE_IN_USE;
13778 app.adjSource = cr.binding.client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013779 app.adjSourceOom = clientAdj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013780 app.adjTarget = s.name;
13781 }
13782 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
13783 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
13784 schedGroup = Process.THREAD_GROUP_DEFAULT;
13785 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013786 }
13787 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013788 if ((cr.flags&Context.BIND_ADJUST_WITH_ACTIVITY) != 0) {
13789 ActivityRecord a = cr.activity;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013790 if (a != null && adj > ProcessList.FOREGROUND_APP_ADJ &&
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013791 (a.visible || a.state == ActivityState.RESUMED
13792 || a.state == ActivityState.PAUSING)) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013793 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013794 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
13795 schedGroup = Process.THREAD_GROUP_DEFAULT;
13796 }
13797 app.hidden = false;
13798 app.adjType = "service";
13799 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13800 .REASON_SERVICE_IN_USE;
13801 app.adjSource = a;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013802 app.adjSourceOom = adj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013803 app.adjTarget = s.name;
13804 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013805 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013806 }
13807 }
13808 }
13809 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013810
Dianne Hackborn287952c2010-09-22 22:34:31 -070013811 // Finally, if this process has active services running in it, we
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013812 // would like to avoid killing it unless it would prevent the current
13813 // application from running. By default we put the process in
13814 // with the rest of the background processes; as we scan through
13815 // its services we may bump it up from there.
13816 if (adj > hiddenAdj) {
13817 adj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013818 app.hidden = false;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013819 app.adjType = "bg-services";
13820 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013821 }
13822
Dianne Hackborn7d608422011-08-07 16:24:18 -070013823 if (app.pubProviders.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013824 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013825 Iterator<ContentProviderRecord> jt = app.pubProviders.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013826 while (jt.hasNext() && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013827 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013828 ContentProviderRecord cpr = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013829 if (cpr.clients.size() != 0) {
13830 Iterator<ProcessRecord> kt = cpr.clients.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013831 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013832 ProcessRecord client = kt.next();
The Android Open Source Project10592532009-03-18 17:39:46 -070013833 if (client == app) {
13834 // Being our own client is not interesting.
13835 continue;
13836 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013837 int myHiddenAdj = hiddenAdj;
13838 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013839 if (client.hiddenAdj > ProcessList.FOREGROUND_APP_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013840 myHiddenAdj = client.hiddenAdj;
13841 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013842 myHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013843 }
13844 }
13845 int clientAdj = computeOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013846 client, myHiddenAdj, TOP_APP, true, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013847 if (adj > clientAdj) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013848 if (app.hasShownUi && app != mHomeProcess
13849 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013850 app.adjType = "bg-ui-provider";
13851 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013852 adj = clientAdj > ProcessList.FOREGROUND_APP_ADJ
13853 ? clientAdj : ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013854 app.adjType = "provider";
13855 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013856 if (!client.hidden) {
13857 app.hidden = false;
13858 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013859 if (client.keeping) {
13860 app.keeping = true;
13861 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070013862 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13863 .REASON_PROVIDER_IN_USE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013864 app.adjSource = client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013865 app.adjSourceOom = clientAdj;
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070013866 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013867 }
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013868 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
13869 schedGroup = Process.THREAD_GROUP_DEFAULT;
13870 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013871 }
13872 }
13873 // If the provider has external (non-framework) process
13874 // dependencies, ensure that its adjustment is at least
13875 // FOREGROUND_APP_ADJ.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080013876 if (cpr.hasExternalProcessHandles()) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013877 if (adj > ProcessList.FOREGROUND_APP_ADJ) {
13878 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013879 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013880 app.hidden = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013881 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013882 app.adjType = "provider";
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070013883 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013884 }
13885 }
13886 }
13887 }
13888
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013889 if (adj == ProcessList.SERVICE_ADJ) {
13890 if (doingAll) {
13891 app.serviceb = mNewNumServiceProcs > (mNumServiceProcs/3);
13892 mNewNumServiceProcs++;
13893 }
13894 if (app.serviceb) {
13895 adj = ProcessList.SERVICE_B_ADJ;
13896 }
13897 } else {
13898 app.serviceb = false;
13899 }
13900
13901 app.nonStoppingAdj = adj;
13902
13903 if (hasStoppingActivities) {
13904 // Only upgrade adjustment.
13905 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13906 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13907 app.adjType = "stopping";
13908 }
13909 }
13910
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013911 app.curRawAdj = adj;
13912
Joe Onorato8a9b2202010-02-26 18:56:32 -080013913 //Slog.i(TAG, "OOM ADJ " + app + ": pid=" + app.pid +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013914 // " adj=" + adj + " curAdj=" + app.curAdj + " maxAdj=" + app.maxAdj);
13915 if (adj > app.maxAdj) {
13916 adj = app.maxAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013917 if (app.maxAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013918 schedGroup = Process.THREAD_GROUP_DEFAULT;
13919 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013920 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013921 if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070013922 app.keeping = true;
13923 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013924
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013925 if (app.hasAboveClient) {
13926 // If this process has bound to any services with BIND_ABOVE_CLIENT,
13927 // then we need to drop its adjustment to be lower than the service's
13928 // in order to honor the request. We want to drop it by one adjustment
13929 // level... but there is special meaning applied to various levels so
13930 // we will skip some of them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013931 if (adj < ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013932 // System process will not get dropped, ever
Dianne Hackborn7d608422011-08-07 16:24:18 -070013933 } else if (adj < ProcessList.VISIBLE_APP_ADJ) {
13934 adj = ProcessList.VISIBLE_APP_ADJ;
13935 } else if (adj < ProcessList.PERCEPTIBLE_APP_ADJ) {
13936 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13937 } else if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
13938 adj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013939 } else if (adj < ProcessList.HIDDEN_APP_MAX_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013940 adj++;
13941 }
13942 }
13943
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013944 app.curAdj = adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013945 app.curSchedGroup = schedGroup;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013946
13947 if (hadForegroundActivities != app.foregroundActivities) {
Jeff Sharkey287bd832011-05-28 19:36:26 -070013948 mHandler.obtainMessage(DISPATCH_FOREGROUND_ACTIVITIES_CHANGED, app.pid, app.info.uid,
13949 app.foregroundActivities).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013950 }
13951
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013952 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013953 }
13954
13955 /**
13956 * Ask a given process to GC right now.
13957 */
13958 final void performAppGcLocked(ProcessRecord app) {
13959 try {
13960 app.lastRequestedGc = SystemClock.uptimeMillis();
13961 if (app.thread != null) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013962 if (app.reportLowMemory) {
13963 app.reportLowMemory = false;
13964 app.thread.scheduleLowMemory();
13965 } else {
13966 app.thread.processInBackground();
13967 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013968 }
13969 } catch (Exception e) {
13970 // whatever.
13971 }
13972 }
13973
13974 /**
13975 * Returns true if things are idle enough to perform GCs.
13976 */
Josh Bartel7f208742010-02-25 11:01:44 -060013977 private final boolean canGcNowLocked() {
Christopher Tatef46723b2012-01-26 14:19:24 -080013978 boolean processingBroadcasts = false;
13979 for (BroadcastQueue q : mBroadcastQueues) {
13980 if (q.mParallelBroadcasts.size() != 0 || q.mOrderedBroadcasts.size() != 0) {
13981 processingBroadcasts = true;
13982 }
13983 }
13984 return !processingBroadcasts
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013985 && (mSleeping || (mMainStack.mResumedActivity != null &&
13986 mMainStack.mResumedActivity.idle));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013987 }
13988
13989 /**
13990 * Perform GCs on all processes that are waiting for it, but only
13991 * if things are idle.
13992 */
13993 final void performAppGcsLocked() {
13994 final int N = mProcessesToGc.size();
13995 if (N <= 0) {
13996 return;
13997 }
Josh Bartel7f208742010-02-25 11:01:44 -060013998 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013999 while (mProcessesToGc.size() > 0) {
14000 ProcessRecord proc = mProcessesToGc.remove(0);
Dianne Hackborn7d608422011-08-07 16:24:18 -070014001 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014002 if ((proc.lastRequestedGc+GC_MIN_INTERVAL)
14003 <= SystemClock.uptimeMillis()) {
14004 // To avoid spamming the system, we will GC processes one
14005 // at a time, waiting a few seconds between each.
14006 performAppGcLocked(proc);
14007 scheduleAppGcsLocked();
14008 return;
14009 } else {
14010 // It hasn't been long enough since we last GCed this
14011 // process... put it in the list to wait for its time.
14012 addProcessToGcListLocked(proc);
14013 break;
14014 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014015 }
14016 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014017
14018 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014019 }
14020 }
14021
14022 /**
14023 * If all looks good, perform GCs on all processes waiting for them.
14024 */
14025 final void performAppGcsIfAppropriateLocked() {
Josh Bartel7f208742010-02-25 11:01:44 -060014026 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014027 performAppGcsLocked();
14028 return;
14029 }
14030 // Still not idle, wait some more.
14031 scheduleAppGcsLocked();
14032 }
14033
14034 /**
14035 * Schedule the execution of all pending app GCs.
14036 */
14037 final void scheduleAppGcsLocked() {
14038 mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014039
14040 if (mProcessesToGc.size() > 0) {
14041 // Schedule a GC for the time to the next process.
14042 ProcessRecord proc = mProcessesToGc.get(0);
14043 Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG);
14044
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014045 long when = proc.lastRequestedGc + GC_MIN_INTERVAL;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014046 long now = SystemClock.uptimeMillis();
14047 if (when < (now+GC_TIMEOUT)) {
14048 when = now + GC_TIMEOUT;
14049 }
14050 mHandler.sendMessageAtTime(msg, when);
14051 }
14052 }
14053
14054 /**
14055 * Add a process to the array of processes waiting to be GCed. Keeps the
14056 * list in sorted order by the last GC time. The process can't already be
14057 * on the list.
14058 */
14059 final void addProcessToGcListLocked(ProcessRecord proc) {
14060 boolean added = false;
14061 for (int i=mProcessesToGc.size()-1; i>=0; i--) {
14062 if (mProcessesToGc.get(i).lastRequestedGc <
14063 proc.lastRequestedGc) {
14064 added = true;
14065 mProcessesToGc.add(i+1, proc);
14066 break;
14067 }
14068 }
14069 if (!added) {
14070 mProcessesToGc.add(0, proc);
14071 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014072 }
14073
14074 /**
14075 * Set up to ask a process to GC itself. This will either do it
14076 * immediately, or put it on the list of processes to gc the next
14077 * time things are idle.
14078 */
14079 final void scheduleAppGcLocked(ProcessRecord app) {
14080 long now = SystemClock.uptimeMillis();
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014081 if ((app.lastRequestedGc+GC_MIN_INTERVAL) > now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014082 return;
14083 }
14084 if (!mProcessesToGc.contains(app)) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014085 addProcessToGcListLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014086 scheduleAppGcsLocked();
14087 }
14088 }
14089
Dianne Hackborn287952c2010-09-22 22:34:31 -070014090 final void checkExcessivePowerUsageLocked(boolean doKills) {
14091 updateCpuStatsNow();
14092
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014093 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborn287952c2010-09-22 22:34:31 -070014094 boolean doWakeKills = doKills;
14095 boolean doCpuKills = doKills;
14096 if (mLastPowerCheckRealtime == 0) {
14097 doWakeKills = false;
14098 }
14099 if (mLastPowerCheckUptime == 0) {
14100 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014101 }
14102 if (stats.isScreenOn()) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070014103 doWakeKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014104 }
14105 final long curRealtime = SystemClock.elapsedRealtime();
Dianne Hackborn287952c2010-09-22 22:34:31 -070014106 final long realtimeSince = curRealtime - mLastPowerCheckRealtime;
14107 final long curUptime = SystemClock.uptimeMillis();
14108 final long uptimeSince = curUptime - mLastPowerCheckUptime;
14109 mLastPowerCheckRealtime = curRealtime;
14110 mLastPowerCheckUptime = curUptime;
14111 if (realtimeSince < WAKE_LOCK_MIN_CHECK_DURATION) {
14112 doWakeKills = false;
14113 }
14114 if (uptimeSince < CPU_MIN_CHECK_DURATION) {
14115 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014116 }
14117 int i = mLruProcesses.size();
14118 while (i > 0) {
14119 i--;
14120 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn287952c2010-09-22 22:34:31 -070014121 if (!app.keeping) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014122 long wtime;
14123 synchronized (stats) {
14124 wtime = stats.getProcessWakeTime(app.info.uid,
14125 app.pid, curRealtime);
14126 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070014127 long wtimeUsed = wtime - app.lastWakeTime;
14128 long cputimeUsed = app.curCpuTime - app.lastCpuTime;
14129 if (DEBUG_POWER) {
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014130 StringBuilder sb = new StringBuilder(128);
14131 sb.append("Wake for ");
14132 app.toShortString(sb);
14133 sb.append(": over ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070014134 TimeUtils.formatDuration(realtimeSince, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014135 sb.append(" used ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070014136 TimeUtils.formatDuration(wtimeUsed, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014137 sb.append(" (");
Dianne Hackborn287952c2010-09-22 22:34:31 -070014138 sb.append((wtimeUsed*100)/realtimeSince);
14139 sb.append("%)");
14140 Slog.i(TAG, sb.toString());
14141 sb.setLength(0);
14142 sb.append("CPU for ");
14143 app.toShortString(sb);
14144 sb.append(": over ");
14145 TimeUtils.formatDuration(uptimeSince, sb);
14146 sb.append(" used ");
14147 TimeUtils.formatDuration(cputimeUsed, sb);
14148 sb.append(" (");
14149 sb.append((cputimeUsed*100)/uptimeSince);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014150 sb.append("%)");
14151 Slog.i(TAG, sb.toString());
14152 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014153 // If a process has held a wake lock for more
14154 // than 50% of the time during this period,
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014155 // that sounds bad. Kill!
Dianne Hackborn287952c2010-09-22 22:34:31 -070014156 if (doWakeKills && realtimeSince > 0
14157 && ((wtimeUsed*100)/realtimeSince) >= 50) {
14158 synchronized (stats) {
14159 stats.reportExcessiveWakeLocked(app.info.uid, app.processName,
14160 realtimeSince, wtimeUsed);
14161 }
14162 Slog.w(TAG, "Excessive wake lock in " + app.processName
14163 + " (pid " + app.pid + "): held " + wtimeUsed
14164 + " during " + realtimeSince);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014165 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14166 app.processName, app.setAdj, "excessive wake lock");
14167 Process.killProcessQuiet(app.pid);
Dianne Hackborn287952c2010-09-22 22:34:31 -070014168 } else if (doCpuKills && uptimeSince > 0
14169 && ((cputimeUsed*100)/uptimeSince) >= 50) {
14170 synchronized (stats) {
14171 stats.reportExcessiveCpuLocked(app.info.uid, app.processName,
14172 uptimeSince, cputimeUsed);
14173 }
14174 Slog.w(TAG, "Excessive CPU in " + app.processName
14175 + " (pid " + app.pid + "): used " + cputimeUsed
14176 + " during " + uptimeSince);
14177 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14178 app.processName, app.setAdj, "excessive cpu");
14179 Process.killProcessQuiet(app.pid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014180 } else {
14181 app.lastWakeTime = wtime;
Dianne Hackborn287952c2010-09-22 22:34:31 -070014182 app.lastCpuTime = app.curCpuTime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014183 }
14184 }
14185 }
14186 }
14187
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014188 private final boolean updateOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014189 ProcessRecord app, int hiddenAdj, ProcessRecord TOP_APP, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014190 app.hiddenAdj = hiddenAdj;
14191
14192 if (app.thread == null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014193 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014194 }
14195
Dianne Hackborn287952c2010-09-22 22:34:31 -070014196 final boolean wasKeeping = app.keeping;
14197
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014198 boolean success = true;
14199
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014200 computeOomAdjLocked(app, hiddenAdj, TOP_APP, false, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014201
Jeff Brown10e89712011-07-08 18:52:57 -070014202 if (app.curRawAdj != app.setRawAdj) {
Jeff Brown10e89712011-07-08 18:52:57 -070014203 if (wasKeeping && !app.keeping) {
14204 // This app is no longer something we want to keep. Note
14205 // its current wake lock time to later know to kill it if
14206 // it is not behaving well.
14207 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
14208 synchronized (stats) {
14209 app.lastWakeTime = stats.getProcessWakeTime(app.info.uid,
14210 app.pid, SystemClock.elapsedRealtime());
14211 }
14212 app.lastCpuTime = app.curCpuTime;
14213 }
14214
14215 app.setRawAdj = app.curRawAdj;
14216 }
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014217
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014218 if (app.curAdj != app.setAdj) {
14219 if (Process.setOomAdj(app.pid, app.curAdj)) {
Dianne Hackbornbbb09ac2011-11-30 11:31:29 -080014220 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014221 TAG, "Set " + app.pid + " " + app.processName +
14222 " adj " + app.curAdj + ": " + app.adjType);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014223 app.setAdj = app.curAdj;
Jeff Brown10e89712011-07-08 18:52:57 -070014224 } else {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014225 success = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014226 Slog.w(TAG, "Failed setting oom adj of " + app + " to " + app.curAdj);
Jeff Brown10e89712011-07-08 18:52:57 -070014227 }
14228 }
14229 if (app.setSchedGroup != app.curSchedGroup) {
14230 app.setSchedGroup = app.curSchedGroup;
14231 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
14232 "Setting process group of " + app.processName
14233 + " to " + app.curSchedGroup);
14234 if (app.waitingToKill != null &&
14235 app.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
14236 Slog.i(TAG, "Killing " + app.toShortString() + ": " + app.waitingToKill);
14237 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14238 app.processName, app.setAdj, app.waitingToKill);
14239 Process.killProcessQuiet(app.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014240 success = false;
Jeff Brown10e89712011-07-08 18:52:57 -070014241 } else {
14242 if (true) {
14243 long oldId = Binder.clearCallingIdentity();
14244 try {
14245 Process.setProcessGroup(app.pid, app.curSchedGroup);
14246 } catch (Exception e) {
14247 Slog.w(TAG, "Failed setting process group of " + app.pid
14248 + " to " + app.curSchedGroup);
14249 e.printStackTrace();
14250 } finally {
14251 Binder.restoreCallingIdentity(oldId);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014252 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014253 } else {
Jeff Brown10e89712011-07-08 18:52:57 -070014254 if (app.thread != null) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070014255 try {
Jeff Brown10e89712011-07-08 18:52:57 -070014256 app.thread.setSchedulingGroup(app.curSchedGroup);
14257 } catch (RemoteException e) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070014258 }
14259 }
14260 }
14261 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014262 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014263 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014264 }
14265
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014266 private final ActivityRecord resumedAppLocked() {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014267 ActivityRecord resumedActivity = mMainStack.mResumedActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014268 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -080014269 resumedActivity = mMainStack.mPausingActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014270 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014271 resumedActivity = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014272 }
14273 }
14274 return resumedActivity;
14275 }
14276
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014277 private final boolean updateOomAdjLocked(ProcessRecord app) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014278 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014279 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
14280 int curAdj = app.curAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070014281 final boolean wasHidden = curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
14282 && curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014283
14284 mAdjSeq++;
14285
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014286 boolean success = updateOomAdjLocked(app, app.hiddenAdj, TOP_APP, false);
Dianne Hackborn7d608422011-08-07 16:24:18 -070014287 final boolean nowHidden = app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
14288 && app.curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014289 if (nowHidden != wasHidden) {
14290 // Changed to/from hidden state, so apps after it in the LRU
14291 // list may also be changed.
14292 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014293 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014294 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014295 }
14296
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014297 final void updateOomAdjLocked() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014298 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014299 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
14300
14301 if (false) {
14302 RuntimeException e = new RuntimeException();
14303 e.fillInStackTrace();
Joe Onorato8a9b2202010-02-26 18:56:32 -080014304 Slog.i(TAG, "updateOomAdj: top=" + TOP_ACT, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014305 }
14306
14307 mAdjSeq++;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014308 mNewNumServiceProcs = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014309
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014310 // Let's determine how many processes we have running vs.
14311 // how many slots we have for background processes; we may want
14312 // to put multiple processes in a slot of there are enough of
14313 // them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014314 int numSlots = ProcessList.HIDDEN_APP_MAX_ADJ - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014315 int factor = (mLruProcesses.size()-4)/numSlots;
14316 if (factor < 1) factor = 1;
14317 int step = 0;
Dianne Hackborn8633e682010-04-22 16:03:41 -070014318 int numHidden = 0;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014319 int numTrimming = 0;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014320
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014321 // First update the OOM adjustment for each of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014322 // application processes based on their current state.
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014323 int i = mLruProcesses.size();
Dianne Hackborn7d608422011-08-07 16:24:18 -070014324 int curHiddenAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014325 while (i > 0) {
14326 i--;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014327 ProcessRecord app = mLruProcesses.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080014328 //Slog.i(TAG, "OOM " + app + ": cur hidden=" + curHiddenAdj);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014329 updateOomAdjLocked(app, curHiddenAdj, TOP_APP, true);
14330 if (curHiddenAdj < ProcessList.HIDDEN_APP_MAX_ADJ
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014331 && app.curAdj == curHiddenAdj) {
14332 step++;
14333 if (step >= factor) {
14334 step = 0;
14335 curHiddenAdj++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014336 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014337 }
14338 if (!app.killedBackground) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070014339 if (app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014340 numHidden++;
14341 if (numHidden > mProcessLimit) {
14342 Slog.i(TAG, "No longer want " + app.processName
14343 + " (pid " + app.pid + "): hidden #" + numHidden);
14344 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14345 app.processName, app.setAdj, "too many background");
14346 app.killedBackground = true;
14347 Process.killProcessQuiet(app.pid);
Dianne Hackborn8633e682010-04-22 16:03:41 -070014348 }
14349 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -080014350 if (!app.killedBackground && app.isolated && app.services.size() <= 0) {
14351 // If this is an isolated process, and there are no
14352 // services running in it, then the process is no longer
14353 // needed. We agressively kill these because we can by
14354 // definition not re-use the same process again, and it is
14355 // good to avoid having whatever code was running in them
14356 // left sitting around after no longer needed.
14357 Slog.i(TAG, "Isolated process " + app.processName
14358 + " (pid " + app.pid + ") no longer needed");
14359 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14360 app.processName, app.setAdj, "isolated not needed");
14361 app.killedBackground = true;
14362 Process.killProcessQuiet(app.pid);
14363 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014364 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
14365 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
14366 && !app.killedBackground) {
14367 numTrimming++;
14368 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014369 }
14370 }
14371
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014372 mNumServiceProcs = mNewNumServiceProcs;
14373
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014374 // Now determine the memory trimming level of background processes.
14375 // Unfortunately we need to start at the back of the list to do this
14376 // properly. We only do this if the number of background apps we
14377 // are managing to keep around is less than half the maximum we desire;
14378 // if we are keeping a good number around, we'll let them use whatever
14379 // memory they want.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014380 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/2)) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014381 final int N = mLruProcesses.size();
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014382 factor = numTrimming/3;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080014383 int minFactor = 2;
14384 if (mHomeProcess != null) minFactor++;
14385 if (mPreviousProcess != null) minFactor++;
14386 if (factor < minFactor) factor = minFactor;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014387 step = 0;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014388 int fgTrimLevel;
14389 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/5)) {
14390 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL;
14391 } else if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/3)) {
14392 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW;
14393 } else {
14394 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE;
14395 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014396 int curLevel = ComponentCallbacks2.TRIM_MEMORY_COMPLETE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014397 for (i=0; i<N; i++) {
14398 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014399 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
14400 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080014401 && !app.killedBackground) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014402 if (app.trimMemoryLevel < curLevel && app.thread != null) {
14403 try {
14404 app.thread.scheduleTrimMemory(curLevel);
14405 } catch (RemoteException e) {
14406 }
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080014407 if (false) {
14408 // For now we won't do this; our memory trimming seems
14409 // to be good enough at this point that destroying
14410 // activities causes more harm than good.
14411 if (curLevel >= ComponentCallbacks2.TRIM_MEMORY_COMPLETE
14412 && app != mHomeProcess && app != mPreviousProcess) {
14413 // For these apps we will also finish their activities
14414 // to help them free memory.
14415 mMainStack.destroyActivitiesLocked(app, false, "trim");
14416 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014417 }
14418 }
14419 app.trimMemoryLevel = curLevel;
14420 step++;
14421 if (step >= factor) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014422 step = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014423 switch (curLevel) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014424 case ComponentCallbacks2.TRIM_MEMORY_COMPLETE:
14425 curLevel = ComponentCallbacks2.TRIM_MEMORY_MODERATE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014426 break;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014427 case ComponentCallbacks2.TRIM_MEMORY_MODERATE:
14428 curLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014429 break;
14430 }
14431 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014432 } else if (app.nonStoppingAdj == ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014433 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014434 && app.thread != null) {
14435 try {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014436 app.thread.scheduleTrimMemory(
14437 ComponentCallbacks2.TRIM_MEMORY_BACKGROUND);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014438 } catch (RemoteException e) {
14439 }
14440 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014441 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014442 } else {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014443 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014444 && app.pendingUiClean) {
14445 // If this application is now in the background and it
14446 // had done UI, then give it the special trim level to
14447 // have it free UI resources.
14448 final int level = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
14449 if (app.trimMemoryLevel < level && app.thread != null) {
14450 try {
14451 app.thread.scheduleTrimMemory(level);
14452 } catch (RemoteException e) {
14453 }
14454 }
14455 app.pendingUiClean = false;
14456 }
14457 if (app.trimMemoryLevel < fgTrimLevel && app.thread != null) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014458 try {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014459 app.thread.scheduleTrimMemory(fgTrimLevel);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014460 } catch (RemoteException e) {
14461 }
14462 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014463 app.trimMemoryLevel = fgTrimLevel;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014464 }
14465 }
14466 } else {
14467 final int N = mLruProcesses.size();
14468 for (i=0; i<N; i++) {
14469 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014470 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014471 && app.pendingUiClean) {
14472 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
14473 && app.thread != null) {
14474 try {
14475 app.thread.scheduleTrimMemory(
14476 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
14477 } catch (RemoteException e) {
14478 }
14479 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014480 app.pendingUiClean = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014481 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014482 app.trimMemoryLevel = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014483 }
14484 }
14485
14486 if (mAlwaysFinishActivities) {
Dianne Hackborn28695e02011-11-02 21:59:51 -070014487 mMainStack.destroyActivitiesLocked(null, false, "always-finish");
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014488 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014489 }
14490
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014491 final void trimApplications() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014492 synchronized (this) {
14493 int i;
14494
14495 // First remove any unused application processes whose package
14496 // has been removed.
14497 for (i=mRemovedProcesses.size()-1; i>=0; i--) {
14498 final ProcessRecord app = mRemovedProcesses.get(i);
14499 if (app.activities.size() == 0
14500 && app.curReceiver == null && app.services.size() == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080014501 Slog.i(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014502 TAG, "Exiting empty application process "
14503 + app.processName + " ("
14504 + (app.thread != null ? app.thread.asBinder() : null)
14505 + ")\n");
14506 if (app.pid > 0 && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070014507 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14508 app.processName, app.setAdj, "empty");
14509 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014510 } else {
14511 try {
14512 app.thread.scheduleExit();
14513 } catch (Exception e) {
14514 // Ignore exceptions.
14515 }
14516 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070014517 cleanUpApplicationRecordLocked(app, false, true, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014518 mRemovedProcesses.remove(i);
14519
14520 if (app.persistent) {
14521 if (app.persistent) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080014522 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014523 }
14524 }
14525 }
14526 }
14527
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014528 // Now update the oom adj for all processes.
14529 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014530 }
14531 }
14532
14533 /** This method sends the specified signal to each of the persistent apps */
14534 public void signalPersistentProcesses(int sig) throws RemoteException {
14535 if (sig != Process.SIGNAL_USR1) {
14536 throw new SecurityException("Only SIGNAL_USR1 is allowed");
14537 }
14538
14539 synchronized (this) {
14540 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
14541 != PackageManager.PERMISSION_GRANTED) {
14542 throw new SecurityException("Requires permission "
14543 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
14544 }
14545
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014546 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
14547 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014548 if (r.thread != null && r.persistent) {
14549 Process.sendSignal(r.pid, sig);
14550 }
14551 }
14552 }
14553 }
14554
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014555 private void stopProfilerLocked(ProcessRecord proc, String path, int profileType) {
14556 if (proc == null || proc == mProfileProc) {
14557 proc = mProfileProc;
14558 path = mProfileFile;
14559 profileType = mProfileType;
14560 clearProfilerLocked();
14561 }
14562 if (proc == null) {
14563 return;
14564 }
14565 try {
14566 proc.thread.profilerControl(false, path, null, profileType);
14567 } catch (RemoteException e) {
14568 throw new IllegalStateException("Process disappeared");
14569 }
14570 }
14571
14572 private void clearProfilerLocked() {
14573 if (mProfileFd != null) {
14574 try {
14575 mProfileFd.close();
14576 } catch (IOException e) {
14577 }
14578 }
14579 mProfileApp = null;
14580 mProfileProc = null;
14581 mProfileFile = null;
14582 mProfileType = 0;
14583 mAutoStopProfiler = false;
14584 }
14585
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014586 public boolean profileControl(String process, boolean start,
Romain Guy7eabe552011-07-21 14:56:34 -070014587 String path, ParcelFileDescriptor fd, int profileType) throws RemoteException {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014588
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014589 try {
14590 synchronized (this) {
14591 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14592 // its own permission.
14593 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14594 != PackageManager.PERMISSION_GRANTED) {
14595 throw new SecurityException("Requires permission "
14596 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014597 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014598
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014599 if (start && fd == null) {
14600 throw new IllegalArgumentException("null fd");
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014601 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014602
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014603 ProcessRecord proc = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014604 if (process != null) {
14605 try {
14606 int pid = Integer.parseInt(process);
14607 synchronized (mPidsSelfLocked) {
14608 proc = mPidsSelfLocked.get(pid);
14609 }
14610 } catch (NumberFormatException e) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014611 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014612
14613 if (proc == null) {
14614 HashMap<String, SparseArray<ProcessRecord>> all
14615 = mProcessNames.getMap();
14616 SparseArray<ProcessRecord> procs = all.get(process);
14617 if (procs != null && procs.size() > 0) {
14618 proc = procs.valueAt(0);
14619 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014620 }
14621 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014622
14623 if (start && (proc == null || proc.thread == null)) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014624 throw new IllegalArgumentException("Unknown process: " + process);
14625 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014626
14627 if (start) {
14628 stopProfilerLocked(null, null, 0);
14629 setProfileApp(proc.info, proc.processName, path, fd, false);
14630 mProfileProc = proc;
14631 mProfileType = profileType;
14632 try {
14633 fd = fd.dup();
14634 } catch (IOException e) {
14635 fd = null;
14636 }
14637 proc.thread.profilerControl(start, path, fd, profileType);
14638 fd = null;
14639 mProfileFd = null;
14640 } else {
14641 stopProfilerLocked(proc, path, profileType);
14642 if (fd != null) {
14643 try {
14644 fd.close();
14645 } catch (IOException e) {
14646 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014647 }
14648 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014649
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014650 return true;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014651 }
14652 } catch (RemoteException e) {
14653 throw new IllegalStateException("Process disappeared");
14654 } finally {
14655 if (fd != null) {
14656 try {
14657 fd.close();
14658 } catch (IOException e) {
14659 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014660 }
14661 }
14662 }
Andy McFadden824c5102010-07-09 16:26:57 -070014663
14664 public boolean dumpHeap(String process, boolean managed,
14665 String path, ParcelFileDescriptor fd) throws RemoteException {
14666
14667 try {
14668 synchronized (this) {
14669 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14670 // its own permission (same as profileControl).
14671 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14672 != PackageManager.PERMISSION_GRANTED) {
14673 throw new SecurityException("Requires permission "
14674 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
14675 }
14676
14677 if (fd == null) {
14678 throw new IllegalArgumentException("null fd");
14679 }
14680
14681 ProcessRecord proc = null;
14682 try {
14683 int pid = Integer.parseInt(process);
14684 synchronized (mPidsSelfLocked) {
14685 proc = mPidsSelfLocked.get(pid);
14686 }
14687 } catch (NumberFormatException e) {
14688 }
14689
14690 if (proc == null) {
14691 HashMap<String, SparseArray<ProcessRecord>> all
14692 = mProcessNames.getMap();
14693 SparseArray<ProcessRecord> procs = all.get(process);
14694 if (procs != null && procs.size() > 0) {
14695 proc = procs.valueAt(0);
14696 }
14697 }
14698
14699 if (proc == null || proc.thread == null) {
14700 throw new IllegalArgumentException("Unknown process: " + process);
14701 }
14702
Dianne Hackbornf02e57b2011-03-01 22:21:04 -080014703 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
14704 if (!isDebuggable) {
Andy McFadden824c5102010-07-09 16:26:57 -070014705 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
14706 throw new SecurityException("Process not debuggable: " + proc);
14707 }
14708 }
14709
14710 proc.thread.dumpHeap(managed, path, fd);
14711 fd = null;
14712 return true;
14713 }
14714 } catch (RemoteException e) {
14715 throw new IllegalStateException("Process disappeared");
14716 } finally {
14717 if (fd != null) {
14718 try {
14719 fd.close();
14720 } catch (IOException e) {
14721 }
14722 }
14723 }
14724 }
14725
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014726 /** In this method we try to acquire our lock to make sure that we have not deadlocked */
14727 public void monitor() {
14728 synchronized (this) { }
14729 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014730
Dianne Hackborna573f6a2012-02-09 16:12:18 -080014731 void onCoreSettingsChange(Bundle settings) {
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014732 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
14733 ProcessRecord processRecord = mLruProcesses.get(i);
14734 try {
14735 if (processRecord.thread != null) {
14736 processRecord.thread.setCoreSettings(settings);
14737 }
14738 } catch (RemoteException re) {
14739 /* ignore */
14740 }
14741 }
14742 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014743
14744 // Multi-user methods
14745
Amith Yamasani742a6712011-05-04 14:49:28 -070014746 private int mCurrentUserId;
14747 private SparseIntArray mLoggedInUsers = new SparseIntArray(5);
14748
14749 public boolean switchUser(int userId) {
14750 final int callingUid = Binder.getCallingUid();
14751 if (callingUid != 0 && callingUid != Process.myUid()) {
14752 Slog.e(TAG, "Trying to switch user from unauthorized app");
14753 return false;
14754 }
14755 if (mCurrentUserId == userId)
14756 return true;
14757
14758 synchronized (this) {
14759 // Check if user is already logged in, otherwise check if user exists first before
14760 // adding to the list of logged in users.
14761 if (mLoggedInUsers.indexOfKey(userId) < 0) {
14762 if (!userExists(userId)) {
14763 return false;
14764 }
14765 mLoggedInUsers.append(userId, userId);
14766 }
14767
14768 mCurrentUserId = userId;
14769 boolean haveActivities = mMainStack.switchUser(userId);
14770 if (!haveActivities) {
14771 startHomeActivityLocked(userId);
14772 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014773
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014774 }
Amith Yamasani13593602012-03-22 16:16:17 -070014775
14776 // Inform of user switch
14777 Intent addedIntent = new Intent(Intent.ACTION_USER_SWITCHED);
14778 addedIntent.putExtra(Intent.EXTRA_USERID, userId);
14779 mContext.sendBroadcast(addedIntent, android.Manifest.permission.MANAGE_ACCOUNTS);
14780
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014781 return true;
14782 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014783
Amith Yamasani52f1d752012-03-28 18:19:29 -070014784 @Override
14785 public UserInfo getCurrentUser() throws RemoteException {
14786 final int callingUid = Binder.getCallingUid();
14787 if (callingUid != 0 && callingUid != Process.myUid()) {
14788 Slog.e(TAG, "Trying to get user from unauthorized app");
14789 return null;
14790 }
14791 return AppGlobals.getPackageManager().getUser(mCurrentUserId);
14792 }
14793
Amith Yamasani13593602012-03-22 16:16:17 -070014794 private void onUserRemoved(Intent intent) {
14795 int extraUserId = intent.getIntExtra(Intent.EXTRA_USERID, -1);
14796 if (extraUserId < 1) return;
14797
14798 // Kill all the processes for the user
14799 ArrayList<Pair<String, Integer>> pkgAndUids = new ArrayList<Pair<String,Integer>>();
14800 synchronized (this) {
14801 HashMap<String,SparseArray<ProcessRecord>> map = mProcessNames.getMap();
14802 for (Entry<String, SparseArray<ProcessRecord>> uidMap : map.entrySet()) {
14803 SparseArray<ProcessRecord> uids = uidMap.getValue();
14804 for (int i = 0; i < uids.size(); i++) {
14805 if (UserId.getUserId(uids.keyAt(i)) == extraUserId) {
14806 pkgAndUids.add(new Pair<String,Integer>(uidMap.getKey(), uids.keyAt(i)));
14807 }
14808 }
14809 }
14810
14811 for (Pair<String,Integer> pkgAndUid : pkgAndUids) {
14812 forceStopPackageLocked(pkgAndUid.first, pkgAndUid.second,
14813 false, false, true, true, extraUserId);
14814 }
14815 }
14816 }
14817
Amith Yamasani742a6712011-05-04 14:49:28 -070014818 private boolean userExists(int userId) {
14819 try {
Amith Yamasani13593602012-03-22 16:16:17 -070014820 UserInfo user = AppGlobals.getPackageManager().getUser(userId);
14821 return user != null;
Amith Yamasani742a6712011-05-04 14:49:28 -070014822 } catch (RemoteException re) {
14823 // Won't happen, in same process
14824 }
14825
14826 return false;
14827 }
14828
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014829 private void checkValidCaller(int uid, int userId) {
14830 if (UserId.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) return;
14831
14832 throw new SecurityException("Caller uid=" + uid
14833 + " is not privileged to communicate with user=" + userId);
14834 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014835
14836 private int applyUserId(int uid, int userId) {
14837 return UserId.getUid(userId, uid);
14838 }
14839
14840 private ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080014841 if (info == null) return null;
Amith Yamasani742a6712011-05-04 14:49:28 -070014842 ApplicationInfo newInfo = new ApplicationInfo(info);
14843 newInfo.uid = applyUserId(info.uid, userId);
14844 if (newInfo.uid >= Process.FIRST_APPLICATION_UID) {
14845 newInfo.dataDir = USER_DATA_DIR + userId + "/"
14846 + info.packageName;
14847 }
14848 return newInfo;
14849 }
14850
14851 ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080014852 if (aInfo == null || aInfo.applicationInfo.uid < Process.FIRST_APPLICATION_UID
Amith Yamasani742a6712011-05-04 14:49:28 -070014853 || userId < 1) {
14854 return aInfo;
14855 }
14856
14857 ActivityInfo info = new ActivityInfo(aInfo);
14858 info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId);
14859 return info;
14860 }
14861
14862 static class ServiceMap {
14863
14864 private final SparseArray<HashMap<ComponentName, ServiceRecord>> mServicesByNamePerUser
14865 = new SparseArray<HashMap<ComponentName, ServiceRecord>>();
14866 private final SparseArray<HashMap<Intent.FilterComparison, ServiceRecord>>
14867 mServicesByIntentPerUser = new SparseArray<
14868 HashMap<Intent.FilterComparison, ServiceRecord>>();
14869
14870 ServiceRecord getServiceByName(ComponentName name, int callingUser) {
14871 // TODO: Deal with global services
14872 if (DEBUG_MU)
14873 Slog.v(TAG_MU, "getServiceByName(" + name + "), callingUser = " + callingUser);
14874 return getServices(callingUser).get(name);
14875 }
14876
14877 ServiceRecord getServiceByName(ComponentName name) {
14878 return getServiceByName(name, -1);
14879 }
14880
14881 ServiceRecord getServiceByIntent(Intent.FilterComparison filter, int callingUser) {
14882 // TODO: Deal with global services
14883 if (DEBUG_MU)
14884 Slog.v(TAG_MU, "getServiceByIntent(" + filter + "), callingUser = " + callingUser);
14885 return getServicesByIntent(callingUser).get(filter);
14886 }
14887
14888 ServiceRecord getServiceByIntent(Intent.FilterComparison filter) {
14889 return getServiceByIntent(filter, -1);
14890 }
14891
14892 void putServiceByName(ComponentName name, int callingUser, ServiceRecord value) {
14893 // TODO: Deal with global services
14894 getServices(callingUser).put(name, value);
14895 }
14896
14897 void putServiceByIntent(Intent.FilterComparison filter, int callingUser,
14898 ServiceRecord value) {
14899 // TODO: Deal with global services
14900 getServicesByIntent(callingUser).put(filter, value);
14901 }
14902
14903 void removeServiceByName(ComponentName name, int callingUser) {
14904 // TODO: Deal with global services
14905 ServiceRecord removed = getServices(callingUser).remove(name);
14906 if (DEBUG_MU)
14907 Slog.v(TAG, "removeServiceByName user=" + callingUser + " name=" + name
14908 + " removed=" + removed);
14909 }
14910
14911 void removeServiceByIntent(Intent.FilterComparison filter, int callingUser) {
14912 // TODO: Deal with global services
14913 ServiceRecord removed = getServicesByIntent(callingUser).remove(filter);
14914 if (DEBUG_MU)
14915 Slog.v(TAG_MU, "removeServiceByIntent user=" + callingUser + " intent=" + filter
14916 + " removed=" + removed);
14917 }
14918
14919 Collection<ServiceRecord> getAllServices(int callingUser) {
14920 // TODO: Deal with global services
14921 return getServices(callingUser).values();
14922 }
14923
14924 private HashMap<ComponentName, ServiceRecord> getServices(int callingUser) {
14925 HashMap map = mServicesByNamePerUser.get(callingUser);
14926 if (map == null) {
14927 map = new HashMap<ComponentName, ServiceRecord>();
14928 mServicesByNamePerUser.put(callingUser, map);
14929 }
14930 return map;
14931 }
14932
14933 private HashMap<Intent.FilterComparison, ServiceRecord> getServicesByIntent(
14934 int callingUser) {
14935 HashMap map = mServicesByIntentPerUser.get(callingUser);
14936 if (map == null) {
14937 map = new HashMap<Intent.FilterComparison, ServiceRecord>();
14938 mServicesByIntentPerUser.put(callingUser, map);
14939 }
14940 return map;
14941 }
14942 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014943}