blob: 77bec41b7193999fb4035d8c131b212075fbf174 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006-2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.am;
18
Jeff Sharkey110a6b62012-03-12 11:12:41 -070019import static android.content.pm.PackageManager.PERMISSION_GRANTED;
20
Dianne Hackborn860755f2010-06-03 18:47:52 -070021import com.android.internal.R;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080022import com.android.internal.os.BatteryStatsImpl;
Dianne Hackborn45ce8642011-07-14 16:10:16 -070023import com.android.internal.os.ProcessStats;
Dianne Hackbornde7faf62009-06-30 13:27:30 -070024import com.android.server.AttributeCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025import com.android.server.IntentResolver;
26import com.android.server.ProcessMap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080027import com.android.server.SystemServer;
28import com.android.server.Watchdog;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070029import com.android.server.am.ActivityStack.ActivityState;
Dianne Hackborna924dc0d2011-02-17 14:22:17 -080030import com.android.server.wm.WindowManagerService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031
Dianne Hackborndd71fc82009-12-16 19:24:32 -080032import dalvik.system.Zygote;
33
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080034import android.app.Activity;
35import android.app.ActivityManager;
36import android.app.ActivityManagerNative;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -070037import android.app.ActivityOptions;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038import android.app.ActivityThread;
39import android.app.AlertDialog;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070040import android.app.AppGlobals;
Jacek Surazskif5b9c722009-05-18 12:09:59 +020041import android.app.ApplicationErrorReport;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import android.app.Dialog;
Dianne Hackbornb06ea702009-07-13 13:07:51 -070043import android.app.IActivityController;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044import android.app.IApplicationThread;
45import android.app.IInstrumentationWatcher;
Dianne Hackborn860755f2010-06-03 18:47:52 -070046import android.app.INotificationManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -070047import android.app.IProcessObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048import android.app.IServiceConnection;
49import android.app.IThumbnailReceiver;
50import android.app.Instrumentation;
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070051import android.app.Notification;
Dianne Hackborn860755f2010-06-03 18:47:52 -070052import android.app.NotificationManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080053import android.app.PendingIntent;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070054import android.app.Service;
Christopher Tate45281862010-03-05 15:46:30 -080055import android.app.backup.IBackupManager;
Jacek Surazskif5b9c722009-05-18 12:09:59 +020056import android.content.ActivityNotFoundException;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -080057import android.content.BroadcastReceiver;
Dianne Hackborn21c241e2012-03-08 13:57:23 -080058import android.content.ClipData;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070059import android.content.ComponentCallbacks2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060import android.content.ComponentName;
Jeff Sharkey110a6b62012-03-12 11:12:41 -070061import android.content.ContentProvider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062import android.content.ContentResolver;
63import android.content.Context;
Christian Mehlmauer7664e202010-07-20 08:46:17 +020064import android.content.DialogInterface;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070065import android.content.IIntentReceiver;
66import android.content.IIntentSender;
Adam Powelldd8fab22012-03-22 17:47:27 -070067import android.content.Intent;
68import android.content.IntentFilter;
Dianne Hackbornfa82f222009-09-17 15:14:12 -070069import android.content.IntentSender;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070import android.content.pm.ActivityInfo;
71import android.content.pm.ApplicationInfo;
72import android.content.pm.ConfigurationInfo;
73import android.content.pm.IPackageDataObserver;
74import android.content.pm.IPackageManager;
75import android.content.pm.InstrumentationInfo;
Dan Egnor66c40e72010-01-26 16:23:11 -080076import android.content.pm.PackageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077import android.content.pm.PackageManager;
Adam Powelldd8fab22012-03-22 17:47:27 -070078import android.content.pm.PackageManager.NameNotFoundException;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070079import android.content.pm.PathPermission;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080080import android.content.pm.ProviderInfo;
81import android.content.pm.ResolveInfo;
82import android.content.pm.ServiceInfo;
Amith Yamasani742a6712011-05-04 14:49:28 -070083import android.content.pm.UserInfo;
Dianne Hackborne2515ee2011-04-27 18:52:56 -040084import android.content.res.CompatibilityInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085import android.content.res.Configuration;
86import android.graphics.Bitmap;
Robert Greenwalt434203a2010-10-11 16:00:27 -070087import android.net.Proxy;
88import android.net.ProxyProperties;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080089import android.net.Uri;
90import android.os.Binder;
Dan Egnor60d87622009-12-16 16:32:58 -080091import android.os.Build;
Dan Egnor42471dd2010-01-07 17:25:22 -080092import android.os.Bundle;
Dianne Hackborn3025ef32009-08-31 21:31:47 -070093import android.os.Debug;
Dan Egnor60d87622009-12-16 16:32:58 -080094import android.os.DropBoxManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080095import android.os.Environment;
Dan Egnor42471dd2010-01-07 17:25:22 -080096import android.os.FileObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080097import android.os.FileUtils;
98import android.os.Handler;
99import android.os.IBinder;
100import android.os.IPermissionController;
101import android.os.Looper;
102import android.os.Message;
103import android.os.Parcel;
104import android.os.ParcelFileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800105import android.os.Process;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700106import android.os.RemoteCallbackList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107import android.os.RemoteException;
108import android.os.ServiceManager;
Brad Fitzpatrick46d42382010-06-11 13:57:58 -0700109import android.os.StrictMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110import android.os.SystemClock;
111import android.os.SystemProperties;
Amith Yamasani742a6712011-05-04 14:49:28 -0700112import android.os.UserId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113import android.provider.Settings;
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700114import android.text.format.Time;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800115import android.util.EventLog;
Joe Onorato5d3bea62010-03-01 13:44:29 -0800116import android.util.Log;
Adam Powelldd8fab22012-03-22 17:47:27 -0700117import android.util.Pair;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118import android.util.PrintWriterPrinter;
Adam Powelldd8fab22012-03-22 17:47:27 -0700119import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800120import android.util.SparseArray;
Amith Yamasani742a6712011-05-04 14:49:28 -0700121import android.util.SparseIntArray;
Dianne Hackborn1ebccf52010-08-15 13:04:34 -0700122import android.util.TimeUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800123import android.view.Gravity;
124import android.view.LayoutInflater;
125import android.view.View;
126import android.view.WindowManager;
127import android.view.WindowManagerPolicy;
128
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700129import java.io.BufferedInputStream;
130import java.io.BufferedOutputStream;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700131import java.io.BufferedReader;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700132import java.io.DataInputStream;
133import java.io.DataOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800134import java.io.File;
135import java.io.FileDescriptor;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700136import java.io.FileInputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800137import java.io.FileNotFoundException;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700138import java.io.FileOutputStream;
Jacek Surazskif5b9c722009-05-18 12:09:59 +0200139import java.io.IOException;
Dan Egnora455d192010-03-12 08:52:28 -0800140import java.io.InputStreamReader;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800141import java.io.PrintWriter;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700142import java.io.StringWriter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800143import java.lang.ref.WeakReference;
144import java.util.ArrayList;
Amith Yamasani742a6712011-05-04 14:49:28 -0700145import java.util.Collection;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700146import java.util.Collections;
147import java.util.Comparator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800148import java.util.HashMap;
149import java.util.HashSet;
150import java.util.Iterator;
151import java.util.List;
152import java.util.Locale;
153import java.util.Map;
Amith Yamasani13593602012-03-22 16:16:17 -0700154import java.util.Map.Entry;
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -0700155import java.util.Set;
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700156import java.util.concurrent.atomic.AtomicBoolean;
157import java.util.concurrent.atomic.AtomicLong;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800158
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700159public final class ActivityManagerService extends ActivityManagerNative
160 implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
Amith Yamasani742a6712011-05-04 14:49:28 -0700161 private static final String USER_DATA_DIR = "/data/user/";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800162 static final String TAG = "ActivityManager";
Amith Yamasani742a6712011-05-04 14:49:28 -0700163 static final String TAG_MU = "ActivityManagerServiceMU";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800164 static final boolean DEBUG = false;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400165 static final boolean localLOGV = DEBUG;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800166 static final boolean DEBUG_SWITCH = localLOGV || false;
167 static final boolean DEBUG_TASKS = localLOGV || false;
168 static final boolean DEBUG_PAUSE = localLOGV || false;
169 static final boolean DEBUG_OOM_ADJ = localLOGV || false;
170 static final boolean DEBUG_TRANSITION = localLOGV || false;
171 static final boolean DEBUG_BROADCAST = localLOGV || false;
Christopher Tatef46723b2012-01-26 14:19:24 -0800172 static final boolean DEBUG_BACKGROUND_BROADCAST = DEBUG_BROADCAST || false;
Dianne Hackborn82f3f002009-06-16 18:49:05 -0700173 static final boolean DEBUG_BROADCAST_LIGHT = DEBUG_BROADCAST || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800174 static final boolean DEBUG_SERVICE = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700175 static final boolean DEBUG_SERVICE_EXECUTING = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800176 static final boolean DEBUG_VISBILITY = localLOGV || false;
177 static final boolean DEBUG_PROCESSES = localLOGV || false;
Dianne Hackborna1e989b2009-09-01 19:54:29 -0700178 static final boolean DEBUG_PROVIDER = localLOGV || false;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800179 static final boolean DEBUG_URI_PERMISSION = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800180 static final boolean DEBUG_USER_LEAVING = localLOGV || false;
The Android Open Source Project10592532009-03-18 17:39:46 -0700181 static final boolean DEBUG_RESULTS = localLOGV || false;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -0700182 static final boolean DEBUG_BACKUP = localLOGV || false;
Dianne Hackborndc6b6352009-09-30 14:20:09 -0700183 static final boolean DEBUG_CONFIGURATION = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700184 static final boolean DEBUG_POWER = localLOGV || false;
185 static final boolean DEBUG_POWER_QUICK = DEBUG_POWER || false;
Amith Yamasani742a6712011-05-04 14:49:28 -0700186 static final boolean DEBUG_MU = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800187 static final boolean VALIDATE_TOKENS = false;
188 static final boolean SHOW_ACTIVITY_START_TIME = true;
189
190 // Control over CPU and battery monitoring.
191 static final long BATTERY_STATS_TIME = 30*60*1000; // write battery stats every 30 minutes.
192 static final boolean MONITOR_CPU_USAGE = true;
193 static final long MONITOR_CPU_MIN_TIME = 5*1000; // don't sample cpu less than every 5 seconds.
194 static final long MONITOR_CPU_MAX_TIME = 0x0fffffff; // wait possibly forever for next cpu sample.
195 static final boolean MONITOR_THREAD_CPU_USAGE = false;
196
Dianne Hackborn1655be42009-05-08 14:29:01 -0700197 // The flags that are set for all calls we make to the package manager.
Dianne Hackborn11b822d2009-07-21 20:03:02 -0700198 static final int STOCK_PM_FLAGS = PackageManager.GET_SHARED_LIBRARY_FILES;
Dianne Hackborn1655be42009-05-08 14:29:01 -0700199
Dianne Hackbornf02e57b2011-03-01 22:21:04 -0800200 private static final String SYSTEM_DEBUGGABLE = "ro.debuggable";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800201
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700202 static final boolean IS_USER_BUILD = "user".equals(Build.TYPE);
203
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800204 // Maximum number of recent tasks that we can remember.
205 static final int MAX_RECENT_TASKS = 20;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700206
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700207 // Amount of time after a call to stopAppSwitches() during which we will
208 // prevent further untrusted switches from happening.
209 static final long APP_SWITCH_DELAY_TIME = 5*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800210
211 // How long we wait for a launched process to attach to the activity manager
212 // before we decide it's never going to come up for real.
213 static final int PROC_START_TIMEOUT = 10*1000;
214
Jeff Brown3f9dd282011-07-08 20:02:19 -0700215 // How long we wait for a launched process to attach to the activity manager
216 // before we decide it's never going to come up for real, when the process was
217 // started with a wrapper for instrumentation (such as Valgrind) because it
218 // could take much longer than usual.
219 static final int PROC_START_TIMEOUT_WITH_WRAPPER = 300*1000;
220
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800221 // How long to wait after going idle before forcing apps to GC.
222 static final int GC_TIMEOUT = 5*1000;
223
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700224 // The minimum amount of time between successive GC requests for a process.
225 static final int GC_MIN_INTERVAL = 60*1000;
226
Dianne Hackborn287952c2010-09-22 22:34:31 -0700227 // The rate at which we check for apps using excessive power -- 15 mins.
228 static final int POWER_CHECK_DELAY = (DEBUG_POWER_QUICK ? 2 : 15) * 60*1000;
229
230 // The minimum sample duration we will allow before deciding we have
231 // enough data on wake locks to start killing things.
232 static final int WAKE_LOCK_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
233
234 // The minimum sample duration we will allow before deciding we have
235 // enough data on CPU usage to start killing things.
236 static final int CPU_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700237
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800238 // How long we allow a receiver to run before giving up on it.
Christopher Tatef46723b2012-01-26 14:19:24 -0800239 static final int BROADCAST_FG_TIMEOUT = 10*1000;
240 static final int BROADCAST_BG_TIMEOUT = 60*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800241
242 // How long we wait for a service to finish executing.
243 static final int SERVICE_TIMEOUT = 20*1000;
244
245 // How long a service needs to be running until restarting its process
246 // is no longer considered to be a relaunch of the service.
247 static final int SERVICE_RESTART_DURATION = 5*1000;
248
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700249 // How long a service needs to be running until it will start back at
250 // SERVICE_RESTART_DURATION after being killed.
251 static final int SERVICE_RESET_RUN_DURATION = 60*1000;
252
253 // Multiplying factor to increase restart duration time by, for each time
254 // a service is killed before it has run for SERVICE_RESET_RUN_DURATION.
255 static final int SERVICE_RESTART_DURATION_FACTOR = 4;
256
257 // The minimum amount of time between restarting services that we allow.
258 // That is, when multiple services are restarting, we won't allow each
259 // to restart less than this amount of time from the last one.
260 static final int SERVICE_MIN_RESTART_TIME_BETWEEN = 10*1000;
261
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800262 // Maximum amount of time for there to be no activity on a service before
263 // we consider it non-essential and allow its process to go on the
264 // LRU background list.
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700265 static final int MAX_SERVICE_INACTIVITY = 30*60*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800266
267 // How long we wait until we timeout on key dispatching.
268 static final int KEY_DISPATCHING_TIMEOUT = 5*1000;
269
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800270 // How long we wait until we timeout on key dispatching during instrumentation.
271 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT = 60*1000;
272
Dan Egnor42471dd2010-01-07 17:25:22 -0800273 static final int MY_PID = Process.myPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800274
275 static final String[] EMPTY_STRING_ARRAY = new String[0];
276
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700277 public ActivityStack mMainStack;
Mike Lockwood3a74bd32011-08-12 13:55:22 -0700278
279 private final boolean mHeadless;
280
Joe Onorato54a4a412011-11-02 20:50:08 -0700281 // Whether we should show our dialogs (ANR, crash, etc) or just perform their
282 // default actuion automatically. Important for devices without direct input
283 // devices.
284 private boolean mShowDialogs = true;
285
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800286 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700287 * Description of a request to start a new activity, which has been held
288 * due to app switches being disabled.
289 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700290 static class PendingActivityLaunch {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700291 ActivityRecord r;
292 ActivityRecord sourceRecord;
Dianne Hackborna4972e92012-03-14 10:38:05 -0700293 int startFlags;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700294 }
295
296 final ArrayList<PendingActivityLaunch> mPendingActivityLaunches
297 = new ArrayList<PendingActivityLaunch>();
298
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800299
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800300 BroadcastQueue mFgBroadcastQueue;
301 BroadcastQueue mBgBroadcastQueue;
Christopher Tatef46723b2012-01-26 14:19:24 -0800302 // Convenient for easy iteration over the queues. Foreground is first
303 // so that dispatch of foreground broadcasts gets precedence.
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800304 final BroadcastQueue[] mBroadcastQueues = new BroadcastQueue[2];
Christopher Tatef46723b2012-01-26 14:19:24 -0800305
306 BroadcastQueue broadcastQueueForIntent(Intent intent) {
307 final boolean isFg = (intent.getFlags() & Intent.FLAG_RECEIVER_FOREGROUND) != 0;
308 if (DEBUG_BACKGROUND_BROADCAST) {
309 Slog.i(TAG, "Broadcast intent " + intent + " on "
310 + (isFg ? "foreground" : "background")
311 + " queue");
312 }
313 return (isFg) ? mFgBroadcastQueue : mBgBroadcastQueue;
314 }
315
316 BroadcastRecord broadcastRecordForReceiverLocked(IBinder receiver) {
317 for (BroadcastQueue queue : mBroadcastQueues) {
318 BroadcastRecord r = queue.getMatchingOrderedReceiver(receiver);
319 if (r != null) {
320 return r;
321 }
322 }
323 return null;
324 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800325
326 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800327 * Activity we have told the window manager to have key focus.
328 */
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700329 ActivityRecord mFocusedActivity = null;
Dianne Hackbornbfe319e2009-09-21 00:34:05 -0700330 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800331 * List of intents that were used to start the most recent tasks.
332 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700333 final ArrayList<TaskRecord> mRecentTasks = new ArrayList<TaskRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800334
335 /**
Dianne Hackborn7d608422011-08-07 16:24:18 -0700336 * Process management.
337 */
338 final ProcessList mProcessList = new ProcessList();
339
340 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800341 * All of the applications we currently have running organized by name.
342 * The keys are strings of the application package name (as
343 * returned by the package manager), and the keys are ApplicationRecord
344 * objects.
345 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700346 final ProcessMap<ProcessRecord> mProcessNames = new ProcessMap<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800347
348 /**
Dianne Hackborna0c283e2012-02-09 10:47:01 -0800349 * The currently running isolated processes.
350 */
351 final SparseArray<ProcessRecord> mIsolatedProcesses = new SparseArray<ProcessRecord>();
352
353 /**
354 * Counter for assigning isolated process uids, to avoid frequently reusing the
355 * same ones.
356 */
357 int mNextIsolatedProcessUid = 0;
358
359 /**
Dianne Hackborn860755f2010-06-03 18:47:52 -0700360 * The currently running heavy-weight process, if any.
361 */
362 ProcessRecord mHeavyWeightProcess = null;
363
364 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800365 * The last time that various processes have crashed.
366 */
367 final ProcessMap<Long> mProcessCrashTimes = new ProcessMap<Long>();
368
369 /**
370 * Set of applications that we consider to be bad, and will reject
371 * incoming broadcasts from (which the user has no control over).
372 * Processes are added to this set when they have crashed twice within
373 * a minimum amount of time; they are removed from it when they are
374 * later restarted (hopefully due to some user action). The value is the
375 * time it was added to the list.
376 */
377 final ProcessMap<Long> mBadProcesses = new ProcessMap<Long>();
378
379 /**
380 * All of the processes we currently have running organized by pid.
381 * The keys are the pid running the application.
382 *
383 * <p>NOTE: This object is protected by its own lock, NOT the global
384 * activity manager lock!
385 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700386 final SparseArray<ProcessRecord> mPidsSelfLocked = new SparseArray<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800387
388 /**
389 * All of the processes that have been forced to be foreground. The key
390 * is the pid of the caller who requested it (we hold a death
391 * link on it).
392 */
393 abstract class ForegroundToken implements IBinder.DeathRecipient {
394 int pid;
395 IBinder token;
396 }
397 final SparseArray<ForegroundToken> mForegroundProcesses
398 = new SparseArray<ForegroundToken>();
399
400 /**
401 * List of records for processes that someone had tried to start before the
402 * system was ready. We don't start them at that point, but ensure they
403 * are started by the time booting is complete.
404 */
405 final ArrayList<ProcessRecord> mProcessesOnHold
406 = new ArrayList<ProcessRecord>();
407
408 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800409 * List of persistent applications that are in the process
410 * of being started.
411 */
412 final ArrayList<ProcessRecord> mPersistentStartingProcesses
413 = new ArrayList<ProcessRecord>();
414
415 /**
416 * Processes that are being forcibly torn down.
417 */
418 final ArrayList<ProcessRecord> mRemovedProcesses
419 = new ArrayList<ProcessRecord>();
420
421 /**
422 * List of running applications, sorted by recent usage.
423 * The first entry in the list is the least recently used.
424 * It contains ApplicationRecord objects. This list does NOT include
425 * any persistent application records (since we never want to exit them).
426 */
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800427 final ArrayList<ProcessRecord> mLruProcesses
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800428 = new ArrayList<ProcessRecord>();
429
430 /**
431 * List of processes that should gc as soon as things are idle.
432 */
433 final ArrayList<ProcessRecord> mProcessesToGc
434 = new ArrayList<ProcessRecord>();
435
436 /**
The Android Open Source Project4df24232009-03-05 14:34:35 -0800437 * This is the process holding what we currently consider to be
438 * the "home" activity.
439 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700440 ProcessRecord mHomeProcess;
The Android Open Source Project4df24232009-03-05 14:34:35 -0800441
442 /**
Dianne Hackbornf35fe232011-11-01 19:25:20 -0700443 * This is the process holding the activity the user last visited that
444 * is in a different process from the one they are currently in.
445 */
446 ProcessRecord mPreviousProcess;
Dianne Hackborn50685602011-12-01 12:23:37 -0800447
448 /**
449 * The time at which the previous process was last visible.
450 */
451 long mPreviousProcessVisibleTime;
452
Dianne Hackbornf35fe232011-11-01 19:25:20 -0700453 /**
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400454 * Packages that the user has asked to have run in screen size
455 * compatibility mode instead of filling the screen.
456 */
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -0700457 final CompatModePackages mCompatModePackages;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400458
459 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800460 * Set of PendingResultRecord objects that are currently active.
461 */
462 final HashSet mPendingResultRecords = new HashSet();
463
464 /**
465 * Set of IntentSenderRecord objects that are currently active.
466 */
467 final HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>> mIntentSenderRecords
468 = new HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>>();
469
470 /**
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -0800471 * Fingerprints (hashCode()) of stack traces that we've
Brad Fitzpatrick143666f2010-06-14 12:40:21 -0700472 * already logged DropBox entries for. Guarded by itself. If
473 * something (rogue user app) forces this over
474 * MAX_DUP_SUPPRESSED_STACKS entries, the contents are cleared.
475 */
476 private final HashSet<Integer> mAlreadyLoggedViolatedStacks = new HashSet<Integer>();
477 private static final int MAX_DUP_SUPPRESSED_STACKS = 5000;
478
479 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -0700480 * Strict Mode background batched logging state.
481 *
482 * The string buffer is guarded by itself, and its lock is also
483 * used to determine if another batched write is already
484 * in-flight.
485 */
486 private final StringBuilder mStrictModeBuffer = new StringBuilder();
487
488 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800489 * Keeps track of all IIntentReceivers that have been registered for
490 * broadcasts. Hash keys are the receiver IBinder, hash value is
491 * a ReceiverList.
492 */
493 final HashMap mRegisteredReceivers = new HashMap();
494
495 /**
496 * Resolver for broadcast intents to registered receivers.
497 * Holds BroadcastFilter (subclass of IntentFilter).
498 */
499 final IntentResolver<BroadcastFilter, BroadcastFilter> mReceiverResolver
500 = new IntentResolver<BroadcastFilter, BroadcastFilter>() {
501 @Override
502 protected boolean allowFilterResult(
503 BroadcastFilter filter, List<BroadcastFilter> dest) {
504 IBinder target = filter.receiverList.receiver.asBinder();
505 for (int i=dest.size()-1; i>=0; i--) {
506 if (dest.get(i).receiverList.receiver.asBinder() == target) {
507 return false;
508 }
509 }
510 return true;
511 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700512
513 @Override
514 protected String packageForFilter(BroadcastFilter filter) {
515 return filter.packageName;
516 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800517 };
518
519 /**
520 * State of all active sticky broadcasts. Keys are the action of the
521 * sticky Intent, values are an ArrayList of all broadcasted intents with
522 * that action (which should usually be one).
523 */
524 final HashMap<String, ArrayList<Intent>> mStickyBroadcasts =
525 new HashMap<String, ArrayList<Intent>>();
526
Amith Yamasani742a6712011-05-04 14:49:28 -0700527 final ServiceMap mServiceMap = new ServiceMap();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800528
529 /**
530 * All currently bound service connections. Keys are the IBinder of
531 * the client's IServiceConnection.
532 */
Dianne Hackborn43d9ac82010-08-25 15:06:25 -0700533 final HashMap<IBinder, ArrayList<ConnectionRecord>> mServiceConnections
534 = new HashMap<IBinder, ArrayList<ConnectionRecord>>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800535
536 /**
537 * List of services that we have been asked to start,
538 * but haven't yet been able to. It is used to hold start requests
539 * while waiting for their corresponding application thread to get
540 * going.
541 */
542 final ArrayList<ServiceRecord> mPendingServices
543 = new ArrayList<ServiceRecord>();
544
545 /**
546 * List of services that are scheduled to restart following a crash.
547 */
548 final ArrayList<ServiceRecord> mRestartingServices
549 = new ArrayList<ServiceRecord>();
550
551 /**
552 * List of services that are in the process of being stopped.
553 */
554 final ArrayList<ServiceRecord> mStoppingServices
555 = new ArrayList<ServiceRecord>();
556
557 /**
Christopher Tate181fafa2009-05-14 11:12:14 -0700558 * Backup/restore process management
559 */
560 String mBackupAppName = null;
561 BackupRecord mBackupTarget = null;
562
563 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800564 * List of PendingThumbnailsRecord objects of clients who are still
565 * waiting to receive all of the thumbnails for a task.
566 */
567 final ArrayList mPendingThumbnails = new ArrayList();
568
569 /**
570 * List of HistoryRecord objects that have been finished and must
571 * still report back to a pending thumbnail receiver.
572 */
573 final ArrayList mCancelledThumbnails = new ArrayList();
574
Amith Yamasani742a6712011-05-04 14:49:28 -0700575 final ProviderMap mProviderMap = new ProviderMap();
576
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800577 /**
578 * List of content providers who have clients waiting for them. The
579 * application is currently being launched and the provider will be
580 * removed from this list once it is published.
581 */
Dianne Hackborn860755f2010-06-03 18:47:52 -0700582 final ArrayList<ContentProviderRecord> mLaunchingProviders
583 = new ArrayList<ContentProviderRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800584
585 /**
586 * Global set of specific Uri permissions that have been granted.
587 */
588 final private SparseArray<HashMap<Uri, UriPermission>> mGrantedUriPermissions
589 = new SparseArray<HashMap<Uri, UriPermission>>();
590
Svetoslav Ganov54d068e2011-03-02 12:58:40 -0800591 CoreSettingsObserver mCoreSettingsObserver;
592
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800593 /**
594 * Thread-local storage used to carry caller permissions over through
595 * indirect content-provider access.
596 * @see #ActivityManagerService.openContentUri()
597 */
598 private class Identity {
599 public int pid;
600 public int uid;
601
602 Identity(int _pid, int _uid) {
603 pid = _pid;
604 uid = _uid;
605 }
606 }
Amith Yamasani742a6712011-05-04 14:49:28 -0700607
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800608 private static ThreadLocal<Identity> sCallerIdentity = new ThreadLocal<Identity>();
609
610 /**
611 * All information we have collected about the runtime performance of
612 * any user id that can impact battery performance.
613 */
614 final BatteryStatsService mBatteryStatsService;
615
616 /**
617 * information about component usage
618 */
619 final UsageStatsService mUsageStatsService;
620
621 /**
622 * Current configuration information. HistoryRecord objects are given
623 * a reference to this object to indicate which configuration they are
624 * currently running in, so this object must be kept immutable.
625 */
626 Configuration mConfiguration = new Configuration();
627
628 /**
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800629 * Current sequencing integer of the configuration, for skipping old
630 * configurations.
631 */
632 int mConfigurationSeq = 0;
633
634 /**
Jack Palevichb90d28c2009-07-22 15:35:24 -0700635 * Hardware-reported OpenGLES version.
636 */
637 final int GL_ES_VERSION;
638
639 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800640 * List of initialization arguments to pass to all processes when binding applications to them.
641 * For example, references to the commonly used services.
642 */
643 HashMap<String, IBinder> mAppBindArgs;
644
645 /**
Dianne Hackbornf210d6b2009-04-13 18:42:49 -0700646 * Temporary to avoid allocations. Protected by main lock.
647 */
648 final StringBuilder mStringBuilder = new StringBuilder(256);
649
650 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800651 * Used to control how we initialize the service.
652 */
653 boolean mStartRunning = false;
654 ComponentName mTopComponent;
655 String mTopAction;
656 String mTopData;
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700657 boolean mProcessesReady = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800658 boolean mSystemReady = false;
659 boolean mBooting = false;
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700660 boolean mWaitingUpdate = false;
661 boolean mDidUpdate = false;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700662 boolean mOnBattery = false;
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700663 boolean mLaunchWarningShown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800664
665 Context mContext;
666
667 int mFactoryTest;
668
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -0700669 boolean mCheckedForSetup;
670
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800671 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700672 * The time at which we will allow normal application switches again,
673 * after a call to {@link #stopAppSwitches()}.
674 */
675 long mAppSwitchesAllowedTime;
676
677 /**
678 * This is set to true after the first switch after mAppSwitchesAllowedTime
679 * is set; any switches after that will clear the time.
680 */
681 boolean mDidAppSwitch;
682
683 /**
Dianne Hackborn287952c2010-09-22 22:34:31 -0700684 * Last time (in realtime) at which we checked for power usage.
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700685 */
Dianne Hackborn287952c2010-09-22 22:34:31 -0700686 long mLastPowerCheckRealtime;
687
688 /**
689 * Last time (in uptime) at which we checked for power usage.
690 */
691 long mLastPowerCheckUptime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700692
693 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800694 * Set while we are wanting to sleep, to prevent any
695 * activities from being started/resumed.
696 */
697 boolean mSleeping = false;
698
699 /**
Dianne Hackbornff5b1582012-04-12 17:24:07 -0700700 * State of external calls telling us if the device is asleep.
701 */
702 boolean mWentToSleep = false;
703
704 /**
705 * State of external call telling us if the lock screen is shown.
706 */
707 boolean mLockScreenShown = false;
708
709 /**
Dianne Hackborn55280a92009-05-07 15:53:46 -0700710 * Set if we are shutting down the system, similar to sleeping.
711 */
712 boolean mShuttingDown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800713
714 /**
715 * Task identifier that activities are currently being started
716 * in. Incremented each time a new task is created.
717 * todo: Replace this with a TokenSpace class that generates non-repeating
718 * integers that won't wrap.
719 */
720 int mCurTask = 1;
721
722 /**
723 * Current sequence id for oom_adj computation traversal.
724 */
725 int mAdjSeq = 0;
726
727 /**
Dianne Hackborn906497c2010-05-10 15:57:38 -0700728 * Current sequence id for process LRU updating.
729 */
730 int mLruSeq = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800731
732 /**
Dianne Hackborne02c88a2011-10-28 13:58:15 -0700733 * Keep track of the number of service processes we last found, to
734 * determine on the next iteration which should be B services.
735 */
736 int mNumServiceProcs = 0;
737 int mNewNumServiceProcs = 0;
738
739 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800740 * System monitoring: number of processes that died since the last
741 * N procs were started.
742 */
743 int[] mProcDeaths = new int[20];
744
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700745 /**
746 * This is set if we had to do a delayed dexopt of an app before launching
747 * it, to increasing the ANR timeouts in that case.
748 */
749 boolean mDidDexOpt;
750
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800751 String mDebugApp = null;
752 boolean mWaitForDebugger = false;
753 boolean mDebugTransient = false;
754 String mOrigDebugApp = null;
755 boolean mOrigWaitForDebugger = false;
756 boolean mAlwaysFinishActivities = false;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700757 IActivityController mController = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700758 String mProfileApp = null;
759 ProcessRecord mProfileProc = null;
760 String mProfileFile;
761 ParcelFileDescriptor mProfileFd;
762 int mProfileType = 0;
763 boolean mAutoStopProfiler = false;
Siva Velusamy92a8b222012-03-09 16:24:04 -0800764 String mOpenGlTraceApp = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800765
Jeff Sharkeya4620792011-05-20 15:29:23 -0700766 final RemoteCallbackList<IProcessObserver> mProcessObservers
767 = new RemoteCallbackList<IProcessObserver>();
768
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800769 /**
770 * Callback of last caller to {@link #requestPss}.
771 */
772 Runnable mRequestPssCallback;
773
774 /**
775 * Remaining processes for which we are waiting results from the last
776 * call to {@link #requestPss}.
777 */
778 final ArrayList<ProcessRecord> mRequestPssList
779 = new ArrayList<ProcessRecord>();
780
781 /**
782 * Runtime statistics collection thread. This object's lock is used to
783 * protect all related state.
784 */
785 final Thread mProcessStatsThread;
786
787 /**
788 * Used to collect process stats when showing not responding dialog.
789 * Protected by mProcessStatsThread.
790 */
791 final ProcessStats mProcessStats = new ProcessStats(
792 MONITOR_THREAD_CPU_USAGE);
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700793 final AtomicLong mLastCpuTime = new AtomicLong(0);
794 final AtomicBoolean mProcessStatsMutexFree = new AtomicBoolean(true);
795
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800796 long mLastWriteTime = 0;
797
798 /**
799 * Set to true after the system has finished booting.
800 */
801 boolean mBooted = false;
802
Dianne Hackborn7d608422011-08-07 16:24:18 -0700803 int mProcessLimit = ProcessList.MAX_HIDDEN_APPS;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700804 int mProcessLimitOverride = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800805
806 WindowManagerService mWindowManager;
807
808 static ActivityManagerService mSelf;
809 static ActivityThread mSystemThread;
810
811 private final class AppDeathRecipient implements IBinder.DeathRecipient {
812 final ProcessRecord mApp;
813 final int mPid;
814 final IApplicationThread mAppThread;
815
816 AppDeathRecipient(ProcessRecord app, int pid,
817 IApplicationThread thread) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800818 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800819 TAG, "New death recipient " + this
820 + " for thread " + thread.asBinder());
821 mApp = app;
822 mPid = pid;
823 mAppThread = thread;
824 }
825
826 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800827 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800828 TAG, "Death received in " + this
829 + " for thread " + mAppThread.asBinder());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800830 synchronized(ActivityManagerService.this) {
831 appDiedLocked(mApp, mPid, mAppThread);
832 }
833 }
834 }
835
836 static final int SHOW_ERROR_MSG = 1;
837 static final int SHOW_NOT_RESPONDING_MSG = 2;
838 static final int SHOW_FACTORY_ERROR_MSG = 3;
839 static final int UPDATE_CONFIGURATION_MSG = 4;
840 static final int GC_BACKGROUND_PROCESSES_MSG = 5;
841 static final int WAIT_FOR_DEBUGGER_MSG = 6;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800842 static final int SERVICE_TIMEOUT_MSG = 12;
843 static final int UPDATE_TIME_ZONE = 13;
844 static final int SHOW_UID_ERROR_MSG = 14;
845 static final int IM_FEELING_LUCKY_MSG = 15;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800846 static final int PROC_START_TIMEOUT_MSG = 20;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700847 static final int DO_PENDING_ACTIVITY_LAUNCHES_MSG = 21;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -0700848 static final int KILL_APPLICATION_MSG = 22;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800849 static final int FINALIZE_PENDING_INTENT_MSG = 23;
Dianne Hackborn860755f2010-06-03 18:47:52 -0700850 static final int POST_HEAVY_NOTIFICATION_MSG = 24;
851 static final int CANCEL_HEAVY_NOTIFICATION_MSG = 25;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700852 static final int SHOW_STRICT_MODE_VIOLATION_MSG = 26;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700853 static final int CHECK_EXCESSIVE_WAKE_LOCKS_MSG = 27;
Robert Greenwalt03595d02010-11-02 14:08:23 -0700854 static final int CLEAR_DNS_CACHE = 28;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700855 static final int UPDATE_HTTP_PROXY = 29;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700856 static final int SHOW_COMPAT_MODE_DIALOG_MSG = 30;
Dianne Hackborn36f80f32011-05-31 18:26:45 -0700857 static final int DISPATCH_FOREGROUND_ACTIVITIES_CHANGED = 31;
858 static final int DISPATCH_PROCESS_DIED = 32;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700859 static final int REPORT_MEM_USAGE = 33;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800860
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800861 static final int FIRST_ACTIVITY_STACK_MSG = 100;
862 static final int FIRST_BROADCAST_QUEUE_MSG = 200;
863 static final int FIRST_COMPAT_MODE_MSG = 300;
864
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800865 AlertDialog mUidAlert;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700866 CompatModeDialog mCompatModeDialog;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700867 long mLastMemUsageReportTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800868
869 final Handler mHandler = new Handler() {
870 //public Handler() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800871 // if (localLOGV) Slog.v(TAG, "Handler started!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800872 //}
873
874 public void handleMessage(Message msg) {
875 switch (msg.what) {
876 case SHOW_ERROR_MSG: {
877 HashMap data = (HashMap) msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800878 synchronized (ActivityManagerService.this) {
879 ProcessRecord proc = (ProcessRecord)data.get("app");
880 if (proc != null && proc.crashDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800881 Slog.e(TAG, "App already has crash dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800882 return;
883 }
884 AppErrorResult res = (AppErrorResult) data.get("result");
Joe Onorato54a4a412011-11-02 20:50:08 -0700885 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Dan Egnorb7f03672009-12-09 16:22:32 -0800886 Dialog d = new AppErrorDialog(mContext, res, proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800887 d.show();
888 proc.crashDialog = d;
889 } else {
890 // The device is asleep, so just pretend that the user
891 // saw a crash dialog and hit "force quit".
892 res.set(0);
893 }
894 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700895
896 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800897 } break;
898 case SHOW_NOT_RESPONDING_MSG: {
899 synchronized (ActivityManagerService.this) {
900 HashMap data = (HashMap) msg.obj;
901 ProcessRecord proc = (ProcessRecord)data.get("app");
902 if (proc != null && proc.anrDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800903 Slog.e(TAG, "App already has anr dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800904 return;
905 }
The Android Open Source Project4df24232009-03-05 14:34:35 -0800906
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700907 Intent intent = new Intent("android.intent.action.ANR");
908 if (!mProcessesReady) {
Christopher Tatef46723b2012-01-26 14:19:24 -0800909 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
910 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700911 }
912 broadcastIntentLocked(null, null, intent,
The Android Open Source Project4df24232009-03-05 14:34:35 -0800913 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -0700914 false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
The Android Open Source Project4df24232009-03-05 14:34:35 -0800915
Justin Kohbc52ca22012-03-29 15:11:44 -0700916 if (mShowDialogs) {
917 Dialog d = new AppNotRespondingDialog(ActivityManagerService.this,
Mike Lockwood69ccdbd2012-04-03 11:53:47 -0700918 mContext, proc, (ActivityRecord)data.get("activity"));
Justin Kohbc52ca22012-03-29 15:11:44 -0700919 d.show();
920 proc.anrDialog = d;
921 } else {
922 // Just kill the app if there is no dialog to be shown.
923 killAppAtUsersRequest(proc, null);
924 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800925 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700926
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700927 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800928 } break;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700929 case SHOW_STRICT_MODE_VIOLATION_MSG: {
930 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj;
931 synchronized (ActivityManagerService.this) {
932 ProcessRecord proc = (ProcessRecord) data.get("app");
933 if (proc == null) {
934 Slog.e(TAG, "App not found when showing strict mode dialog.");
935 break;
936 }
937 if (proc.crashDialog != null) {
938 Slog.e(TAG, "App already has strict mode dialog: " + proc);
939 return;
940 }
941 AppErrorResult res = (AppErrorResult) data.get("result");
Joe Onorato54a4a412011-11-02 20:50:08 -0700942 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700943 Dialog d = new StrictModeViolationDialog(mContext, res, proc);
944 d.show();
945 proc.crashDialog = d;
946 } else {
947 // The device is asleep, so just pretend that the user
948 // saw a crash dialog and hit "force quit".
949 res.set(0);
950 }
951 }
952 ensureBootCompleted();
953 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800954 case SHOW_FACTORY_ERROR_MSG: {
955 Dialog d = new FactoryErrorDialog(
956 mContext, msg.getData().getCharSequence("msg"));
957 d.show();
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700958 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800959 } break;
960 case UPDATE_CONFIGURATION_MSG: {
961 final ContentResolver resolver = mContext.getContentResolver();
962 Settings.System.putConfiguration(resolver, (Configuration)msg.obj);
963 } break;
964 case GC_BACKGROUND_PROCESSES_MSG: {
965 synchronized (ActivityManagerService.this) {
966 performAppGcsIfAppropriateLocked();
967 }
968 } break;
969 case WAIT_FOR_DEBUGGER_MSG: {
970 synchronized (ActivityManagerService.this) {
971 ProcessRecord app = (ProcessRecord)msg.obj;
972 if (msg.arg1 != 0) {
973 if (!app.waitedForDebugger) {
974 Dialog d = new AppWaitingForDebuggerDialog(
975 ActivityManagerService.this,
976 mContext, app);
977 app.waitDialog = d;
978 app.waitedForDebugger = true;
979 d.show();
980 }
981 } else {
982 if (app.waitDialog != null) {
983 app.waitDialog.dismiss();
984 app.waitDialog = null;
985 }
986 }
987 }
988 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800989 case SERVICE_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700990 if (mDidDexOpt) {
991 mDidDexOpt = false;
992 Message nmsg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
993 nmsg.obj = msg.obj;
994 mHandler.sendMessageDelayed(nmsg, SERVICE_TIMEOUT);
995 return;
996 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800997 serviceTimeout((ProcessRecord)msg.obj);
998 } break;
999 case UPDATE_TIME_ZONE: {
1000 synchronized (ActivityManagerService.this) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001001 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1002 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001003 if (r.thread != null) {
1004 try {
1005 r.thread.updateTimeZone();
1006 } catch (RemoteException ex) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001007 Slog.w(TAG, "Failed to update time zone for: " + r.info.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001008 }
1009 }
1010 }
1011 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001012 } break;
Robert Greenwalt03595d02010-11-02 14:08:23 -07001013 case CLEAR_DNS_CACHE: {
1014 synchronized (ActivityManagerService.this) {
1015 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1016 ProcessRecord r = mLruProcesses.get(i);
1017 if (r.thread != null) {
1018 try {
1019 r.thread.clearDnsCache();
1020 } catch (RemoteException ex) {
1021 Slog.w(TAG, "Failed to clear dns cache for: " + r.info.processName);
1022 }
1023 }
1024 }
1025 }
1026 } break;
Robert Greenwalt434203a2010-10-11 16:00:27 -07001027 case UPDATE_HTTP_PROXY: {
1028 ProxyProperties proxy = (ProxyProperties)msg.obj;
1029 String host = "";
1030 String port = "";
1031 String exclList = "";
1032 if (proxy != null) {
1033 host = proxy.getHost();
1034 port = Integer.toString(proxy.getPort());
1035 exclList = proxy.getExclusionList();
1036 }
1037 synchronized (ActivityManagerService.this) {
1038 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1039 ProcessRecord r = mLruProcesses.get(i);
1040 if (r.thread != null) {
1041 try {
1042 r.thread.setHttpProxy(host, port, exclList);
1043 } catch (RemoteException ex) {
1044 Slog.w(TAG, "Failed to update http proxy for: " +
1045 r.info.processName);
1046 }
1047 }
1048 }
1049 }
1050 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001051 case SHOW_UID_ERROR_MSG: {
Joe Onorato54a4a412011-11-02 20:50:08 -07001052 String title = "System UIDs Inconsistent";
1053 String text = "UIDs on the system are inconsistent, you need to wipe your"
1054 + " data partition or your device will be unstable.";
1055 Log.e(TAG, title + ": " + text);
1056 if (mShowDialogs) {
1057 // XXX This is a temporary dialog, no need to localize.
1058 AlertDialog d = new BaseErrorDialog(mContext);
1059 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
1060 d.setCancelable(false);
1061 d.setTitle(title);
1062 d.setMessage(text);
1063 d.setButton(DialogInterface.BUTTON_POSITIVE, "I'm Feeling Lucky",
1064 mHandler.obtainMessage(IM_FEELING_LUCKY_MSG));
1065 mUidAlert = d;
1066 d.show();
1067 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001068 } break;
1069 case IM_FEELING_LUCKY_MSG: {
1070 if (mUidAlert != null) {
1071 mUidAlert.dismiss();
1072 mUidAlert = null;
1073 }
1074 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001075 case PROC_START_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001076 if (mDidDexOpt) {
1077 mDidDexOpt = false;
1078 Message nmsg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
1079 nmsg.obj = msg.obj;
1080 mHandler.sendMessageDelayed(nmsg, PROC_START_TIMEOUT);
1081 return;
1082 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001083 ProcessRecord app = (ProcessRecord)msg.obj;
1084 synchronized (ActivityManagerService.this) {
1085 processStartTimedOutLocked(app);
1086 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001087 } break;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07001088 case DO_PENDING_ACTIVITY_LAUNCHES_MSG: {
1089 synchronized (ActivityManagerService.this) {
1090 doPendingActivityLaunchesLocked(true);
1091 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001092 } break;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001093 case KILL_APPLICATION_MSG: {
1094 synchronized (ActivityManagerService.this) {
1095 int uid = msg.arg1;
1096 boolean restart = (msg.arg2 == 1);
1097 String pkg = (String) msg.obj;
Amith Yamasani483f3b02012-03-13 16:08:00 -07001098 forceStopPackageLocked(pkg, uid, restart, false, true, false,
1099 UserId.getUserId(uid));
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001100 }
1101 } break;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001102 case FINALIZE_PENDING_INTENT_MSG: {
1103 ((PendingIntentRecord)msg.obj).completeFinalize();
1104 } break;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001105 case POST_HEAVY_NOTIFICATION_MSG: {
1106 INotificationManager inm = NotificationManager.getService();
1107 if (inm == null) {
1108 return;
1109 }
1110
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001111 ActivityRecord root = (ActivityRecord)msg.obj;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001112 ProcessRecord process = root.app;
1113 if (process == null) {
1114 return;
1115 }
1116
1117 try {
1118 Context context = mContext.createPackageContext(process.info.packageName, 0);
1119 String text = mContext.getString(R.string.heavy_weight_notification,
1120 context.getApplicationInfo().loadLabel(context.getPackageManager()));
1121 Notification notification = new Notification();
1122 notification.icon = com.android.internal.R.drawable.stat_sys_adb; //context.getApplicationInfo().icon;
1123 notification.when = 0;
1124 notification.flags = Notification.FLAG_ONGOING_EVENT;
1125 notification.tickerText = text;
1126 notification.defaults = 0; // please be quiet
1127 notification.sound = null;
1128 notification.vibrate = null;
1129 notification.setLatestEventInfo(context, text,
1130 mContext.getText(R.string.heavy_weight_notification_detail),
1131 PendingIntent.getActivity(mContext, 0, root.intent,
1132 PendingIntent.FLAG_CANCEL_CURRENT));
1133
1134 try {
1135 int[] outId = new int[1];
1136 inm.enqueueNotification("android", R.string.heavy_weight_notification,
1137 notification, outId);
1138 } catch (RuntimeException e) {
1139 Slog.w(ActivityManagerService.TAG,
1140 "Error showing notification for heavy-weight app", e);
1141 } catch (RemoteException e) {
1142 }
1143 } catch (NameNotFoundException e) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07001144 Slog.w(TAG, "Unable to create context for heavy notification", e);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001145 }
1146 } break;
1147 case CANCEL_HEAVY_NOTIFICATION_MSG: {
1148 INotificationManager inm = NotificationManager.getService();
1149 if (inm == null) {
1150 return;
1151 }
1152 try {
1153 inm.cancelNotification("android",
1154 R.string.heavy_weight_notification);
1155 } catch (RuntimeException e) {
1156 Slog.w(ActivityManagerService.TAG,
1157 "Error canceling notification for service", e);
1158 } catch (RemoteException e) {
1159 }
1160 } break;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001161 case CHECK_EXCESSIVE_WAKE_LOCKS_MSG: {
1162 synchronized (ActivityManagerService.this) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001163 checkExcessivePowerUsageLocked(true);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07001164 removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001165 Message nmsg = obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
1166 sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001167 }
1168 } break;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001169 case SHOW_COMPAT_MODE_DIALOG_MSG: {
1170 synchronized (ActivityManagerService.this) {
1171 ActivityRecord ar = (ActivityRecord)msg.obj;
1172 if (mCompatModeDialog != null) {
1173 if (mCompatModeDialog.mAppInfo.packageName.equals(
1174 ar.info.applicationInfo.packageName)) {
1175 return;
1176 }
1177 mCompatModeDialog.dismiss();
1178 mCompatModeDialog = null;
1179 }
Dianne Hackborn29478262011-06-07 15:44:22 -07001180 if (ar != null && false) {
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001181 if (mCompatModePackages.getPackageAskCompatModeLocked(
1182 ar.packageName)) {
1183 int mode = mCompatModePackages.computeCompatModeLocked(
1184 ar.info.applicationInfo);
1185 if (mode == ActivityManager.COMPAT_MODE_DISABLED
1186 || mode == ActivityManager.COMPAT_MODE_ENABLED) {
1187 mCompatModeDialog = new CompatModeDialog(
1188 ActivityManagerService.this, mContext,
1189 ar.info.applicationInfo);
1190 mCompatModeDialog.show();
1191 }
1192 }
1193 }
1194 }
Dianne Hackborn36f80f32011-05-31 18:26:45 -07001195 break;
1196 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001197 case DISPATCH_FOREGROUND_ACTIVITIES_CHANGED: {
Jeff Sharkey287bd832011-05-28 19:36:26 -07001198 final int pid = msg.arg1;
1199 final int uid = msg.arg2;
1200 final boolean foregroundActivities = (Boolean) msg.obj;
1201 dispatchForegroundActivitiesChanged(pid, uid, foregroundActivities);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001202 break;
1203 }
1204 case DISPATCH_PROCESS_DIED: {
Jeff Sharkey287bd832011-05-28 19:36:26 -07001205 final int pid = msg.arg1;
1206 final int uid = msg.arg2;
1207 dispatchProcessDied(pid, uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001208 break;
1209 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001210 case REPORT_MEM_USAGE: {
1211 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
1212 if (!isDebuggable) {
1213 return;
1214 }
1215 synchronized (ActivityManagerService.this) {
1216 long now = SystemClock.uptimeMillis();
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001217 if (now < (mLastMemUsageReportTime+5*60*1000)) {
1218 // Don't report more than every 5 minutes to somewhat
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001219 // avoid spamming.
1220 return;
1221 }
1222 mLastMemUsageReportTime = now;
1223 }
1224 Thread thread = new Thread() {
1225 @Override public void run() {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001226 StringBuilder dropBuilder = new StringBuilder(1024);
1227 StringBuilder logBuilder = new StringBuilder(1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -08001228 StringWriter oomSw = new StringWriter();
1229 PrintWriter oomPw = new PrintWriter(oomSw);
1230 StringWriter catSw = new StringWriter();
1231 PrintWriter catPw = new PrintWriter(catSw);
1232 String[] emptyArgs = new String[] { };
1233 StringBuilder tag = new StringBuilder(128);
1234 StringBuilder stack = new StringBuilder(128);
1235 tag.append("Low on memory -- ");
1236 dumpApplicationMemoryUsage(null, oomPw, " ", emptyArgs, true, catPw,
1237 tag, stack);
1238 dropBuilder.append(stack);
1239 dropBuilder.append('\n');
1240 dropBuilder.append('\n');
1241 String oomString = oomSw.toString();
1242 dropBuilder.append(oomString);
1243 dropBuilder.append('\n');
1244 logBuilder.append(oomString);
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001245 try {
1246 java.lang.Process proc = Runtime.getRuntime().exec(new String[] {
1247 "procrank", });
1248 final InputStreamReader converter = new InputStreamReader(
1249 proc.getInputStream());
1250 BufferedReader in = new BufferedReader(converter);
1251 String line;
1252 while (true) {
1253 line = in.readLine();
1254 if (line == null) {
1255 break;
1256 }
1257 if (line.length() > 0) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001258 logBuilder.append(line);
1259 logBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001260 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001261 dropBuilder.append(line);
1262 dropBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001263 }
1264 converter.close();
1265 } catch (IOException e) {
1266 }
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001267 synchronized (ActivityManagerService.this) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08001268 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001269 dumpProcessesLocked(null, catPw, emptyArgs, 0, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001270 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001271 dumpServicesLocked(null, catPw, emptyArgs, 0, false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001272 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001273 dumpActivitiesLocked(null, catPw, emptyArgs, 0, false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001274 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001275 dropBuilder.append(catSw.toString());
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001276 addErrorToDropBox("lowmem", null, "system_server", null,
1277 null, tag.toString(), dropBuilder.toString(), null, null);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001278 Slog.i(TAG, logBuilder.toString());
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001279 synchronized (ActivityManagerService.this) {
1280 long now = SystemClock.uptimeMillis();
1281 if (mLastMemUsageReportTime < now) {
1282 mLastMemUsageReportTime = now;
1283 }
1284 }
1285 }
1286 };
1287 thread.start();
1288 break;
1289 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001290 }
1291 }
1292 };
1293
1294 public static void setSystemProcess() {
1295 try {
1296 ActivityManagerService m = mSelf;
1297
Dianne Hackborna573f6a2012-02-09 16:12:18 -08001298 ServiceManager.addService("activity", m, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001299 ServiceManager.addService("meminfo", new MemBinder(m));
Chet Haase9c1e23b2011-03-24 10:51:31 -07001300 ServiceManager.addService("gfxinfo", new GraphicsBinder(m));
Jeff Brown6754ba22011-12-14 20:20:01 -08001301 ServiceManager.addService("dbinfo", new DbBinder(m));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001302 if (MONITOR_CPU_USAGE) {
1303 ServiceManager.addService("cpuinfo", new CpuBinder(m));
1304 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001305 ServiceManager.addService("permission", new PermissionController(m));
1306
1307 ApplicationInfo info =
1308 mSelf.mContext.getPackageManager().getApplicationInfo(
Amith Yamasani483f3b02012-03-13 16:08:00 -07001309 "android", STOCK_PM_FLAGS);
Mike Cleron432b7132009-09-24 15:28:29 -07001310 mSystemThread.installSystemApplicationInfo(info);
1311
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001312 synchronized (mSelf) {
1313 ProcessRecord app = mSelf.newProcessRecordLocked(
1314 mSystemThread.getApplicationThread(), info,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001315 info.processName, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001316 app.persistent = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08001317 app.pid = MY_PID;
Dianne Hackborn7d608422011-08-07 16:24:18 -07001318 app.maxAdj = ProcessList.SYSTEM_ADJ;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001319 mSelf.mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001320 synchronized (mSelf.mPidsSelfLocked) {
1321 mSelf.mPidsSelfLocked.put(app.pid, app);
1322 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001323 mSelf.updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001324 }
1325 } catch (PackageManager.NameNotFoundException e) {
1326 throw new RuntimeException(
1327 "Unable to find android system package", e);
1328 }
1329 }
1330
1331 public void setWindowManager(WindowManagerService wm) {
1332 mWindowManager = wm;
1333 }
1334
1335 public static final Context main(int factoryTest) {
1336 AThread thr = new AThread();
1337 thr.start();
1338
1339 synchronized (thr) {
1340 while (thr.mService == null) {
1341 try {
1342 thr.wait();
1343 } catch (InterruptedException e) {
1344 }
1345 }
1346 }
1347
1348 ActivityManagerService m = thr.mService;
1349 mSelf = m;
1350 ActivityThread at = ActivityThread.systemMain();
1351 mSystemThread = at;
1352 Context context = at.getSystemContext();
Dianne Hackborn247fe742011-01-08 17:25:57 -08001353 context.setTheme(android.R.style.Theme_Holo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001354 m.mContext = context;
1355 m.mFactoryTest = factoryTest;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001356 m.mMainStack = new ActivityStack(m, context, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001357
1358 m.mBatteryStatsService.publish(context);
1359 m.mUsageStatsService.publish(context);
1360
1361 synchronized (thr) {
1362 thr.mReady = true;
1363 thr.notifyAll();
1364 }
1365
1366 m.startRunning(null, null, null, null);
1367
1368 return context;
1369 }
1370
1371 public static ActivityManagerService self() {
1372 return mSelf;
1373 }
1374
1375 static class AThread extends Thread {
1376 ActivityManagerService mService;
1377 boolean mReady = false;
1378
1379 public AThread() {
1380 super("ActivityManager");
1381 }
1382
1383 public void run() {
1384 Looper.prepare();
1385
1386 android.os.Process.setThreadPriority(
1387 android.os.Process.THREAD_PRIORITY_FOREGROUND);
Christopher Tate160edb32010-06-30 17:46:30 -07001388 android.os.Process.setCanSelfBackground(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001389
1390 ActivityManagerService m = new ActivityManagerService();
1391
1392 synchronized (this) {
1393 mService = m;
1394 notifyAll();
1395 }
1396
1397 synchronized (this) {
1398 while (!mReady) {
1399 try {
1400 wait();
1401 } catch (InterruptedException e) {
1402 }
1403 }
1404 }
1405
Brad Fitzpatrickec062f62010-11-03 09:56:54 -07001406 // For debug builds, log event loop stalls to dropbox for analysis.
1407 if (StrictMode.conditionallyEnableDebugLogging()) {
1408 Slog.i(TAG, "Enabled StrictMode logging for AThread's Looper");
1409 }
1410
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001411 Looper.loop();
1412 }
1413 }
1414
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001415 static class MemBinder extends Binder {
1416 ActivityManagerService mActivityManagerService;
1417 MemBinder(ActivityManagerService activityManagerService) {
1418 mActivityManagerService = activityManagerService;
1419 }
1420
1421 @Override
1422 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001423 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1424 != PackageManager.PERMISSION_GRANTED) {
1425 pw.println("Permission Denial: can't dump meminfo from from pid="
1426 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1427 + " without permission " + android.Manifest.permission.DUMP);
1428 return;
1429 }
1430
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001431 mActivityManagerService.dumpApplicationMemoryUsage(fd, pw, " ", args,
Dianne Hackborn672342c2011-11-29 11:29:02 -08001432 false, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001433 }
1434 }
1435
Chet Haase9c1e23b2011-03-24 10:51:31 -07001436 static class GraphicsBinder extends Binder {
1437 ActivityManagerService mActivityManagerService;
1438 GraphicsBinder(ActivityManagerService activityManagerService) {
1439 mActivityManagerService = activityManagerService;
1440 }
1441
1442 @Override
1443 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001444 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1445 != PackageManager.PERMISSION_GRANTED) {
1446 pw.println("Permission Denial: can't dump gfxinfo from from pid="
1447 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1448 + " without permission " + android.Manifest.permission.DUMP);
1449 return;
1450 }
1451
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001452 mActivityManagerService.dumpGraphicsHardwareUsage(fd, pw, args);
Chet Haase9c1e23b2011-03-24 10:51:31 -07001453 }
1454 }
1455
Jeff Brown6754ba22011-12-14 20:20:01 -08001456 static class DbBinder extends Binder {
1457 ActivityManagerService mActivityManagerService;
1458 DbBinder(ActivityManagerService activityManagerService) {
1459 mActivityManagerService = activityManagerService;
1460 }
1461
1462 @Override
1463 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1464 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1465 != PackageManager.PERMISSION_GRANTED) {
1466 pw.println("Permission Denial: can't dump dbinfo from from pid="
1467 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1468 + " without permission " + android.Manifest.permission.DUMP);
1469 return;
1470 }
1471
1472 mActivityManagerService.dumpDbInfo(fd, pw, args);
1473 }
1474 }
1475
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001476 static class CpuBinder extends Binder {
1477 ActivityManagerService mActivityManagerService;
1478 CpuBinder(ActivityManagerService activityManagerService) {
1479 mActivityManagerService = activityManagerService;
1480 }
1481
1482 @Override
1483 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001484 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1485 != PackageManager.PERMISSION_GRANTED) {
1486 pw.println("Permission Denial: can't dump cpuinfo from from pid="
1487 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1488 + " without permission " + android.Manifest.permission.DUMP);
1489 return;
1490 }
1491
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001492 synchronized (mActivityManagerService.mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07001493 pw.print(mActivityManagerService.mProcessStats.printCurrentLoad());
1494 pw.print(mActivityManagerService.mProcessStats.printCurrentState(
1495 SystemClock.uptimeMillis()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001496 }
1497 }
1498 }
1499
1500 private ActivityManagerService() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001501 Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
Dianne Hackborn2c6c5e62009-10-08 17:55:49 -07001502
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001503 mFgBroadcastQueue = new BroadcastQueue(this, "foreground", BROADCAST_FG_TIMEOUT);
1504 mBgBroadcastQueue = new BroadcastQueue(this, "background", BROADCAST_BG_TIMEOUT);
1505 mBroadcastQueues[0] = mFgBroadcastQueue;
1506 mBroadcastQueues[1] = mBgBroadcastQueue;
1507
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001508 File dataDir = Environment.getDataDirectory();
1509 File systemDir = new File(dataDir, "system");
1510 systemDir.mkdirs();
1511 mBatteryStatsService = new BatteryStatsService(new File(
1512 systemDir, "batterystats.bin").toString());
1513 mBatteryStatsService.getActiveStatistics().readLocked();
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001514 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
Dianne Hackborn287952c2010-09-22 22:34:31 -07001515 mOnBattery = DEBUG_POWER ? true
1516 : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001517 mBatteryStatsService.getActiveStatistics().setCallback(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001518
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001519 mUsageStatsService = new UsageStatsService(new File(
Dianne Hackborn6447ca32009-04-07 19:50:08 -07001520 systemDir, "usagestats").toString());
Mike Lockwood3a74bd32011-08-12 13:55:22 -07001521 mHeadless = "1".equals(SystemProperties.get("ro.config.headless", "0"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001522
Jack Palevichb90d28c2009-07-22 15:35:24 -07001523 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",
1524 ConfigurationInfo.GL_ES_VERSION_UNDEFINED);
1525
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001526 mConfiguration.setToDefaults();
1527 mConfiguration.locale = Locale.getDefault();
Dianne Hackborn813075a62011-11-14 17:45:19 -08001528 mConfigurationSeq = mConfiguration.seq = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001529 mProcessStats.init();
1530
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07001531 mCompatModePackages = new CompatModePackages(this, systemDir);
1532
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001533 // Add ourself to the Watchdog monitors.
1534 Watchdog.getInstance().addMonitor(this);
1535
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001536 mProcessStatsThread = new Thread("ProcessStats") {
1537 public void run() {
1538 while (true) {
1539 try {
1540 try {
1541 synchronized(this) {
1542 final long now = SystemClock.uptimeMillis();
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001543 long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001544 long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001545 //Slog.i(TAG, "Cpu delay=" + nextCpuDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001546 // + ", write delay=" + nextWriteDelay);
1547 if (nextWriteDelay < nextCpuDelay) {
1548 nextCpuDelay = nextWriteDelay;
1549 }
1550 if (nextCpuDelay > 0) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001551 mProcessStatsMutexFree.set(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001552 this.wait(nextCpuDelay);
1553 }
1554 }
1555 } catch (InterruptedException e) {
1556 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001557 updateCpuStatsNow();
1558 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001559 Slog.e(TAG, "Unexpected exception collecting process stats", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001560 }
1561 }
1562 }
1563 };
1564 mProcessStatsThread.start();
1565 }
1566
1567 @Override
1568 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1569 throws RemoteException {
1570 try {
1571 return super.onTransact(code, data, reply, flags);
1572 } catch (RuntimeException e) {
1573 // The activity manager only throws security exceptions, so let's
1574 // log all others.
1575 if (!(e instanceof SecurityException)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001576 Slog.e(TAG, "Activity Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001577 }
1578 throw e;
1579 }
1580 }
1581
1582 void updateCpuStats() {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001583 final long now = SystemClock.uptimeMillis();
1584 if (mLastCpuTime.get() >= now - MONITOR_CPU_MIN_TIME) {
1585 return;
1586 }
1587 if (mProcessStatsMutexFree.compareAndSet(true, false)) {
1588 synchronized (mProcessStatsThread) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001589 mProcessStatsThread.notify();
1590 }
1591 }
1592 }
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001593
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001594 void updateCpuStatsNow() {
1595 synchronized (mProcessStatsThread) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001596 mProcessStatsMutexFree.set(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001597 final long now = SystemClock.uptimeMillis();
1598 boolean haveNewCpuStats = false;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07001599
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001600 if (MONITOR_CPU_USAGE &&
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001601 mLastCpuTime.get() < (now-MONITOR_CPU_MIN_TIME)) {
1602 mLastCpuTime.set(now);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001603 haveNewCpuStats = true;
1604 mProcessStats.update();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001605 //Slog.i(TAG, mProcessStats.printCurrentState());
1606 //Slog.i(TAG, "Total CPU usage: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001607 // + mProcessStats.getTotalCpuPercent() + "%");
1608
Joe Onorato8a9b2202010-02-26 18:56:32 -08001609 // Slog the cpu usage if the property is set.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001610 if ("true".equals(SystemProperties.get("events.cpu"))) {
1611 int user = mProcessStats.getLastUserTime();
1612 int system = mProcessStats.getLastSystemTime();
1613 int iowait = mProcessStats.getLastIoWaitTime();
1614 int irq = mProcessStats.getLastIrqTime();
1615 int softIrq = mProcessStats.getLastSoftIrqTime();
1616 int idle = mProcessStats.getLastIdleTime();
1617
1618 int total = user + system + iowait + irq + softIrq + idle;
1619 if (total == 0) total = 1;
1620
Doug Zongker2bec3d42009-12-04 12:52:44 -08001621 EventLog.writeEvent(EventLogTags.CPU,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001622 ((user+system+iowait+irq+softIrq) * 100) / total,
1623 (user * 100) / total,
1624 (system * 100) / total,
1625 (iowait * 100) / total,
1626 (irq * 100) / total,
1627 (softIrq * 100) / total);
1628 }
1629 }
1630
Amith Yamasanie43530a2009-08-21 13:11:37 -07001631 long[] cpuSpeedTimes = mProcessStats.getLastCpuSpeedTimes();
Amith Yamasani819f9282009-06-24 23:18:15 -07001632 final BatteryStatsImpl bstats = mBatteryStatsService.getActiveStatistics();
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001633 synchronized(bstats) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001634 synchronized(mPidsSelfLocked) {
1635 if (haveNewCpuStats) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001636 if (mOnBattery) {
1637 int perc = bstats.startAddingCpuLocked();
1638 int totalUTime = 0;
1639 int totalSTime = 0;
Dianne Hackborn287952c2010-09-22 22:34:31 -07001640 final int N = mProcessStats.countStats();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001641 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001642 ProcessStats.Stats st = mProcessStats.getStats(i);
1643 if (!st.working) {
1644 continue;
1645 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001646 ProcessRecord pr = mPidsSelfLocked.get(st.pid);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001647 int otherUTime = (st.rel_utime*perc)/100;
1648 int otherSTime = (st.rel_stime*perc)/100;
1649 totalUTime += otherUTime;
1650 totalSTime += otherSTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001651 if (pr != null) {
1652 BatteryStatsImpl.Uid.Proc ps = pr.batteryStats;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001653 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1654 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001655 ps.addSpeedStepTimes(cpuSpeedTimes);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001656 pr.curCpuTime += (st.rel_utime+st.rel_stime) * 10;
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001657 } else {
1658 BatteryStatsImpl.Uid.Proc ps =
Amith Yamasani819f9282009-06-24 23:18:15 -07001659 bstats.getProcessStatsLocked(st.name, st.pid);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001660 if (ps != null) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001661 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1662 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001663 ps.addSpeedStepTimes(cpuSpeedTimes);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001664 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001665 }
1666 }
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001667 bstats.finishAddingCpuLocked(perc, totalUTime,
1668 totalSTime, cpuSpeedTimes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001669 }
1670 }
1671 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001672
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001673 if (mLastWriteTime < (now-BATTERY_STATS_TIME)) {
1674 mLastWriteTime = now;
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001675 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001676 }
1677 }
1678 }
1679 }
1680
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001681 @Override
1682 public void batteryNeedsCpuUpdate() {
1683 updateCpuStatsNow();
1684 }
1685
1686 @Override
1687 public void batteryPowerChanged(boolean onBattery) {
1688 // When plugging in, update the CPU stats first before changing
1689 // the plug state.
1690 updateCpuStatsNow();
1691 synchronized (this) {
1692 synchronized(mPidsSelfLocked) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001693 mOnBattery = DEBUG_POWER ? true : onBattery;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001694 }
1695 }
1696 }
1697
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001698 /**
1699 * Initialize the application bind args. These are passed to each
1700 * process when the bindApplication() IPC is sent to the process. They're
1701 * lazily setup to make sure the services are running when they're asked for.
1702 */
1703 private HashMap<String, IBinder> getCommonServicesLocked() {
1704 if (mAppBindArgs == null) {
1705 mAppBindArgs = new HashMap<String, IBinder>();
1706
1707 // Setup the application init args
1708 mAppBindArgs.put("package", ServiceManager.getService("package"));
1709 mAppBindArgs.put("window", ServiceManager.getService("window"));
1710 mAppBindArgs.put(Context.ALARM_SERVICE,
1711 ServiceManager.getService(Context.ALARM_SERVICE));
1712 }
1713 return mAppBindArgs;
1714 }
1715
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001716 final void setFocusedActivityLocked(ActivityRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001717 if (mFocusedActivity != r) {
1718 mFocusedActivity = r;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001719 if (r != null) {
1720 mWindowManager.setFocusedApp(r.appToken, true);
1721 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001722 }
1723 }
1724
Dianne Hackborn906497c2010-05-10 15:57:38 -07001725 private final void updateLruProcessInternalLocked(ProcessRecord app,
1726 boolean oomAdj, boolean updateActivityTime, int bestPos) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001727 // put it on the LRU to keep track of when it should be exited.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001728 int lrui = mLruProcesses.indexOf(app);
1729 if (lrui >= 0) mLruProcesses.remove(lrui);
1730
1731 int i = mLruProcesses.size()-1;
1732 int skipTop = 0;
1733
Dianne Hackborn906497c2010-05-10 15:57:38 -07001734 app.lruSeq = mLruSeq;
1735
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001736 // compute the new weight for this process.
1737 if (updateActivityTime) {
1738 app.lastActivityTime = SystemClock.uptimeMillis();
1739 }
1740 if (app.activities.size() > 0) {
1741 // If this process has activities, we more strongly want to keep
1742 // it around.
1743 app.lruWeight = app.lastActivityTime;
1744 } else if (app.pubProviders.size() > 0) {
1745 // If this process contains content providers, we want to keep
1746 // it a little more strongly.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001747 app.lruWeight = app.lastActivityTime - ProcessList.CONTENT_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001748 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001749 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001750 } else {
1751 // If this process doesn't have activities, we less strongly
1752 // want to keep it around, and generally want to avoid getting
1753 // in front of any very recently used activities.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001754 app.lruWeight = app.lastActivityTime - ProcessList.EMPTY_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001755 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001756 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001757 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001758
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001759 while (i >= 0) {
1760 ProcessRecord p = mLruProcesses.get(i);
1761 // If this app shouldn't be in front of the first N background
1762 // apps, then skip over that many that are currently hidden.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001763 if (skipTop > 0 && p.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001764 skipTop--;
1765 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001766 if (p.lruWeight <= app.lruWeight || i < bestPos) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001767 mLruProcesses.add(i+1, app);
1768 break;
1769 }
1770 i--;
1771 }
1772 if (i < 0) {
1773 mLruProcesses.add(0, app);
1774 }
1775
Dianne Hackborn906497c2010-05-10 15:57:38 -07001776 // If the app is currently using a content provider or service,
1777 // bump those processes as well.
1778 if (app.connections.size() > 0) {
1779 for (ConnectionRecord cr : app.connections) {
1780 if (cr.binding != null && cr.binding.service != null
1781 && cr.binding.service.app != null
1782 && cr.binding.service.app.lruSeq != mLruSeq) {
1783 updateLruProcessInternalLocked(cr.binding.service.app, oomAdj,
1784 updateActivityTime, i+1);
1785 }
1786 }
1787 }
1788 if (app.conProviders.size() > 0) {
1789 for (ContentProviderRecord cpr : app.conProviders.keySet()) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07001790 if (cpr.proc != null && cpr.proc.lruSeq != mLruSeq) {
1791 updateLruProcessInternalLocked(cpr.proc, oomAdj,
Dianne Hackborn906497c2010-05-10 15:57:38 -07001792 updateActivityTime, i+1);
1793 }
1794 }
1795 }
1796
Joe Onorato8a9b2202010-02-26 18:56:32 -08001797 //Slog.i(TAG, "Putting proc to front: " + app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001798 if (oomAdj) {
1799 updateOomAdjLocked();
1800 }
1801 }
1802
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001803 final void updateLruProcessLocked(ProcessRecord app,
Dianne Hackborn906497c2010-05-10 15:57:38 -07001804 boolean oomAdj, boolean updateActivityTime) {
1805 mLruSeq++;
1806 updateLruProcessInternalLocked(app, oomAdj, updateActivityTime, 0);
1807 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001808
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001809 final ProcessRecord getProcessRecordLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001810 String processName, int uid) {
Amith Yamasania4a54e22012-04-16 15:44:19 -07001811 if (uid == Process.SYSTEM_UID) {
Amith Yamasani0184ce92012-03-28 22:41:41 -07001812 // The system gets to run in any process. If there are multiple
1813 // processes with the same uid, just pick the first (this
1814 // should never happen).
1815 SparseArray<ProcessRecord> procs = mProcessNames.getMap().get(
1816 processName);
Amith Yamasania4a54e22012-04-16 15:44:19 -07001817 if (procs == null) return null;
1818 final int N = procs.size();
1819 for (int i = 0; i < N; i++) {
1820 if (UserId.isSameUser(procs.keyAt(i), uid)) return procs.valueAt(i);
1821 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001822 }
1823 ProcessRecord proc = mProcessNames.get(processName, uid);
1824 return proc;
1825 }
1826
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001827 void ensurePackageDexOpt(String packageName) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001828 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001829 try {
1830 if (pm.performDexOpt(packageName)) {
1831 mDidDexOpt = true;
1832 }
1833 } catch (RemoteException e) {
1834 }
1835 }
1836
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001837 boolean isNextTransitionForward() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001838 int transit = mWindowManager.getPendingAppTransition();
1839 return transit == WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
1840 || transit == WindowManagerPolicy.TRANSIT_TASK_OPEN
1841 || transit == WindowManagerPolicy.TRANSIT_TASK_TO_FRONT;
1842 }
1843
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001844 final ProcessRecord startProcessLocked(String processName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001845 ApplicationInfo info, boolean knownToBeDead, int intentFlags,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001846 String hostingType, ComponentName hostingName, boolean allowWhileBooting,
1847 boolean isolated) {
1848 ProcessRecord app;
1849 if (!isolated) {
1850 app = getProcessRecordLocked(processName, info.uid);
1851 } else {
1852 // If this is an isolated process, it can't re-use an existing process.
1853 app = null;
1854 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001855 // We don't have to do anything more if:
1856 // (1) There is an existing application record; and
1857 // (2) The caller doesn't think it is dead, OR there is no thread
1858 // object attached to it so we know it couldn't have crashed; and
1859 // (3) There is a pid assigned to it, so it is either starting or
1860 // already running.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001861 if (DEBUG_PROCESSES) Slog.v(TAG, "startProcess: name=" + processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001862 + " app=" + app + " knownToBeDead=" + knownToBeDead
1863 + " thread=" + (app != null ? app.thread : null)
1864 + " pid=" + (app != null ? app.pid : -1));
Magnus Edlund7bb25812010-02-24 15:45:06 +01001865 if (app != null && app.pid > 0) {
1866 if (!knownToBeDead || app.thread == null) {
Dianne Hackborn20cb56e2010-03-04 00:58:29 -08001867 // We already have the app running, or are waiting for it to
1868 // come up (we have a pid but not yet its thread), so keep it.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001869 if (DEBUG_PROCESSES) Slog.v(TAG, "App already running: " + app);
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001870 // If this is a new package in the process, add the package to the list
1871 app.addPackage(info.packageName);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001872 return app;
1873 } else {
1874 // An application record is attached to a previous process,
1875 // clean it up now.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001876 if (DEBUG_PROCESSES) Slog.v(TAG, "App died: " + app);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07001877 handleAppDiedLocked(app, true, true);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001878 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001879 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01001880
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001881 String hostingNameStr = hostingName != null
1882 ? hostingName.flattenToShortString() : null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001883
1884 if (!isolated) {
1885 if ((intentFlags&Intent.FLAG_FROM_BACKGROUND) != 0) {
1886 // If we are in the background, then check to see if this process
1887 // is bad. If so, we will just silently fail.
1888 if (mBadProcesses.get(info.processName, info.uid) != null) {
1889 if (DEBUG_PROCESSES) Slog.v(TAG, "Bad process: " + info.uid
1890 + "/" + info.processName);
1891 return null;
1892 }
1893 } else {
1894 // When the user is explicitly starting a process, then clear its
1895 // crash count so that we won't make it bad until they see at
1896 // least one crash dialog again, and make the process good again
1897 // if it had been bad.
1898 if (DEBUG_PROCESSES) Slog.v(TAG, "Clearing bad process: " + info.uid
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001899 + "/" + info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001900 mProcessCrashTimes.remove(info.processName, info.uid);
1901 if (mBadProcesses.get(info.processName, info.uid) != null) {
1902 EventLog.writeEvent(EventLogTags.AM_PROC_GOOD, info.uid,
1903 info.processName);
1904 mBadProcesses.remove(info.processName, info.uid);
1905 if (app != null) {
1906 app.bad = false;
1907 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001908 }
1909 }
1910 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001911
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001912 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001913 app = newProcessRecordLocked(null, info, processName, isolated);
1914 if (app == null) {
1915 Slog.w(TAG, "Failed making new process record for "
1916 + processName + "/" + info.uid + " isolated=" + isolated);
1917 return null;
1918 }
1919 mProcessNames.put(processName, app.uid, app);
1920 if (isolated) {
1921 mIsolatedProcesses.put(app.uid, app);
1922 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001923 } else {
1924 // If this is a new package in the process, add the package to the list
1925 app.addPackage(info.packageName);
1926 }
1927
1928 // If the system is not ready yet, then hold off on starting this
1929 // process until it is.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001930 if (!mProcessesReady
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001931 && !isAllowedWhileBooting(info)
1932 && !allowWhileBooting) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001933 if (!mProcessesOnHold.contains(app)) {
1934 mProcessesOnHold.add(app);
1935 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001936 if (DEBUG_PROCESSES) Slog.v(TAG, "System not ready, putting on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001937 return app;
1938 }
1939
1940 startProcessLocked(app, hostingType, hostingNameStr);
1941 return (app.pid != 0) ? app : null;
1942 }
1943
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001944 boolean isAllowedWhileBooting(ApplicationInfo ai) {
1945 return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0;
1946 }
1947
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001948 private final void startProcessLocked(ProcessRecord app,
1949 String hostingType, String hostingNameStr) {
1950 if (app.pid > 0 && app.pid != MY_PID) {
1951 synchronized (mPidsSelfLocked) {
1952 mPidsSelfLocked.remove(app.pid);
1953 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
1954 }
1955 app.pid = 0;
1956 }
1957
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001958 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
1959 "startProcessLocked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001960 mProcessesOnHold.remove(app);
1961
1962 updateCpuStats();
1963
1964 System.arraycopy(mProcDeaths, 0, mProcDeaths, 1, mProcDeaths.length-1);
1965 mProcDeaths[0] = 0;
1966
1967 try {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001968 int uid = app.uid;
Amith Yamasani742a6712011-05-04 14:49:28 -07001969
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001970 int[] gids = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001971 if (!app.isolated) {
1972 try {
1973 gids = mContext.getPackageManager().getPackageGids(
1974 app.info.packageName);
1975 } catch (PackageManager.NameNotFoundException e) {
1976 Slog.w(TAG, "Unable to retrieve gids", e);
1977 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001978 }
1979 if (mFactoryTest != SystemServer.FACTORY_TEST_OFF) {
1980 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
1981 && mTopComponent != null
1982 && app.processName.equals(mTopComponent.getPackageName())) {
1983 uid = 0;
1984 }
1985 if (mFactoryTest == SystemServer.FACTORY_TEST_HIGH_LEVEL
1986 && (app.info.flags&ApplicationInfo.FLAG_FACTORY_TEST) != 0) {
1987 uid = 0;
1988 }
1989 }
1990 int debugFlags = 0;
1991 if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
1992 debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;
Elliott Hughesfa36aee2011-06-17 14:39:41 -07001993 // Also turn on CheckJNI for debuggable apps. It's quite
1994 // awkward to turn on otherwise.
1995 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001996 }
Ben Cheng6c0afff2010-02-14 16:18:56 -08001997 // Run the app in safe mode if its manifest requests so or the
1998 // system is booted in safe mode.
1999 if ((app.info.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0 ||
2000 Zygote.systemInSafeMode == true) {
Ben Cheng23085b72010-02-08 16:06:32 -08002001 debugFlags |= Zygote.DEBUG_ENABLE_SAFEMODE;
2002 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002003 if ("1".equals(SystemProperties.get("debug.checkjni"))) {
2004 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
2005 }
Elliott Hughesae07ecf2011-07-06 17:33:27 -07002006 if ("1".equals(SystemProperties.get("debug.jni.logging"))) {
2007 debugFlags |= Zygote.DEBUG_ENABLE_JNI_LOGGING;
2008 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002009 if ("1".equals(SystemProperties.get("debug.assert"))) {
2010 debugFlags |= Zygote.DEBUG_ENABLE_ASSERT;
2011 }
Jeff Brown3f9dd282011-07-08 20:02:19 -07002012
2013 // Start the process. It will either succeed and return a result containing
2014 // the PID of the new process, or else throw a RuntimeException.
2015 Process.ProcessStartResult startResult = Process.start("android.app.ActivityThread",
Elliott Hughese1dfcb72011-07-08 11:08:07 -07002016 app.processName, uid, uid, gids, debugFlags,
2017 app.info.targetSdkVersion, null);
Jeff Brown3f9dd282011-07-08 20:02:19 -07002018
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002019 BatteryStatsImpl bs = app.batteryStats.getBatteryStats();
2020 synchronized (bs) {
2021 if (bs.isOnBattery()) {
2022 app.batteryStats.incStartsLocked();
2023 }
2024 }
2025
Jeff Brown3f9dd282011-07-08 20:02:19 -07002026 EventLog.writeEvent(EventLogTags.AM_PROC_START, startResult.pid, uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002027 app.processName, hostingType,
2028 hostingNameStr != null ? hostingNameStr : "");
2029
2030 if (app.persistent) {
Jeff Brown3f9dd282011-07-08 20:02:19 -07002031 Watchdog.getInstance().processStarted(app.processName, startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002032 }
2033
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07002034 StringBuilder buf = mStringBuilder;
2035 buf.setLength(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002036 buf.append("Start proc ");
2037 buf.append(app.processName);
2038 buf.append(" for ");
2039 buf.append(hostingType);
2040 if (hostingNameStr != null) {
2041 buf.append(" ");
2042 buf.append(hostingNameStr);
2043 }
2044 buf.append(": pid=");
Jeff Brown3f9dd282011-07-08 20:02:19 -07002045 buf.append(startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002046 buf.append(" uid=");
2047 buf.append(uid);
2048 buf.append(" gids={");
2049 if (gids != null) {
2050 for (int gi=0; gi<gids.length; gi++) {
2051 if (gi != 0) buf.append(", ");
2052 buf.append(gids[gi]);
2053
2054 }
2055 }
2056 buf.append("}");
Joe Onorato8a9b2202010-02-26 18:56:32 -08002057 Slog.i(TAG, buf.toString());
Jeff Brown3f9dd282011-07-08 20:02:19 -07002058 app.pid = startResult.pid;
2059 app.usingWrapper = startResult.usingWrapper;
2060 app.removed = false;
2061 synchronized (mPidsSelfLocked) {
2062 this.mPidsSelfLocked.put(startResult.pid, app);
2063 Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
2064 msg.obj = app;
2065 mHandler.sendMessageDelayed(msg, startResult.usingWrapper
2066 ? PROC_START_TIMEOUT_WITH_WRAPPER : PROC_START_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002067 }
2068 } catch (RuntimeException e) {
2069 // XXX do better error recovery.
2070 app.pid = 0;
Joe Onorato8a9b2202010-02-26 18:56:32 -08002071 Slog.e(TAG, "Failure starting process " + app.processName, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002072 }
2073 }
2074
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002075 void updateUsageStats(ActivityRecord resumedComponent, boolean resumed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002076 if (resumed) {
2077 mUsageStatsService.noteResumeComponent(resumedComponent.realActivity);
2078 } else {
2079 mUsageStatsService.notePauseComponent(resumedComponent.realActivity);
2080 }
2081 }
2082
Amith Yamasani742a6712011-05-04 14:49:28 -07002083 boolean startHomeActivityLocked(int userId) {
Mike Lockwooda8f767a2011-08-31 14:32:37 -04002084 if (mHeadless) {
2085 // Added because none of the other calls to ensureBootCompleted seem to fire
2086 // when running headless.
2087 ensureBootCompleted();
2088 return false;
2089 }
2090
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002091 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2092 && mTopAction == null) {
2093 // We are running in factory test mode, but unable to find
2094 // the factory test app, so just sit around displaying the
2095 // error message and don't try to start anything.
2096 return false;
2097 }
2098 Intent intent = new Intent(
2099 mTopAction,
2100 mTopData != null ? Uri.parse(mTopData) : null);
2101 intent.setComponent(mTopComponent);
2102 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
2103 intent.addCategory(Intent.CATEGORY_HOME);
2104 }
2105 ActivityInfo aInfo =
2106 intent.resolveActivityInfo(mContext.getPackageManager(),
2107 STOCK_PM_FLAGS);
2108 if (aInfo != null) {
2109 intent.setComponent(new ComponentName(
2110 aInfo.applicationInfo.packageName, aInfo.name));
2111 // Don't do this if the home app is currently being
2112 // instrumented.
Amith Yamasani742a6712011-05-04 14:49:28 -07002113 aInfo = new ActivityInfo(aInfo);
2114 aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002115 ProcessRecord app = getProcessRecordLocked(aInfo.processName,
2116 aInfo.applicationInfo.uid);
2117 if (app == null || app.instrumentationClass == null) {
2118 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002119 mMainStack.startActivityLocked(null, intent, null, aInfo,
2120 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002121 }
2122 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002123
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002124 return true;
2125 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002126
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002127 /**
2128 * Starts the "new version setup screen" if appropriate.
2129 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002130 void startSetupActivityLocked() {
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002131 // Only do this once per boot.
2132 if (mCheckedForSetup) {
2133 return;
2134 }
2135
2136 // We will show this screen if the current one is a different
2137 // version than the last one shown, and we are not running in
2138 // low-level factory test mode.
2139 final ContentResolver resolver = mContext.getContentResolver();
2140 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL &&
2141 Settings.Secure.getInt(resolver,
2142 Settings.Secure.DEVICE_PROVISIONED, 0) != 0) {
2143 mCheckedForSetup = true;
2144
2145 // See if we should be showing the platform update setup UI.
2146 Intent intent = new Intent(Intent.ACTION_UPGRADE_SETUP);
2147 List<ResolveInfo> ris = mSelf.mContext.getPackageManager()
2148 .queryIntentActivities(intent, PackageManager.GET_META_DATA);
2149
2150 // We don't allow third party apps to replace this.
2151 ResolveInfo ri = null;
2152 for (int i=0; ris != null && i<ris.size(); i++) {
2153 if ((ris.get(i).activityInfo.applicationInfo.flags
2154 & ApplicationInfo.FLAG_SYSTEM) != 0) {
2155 ri = ris.get(i);
2156 break;
2157 }
2158 }
2159
2160 if (ri != null) {
2161 String vers = ri.activityInfo.metaData != null
2162 ? ri.activityInfo.metaData.getString(Intent.METADATA_SETUP_VERSION)
2163 : null;
2164 if (vers == null && ri.activityInfo.applicationInfo.metaData != null) {
2165 vers = ri.activityInfo.applicationInfo.metaData.getString(
2166 Intent.METADATA_SETUP_VERSION);
2167 }
2168 String lastVers = Settings.Secure.getString(
2169 resolver, Settings.Secure.LAST_SETUP_SHOWN);
2170 if (vers != null && !vers.equals(lastVers)) {
2171 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2172 intent.setComponent(new ComponentName(
2173 ri.activityInfo.packageName, ri.activityInfo.name));
Dianne Hackborna4972e92012-03-14 10:38:05 -07002174 mMainStack.startActivityLocked(null, intent, null, ri.activityInfo,
2175 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002176 }
2177 }
2178 }
2179 }
2180
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002181 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002182 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002183 }
2184
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002185 void enforceNotIsolatedCaller(String caller) {
2186 if (UserId.isIsolated(Binder.getCallingUid())) {
2187 throw new SecurityException("Isolated process not allowed to call " + caller);
2188 }
2189 }
2190
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002191 public int getFrontActivityScreenCompatMode() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002192 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002193 synchronized (this) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002194 return mCompatModePackages.getFrontActivityScreenCompatModeLocked();
2195 }
2196 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002197
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002198 public void setFrontActivityScreenCompatMode(int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002199 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2200 "setFrontActivityScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002201 synchronized (this) {
2202 mCompatModePackages.setFrontActivityScreenCompatModeLocked(mode);
2203 }
2204 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002205
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002206 public int getPackageScreenCompatMode(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002207 enforceNotIsolatedCaller("getPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002208 synchronized (this) {
2209 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
2210 }
2211 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002212
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002213 public void setPackageScreenCompatMode(String packageName, int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002214 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2215 "setPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002216 synchronized (this) {
2217 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002218 }
2219 }
2220
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002221 public boolean getPackageAskScreenCompat(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002222 enforceNotIsolatedCaller("getPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002223 synchronized (this) {
2224 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
2225 }
2226 }
2227
2228 public void setPackageAskScreenCompat(String packageName, boolean ask) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002229 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2230 "setPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002231 synchronized (this) {
2232 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
2233 }
2234 }
2235
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002236 void reportResumedActivityLocked(ActivityRecord r) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002237 //Slog.i(TAG, "**** REPORT RESUME: " + r);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002238
2239 final int identHash = System.identityHashCode(r);
2240 updateUsageStats(r, true);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002241 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002242
Jeff Sharkeya4620792011-05-20 15:29:23 -07002243 private void dispatchForegroundActivitiesChanged(int pid, int uid, boolean foregroundActivities) {
2244 int i = mProcessObservers.beginBroadcast();
2245 while (i > 0) {
2246 i--;
2247 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2248 if (observer != null) {
2249 try {
2250 observer.onForegroundActivitiesChanged(pid, uid, foregroundActivities);
2251 } catch (RemoteException e) {
2252 }
2253 }
2254 }
2255 mProcessObservers.finishBroadcast();
2256 }
2257
2258 private void dispatchProcessDied(int pid, int uid) {
2259 int i = mProcessObservers.beginBroadcast();
2260 while (i > 0) {
2261 i--;
2262 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2263 if (observer != null) {
2264 try {
2265 observer.onProcessDied(pid, uid);
2266 } catch (RemoteException e) {
2267 }
2268 }
2269 }
2270 mProcessObservers.finishBroadcast();
2271 }
2272
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002273 final void doPendingActivityLaunchesLocked(boolean doResume) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002274 final int N = mPendingActivityLaunches.size();
2275 if (N <= 0) {
2276 return;
2277 }
2278 for (int i=0; i<N; i++) {
2279 PendingActivityLaunch pal = mPendingActivityLaunches.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002280 mMainStack.startActivityUncheckedLocked(pal.r, pal.sourceRecord,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002281 pal.startFlags, doResume && i == (N-1), null);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002282 }
2283 mPendingActivityLaunches.clear();
2284 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002285
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002286 public final int startActivity(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002287 Intent intent, String resolvedType, IBinder resultTo,
2288 String resultWho, int requestCode, int startFlags,
2289 String profileFile, ParcelFileDescriptor profileFd, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002290 enforceNotIsolatedCaller("startActivity");
Amith Yamasani742a6712011-05-04 14:49:28 -07002291 int userId = 0;
2292 if (intent.getCategories() != null && intent.getCategories().contains(Intent.CATEGORY_HOME)) {
2293 // Requesting home, set the identity to the current user
2294 // HACK!
2295 userId = mCurrentUserId;
2296 } else {
2297 // TODO: Fix this in a better way - calls coming from SystemUI should probably carry
2298 // the current user's userId
2299 if (Binder.getCallingUid() < Process.FIRST_APPLICATION_UID) {
2300 userId = 0;
2301 } else {
2302 userId = Binder.getOrigCallingUser();
2303 }
2304 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002305 return mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002306 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
2307 null, null, options, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002308 }
2309
2310 public final WaitResult startActivityAndWait(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002311 Intent intent, String resolvedType, IBinder resultTo,
2312 String resultWho, int requestCode, int startFlags, String profileFile,
2313 ParcelFileDescriptor profileFd, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002314 enforceNotIsolatedCaller("startActivityAndWait");
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002315 WaitResult res = new WaitResult();
Amith Yamasani742a6712011-05-04 14:49:28 -07002316 int userId = Binder.getOrigCallingUser();
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002317 mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002318 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
2319 res, null, options, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002320 return res;
2321 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08002322
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002323 public final int startActivityWithConfig(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002324 Intent intent, String resolvedType, IBinder resultTo,
2325 String resultWho, int requestCode, int startFlags, Configuration config,
2326 Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002327 enforceNotIsolatedCaller("startActivityWithConfig");
Amith Yamasani742a6712011-05-04 14:49:28 -07002328 int ret = mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002329 resultTo, resultWho, requestCode, startFlags,
2330 null, null, null, config, options, Binder.getOrigCallingUser());
Amith Yamasani742a6712011-05-04 14:49:28 -07002331 return ret;
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002332 }
2333
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002334 public int startActivityIntentSender(IApplicationThread caller,
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002335 IntentSender intent, Intent fillInIntent, String resolvedType,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002336 IBinder resultTo, String resultWho, int requestCode,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002337 int flagsMask, int flagsValues, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002338 enforceNotIsolatedCaller("startActivityIntentSender");
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002339 // Refuse possible leaked file descriptors
2340 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
2341 throw new IllegalArgumentException("File descriptors passed in Intent");
2342 }
2343
2344 IIntentSender sender = intent.getTarget();
2345 if (!(sender instanceof PendingIntentRecord)) {
2346 throw new IllegalArgumentException("Bad PendingIntent object");
2347 }
2348
2349 PendingIntentRecord pir = (PendingIntentRecord)sender;
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002350
2351 synchronized (this) {
2352 // If this is coming from the currently resumed activity, it is
2353 // effectively saying that app switches are allowed at this point.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002354 if (mMainStack.mResumedActivity != null
2355 && mMainStack.mResumedActivity.info.applicationInfo.uid ==
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002356 Binder.getCallingUid()) {
2357 mAppSwitchesAllowedTime = 0;
2358 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002359 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002360 int ret = pir.sendInner(0, fillInIntent, resolvedType, null, null,
2361 resultTo, resultWho, requestCode, flagsMask, flagsValues, options);
Amith Yamasani742a6712011-05-04 14:49:28 -07002362 return ret;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002363 }
2364
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002365 public boolean startNextMatchingActivity(IBinder callingActivity,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002366 Intent intent, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002367 // Refuse possible leaked file descriptors
2368 if (intent != null && intent.hasFileDescriptors() == true) {
2369 throw new IllegalArgumentException("File descriptors passed in Intent");
2370 }
2371
2372 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002373 ActivityRecord r = mMainStack.isInStackLocked(callingActivity);
2374 if (r == null) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002375 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002376 return false;
2377 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002378 if (r.app == null || r.app.thread == null) {
2379 // The caller is not running... d'oh!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002380 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002381 return false;
2382 }
2383 intent = new Intent(intent);
2384 // The caller is not allowed to change the data.
2385 intent.setDataAndType(r.intent.getData(), r.intent.getType());
2386 // And we are resetting to find the next component...
2387 intent.setComponent(null);
2388
2389 ActivityInfo aInfo = null;
2390 try {
2391 List<ResolveInfo> resolves =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002392 AppGlobals.getPackageManager().queryIntentActivities(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002393 intent, r.resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002394 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
2395 UserId.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002396
2397 // Look for the original activity in the list...
2398 final int N = resolves != null ? resolves.size() : 0;
2399 for (int i=0; i<N; i++) {
2400 ResolveInfo rInfo = resolves.get(i);
2401 if (rInfo.activityInfo.packageName.equals(r.packageName)
2402 && rInfo.activityInfo.name.equals(r.info.name)) {
2403 // We found the current one... the next matching is
2404 // after it.
2405 i++;
2406 if (i<N) {
2407 aInfo = resolves.get(i).activityInfo;
2408 }
2409 break;
2410 }
2411 }
2412 } catch (RemoteException e) {
2413 }
2414
2415 if (aInfo == null) {
2416 // Nobody who is next!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002417 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002418 return false;
2419 }
2420
2421 intent.setComponent(new ComponentName(
2422 aInfo.applicationInfo.packageName, aInfo.name));
2423 intent.setFlags(intent.getFlags()&~(
2424 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
2425 Intent.FLAG_ACTIVITY_CLEAR_TOP|
2426 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
2427 Intent.FLAG_ACTIVITY_NEW_TASK));
2428
2429 // Okay now we need to start the new activity, replacing the
2430 // currently running activity. This is a little tricky because
2431 // we want to start the new one as if the current one is finished,
2432 // but not finish the current one first so that there is no flicker.
2433 // And thus...
2434 final boolean wasFinishing = r.finishing;
2435 r.finishing = true;
2436
2437 // Propagate reply information over to the new activity.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002438 final ActivityRecord resultTo = r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002439 final String resultWho = r.resultWho;
2440 final int requestCode = r.requestCode;
2441 r.resultTo = null;
2442 if (resultTo != null) {
2443 resultTo.removeResultsLocked(r, resultWho, requestCode);
2444 }
2445
2446 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002447 int res = mMainStack.startActivityLocked(r.app.thread, intent,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002448 r.resolvedType, aInfo, resultTo != null ? resultTo.appToken : null,
2449 resultWho, requestCode, -1, r.launchedFromUid, 0,
2450 options, false, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002451 Binder.restoreCallingIdentity(origId);
2452
2453 r.finishing = wasFinishing;
Dianne Hackborna4972e92012-03-14 10:38:05 -07002454 if (res != ActivityManager.START_SUCCESS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002455 return false;
2456 }
2457 return true;
2458 }
2459 }
2460
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002461 public final int startActivityInPackage(int uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002462 Intent intent, String resolvedType, IBinder resultTo,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002463 String resultWho, int requestCode, int startFlags, Bundle options) {
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002464
2465 // This is so super not safe, that only the system (or okay root)
2466 // can do it.
Amith Yamasani742a6712011-05-04 14:49:28 -07002467 int userId = Binder.getOrigCallingUser();
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002468 final int callingUid = Binder.getCallingUid();
2469 if (callingUid != 0 && callingUid != Process.myUid()) {
2470 throw new SecurityException(
2471 "startActivityInPackage only available to the system");
2472 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002473
Amith Yamasani742a6712011-05-04 14:49:28 -07002474 int ret = mMainStack.startActivityMayWait(null, uid, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002475 resultTo, resultWho, requestCode, startFlags,
2476 null, null, null, null, options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002477 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002478 }
2479
2480 public final int startActivities(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002481 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002482 enforceNotIsolatedCaller("startActivities");
Amith Yamasani742a6712011-05-04 14:49:28 -07002483 int ret = mMainStack.startActivities(caller, -1, intents, resolvedTypes, resultTo,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002484 options, Binder.getOrigCallingUser());
Amith Yamasani742a6712011-05-04 14:49:28 -07002485 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002486 }
2487
2488 public final int startActivitiesInPackage(int uid,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002489 Intent[] intents, String[] resolvedTypes, IBinder resultTo,
2490 Bundle options) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002491
2492 // This is so super not safe, that only the system (or okay root)
2493 // can do it.
2494 final int callingUid = Binder.getCallingUid();
2495 if (callingUid != 0 && callingUid != Process.myUid()) {
2496 throw new SecurityException(
2497 "startActivityInPackage only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002498 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002499 int ret = mMainStack.startActivities(null, uid, intents, resolvedTypes, resultTo,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002500 options, UserId.getUserId(uid));
Amith Yamasani742a6712011-05-04 14:49:28 -07002501 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002502 }
2503
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002504 final void addRecentTaskLocked(TaskRecord task) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002505 int N = mRecentTasks.size();
Dianne Hackborn7c0e75e2010-12-21 19:15:40 -08002506 // Quick case: check if the top-most recent task is the same.
2507 if (N > 0 && mRecentTasks.get(0) == task) {
2508 return;
2509 }
2510 // Remove any existing entries that are the same kind of task.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002511 for (int i=0; i<N; i++) {
2512 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07002513 if (task.userId == tr.userId
2514 && ((task.affinity != null && task.affinity.equals(tr.affinity))
2515 || (task.intent != null && task.intent.filterEquals(tr.intent)))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002516 mRecentTasks.remove(i);
2517 i--;
2518 N--;
2519 if (task.intent == null) {
2520 // If the new recent task we are adding is not fully
2521 // specified, then replace it with the existing recent task.
2522 task = tr;
2523 }
2524 }
2525 }
2526 if (N >= MAX_RECENT_TASKS) {
2527 mRecentTasks.remove(N-1);
2528 }
2529 mRecentTasks.add(0, task);
2530 }
2531
2532 public void setRequestedOrientation(IBinder token,
2533 int requestedOrientation) {
2534 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002535 ActivityRecord r = mMainStack.isInStackLocked(token);
2536 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002537 return;
2538 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002539 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornbe707852011-11-11 14:32:10 -08002540 mWindowManager.setAppOrientation(r.appToken, requestedOrientation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002541 Configuration config = mWindowManager.updateOrientationFromAppTokens(
The Android Open Source Project10592532009-03-18 17:39:46 -07002542 mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -08002543 r.mayFreezeScreenLocked(r.app) ? r.appToken : null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002544 if (config != null) {
2545 r.frozenBeforeDestroy = true;
Dianne Hackborn813075a62011-11-14 17:45:19 -08002546 if (!updateConfigurationLocked(config, r, false, false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002547 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002548 }
2549 }
2550 Binder.restoreCallingIdentity(origId);
2551 }
2552 }
2553
2554 public int getRequestedOrientation(IBinder token) {
2555 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002556 ActivityRecord r = mMainStack.isInStackLocked(token);
2557 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002558 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
2559 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08002560 return mWindowManager.getAppOrientation(r.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002561 }
2562 }
2563
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002564 /**
2565 * This is the internal entry point for handling Activity.finish().
2566 *
2567 * @param token The Binder token referencing the Activity we want to finish.
2568 * @param resultCode Result code, if any, from this Activity.
2569 * @param resultData Result data (Intent), if any, from this Activity.
2570 *
Alexey Tarasov83bad3d2009-08-12 15:05:43 +11002571 * @return Returns true if the activity successfully finished, or false if it is still running.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002572 */
2573 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData) {
2574 // Refuse possible leaked file descriptors
2575 if (resultData != null && resultData.hasFileDescriptors() == true) {
2576 throw new IllegalArgumentException("File descriptors passed in Intent");
2577 }
2578
2579 synchronized(this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002580 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002581 // Find the first activity that is not finishing.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002582 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002583 if (next != null) {
2584 // ask watcher if this is allowed
2585 boolean resumeOK = true;
2586 try {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002587 resumeOK = mController.activityResuming(next.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002588 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002589 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002590 }
2591
2592 if (!resumeOK) {
2593 return false;
2594 }
2595 }
2596 }
2597 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002598 boolean res = mMainStack.requestFinishActivityLocked(token, resultCode,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002599 resultData, "app-request");
2600 Binder.restoreCallingIdentity(origId);
2601 return res;
2602 }
2603 }
2604
Dianne Hackborn860755f2010-06-03 18:47:52 -07002605 public final void finishHeavyWeightApp() {
2606 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2607 != PackageManager.PERMISSION_GRANTED) {
2608 String msg = "Permission Denial: finishHeavyWeightApp() from pid="
2609 + Binder.getCallingPid()
2610 + ", uid=" + Binder.getCallingUid()
2611 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2612 Slog.w(TAG, msg);
2613 throw new SecurityException(msg);
2614 }
2615
2616 synchronized(this) {
2617 if (mHeavyWeightProcess == null) {
2618 return;
2619 }
2620
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002621 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>(
Dianne Hackborn860755f2010-06-03 18:47:52 -07002622 mHeavyWeightProcess.activities);
2623 for (int i=0; i<activities.size(); i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002624 ActivityRecord r = activities.get(i);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002625 if (!r.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002626 int index = mMainStack.indexOfTokenLocked(r.appToken);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002627 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002628 mMainStack.finishActivityLocked(r, index, Activity.RESULT_CANCELED,
Dianne Hackborn860755f2010-06-03 18:47:52 -07002629 null, "finish-heavy");
2630 }
2631 }
2632 }
2633
2634 mHeavyWeightProcess = null;
2635 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
2636 }
2637 }
2638
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002639 public void crashApplication(int uid, int initialPid, String packageName,
2640 String message) {
2641 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2642 != PackageManager.PERMISSION_GRANTED) {
2643 String msg = "Permission Denial: crashApplication() from pid="
2644 + Binder.getCallingPid()
2645 + ", uid=" + Binder.getCallingUid()
2646 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2647 Slog.w(TAG, msg);
2648 throw new SecurityException(msg);
2649 }
2650
2651 synchronized(this) {
2652 ProcessRecord proc = null;
2653
2654 // Figure out which process to kill. We don't trust that initialPid
2655 // still has any relation to current pids, so must scan through the
2656 // list.
2657 synchronized (mPidsSelfLocked) {
2658 for (int i=0; i<mPidsSelfLocked.size(); i++) {
2659 ProcessRecord p = mPidsSelfLocked.valueAt(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002660 if (p.uid != uid) {
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002661 continue;
2662 }
2663 if (p.pid == initialPid) {
2664 proc = p;
2665 break;
2666 }
2667 for (String str : p.pkgList) {
2668 if (str.equals(packageName)) {
2669 proc = p;
2670 }
2671 }
2672 }
2673 }
2674
2675 if (proc == null) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07002676 Slog.w(TAG, "crashApplication: nothing for uid=" + uid
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002677 + " initialPid=" + initialPid
2678 + " packageName=" + packageName);
2679 return;
2680 }
2681
2682 if (proc.thread != null) {
Dianne Hackborn9f531192010-08-04 17:48:03 -07002683 if (proc.pid == Process.myPid()) {
2684 Log.w(TAG, "crashApplication: trying to crash self!");
2685 return;
2686 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002687 long ident = Binder.clearCallingIdentity();
2688 try {
2689 proc.thread.scheduleCrash(message);
2690 } catch (RemoteException e) {
2691 }
2692 Binder.restoreCallingIdentity(ident);
2693 }
2694 }
2695 }
2696
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002697 public final void finishSubActivity(IBinder token, String resultWho,
2698 int requestCode) {
2699 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002700 ActivityRecord self = mMainStack.isInStackLocked(token);
2701 if (self == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002702 return;
2703 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002704
2705 final long origId = Binder.clearCallingIdentity();
2706
2707 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002708 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2709 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002710 if (r.resultTo == self && r.requestCode == requestCode) {
2711 if ((r.resultWho == null && resultWho == null) ||
2712 (r.resultWho != null && r.resultWho.equals(resultWho))) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002713 mMainStack.finishActivityLocked(r, i,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002714 Activity.RESULT_CANCELED, null, "request-sub");
2715 }
2716 }
2717 }
2718
2719 Binder.restoreCallingIdentity(origId);
2720 }
2721 }
2722
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002723 public boolean willActivityBeVisible(IBinder token) {
2724 synchronized(this) {
2725 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002726 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2727 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08002728 if (r.appToken == token) {
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002729 return true;
2730 }
2731 if (r.fullscreen && !r.finishing) {
2732 return false;
2733 }
2734 }
2735 return true;
2736 }
2737 }
2738
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002739 public void overridePendingTransition(IBinder token, String packageName,
2740 int enterAnim, int exitAnim) {
2741 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002742 ActivityRecord self = mMainStack.isInStackLocked(token);
2743 if (self == null) {
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002744 return;
2745 }
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002746
2747 final long origId = Binder.clearCallingIdentity();
2748
2749 if (self.state == ActivityState.RESUMED
2750 || self.state == ActivityState.PAUSING) {
2751 mWindowManager.overridePendingAppTransition(packageName,
2752 enterAnim, exitAnim);
2753 }
2754
2755 Binder.restoreCallingIdentity(origId);
2756 }
2757 }
2758
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002759 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002760 * Main function for removing an existing process from the activity manager
2761 * as a result of that process going away. Clears out all connections
2762 * to the process.
2763 */
2764 private final void handleAppDiedLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002765 boolean restarting, boolean allowRestart) {
2766 cleanUpApplicationRecordLocked(app, restarting, allowRestart, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002767 if (!restarting) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002768 mLruProcesses.remove(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002769 }
2770
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002771 if (mProfileProc == app) {
2772 clearProfilerLocked();
2773 }
2774
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002775 // Just in case...
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002776 if (mMainStack.mPausingActivity != null && mMainStack.mPausingActivity.app == app) {
2777 if (DEBUG_PAUSE) Slog.v(TAG, "App died while pausing: " +mMainStack.mPausingActivity);
2778 mMainStack.mPausingActivity = null;
2779 }
2780 if (mMainStack.mLastPausedActivity != null && mMainStack.mLastPausedActivity.app == app) {
2781 mMainStack.mLastPausedActivity = null;
2782 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002783
2784 // Remove this application's activities from active lists.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002785 mMainStack.removeHistoryRecordsForAppLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002786
2787 boolean atTop = true;
2788 boolean hasVisibleActivities = false;
2789
2790 // Clean out the history list.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002791 int i = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08002792 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002793 TAG, "Removing app " + app + " from history with " + i + " entries");
2794 while (i > 0) {
2795 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002796 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002797 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002798 TAG, "Record #" + i + " " + r + ": app=" + r.app);
2799 if (r.app == app) {
2800 if ((!r.haveState && !r.stateNotNeeded) || r.finishing) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002801 if (ActivityStack.DEBUG_ADD_REMOVE) {
2802 RuntimeException here = new RuntimeException("here");
2803 here.fillInStackTrace();
2804 Slog.i(TAG, "Removing activity " + r + " from stack at " + i
2805 + ": haveState=" + r.haveState
2806 + " stateNotNeeded=" + r.stateNotNeeded
2807 + " finishing=" + r.finishing
2808 + " state=" + r.state, here);
2809 }
2810 if (!r.finishing) {
2811 Slog.w(TAG, "Force removing " + r + ": app died, no saved state");
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -08002812 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
2813 System.identityHashCode(r),
2814 r.task.taskId, r.shortComponentName,
2815 "proc died without state saved");
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002816 }
Dianne Hackborn5c607432012-02-28 14:44:19 -08002817 mMainStack.removeActivityFromHistoryLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002818
2819 } else {
2820 // We have the current state for this activity, so
2821 // it can be restarted later when needed.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002822 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002823 TAG, "Keeping entry, setting app to null");
2824 if (r.visible) {
2825 hasVisibleActivities = true;
2826 }
2827 r.app = null;
2828 r.nowVisible = false;
2829 if (!r.haveState) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002830 if (ActivityStack.DEBUG_SAVED_STATE) Slog.i(TAG,
2831 "App died, clearing saved state of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002832 r.icicle = null;
2833 }
2834 }
2835
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002836 r.stack.cleanUpActivityLocked(r, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002837 }
2838 atTop = false;
2839 }
2840
2841 app.activities.clear();
2842
2843 if (app.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002844 Slog.w(TAG, "Crash of app " + app.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002845 + " running instrumentation " + app.instrumentationClass);
2846 Bundle info = new Bundle();
2847 info.putString("shortMsg", "Process crashed.");
2848 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
2849 }
2850
2851 if (!restarting) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002852 if (!mMainStack.resumeTopActivityLocked(null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002853 // If there was nothing to resume, and we are not already
2854 // restarting this process, but there is a visible activity that
2855 // is hosted by the process... then make sure all visible
2856 // activities are running, taking care of restarting this
2857 // process.
2858 if (hasVisibleActivities) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002859 mMainStack.ensureActivitiesVisibleLocked(null, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002860 }
2861 }
2862 }
2863 }
2864
2865 private final int getLRURecordIndexForAppLocked(IApplicationThread thread) {
2866 IBinder threadBinder = thread.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002867 // Find the application record.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002868 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2869 ProcessRecord rec = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002870 if (rec.thread != null && rec.thread.asBinder() == threadBinder) {
2871 return i;
2872 }
2873 }
2874 return -1;
2875 }
2876
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002877 final ProcessRecord getRecordForAppLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002878 IApplicationThread thread) {
2879 if (thread == null) {
2880 return null;
2881 }
2882
2883 int appIndex = getLRURecordIndexForAppLocked(thread);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002884 return appIndex >= 0 ? mLruProcesses.get(appIndex) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002885 }
2886
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002887 final void appDiedLocked(ProcessRecord app, int pid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002888 IApplicationThread thread) {
2889
2890 mProcDeaths[0]++;
2891
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002892 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
2893 synchronized (stats) {
2894 stats.noteProcessDiedLocked(app.info.uid, pid);
2895 }
2896
Magnus Edlund7bb25812010-02-24 15:45:06 +01002897 // Clean up already done if the process has been re-started.
2898 if (app.pid == pid && app.thread != null &&
2899 app.thread.asBinder() == thread.asBinder()) {
Dianne Hackborn906497c2010-05-10 15:57:38 -07002900 if (!app.killedBackground) {
2901 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
2902 + ") has died.");
2903 }
Doug Zongker2bec3d42009-12-04 12:52:44 -08002904 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002905 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002906 TAG, "Dying app: " + app + ", pid: " + pid
2907 + ", thread: " + thread.asBinder());
2908 boolean doLowMem = app.instrumentationClass == null;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002909 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002910
2911 if (doLowMem) {
2912 // If there are no longer any background processes running,
2913 // and the app that died was not running instrumentation,
2914 // then tell everyone we are now low on memory.
2915 boolean haveBg = false;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002916 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2917 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -07002918 if (rec.thread != null && rec.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002919 haveBg = true;
2920 break;
2921 }
2922 }
2923
2924 if (!haveBg) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002925 EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mLruProcesses.size());
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002926 long now = SystemClock.uptimeMillis();
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002927 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2928 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn36124872009-10-08 16:22:03 -07002929 if (rec != app && rec.thread != null &&
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002930 (rec.lastLowMemory+GC_MIN_INTERVAL) <= now) {
2931 // The low memory report is overriding any current
2932 // state for a GC request. Make sure to do
Dianne Hackborn32907cf2010-06-10 17:50:20 -07002933 // heavy/important/visible/foreground processes first.
Dianne Hackborn7d608422011-08-07 16:24:18 -07002934 if (rec.setAdj <= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002935 rec.lastRequestedGc = 0;
2936 } else {
2937 rec.lastRequestedGc = rec.lastLowMemory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002938 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002939 rec.reportLowMemory = true;
2940 rec.lastLowMemory = now;
2941 mProcessesToGc.remove(rec);
2942 addProcessToGcListLocked(rec);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002943 }
2944 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07002945 mHandler.sendEmptyMessage(REPORT_MEM_USAGE);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002946 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002947 }
2948 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01002949 } else if (app.pid != pid) {
2950 // A new process has already been started.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002951 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
Magnus Edlund7bb25812010-02-24 15:45:06 +01002952 + ") has died and restarted (pid " + app.pid + ").");
Dianne Hackborn28a8c2b2010-03-01 11:30:02 -08002953 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08002954 } else if (DEBUG_PROCESSES) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002955 Slog.d(TAG, "Received spurious death notification for thread "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002956 + thread.asBinder());
2957 }
2958 }
2959
Dan Egnor42471dd2010-01-07 17:25:22 -08002960 /**
2961 * If a stack trace dump file is configured, dump process stack traces.
Christopher Tate6ee412d2010-05-28 12:01:56 -07002962 * @param clearTraces causes the dump file to be erased prior to the new
2963 * traces being written, if true; when false, the new traces will be
2964 * appended to any existing file content.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002965 * @param firstPids of dalvik VM processes to dump stack traces for first
2966 * @param lastPids of dalvik VM processes to dump stack traces for last
Dan Egnor42471dd2010-01-07 17:25:22 -08002967 * @return file containing stack traces, or null if no dump file is configured
2968 */
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002969 public static File dumpStackTraces(boolean clearTraces, ArrayList<Integer> firstPids,
2970 ProcessStats processStats, SparseArray<Boolean> lastPids) {
Dan Egnor42471dd2010-01-07 17:25:22 -08002971 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
2972 if (tracesPath == null || tracesPath.length() == 0) {
2973 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002974 }
Dan Egnor42471dd2010-01-07 17:25:22 -08002975
2976 File tracesFile = new File(tracesPath);
2977 try {
2978 File tracesDir = tracesFile.getParentFile();
2979 if (!tracesDir.exists()) tracesFile.mkdirs();
2980 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
2981
Christopher Tate6ee412d2010-05-28 12:01:56 -07002982 if (clearTraces && tracesFile.exists()) tracesFile.delete();
Dan Egnor42471dd2010-01-07 17:25:22 -08002983 tracesFile.createNewFile();
2984 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
2985 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002986 Slog.w(TAG, "Unable to prepare ANR traces file: " + tracesPath, e);
Dan Egnor42471dd2010-01-07 17:25:22 -08002987 return null;
2988 }
2989
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07002990 dumpStackTraces(tracesPath, firstPids, processStats, lastPids);
2991 return tracesFile;
2992 }
2993
2994 private static void dumpStackTraces(String tracesPath, ArrayList<Integer> firstPids,
2995 ProcessStats processStats, SparseArray<Boolean> lastPids) {
Dan Egnor42471dd2010-01-07 17:25:22 -08002996 // Use a FileObserver to detect when traces finish writing.
2997 // The order of traces is considered important to maintain for legibility.
2998 FileObserver observer = new FileObserver(tracesPath, FileObserver.CLOSE_WRITE) {
2999 public synchronized void onEvent(int event, String path) { notify(); }
3000 };
3001
3002 try {
3003 observer.startWatching();
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003004
3005 // First collect all of the stacks of the most important pids.
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003006 if (firstPids != null) {
3007 try {
3008 int num = firstPids.size();
3009 for (int i = 0; i < num; i++) {
3010 synchronized (observer) {
3011 Process.sendSignal(firstPids.get(i), Process.SIGNAL_QUIT);
3012 observer.wait(200); // Wait for write-close, give up after 200msec
3013 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003014 }
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003015 } catch (InterruptedException e) {
3016 Log.wtf(TAG, e);
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003017 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003018 }
3019
3020 // Next measure CPU usage.
3021 if (processStats != null) {
3022 processStats.init();
3023 System.gc();
3024 processStats.update();
3025 try {
3026 synchronized (processStats) {
3027 processStats.wait(500); // measure over 1/2 second.
3028 }
3029 } catch (InterruptedException e) {
3030 }
3031 processStats.update();
3032
3033 // We'll take the stack crawls of just the top apps using CPU.
3034 final int N = processStats.countWorkingStats();
3035 int numProcs = 0;
3036 for (int i=0; i<N && numProcs<5; i++) {
3037 ProcessStats.Stats stats = processStats.getWorkingStats(i);
3038 if (lastPids.indexOfKey(stats.pid) >= 0) {
3039 numProcs++;
3040 try {
3041 synchronized (observer) {
3042 Process.sendSignal(stats.pid, Process.SIGNAL_QUIT);
3043 observer.wait(200); // Wait for write-close, give up after 200msec
3044 }
3045 } catch (InterruptedException e) {
3046 Log.wtf(TAG, e);
3047 }
3048
3049 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003050 }
3051 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003052
Dan Egnor42471dd2010-01-07 17:25:22 -08003053 } finally {
3054 observer.stopWatching();
3055 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003056 }
3057
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003058 final void logAppTooSlow(ProcessRecord app, long startTime, String msg) {
Dianne Hackborn69dc66e2012-03-26 10:50:54 -07003059 if (true || IS_USER_BUILD) {
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003060 return;
3061 }
3062 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
3063 if (tracesPath == null || tracesPath.length() == 0) {
3064 return;
3065 }
3066
3067 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
3068 StrictMode.allowThreadDiskWrites();
3069 try {
3070 final File tracesFile = new File(tracesPath);
3071 final File tracesDir = tracesFile.getParentFile();
3072 final File tracesTmp = new File(tracesDir, "__tmp__");
3073 try {
3074 if (!tracesDir.exists()) tracesFile.mkdirs();
3075 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
3076
3077 if (tracesFile.exists()) {
3078 tracesTmp.delete();
3079 tracesFile.renameTo(tracesTmp);
3080 }
3081 StringBuilder sb = new StringBuilder();
3082 Time tobj = new Time();
3083 tobj.set(System.currentTimeMillis());
3084 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
3085 sb.append(": ");
3086 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
3087 sb.append(" since ");
3088 sb.append(msg);
3089 FileOutputStream fos = new FileOutputStream(tracesFile);
3090 fos.write(sb.toString().getBytes());
3091 if (app == null) {
3092 fos.write("\n*** No application process!".getBytes());
3093 }
3094 fos.close();
3095 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
3096 } catch (IOException e) {
3097 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesPath, e);
3098 return;
3099 }
3100
3101 if (app != null) {
3102 ArrayList<Integer> firstPids = new ArrayList<Integer>();
3103 firstPids.add(app.pid);
3104 dumpStackTraces(tracesPath, firstPids, null, null);
3105 }
3106
3107 File lastTracesFile = null;
3108 File curTracesFile = null;
3109 for (int i=9; i>=0; i--) {
3110 String name = String.format("slow%02d.txt", i);
3111 curTracesFile = new File(tracesDir, name);
3112 if (curTracesFile.exists()) {
3113 if (lastTracesFile != null) {
3114 curTracesFile.renameTo(lastTracesFile);
3115 } else {
3116 curTracesFile.delete();
3117 }
3118 }
3119 lastTracesFile = curTracesFile;
3120 }
3121 tracesFile.renameTo(curTracesFile);
3122 if (tracesTmp.exists()) {
3123 tracesTmp.renameTo(tracesFile);
3124 }
3125 } finally {
3126 StrictMode.setThreadPolicy(oldPolicy);
3127 }
3128 }
3129
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003130 final void appNotResponding(ProcessRecord app, ActivityRecord activity,
3131 ActivityRecord parent, final String annotation) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003132 ArrayList<Integer> firstPids = new ArrayList<Integer>(5);
3133 SparseArray<Boolean> lastPids = new SparseArray<Boolean>(20);
3134
Dianne Hackborn287952c2010-09-22 22:34:31 -07003135 if (mController != null) {
3136 try {
3137 // 0 == continue, -1 = kill process immediately
3138 int res = mController.appEarlyNotResponding(app.processName, app.pid, annotation);
3139 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3140 } catch (RemoteException e) {
3141 mController = null;
3142 }
3143 }
3144
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003145 long anrTime = SystemClock.uptimeMillis();
3146 if (MONITOR_CPU_USAGE) {
3147 updateCpuStatsNow();
3148 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003149
3150 synchronized (this) {
3151 // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down.
3152 if (mShuttingDown) {
3153 Slog.i(TAG, "During shutdown skipping ANR: " + app + " " + annotation);
3154 return;
3155 } else if (app.notResponding) {
3156 Slog.i(TAG, "Skipping duplicate ANR: " + app + " " + annotation);
3157 return;
3158 } else if (app.crashing) {
3159 Slog.i(TAG, "Crashing app skipping ANR: " + app + " " + annotation);
3160 return;
3161 }
3162
3163 // In case we come through here for the same app before completing
3164 // this one, mark as anring now so we will bail out.
3165 app.notResponding = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08003166
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003167 // Log the ANR to the event log.
3168 EventLog.writeEvent(EventLogTags.AM_ANR, app.pid, app.processName, app.info.flags,
3169 annotation);
Dan Egnor42471dd2010-01-07 17:25:22 -08003170
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003171 // Dump thread traces as quickly as we can, starting with "interesting" processes.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003172 firstPids.add(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003173
3174 int parentPid = app.pid;
3175 if (parent != null && parent.app != null && parent.app.pid > 0) parentPid = parent.app.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003176 if (parentPid != app.pid) firstPids.add(parentPid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003177
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003178 if (MY_PID != app.pid && MY_PID != parentPid) firstPids.add(MY_PID);
Dan Egnor42471dd2010-01-07 17:25:22 -08003179
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003180 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
3181 ProcessRecord r = mLruProcesses.get(i);
3182 if (r != null && r.thread != null) {
3183 int pid = r.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003184 if (pid > 0 && pid != app.pid && pid != parentPid && pid != MY_PID) {
3185 if (r.persistent) {
3186 firstPids.add(pid);
3187 } else {
3188 lastPids.put(pid, Boolean.TRUE);
3189 }
3190 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003191 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003192 }
3193 }
3194
Dan Egnor42471dd2010-01-07 17:25:22 -08003195 // Log the ANR to the main log.
Jeff Browndeb6ed82012-04-10 14:26:26 -07003196 StringBuilder info = new StringBuilder();
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07003197 info.setLength(0);
Dan Egnor42471dd2010-01-07 17:25:22 -08003198 info.append("ANR in ").append(app.processName);
3199 if (activity != null && activity.shortComponentName != null) {
3200 info.append(" (").append(activity.shortComponentName).append(")");
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07003201 }
Eric Rowe6f4f6192010-02-17 18:29:04 -08003202 info.append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003203 if (annotation != null) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003204 info.append("Reason: ").append(annotation).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003205 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003206 if (parent != null && parent != activity) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003207 info.append("Parent: ").append(parent.shortComponentName).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003208 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003209
Dianne Hackborn287952c2010-09-22 22:34:31 -07003210 final ProcessStats processStats = new ProcessStats(true);
3211
3212 File tracesFile = dumpStackTraces(true, firstPids, processStats, lastPids);
3213
Dan Egnor42471dd2010-01-07 17:25:22 -08003214 String cpuInfo = null;
3215 if (MONITOR_CPU_USAGE) {
3216 updateCpuStatsNow();
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003217 synchronized (mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003218 cpuInfo = mProcessStats.printCurrentState(anrTime);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003219 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003220 info.append(processStats.printCurrentLoad());
Dan Egnor42471dd2010-01-07 17:25:22 -08003221 info.append(cpuInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003222 }
3223
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003224 info.append(processStats.printCurrentState(anrTime));
3225
Joe Onorato8a9b2202010-02-26 18:56:32 -08003226 Slog.e(TAG, info.toString());
Dan Egnor42471dd2010-01-07 17:25:22 -08003227 if (tracesFile == null) {
3228 // There is no trace file, so dump (only) the alleged culprit's threads to the log
3229 Process.sendSignal(app.pid, Process.SIGNAL_QUIT);
3230 }
3231
Jeff Sharkeya353d262011-10-28 11:12:06 -07003232 addErrorToDropBox("anr", app, app.processName, activity, parent, annotation,
3233 cpuInfo, tracesFile, null);
Dan Egnor42471dd2010-01-07 17:25:22 -08003234
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003235 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003236 try {
Dan Egnor42471dd2010-01-07 17:25:22 -08003237 // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately
3238 int res = mController.appNotResponding(app.processName, app.pid, info.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003239 if (res != 0) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003240 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3241 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003242 }
3243 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003244 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003245 }
3246 }
3247
Dan Egnor42471dd2010-01-07 17:25:22 -08003248 // Unless configured otherwise, swallow ANRs in background processes & kill the process.
3249 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
3250 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003251
3252 synchronized (this) {
3253 if (!showBackground && !app.isInterestingToUserLocked() && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003254 Slog.w(TAG, "Killing " + app + ": background ANR");
3255 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
3256 app.processName, app.setAdj, "background ANR");
3257 Process.killProcessQuiet(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003258 return;
3259 }
3260
3261 // Set the app's notResponding state, and look up the errorReportReceiver
3262 makeAppNotRespondingLocked(app,
3263 activity != null ? activity.shortComponentName : null,
3264 annotation != null ? "ANR " + annotation : "ANR",
3265 info.toString());
3266
3267 // Bring up the infamous App Not Responding dialog
3268 Message msg = Message.obtain();
3269 HashMap map = new HashMap();
3270 msg.what = SHOW_NOT_RESPONDING_MSG;
3271 msg.obj = map;
3272 map.put("app", app);
3273 if (activity != null) {
3274 map.put("activity", activity);
3275 }
3276
3277 mHandler.sendMessage(msg);
Dan Egnor42471dd2010-01-07 17:25:22 -08003278 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003279 }
3280
Dianne Hackborn0dad3642010-09-09 21:25:35 -07003281 final void showLaunchWarningLocked(final ActivityRecord cur, final ActivityRecord next) {
3282 if (!mLaunchWarningShown) {
3283 mLaunchWarningShown = true;
3284 mHandler.post(new Runnable() {
3285 @Override
3286 public void run() {
3287 synchronized (ActivityManagerService.this) {
3288 final Dialog d = new LaunchWarningWindow(mContext, cur, next);
3289 d.show();
3290 mHandler.postDelayed(new Runnable() {
3291 @Override
3292 public void run() {
3293 synchronized (ActivityManagerService.this) {
3294 d.dismiss();
3295 mLaunchWarningShown = false;
3296 }
3297 }
3298 }, 4000);
3299 }
3300 }
3301 });
3302 }
3303 }
3304
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003305 public boolean clearApplicationUserData(final String packageName,
Amith Yamasani742a6712011-05-04 14:49:28 -07003306 final IPackageDataObserver observer, final int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003307 enforceNotIsolatedCaller("clearApplicationUserData");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003308 int uid = Binder.getCallingUid();
3309 int pid = Binder.getCallingPid();
3310 long callingId = Binder.clearCallingIdentity();
3311 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003312 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003313 int pkgUid = -1;
3314 synchronized(this) {
3315 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003316 pkgUid = pm.getPackageUid(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003317 } catch (RemoteException e) {
3318 }
3319 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003320 Slog.w(TAG, "Invalid packageName:" + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003321 return false;
3322 }
3323 if (uid == pkgUid || checkComponentPermission(
3324 android.Manifest.permission.CLEAR_APP_USER_DATA,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08003325 pid, uid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003326 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003327 forceStopPackageLocked(packageName, pkgUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003328 } else {
3329 throw new SecurityException(pid+" does not have permission:"+
3330 android.Manifest.permission.CLEAR_APP_USER_DATA+" to clear data" +
3331 "for process:"+packageName);
3332 }
3333 }
3334
3335 try {
3336 //clear application user data
Amith Yamasani483f3b02012-03-13 16:08:00 -07003337 pm.clearApplicationUserData(packageName, observer, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003338 Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED,
3339 Uri.fromParts("package", packageName, null));
3340 intent.putExtra(Intent.EXTRA_UID, pkgUid);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003341 broadcastIntentInPackage("android", Process.SYSTEM_UID, intent,
Amith Yamasani742a6712011-05-04 14:49:28 -07003342 null, null, 0, null, null, null, false, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003343 } catch (RemoteException e) {
3344 }
3345 } finally {
3346 Binder.restoreCallingIdentity(callingId);
3347 }
3348 return true;
3349 }
3350
Dianne Hackborn03abb812010-01-04 18:43:19 -08003351 public void killBackgroundProcesses(final String packageName) {
3352 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3353 != PackageManager.PERMISSION_GRANTED &&
3354 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES)
3355 != PackageManager.PERMISSION_GRANTED) {
3356 String msg = "Permission Denial: killBackgroundProcesses() from pid="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003357 + Binder.getCallingPid()
3358 + ", uid=" + Binder.getCallingUid()
Dianne Hackborn03abb812010-01-04 18:43:19 -08003359 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003360 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003361 throw new SecurityException(msg);
3362 }
3363
Amith Yamasani483f3b02012-03-13 16:08:00 -07003364 int userId = UserId.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003365 long callingId = Binder.clearCallingIdentity();
3366 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003367 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003368 int pkgUid = -1;
3369 synchronized(this) {
3370 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003371 pkgUid = pm.getPackageUid(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003372 } catch (RemoteException e) {
3373 }
3374 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003375 Slog.w(TAG, "Invalid packageName: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003376 return;
3377 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003378 killPackageProcessesLocked(packageName, pkgUid,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003379 ProcessList.SERVICE_ADJ, false, true, true, false, "kill background");
3380 }
3381 } finally {
3382 Binder.restoreCallingIdentity(callingId);
3383 }
3384 }
3385
3386 public void killAllBackgroundProcesses() {
3387 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3388 != PackageManager.PERMISSION_GRANTED) {
3389 String msg = "Permission Denial: killAllBackgroundProcesses() from pid="
3390 + Binder.getCallingPid()
3391 + ", uid=" + Binder.getCallingUid()
3392 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
3393 Slog.w(TAG, msg);
3394 throw new SecurityException(msg);
3395 }
3396
3397 long callingId = Binder.clearCallingIdentity();
3398 try {
3399 synchronized(this) {
3400 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
3401 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3402 final int NA = apps.size();
3403 for (int ia=0; ia<NA; ia++) {
3404 ProcessRecord app = apps.valueAt(ia);
3405 if (app.persistent) {
3406 // we don't kill persistent processes
3407 continue;
3408 }
3409 if (app.removed) {
3410 procs.add(app);
3411 } else if (app.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
3412 app.removed = true;
3413 procs.add(app);
3414 }
3415 }
3416 }
3417
3418 int N = procs.size();
3419 for (int i=0; i<N; i++) {
3420 removeProcessLocked(procs.get(i), false, true, "kill all background");
3421 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003422 }
3423 } finally {
3424 Binder.restoreCallingIdentity(callingId);
3425 }
3426 }
3427
3428 public void forceStopPackage(final String packageName) {
3429 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3430 != PackageManager.PERMISSION_GRANTED) {
3431 String msg = "Permission Denial: forceStopPackage() from pid="
3432 + Binder.getCallingPid()
3433 + ", uid=" + Binder.getCallingUid()
3434 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003435 Slog.w(TAG, msg);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003436 throw new SecurityException(msg);
3437 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07003438 final int userId = UserId.getCallingUserId();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003439 long callingId = Binder.clearCallingIdentity();
3440 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003441 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003442 int pkgUid = -1;
3443 synchronized(this) {
3444 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003445 pkgUid = pm.getPackageUid(packageName, userId);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003446 } catch (RemoteException e) {
3447 }
3448 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003449 Slog.w(TAG, "Invalid packageName: " + packageName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003450 return;
3451 }
3452 forceStopPackageLocked(packageName, pkgUid);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003453 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003454 pm.setPackageStoppedState(packageName, true, userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003455 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08003456 } catch (IllegalArgumentException e) {
3457 Slog.w(TAG, "Failed trying to unstop package "
3458 + packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003459 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003460 }
3461 } finally {
3462 Binder.restoreCallingIdentity(callingId);
3463 }
3464 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003465
3466 /*
3467 * The pkg name and uid have to be specified.
3468 * @see android.app.IActivityManager#killApplicationWithUid(java.lang.String, int)
3469 */
3470 public void killApplicationWithUid(String pkg, int uid) {
3471 if (pkg == null) {
3472 return;
3473 }
3474 // Make sure the uid is valid.
3475 if (uid < 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003476 Slog.w(TAG, "Invalid uid specified for pkg : " + pkg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003477 return;
3478 }
3479 int callerUid = Binder.getCallingUid();
3480 // Only the system server can kill an application
3481 if (callerUid == Process.SYSTEM_UID) {
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07003482 // Post an aysnc message to kill the application
3483 Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG);
3484 msg.arg1 = uid;
3485 msg.arg2 = 0;
3486 msg.obj = pkg;
Suchi Amalapurapud50066f2009-08-18 16:57:41 -07003487 mHandler.sendMessage(msg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003488 } else {
3489 throw new SecurityException(callerUid + " cannot kill pkg: " +
3490 pkg);
3491 }
3492 }
3493
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003494 public void closeSystemDialogs(String reason) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003495 enforceNotIsolatedCaller("closeSystemDialogs");
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003496 Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003497 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003498 if (reason != null) {
3499 intent.putExtra("reason", reason);
3500 }
3501
3502 final int uid = Binder.getCallingUid();
3503 final long origId = Binder.clearCallingIdentity();
3504 synchronized (this) {
Dianne Hackbornffa42482009-09-23 22:20:11 -07003505 mWindowManager.closeSystemDialogs(reason);
3506
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08003507 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003508 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornffa42482009-09-23 22:20:11 -07003509 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003510 r.stack.finishActivityLocked(r, i,
Dianne Hackbornffa42482009-09-23 22:20:11 -07003511 Activity.RESULT_CANCELED, null, "close-sys");
3512 }
3513 }
3514
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003515 broadcastIntentLocked(null, null, intent, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07003516 null, 0, null, null, null, false, false, -1, uid, 0 /* TODO: Verify */);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003517 }
3518 Binder.restoreCallingIdentity(origId);
3519 }
3520
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003521 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids)
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003522 throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003523 enforceNotIsolatedCaller("getProcessMemoryInfo");
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003524 Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length];
3525 for (int i=pids.length-1; i>=0; i--) {
3526 infos[i] = new Debug.MemoryInfo();
3527 Debug.getMemoryInfo(pids[i], infos[i]);
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003528 }
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003529 return infos;
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003530 }
Christopher Tate5e1ab332009-09-01 20:32:49 -07003531
Dianne Hackbornb437e092011-08-05 17:50:29 -07003532 public long[] getProcessPss(int[] pids) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003533 enforceNotIsolatedCaller("getProcessPss");
Dianne Hackbornb437e092011-08-05 17:50:29 -07003534 long[] pss = new long[pids.length];
3535 for (int i=pids.length-1; i>=0; i--) {
3536 pss[i] = Debug.getPss(pids[i]);
3537 }
3538 return pss;
3539 }
3540
Christopher Tate5e1ab332009-09-01 20:32:49 -07003541 public void killApplicationProcess(String processName, int uid) {
3542 if (processName == null) {
3543 return;
3544 }
3545
3546 int callerUid = Binder.getCallingUid();
3547 // Only the system server can kill an application
3548 if (callerUid == Process.SYSTEM_UID) {
3549 synchronized (this) {
3550 ProcessRecord app = getProcessRecordLocked(processName, uid);
Christopher Tate4a627c72011-04-01 14:43:32 -07003551 if (app != null && app.thread != null) {
Christopher Tate5e1ab332009-09-01 20:32:49 -07003552 try {
3553 app.thread.scheduleSuicide();
3554 } catch (RemoteException e) {
3555 // If the other end already died, then our work here is done.
3556 }
3557 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003558 Slog.w(TAG, "Process/uid not found attempting kill of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07003559 + processName + " / " + uid);
3560 }
3561 }
3562 } else {
3563 throw new SecurityException(callerUid + " cannot kill app process: " +
3564 processName);
3565 }
3566 }
3567
Dianne Hackborn03abb812010-01-04 18:43:19 -08003568 private void forceStopPackageLocked(final String packageName, int uid) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003569 forceStopPackageLocked(packageName, uid, false, false, true, false, UserId.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003570 Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED,
3571 Uri.fromParts("package", packageName, null));
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003572 if (!mProcessesReady) {
3573 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3574 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003575 intent.putExtra(Intent.EXTRA_UID, uid);
3576 broadcastIntentLocked(null, null, intent,
3577 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07003578 false, false,
3579 MY_PID, Process.SYSTEM_UID, UserId.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003580 }
3581
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003582 private final boolean killPackageProcessesLocked(String packageName, int uid,
Christopher Tate3dacd842011-08-19 14:56:15 -07003583 int minOomAdj, boolean callerWillRestart, boolean allowRestart, boolean doit,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003584 boolean evenPersistent, String reason) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003585 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003586
Dianne Hackborn03abb812010-01-04 18:43:19 -08003587 // Remove all processes this package may have touched: all with the
3588 // same UID (except for the system or root user), and all whose name
3589 // matches the package name.
3590 final String procNamePrefix = packageName + ":";
3591 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3592 final int NA = apps.size();
3593 for (int ia=0; ia<NA; ia++) {
3594 ProcessRecord app = apps.valueAt(ia);
Christopher Tate3dacd842011-08-19 14:56:15 -07003595 if (app.persistent && !evenPersistent) {
Christopher Tate064d8422011-07-26 15:38:07 -07003596 // we don't kill persistent processes
3597 continue;
3598 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003599 if (app.removed) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003600 if (doit) {
3601 procs.add(app);
3602 }
Amith Yamasani13593602012-03-22 16:16:17 -07003603 // If uid is specified and the uid and process name match
3604 // Or, the uid is not specified and the process name matches
3605 } else if (((uid > 0 && uid != Process.SYSTEM_UID && app.info.uid == uid)
Amith Yamasani34db3d62012-04-02 16:35:19 -07003606 || ((app.processName.equals(packageName)
3607 || app.processName.startsWith(procNamePrefix))
3608 && uid < 0))) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003609 if (app.setAdj >= minOomAdj) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003610 if (!doit) {
3611 return true;
3612 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003613 app.removed = true;
3614 procs.add(app);
3615 }
3616 }
3617 }
3618 }
3619
3620 int N = procs.size();
3621 for (int i=0; i<N; i++) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003622 removeProcessLocked(procs.get(i), callerWillRestart, allowRestart, reason);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003623 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003624 return N > 0;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003625 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003626
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003627 private final boolean forceStopPackageLocked(String name, int uid,
Christopher Tate3dacd842011-08-19 14:56:15 -07003628 boolean callerWillRestart, boolean purgeCache, boolean doit,
Amith Yamasani483f3b02012-03-13 16:08:00 -07003629 boolean evenPersistent, int userId) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003630 int i;
3631 int N;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003632
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003633 if (uid < 0) {
3634 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003635 uid = AppGlobals.getPackageManager().getPackageUid(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003636 } catch (RemoteException e) {
3637 }
3638 }
3639
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003640 if (doit) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003641 Slog.i(TAG, "Force stopping package " + name + " uid=" + uid);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003642
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003643 Iterator<SparseArray<Long>> badApps = mProcessCrashTimes.getMap().values().iterator();
3644 while (badApps.hasNext()) {
3645 SparseArray<Long> ba = badApps.next();
3646 if (ba.get(uid) != null) {
3647 badApps.remove();
3648 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003649 }
3650 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003651
3652 boolean didSomething = killPackageProcessesLocked(name, uid, -100,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003653 callerWillRestart, false, doit, evenPersistent, "force stop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003654
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003655 TaskRecord lastTask = null;
3656 for (i=0; i<mMainStack.mHistory.size(); i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003657 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003658 final boolean samePackage = r.packageName.equals(name);
Amith Yamasani13593602012-03-22 16:16:17 -07003659 if (r.userId == userId
3660 && (samePackage || r.task == lastTask)
Christopher Tate3dacd842011-08-19 14:56:15 -07003661 && (r.app == null || evenPersistent || !r.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003662 if (!doit) {
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003663 if (r.finishing) {
3664 // If this activity is just finishing, then it is not
3665 // interesting as far as something to stop.
3666 continue;
3667 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003668 return true;
3669 }
3670 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003671 Slog.i(TAG, " Force finishing activity " + r);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003672 if (samePackage) {
3673 if (r.app != null) {
3674 r.app.removed = true;
3675 }
3676 r.app = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003677 }
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003678 lastTask = r.task;
3679 if (r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003680 null, "force-stop", true)) {
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003681 i--;
3682 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003683 }
3684 }
3685
3686 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
Amith Yamasani742a6712011-05-04 14:49:28 -07003687 for (ServiceRecord service : mServiceMap.getAllServices(userId)) {
Christopher Tate064d8422011-07-26 15:38:07 -07003688 if (service.packageName.equals(name)
Christopher Tate3dacd842011-08-19 14:56:15 -07003689 && (service.app == null || evenPersistent || !service.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003690 if (!doit) {
3691 return true;
3692 }
3693 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003694 Slog.i(TAG, " Force stopping service " + service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003695 if (service.app != null) {
3696 service.app.removed = true;
3697 }
3698 service.app = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003699 service.isolatedProc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003700 services.add(service);
3701 }
3702 }
3703
3704 N = services.size();
3705 for (i=0; i<N; i++) {
3706 bringDownServiceLocked(services.get(i), true);
3707 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003708
3709 ArrayList<ContentProviderRecord> providers = new ArrayList<ContentProviderRecord>();
Amith Yamasani13593602012-03-22 16:16:17 -07003710 for (ContentProviderRecord provider : mProviderMap.getProvidersByClass(userId).values()) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003711 if (provider.info.packageName.equals(name)
3712 && (provider.proc == null || evenPersistent || !provider.proc.persistent)) {
3713 if (!doit) {
3714 return true;
3715 }
3716 didSomething = true;
3717 providers.add(provider);
3718 }
3719 }
3720
3721 N = providers.size();
3722 for (i=0; i<N; i++) {
3723 removeDyingProviderLocked(null, providers.get(i));
3724 }
3725
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003726 if (doit) {
3727 if (purgeCache) {
3728 AttributeCache ac = AttributeCache.instance();
3729 if (ac != null) {
3730 ac.removePackage(name);
3731 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003732 }
Dianne Hackborn38cc8962011-10-13 11:33:55 -07003733 if (mBooted) {
3734 mMainStack.resumeTopActivityLocked(null);
3735 mMainStack.scheduleIdleLocked();
3736 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003737 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003738
3739 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003740 }
3741
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003742 private final boolean removeProcessLocked(ProcessRecord app,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003743 boolean callerWillRestart, boolean allowRestart, String reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003744 final String name = app.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003745 final int uid = app.uid;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003746 if (DEBUG_PROCESSES) Slog.d(
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003747 TAG, "Force removing proc " + app.toShortString() + " (" + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003748 + "/" + uid + ")");
3749
3750 mProcessNames.remove(name, uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003751 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003752 if (mHeavyWeightProcess == app) {
3753 mHeavyWeightProcess = null;
3754 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3755 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003756 boolean needRestart = false;
3757 if (app.pid > 0 && app.pid != MY_PID) {
3758 int pid = app.pid;
3759 synchronized (mPidsSelfLocked) {
3760 mPidsSelfLocked.remove(pid);
3761 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3762 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003763 Slog.i(TAG, "Killing proc " + app.toShortString() + ": " + reason);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003764 handleAppDiedLocked(app, true, allowRestart);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003765 mLruProcesses.remove(app);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003766 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003767
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003768 if (app.persistent && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003769 if (!callerWillRestart) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003770 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003771 } else {
3772 needRestart = true;
3773 }
3774 }
3775 } else {
3776 mRemovedProcesses.add(app);
3777 }
3778
3779 return needRestart;
3780 }
3781
3782 private final void processStartTimedOutLocked(ProcessRecord app) {
3783 final int pid = app.pid;
3784 boolean gone = false;
3785 synchronized (mPidsSelfLocked) {
3786 ProcessRecord knownApp = mPidsSelfLocked.get(pid);
3787 if (knownApp != null && knownApp.thread == null) {
3788 mPidsSelfLocked.remove(pid);
3789 gone = true;
3790 }
3791 }
3792
3793 if (gone) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003794 Slog.w(TAG, "Process " + app + " failed to attach");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003795 EventLog.writeEvent(EventLogTags.AM_PROCESS_START_TIMEOUT, pid, app.uid,
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003796 app.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003797 mProcessNames.remove(app.processName, app.uid);
3798 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003799 if (mHeavyWeightProcess == app) {
3800 mHeavyWeightProcess = null;
3801 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3802 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003803 // Take care of any launching providers waiting for this process.
3804 checkAppInLaunchingProvidersLocked(app, true);
3805 // Take care of any services that are waiting for the process.
3806 for (int i=0; i<mPendingServices.size(); i++) {
3807 ServiceRecord sr = mPendingServices.get(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003808 if ((app.uid == sr.appInfo.uid
3809 && app.processName.equals(sr.processName))
3810 || sr.isolatedProc == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003811 Slog.w(TAG, "Forcing bringing down service: " + sr);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003812 sr.isolatedProc = null;
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003813 mPendingServices.remove(i);
3814 i--;
3815 bringDownServiceLocked(sr, true);
3816 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003817 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003818 EventLog.writeEvent(EventLogTags.AM_KILL, pid,
3819 app.processName, app.setAdj, "start timeout");
3820 Process.killProcessQuiet(pid);
Christopher Tate181fafa2009-05-14 11:12:14 -07003821 if (mBackupTarget != null && mBackupTarget.app.pid == pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003822 Slog.w(TAG, "Unattached app died before backup, skipping");
Christopher Tate181fafa2009-05-14 11:12:14 -07003823 try {
3824 IBackupManager bm = IBackupManager.Stub.asInterface(
3825 ServiceManager.getService(Context.BACKUP_SERVICE));
3826 bm.agentDisconnected(app.info.packageName);
3827 } catch (RemoteException e) {
3828 // Can't happen; the backup manager is local
3829 }
3830 }
Christopher Tatef46723b2012-01-26 14:19:24 -08003831 if (isPendingBroadcastProcessLocked(pid)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003832 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
Christopher Tatef46723b2012-01-26 14:19:24 -08003833 skipPendingBroadcastLocked(pid);
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003834 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003835 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003836 Slog.w(TAG, "Spurious process start timeout - pid not known for " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003837 }
3838 }
3839
3840 private final boolean attachApplicationLocked(IApplicationThread thread,
3841 int pid) {
3842
3843 // Find the application record that is being attached... either via
3844 // the pid if we are running in multiple processes, or just pull the
3845 // next app record if we are emulating process with anonymous threads.
3846 ProcessRecord app;
3847 if (pid != MY_PID && pid >= 0) {
3848 synchronized (mPidsSelfLocked) {
3849 app = mPidsSelfLocked.get(pid);
3850 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003851 } else {
3852 app = null;
3853 }
3854
3855 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003856 Slog.w(TAG, "No pending application record for pid " + pid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003857 + " (IApplicationThread " + thread + "); dropping process");
Doug Zongker2bec3d42009-12-04 12:52:44 -08003858 EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003859 if (pid > 0 && pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003860 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003861 } else {
3862 try {
3863 thread.scheduleExit();
3864 } catch (Exception e) {
3865 // Ignore exceptions.
3866 }
3867 }
3868 return false;
3869 }
3870
3871 // If this application record is still attached to a previous
3872 // process, clean it up now.
3873 if (app.thread != null) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003874 handleAppDiedLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003875 }
3876
3877 // Tell the process all about itself.
3878
Joe Onorato8a9b2202010-02-26 18:56:32 -08003879 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003880 TAG, "Binding process pid " + pid + " to record " + app);
3881
3882 String processName = app.processName;
3883 try {
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07003884 AppDeathRecipient adr = new AppDeathRecipient(
3885 app, pid, thread);
3886 thread.asBinder().linkToDeath(adr, 0);
3887 app.deathRecipient = adr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003888 } catch (RemoteException e) {
3889 app.resetPackageList();
3890 startProcessLocked(app, "link fail", processName);
3891 return false;
3892 }
3893
Doug Zongker2bec3d42009-12-04 12:52:44 -08003894 EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.pid, app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003895
3896 app.thread = thread;
3897 app.curAdj = app.setAdj = -100;
Dianne Hackborn09c916b2009-12-08 14:50:51 -08003898 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
3899 app.setSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003900 app.forcingToForeground = null;
3901 app.foregroundServices = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07003902 app.hasShownUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003903 app.debugging = false;
3904
3905 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3906
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003907 boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003908 List providers = normalMode ? generateApplicationProvidersLocked(app) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003909
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003910 if (!normalMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003911 Slog.i(TAG, "Launching preboot mode app: " + app);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003912 }
3913
Joe Onorato8a9b2202010-02-26 18:56:32 -08003914 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003915 TAG, "New app record " + app
3916 + " thread=" + thread.asBinder() + " pid=" + pid);
3917 try {
3918 int testMode = IApplicationThread.DEBUG_OFF;
3919 if (mDebugApp != null && mDebugApp.equals(processName)) {
3920 testMode = mWaitForDebugger
3921 ? IApplicationThread.DEBUG_WAIT
3922 : IApplicationThread.DEBUG_ON;
3923 app.debugging = true;
3924 if (mDebugTransient) {
3925 mDebugApp = mOrigDebugApp;
3926 mWaitForDebugger = mOrigWaitForDebugger;
3927 }
3928 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003929 String profileFile = app.instrumentationProfileFile;
3930 ParcelFileDescriptor profileFd = null;
3931 boolean profileAutoStop = false;
3932 if (mProfileApp != null && mProfileApp.equals(processName)) {
3933 mProfileProc = app;
3934 profileFile = mProfileFile;
3935 profileFd = mProfileFd;
3936 profileAutoStop = mAutoStopProfiler;
3937 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08003938 boolean enableOpenGlTrace = false;
3939 if (mOpenGlTraceApp != null && mOpenGlTraceApp.equals(processName)) {
3940 enableOpenGlTrace = true;
3941 mOpenGlTraceApp = null;
3942 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003943
Christopher Tate181fafa2009-05-14 11:12:14 -07003944 // If the app is being launched for restore or full backup, set it up specially
3945 boolean isRestrictedBackupMode = false;
3946 if (mBackupTarget != null && mBackupAppName.equals(processName)) {
3947 isRestrictedBackupMode = (mBackupTarget.backupMode == BackupRecord.RESTORE)
Christopher Tate75a99702011-05-18 16:28:19 -07003948 || (mBackupTarget.backupMode == BackupRecord.RESTORE_FULL)
Christopher Tate181fafa2009-05-14 11:12:14 -07003949 || (mBackupTarget.backupMode == BackupRecord.BACKUP_FULL);
3950 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003951
Dianne Hackbornd7f6daa2009-06-22 17:06:35 -07003952 ensurePackageDexOpt(app.instrumentationInfo != null
3953 ? app.instrumentationInfo.packageName
3954 : app.info.packageName);
3955 if (app.instrumentationClass != null) {
3956 ensurePackageDexOpt(app.instrumentationClass.getPackageName());
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003957 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08003958 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Binding proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003959 + processName + " with config " + mConfiguration);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003960 ApplicationInfo appInfo = app.instrumentationInfo != null
3961 ? app.instrumentationInfo : app.info;
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -07003962 app.compat = compatibilityInfoForPackageLocked(appInfo);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003963 if (profileFd != null) {
3964 profileFd = profileFd.dup();
3965 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003966 thread.bindApplication(processName, appInfo, providers,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003967 app.instrumentationClass, profileFile, profileFd, profileAutoStop,
Siva Velusamy92a8b222012-03-09 16:24:04 -08003968 app.instrumentationArguments, app.instrumentationWatcher, testMode,
3969 enableOpenGlTrace, isRestrictedBackupMode || !normalMode, app.persistent,
Dianne Hackborn813075a62011-11-14 17:45:19 -08003970 new Configuration(mConfiguration), app.compat, getCommonServicesLocked(),
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08003971 mCoreSettingsObserver.getCoreSettingsLocked());
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003972 updateLruProcessLocked(app, false, true);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003973 app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003974 } catch (Exception e) {
3975 // todo: Yikes! What should we do? For now we will try to
3976 // start another process, but that could easily get us in
3977 // an infinite loop of restarting processes...
Joe Onorato8a9b2202010-02-26 18:56:32 -08003978 Slog.w(TAG, "Exception thrown during bind!", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003979
3980 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07003981 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003982 startProcessLocked(app, "bind fail", processName);
3983 return false;
3984 }
3985
3986 // Remove this record from the list of starting applications.
3987 mPersistentStartingProcesses.remove(app);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003988 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
3989 "Attach application locked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003990 mProcessesOnHold.remove(app);
3991
3992 boolean badApp = false;
3993 boolean didSomething = false;
3994
3995 // See if the top visible activity is waiting to run in this process...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003996 ActivityRecord hr = mMainStack.topRunningActivityLocked(null);
Christopher Tate04c0af82010-06-07 18:35:20 -07003997 if (hr != null && normalMode) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003998 if (hr.app == null && app.uid == hr.info.applicationInfo.uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003999 && processName.equals(hr.processName)) {
4000 try {
Mike Lockwood3a74bd32011-08-12 13:55:22 -07004001 if (mHeadless) {
4002 Slog.e(TAG, "Starting activities not supported on headless device: " + hr);
4003 } else if (mMainStack.realStartActivityLocked(hr, app, true, true)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004004 didSomething = true;
4005 }
4006 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004007 Slog.w(TAG, "Exception in new application when starting activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004008 + hr.intent.getComponent().flattenToShortString(), e);
4009 badApp = true;
4010 }
4011 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004012 mMainStack.ensureActivitiesVisibleLocked(hr, null, processName, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004013 }
4014 }
4015
4016 // Find any services that should be running in this process...
4017 if (!badApp && mPendingServices.size() > 0) {
4018 ServiceRecord sr = null;
4019 try {
4020 for (int i=0; i<mPendingServices.size(); i++) {
4021 sr = mPendingServices.get(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004022 if (app != sr.isolatedProc && (app.uid != sr.appInfo.uid
4023 || !processName.equals(sr.processName))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004024 continue;
4025 }
4026
4027 mPendingServices.remove(i);
4028 i--;
4029 realStartServiceLocked(sr, app);
4030 didSomething = true;
4031 }
4032 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004033 Slog.w(TAG, "Exception in new application when starting service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004034 + sr.shortName, e);
4035 badApp = true;
4036 }
4037 }
4038
Christopher Tatef46723b2012-01-26 14:19:24 -08004039 // Check if a next-broadcast receiver is in this process...
4040 if (!badApp && isPendingBroadcastProcessLocked(pid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004041 try {
Christopher Tatef46723b2012-01-26 14:19:24 -08004042 didSomething = sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004043 } catch (Exception e) {
Christopher Tatef46723b2012-01-26 14:19:24 -08004044 // If the app died trying to launch the receiver we declare it 'bad'
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004045 badApp = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004046 }
4047 }
4048
Christopher Tate181fafa2009-05-14 11:12:14 -07004049 // Check whether the next backup agent is in this process...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004050 if (!badApp && mBackupTarget != null && mBackupTarget.appInfo.uid == app.uid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004051 if (DEBUG_BACKUP) Slog.v(TAG, "New app is backup target, launching agent for " + app);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004052 ensurePackageDexOpt(mBackupTarget.appInfo.packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07004053 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004054 thread.scheduleCreateBackupAgent(mBackupTarget.appInfo,
4055 compatibilityInfoForPackageLocked(mBackupTarget.appInfo),
4056 mBackupTarget.backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -07004057 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004058 Slog.w(TAG, "Exception scheduling backup agent creation: ");
Christopher Tate181fafa2009-05-14 11:12:14 -07004059 e.printStackTrace();
4060 }
4061 }
4062
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004063 if (badApp) {
4064 // todo: Also need to kill application to deal with all
4065 // kinds of exceptions.
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004066 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004067 return false;
4068 }
4069
4070 if (!didSomething) {
4071 updateOomAdjLocked();
4072 }
4073
4074 return true;
4075 }
4076
4077 public final void attachApplication(IApplicationThread thread) {
4078 synchronized (this) {
4079 int callingPid = Binder.getCallingPid();
4080 final long origId = Binder.clearCallingIdentity();
4081 attachApplicationLocked(thread, callingPid);
4082 Binder.restoreCallingIdentity(origId);
4083 }
4084 }
4085
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004086 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004087 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004088 ActivityRecord r = mMainStack.activityIdleInternal(token, false, config);
4089 if (stopProfiling) {
4090 synchronized (this) {
4091 if (mProfileProc == r.app) {
4092 if (mProfileFd != null) {
4093 try {
4094 mProfileFd.close();
4095 } catch (IOException e) {
4096 }
4097 clearProfilerLocked();
4098 }
4099 }
4100 }
4101 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004102 Binder.restoreCallingIdentity(origId);
4103 }
4104
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004105 void enableScreenAfterBoot() {
Doug Zongker2bec3d42009-12-04 12:52:44 -08004106 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004107 SystemClock.uptimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004108 mWindowManager.enableScreenAfterBoot();
4109 }
4110
Dianne Hackborn661cd522011-08-22 00:26:20 -07004111 public void showBootMessage(final CharSequence msg, final boolean always) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004112 enforceNotIsolatedCaller("showBootMessage");
Dianne Hackborn661cd522011-08-22 00:26:20 -07004113 mWindowManager.showBootMessage(msg, always);
4114 }
4115
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004116 public void dismissKeyguardOnNextActivity() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004117 enforceNotIsolatedCaller("dismissKeyguardOnNextActivity");
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004118 synchronized (this) {
4119 mMainStack.dismissKeyguardOnNextActivityLocked();
4120 }
4121 }
4122
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004123 final void finishBooting() {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004124 IntentFilter pkgFilter = new IntentFilter();
4125 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
4126 pkgFilter.addDataScheme("package");
4127 mContext.registerReceiver(new BroadcastReceiver() {
4128 @Override
4129 public void onReceive(Context context, Intent intent) {
4130 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
4131 if (pkgs != null) {
4132 for (String pkg : pkgs) {
Vairavan Srinivasan61f07652010-07-22 13:36:40 -07004133 synchronized (ActivityManagerService.this) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07004134 if (forceStopPackageLocked(pkg, -1, false, false, false, false, 0)) {
4135 setResultCode(Activity.RESULT_OK);
4136 return;
4137 }
4138 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004139 }
4140 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004141 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004142 }, pkgFilter);
Amith Yamasani13593602012-03-22 16:16:17 -07004143
4144 IntentFilter userFilter = new IntentFilter();
4145 userFilter.addAction(Intent.ACTION_USER_REMOVED);
4146 mContext.registerReceiver(new BroadcastReceiver() {
4147 @Override
4148 public void onReceive(Context context, Intent intent) {
4149 onUserRemoved(intent);
4150 }
4151 }, userFilter);
4152
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004153 synchronized (this) {
4154 // Ensure that any processes we had put on hold are now started
4155 // up.
4156 final int NP = mProcessesOnHold.size();
4157 if (NP > 0) {
4158 ArrayList<ProcessRecord> procs =
4159 new ArrayList<ProcessRecord>(mProcessesOnHold);
4160 for (int ip=0; ip<NP; ip++) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004161 if (DEBUG_PROCESSES) Slog.v(TAG, "Starting process on hold: "
4162 + procs.get(ip));
4163 startProcessLocked(procs.get(ip), "on-hold", null);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004164 }
4165 }
4166
4167 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004168 // Start looking for apps that are abusing wake locks.
4169 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07004170 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004171 // Tell anyone interested that we are done booting!
Dianne Hackbornf4c454b2010-08-11 12:47:41 -07004172 SystemProperties.set("sys.boot_completed", "1");
Guang Zhu191713a2012-01-12 12:02:22 -08004173 SystemProperties.set("dev.bootcomplete", "1");
Amith Yamasani742a6712011-05-04 14:49:28 -07004174 /* TODO: Send this to all users that are to be logged in on startup */
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004175 broadcastIntentLocked(null, null,
4176 new Intent(Intent.ACTION_BOOT_COMPLETED, null),
4177 null, null, 0, null, null,
4178 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
Amith Yamasani742a6712011-05-04 14:49:28 -07004179 false, false, MY_PID, Process.SYSTEM_UID, Binder.getOrigCallingUser());
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004180 }
4181 }
4182 }
4183
4184 final void ensureBootCompleted() {
4185 boolean booting;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004186 boolean enableScreen;
4187 synchronized (this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004188 booting = mBooting;
4189 mBooting = false;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004190 enableScreen = !mBooted;
4191 mBooted = true;
4192 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004193
4194 if (booting) {
4195 finishBooting();
4196 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004197
4198 if (enableScreen) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004199 enableScreenAfterBoot();
4200 }
4201 }
4202
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004203 public final void activityPaused(IBinder token) {
4204 final long origId = Binder.clearCallingIdentity();
4205 mMainStack.activityPaused(token, false);
4206 Binder.restoreCallingIdentity(origId);
4207 }
4208
4209 public final void activityStopped(IBinder token, Bundle icicle, Bitmap thumbnail,
4210 CharSequence description) {
4211 if (localLOGV) Slog.v(
4212 TAG, "Activity stopped: token=" + token);
4213
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004214 // Refuse possible leaked file descriptors
4215 if (icicle != null && icicle.hasFileDescriptors()) {
4216 throw new IllegalArgumentException("File descriptors passed in Bundle");
4217 }
4218
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004219 ActivityRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004220
4221 final long origId = Binder.clearCallingIdentity();
4222
4223 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004224 r = mMainStack.isInStackLocked(token);
4225 if (r != null) {
4226 r.stack.activityStoppedLocked(r, icicle, thumbnail, description);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004227 }
4228 }
4229
4230 if (r != null) {
4231 sendPendingThumbnail(r, null, null, null, false);
4232 }
4233
4234 trimApplications();
4235
4236 Binder.restoreCallingIdentity(origId);
4237 }
4238
4239 public final void activityDestroyed(IBinder token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004240 if (DEBUG_SWITCH) Slog.v(TAG, "ACTIVITY DESTROYED: " + token);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004241 mMainStack.activityDestroyed(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004242 }
4243
4244 public String getCallingPackage(IBinder token) {
4245 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004246 ActivityRecord r = getCallingRecordLocked(token);
Dianne Hackborn9bbcb912009-10-20 15:42:38 -07004247 return r != null && r.app != null ? r.info.packageName : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004248 }
4249 }
4250
4251 public ComponentName getCallingActivity(IBinder token) {
4252 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004253 ActivityRecord r = getCallingRecordLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004254 return r != null ? r.intent.getComponent() : null;
4255 }
4256 }
4257
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004258 private ActivityRecord getCallingRecordLocked(IBinder token) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004259 ActivityRecord r = mMainStack.isInStackLocked(token);
4260 if (r == null) {
4261 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004262 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004263 return r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004264 }
4265
4266 public ComponentName getActivityClassForToken(IBinder token) {
4267 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004268 ActivityRecord r = mMainStack.isInStackLocked(token);
4269 if (r == null) {
4270 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004271 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004272 return r.intent.getComponent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004273 }
4274 }
4275
4276 public String getPackageForToken(IBinder token) {
4277 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004278 ActivityRecord r = mMainStack.isInStackLocked(token);
4279 if (r == null) {
4280 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004281 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004282 return r.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004283 }
4284 }
4285
4286 public IIntentSender getIntentSender(int type,
4287 String packageName, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004288 int requestCode, Intent[] intents, String[] resolvedTypes,
4289 int flags, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004290 enforceNotIsolatedCaller("getIntentSender");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004291 // Refuse possible leaked file descriptors
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004292 if (intents != null) {
4293 if (intents.length < 1) {
4294 throw new IllegalArgumentException("Intents array length must be >= 1");
4295 }
4296 for (int i=0; i<intents.length; i++) {
4297 Intent intent = intents[i];
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004298 if (intent != null) {
4299 if (intent.hasFileDescriptors()) {
4300 throw new IllegalArgumentException("File descriptors passed in Intent");
4301 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07004302 if (type == ActivityManager.INTENT_SENDER_BROADCAST &&
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004303 (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
4304 throw new IllegalArgumentException(
4305 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
4306 }
4307 intents[i] = new Intent(intent);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004308 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004309 }
4310 if (resolvedTypes != null && resolvedTypes.length != intents.length) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004311 throw new IllegalArgumentException(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004312 "Intent array length does not match resolvedTypes length");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004313 }
4314 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004315 if (options != null) {
4316 if (options.hasFileDescriptors()) {
4317 throw new IllegalArgumentException("File descriptors passed in options");
4318 }
4319 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004320
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004321 synchronized(this) {
4322 int callingUid = Binder.getCallingUid();
4323 try {
Jeff Brown10e89712011-07-08 18:52:57 -07004324 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004325 int uid = AppGlobals.getPackageManager()
Amith Yamasani483f3b02012-03-13 16:08:00 -07004326 .getPackageUid(packageName, UserId.getUserId(callingUid));
4327 if (!UserId.isSameApp(callingUid, uid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004328 String msg = "Permission Denial: getIntentSender() from pid="
4329 + Binder.getCallingPid()
4330 + ", uid=" + Binder.getCallingUid()
4331 + ", (need uid=" + uid + ")"
4332 + " is not allowed to send as package " + packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004333 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004334 throw new SecurityException(msg);
4335 }
4336 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004337
Amith Yamasani742a6712011-05-04 14:49:28 -07004338 if (DEBUG_MU)
4339 Slog.i(TAG_MU, "Getting intent sender for origCallingUid="
4340 + Binder.getOrigCallingUid());
4341 return getIntentSenderLocked(type, packageName, Binder.getOrigCallingUid(),
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004342 token, resultWho, requestCode, intents, resolvedTypes, flags, options);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004343
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004344 } catch (RemoteException e) {
4345 throw new SecurityException(e);
4346 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004347 }
4348 }
4349
4350 IIntentSender getIntentSenderLocked(int type,
4351 String packageName, int callingUid, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004352 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
4353 Bundle options) {
Amith Yamasani742a6712011-05-04 14:49:28 -07004354 if (DEBUG_MU)
4355 Slog.v(TAG_MU, "getIntentSenderLocked(): uid=" + callingUid);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004356 ActivityRecord activity = null;
Dianne Hackborna4972e92012-03-14 10:38:05 -07004357 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004358 activity = mMainStack.isInStackLocked(token);
4359 if (activity == null) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004360 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004361 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004362 if (activity.finishing) {
4363 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004364 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004365 }
4366
4367 final boolean noCreate = (flags&PendingIntent.FLAG_NO_CREATE) != 0;
4368 final boolean cancelCurrent = (flags&PendingIntent.FLAG_CANCEL_CURRENT) != 0;
4369 final boolean updateCurrent = (flags&PendingIntent.FLAG_UPDATE_CURRENT) != 0;
4370 flags &= ~(PendingIntent.FLAG_NO_CREATE|PendingIntent.FLAG_CANCEL_CURRENT
4371 |PendingIntent.FLAG_UPDATE_CURRENT);
4372
4373 PendingIntentRecord.Key key = new PendingIntentRecord.Key(
4374 type, packageName, activity, resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004375 requestCode, intents, resolvedTypes, flags, options);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004376 WeakReference<PendingIntentRecord> ref;
4377 ref = mIntentSenderRecords.get(key);
4378 PendingIntentRecord rec = ref != null ? ref.get() : null;
4379 if (rec != null) {
4380 if (!cancelCurrent) {
4381 if (updateCurrent) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004382 if (rec.key.requestIntent != null) {
4383 rec.key.requestIntent.replaceExtras(intents != null ? intents[0] : null);
4384 }
4385 if (intents != null) {
4386 intents[intents.length-1] = rec.key.requestIntent;
4387 rec.key.allIntents = intents;
4388 rec.key.allResolvedTypes = resolvedTypes;
4389 } else {
4390 rec.key.allIntents = null;
4391 rec.key.allResolvedTypes = null;
4392 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004393 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004394 return rec;
4395 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004396 rec.canceled = true;
4397 mIntentSenderRecords.remove(key);
4398 }
4399 if (noCreate) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004400 return rec;
4401 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004402 rec = new PendingIntentRecord(this, key, callingUid);
4403 mIntentSenderRecords.put(key, rec.ref);
Dianne Hackborna4972e92012-03-14 10:38:05 -07004404 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004405 if (activity.pendingResults == null) {
4406 activity.pendingResults
4407 = new HashSet<WeakReference<PendingIntentRecord>>();
4408 }
4409 activity.pendingResults.add(rec.ref);
4410 }
4411 return rec;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004412 }
4413
4414 public void cancelIntentSender(IIntentSender sender) {
4415 if (!(sender instanceof PendingIntentRecord)) {
4416 return;
4417 }
4418 synchronized(this) {
4419 PendingIntentRecord rec = (PendingIntentRecord)sender;
4420 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004421 int uid = AppGlobals.getPackageManager()
Amith Yamasani483f3b02012-03-13 16:08:00 -07004422 .getPackageUid(rec.key.packageName, UserId.getCallingUserId());
Amith Yamasani04e0d262012-02-14 11:50:53 -08004423 if (!UserId.isSameApp(uid, Binder.getCallingUid())) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004424 String msg = "Permission Denial: cancelIntentSender() from pid="
4425 + Binder.getCallingPid()
4426 + ", uid=" + Binder.getCallingUid()
4427 + " is not allowed to cancel packges "
4428 + rec.key.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004429 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004430 throw new SecurityException(msg);
4431 }
4432 } catch (RemoteException e) {
4433 throw new SecurityException(e);
4434 }
4435 cancelIntentSenderLocked(rec, true);
4436 }
4437 }
4438
4439 void cancelIntentSenderLocked(PendingIntentRecord rec, boolean cleanActivity) {
4440 rec.canceled = true;
4441 mIntentSenderRecords.remove(rec.key);
4442 if (cleanActivity && rec.key.activity != null) {
4443 rec.key.activity.pendingResults.remove(rec.ref);
4444 }
4445 }
4446
4447 public String getPackageForIntentSender(IIntentSender pendingResult) {
4448 if (!(pendingResult instanceof PendingIntentRecord)) {
4449 return null;
4450 }
Brad Fitzpatrickb213d102010-04-19 11:58:52 -07004451 try {
4452 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4453 return res.key.packageName;
4454 } catch (ClassCastException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004455 }
4456 return null;
4457 }
4458
Christopher Tatec4a07d12012-04-06 14:19:13 -07004459 public int getUidForIntentSender(IIntentSender sender) {
4460 if (sender instanceof PendingIntentRecord) {
4461 try {
4462 PendingIntentRecord res = (PendingIntentRecord)sender;
4463 return res.uid;
4464 } catch (ClassCastException e) {
4465 }
4466 }
4467 return -1;
4468 }
4469
Dianne Hackborn6c418d52011-06-29 14:05:33 -07004470 public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) {
4471 if (!(pendingResult instanceof PendingIntentRecord)) {
4472 return false;
4473 }
4474 try {
4475 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4476 if (res.key.allIntents == null) {
4477 return false;
4478 }
4479 for (int i=0; i<res.key.allIntents.length; i++) {
4480 Intent intent = res.key.allIntents[i];
4481 if (intent.getPackage() != null && intent.getComponent() != null) {
4482 return false;
4483 }
4484 }
4485 return true;
4486 } catch (ClassCastException e) {
4487 }
4488 return false;
4489 }
4490
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004491 public void setProcessLimit(int max) {
4492 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4493 "setProcessLimit()");
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004494 synchronized (this) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07004495 mProcessLimit = max < 0 ? ProcessList.MAX_HIDDEN_APPS : max;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004496 mProcessLimitOverride = max;
4497 }
4498 trimApplications();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004499 }
4500
4501 public int getProcessLimit() {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004502 synchronized (this) {
4503 return mProcessLimitOverride;
4504 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004505 }
4506
4507 void foregroundTokenDied(ForegroundToken token) {
4508 synchronized (ActivityManagerService.this) {
4509 synchronized (mPidsSelfLocked) {
4510 ForegroundToken cur
4511 = mForegroundProcesses.get(token.pid);
4512 if (cur != token) {
4513 return;
4514 }
4515 mForegroundProcesses.remove(token.pid);
4516 ProcessRecord pr = mPidsSelfLocked.get(token.pid);
4517 if (pr == null) {
4518 return;
4519 }
4520 pr.forcingToForeground = null;
4521 pr.foregroundServices = false;
4522 }
4523 updateOomAdjLocked();
4524 }
4525 }
4526
4527 public void setProcessForeground(IBinder token, int pid, boolean isForeground) {
4528 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4529 "setProcessForeground()");
4530 synchronized(this) {
4531 boolean changed = false;
4532
4533 synchronized (mPidsSelfLocked) {
4534 ProcessRecord pr = mPidsSelfLocked.get(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004535 if (pr == null && isForeground) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004536 Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004537 return;
4538 }
4539 ForegroundToken oldToken = mForegroundProcesses.get(pid);
4540 if (oldToken != null) {
4541 oldToken.token.unlinkToDeath(oldToken, 0);
4542 mForegroundProcesses.remove(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004543 if (pr != null) {
4544 pr.forcingToForeground = null;
4545 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004546 changed = true;
4547 }
4548 if (isForeground && token != null) {
4549 ForegroundToken newToken = new ForegroundToken() {
4550 public void binderDied() {
4551 foregroundTokenDied(this);
4552 }
4553 };
4554 newToken.pid = pid;
4555 newToken.token = token;
4556 try {
4557 token.linkToDeath(newToken, 0);
4558 mForegroundProcesses.put(pid, newToken);
4559 pr.forcingToForeground = token;
4560 changed = true;
4561 } catch (RemoteException e) {
4562 // If the process died while doing this, we will later
4563 // do the cleanup with the process death link.
4564 }
4565 }
4566 }
4567
4568 if (changed) {
4569 updateOomAdjLocked();
4570 }
4571 }
4572 }
4573
4574 // =========================================================
4575 // PERMISSIONS
4576 // =========================================================
4577
4578 static class PermissionController extends IPermissionController.Stub {
4579 ActivityManagerService mActivityManagerService;
4580 PermissionController(ActivityManagerService activityManagerService) {
4581 mActivityManagerService = activityManagerService;
4582 }
4583
4584 public boolean checkPermission(String permission, int pid, int uid) {
4585 return mActivityManagerService.checkPermission(permission, pid,
4586 uid) == PackageManager.PERMISSION_GRANTED;
4587 }
4588 }
4589
4590 /**
4591 * This can be called with or without the global lock held.
4592 */
4593 int checkComponentPermission(String permission, int pid, int uid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004594 int owningUid, boolean exported) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004595 // We might be performing an operation on behalf of an indirect binder
4596 // invocation, e.g. via {@link #openContentUri}. Check and adjust the
4597 // client identity accordingly before proceeding.
4598 Identity tlsIdentity = sCallerIdentity.get();
4599 if (tlsIdentity != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004600 Slog.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004601 + tlsIdentity.pid + "," + tlsIdentity.uid + "}");
4602 uid = tlsIdentity.uid;
4603 pid = tlsIdentity.pid;
4604 }
4605
4606 // Root, system server and our own process get to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07004607 if (uid == 0 || uid == Process.SYSTEM_UID || pid == MY_PID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004608 return PackageManager.PERMISSION_GRANTED;
4609 }
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004610 // Isolated processes don't get any permissions.
4611 if (UserId.isIsolated(uid)) {
4612 return PackageManager.PERMISSION_DENIED;
4613 }
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004614 // If there is a uid that owns whatever is being accessed, it has
4615 // blanket access to it regardless of the permissions it requires.
Amith Yamasani742a6712011-05-04 14:49:28 -07004616 if (owningUid >= 0 && UserId.isSameApp(uid, owningUid)) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004617 return PackageManager.PERMISSION_GRANTED;
4618 }
4619 // If the target is not exported, then nobody else can get to it.
4620 if (!exported) {
4621 Slog.w(TAG, "Permission denied: checkComponentPermission() owningUid=" + owningUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004622 return PackageManager.PERMISSION_DENIED;
4623 }
4624 if (permission == null) {
4625 return PackageManager.PERMISSION_GRANTED;
4626 }
4627 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004628 return AppGlobals.getPackageManager()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004629 .checkUidPermission(permission, uid);
4630 } catch (RemoteException e) {
4631 // Should never happen, but if it does... deny!
Joe Onorato8a9b2202010-02-26 18:56:32 -08004632 Slog.e(TAG, "PackageManager is dead?!?", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004633 }
4634 return PackageManager.PERMISSION_DENIED;
4635 }
4636
4637 /**
4638 * As the only public entry point for permissions checking, this method
4639 * can enforce the semantic that requesting a check on a null global
4640 * permission is automatically denied. (Internally a null permission
4641 * string is used when calling {@link #checkComponentPermission} in cases
4642 * when only uid-based security is needed.)
4643 *
4644 * This can be called with or without the global lock held.
4645 */
4646 public int checkPermission(String permission, int pid, int uid) {
4647 if (permission == null) {
4648 return PackageManager.PERMISSION_DENIED;
4649 }
Amith Yamasani742a6712011-05-04 14:49:28 -07004650 return checkComponentPermission(permission, pid, UserId.getAppId(uid), -1, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004651 }
4652
4653 /**
4654 * Binder IPC calls go through the public entry point.
4655 * This can be called with or without the global lock held.
4656 */
4657 int checkCallingPermission(String permission) {
4658 return checkPermission(permission,
4659 Binder.getCallingPid(),
Amith Yamasani742a6712011-05-04 14:49:28 -07004660 UserId.getAppId(Binder.getCallingUid()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004661 }
4662
4663 /**
4664 * This can be called with or without the global lock held.
4665 */
4666 void enforceCallingPermission(String permission, String func) {
4667 if (checkCallingPermission(permission)
4668 == PackageManager.PERMISSION_GRANTED) {
4669 return;
4670 }
4671
4672 String msg = "Permission Denial: " + func + " from pid="
4673 + Binder.getCallingPid()
4674 + ", uid=" + Binder.getCallingUid()
4675 + " requires " + permission;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004676 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004677 throw new SecurityException(msg);
4678 }
4679
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004680 /**
4681 * Determine if UID is holding permissions required to access {@link Uri} in
4682 * the given {@link ProviderInfo}. Final permission checking is always done
4683 * in {@link ContentProvider}.
4684 */
4685 private final boolean checkHoldingPermissionsLocked(
4686 IPackageManager pm, ProviderInfo pi, Uri uri, int uid, int modeFlags) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004687 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4688 "checkHoldingPermissionsLocked: uri=" + uri + " uid=" + uid);
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004689
4690 if (pi.applicationInfo.uid == uid) {
4691 return true;
4692 } else if (!pi.exported) {
4693 return false;
4694 }
4695
4696 boolean readMet = (modeFlags & Intent.FLAG_GRANT_READ_URI_PERMISSION) == 0;
4697 boolean writeMet = (modeFlags & Intent.FLAG_GRANT_WRITE_URI_PERMISSION) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004698 try {
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004699 // check if target holds top-level <provider> permissions
4700 if (!readMet && pi.readPermission != null
4701 && (pm.checkUidPermission(pi.readPermission, uid) == PERMISSION_GRANTED)) {
4702 readMet = true;
4703 }
4704 if (!writeMet && pi.writePermission != null
4705 && (pm.checkUidPermission(pi.writePermission, uid) == PERMISSION_GRANTED)) {
4706 writeMet = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004707 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004708
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004709 // track if unprotected read/write is allowed; any denied
4710 // <path-permission> below removes this ability
4711 boolean allowDefaultRead = pi.readPermission == null;
4712 boolean allowDefaultWrite = pi.writePermission == null;
Dianne Hackborn48058e82010-09-27 16:53:23 -07004713
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004714 // check if target holds any <path-permission> that match uri
4715 final PathPermission[] pps = pi.pathPermissions;
4716 if (pps != null) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004717 final String path = uri.getPath();
4718 int i = pps.length;
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004719 while (i > 0 && (!readMet || !writeMet)) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004720 i--;
4721 PathPermission pp = pps[i];
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004722 if (pp.match(path)) {
4723 if (!readMet) {
4724 final String pprperm = pp.getReadPermission();
4725 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking read perm for "
4726 + pprperm + " for " + pp.getPath()
4727 + ": match=" + pp.match(path)
4728 + " check=" + pm.checkUidPermission(pprperm, uid));
4729 if (pprperm != null) {
4730 if (pm.checkUidPermission(pprperm, uid) == PERMISSION_GRANTED) {
4731 readMet = true;
4732 } else {
4733 allowDefaultRead = false;
4734 }
4735 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004736 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004737 if (!writeMet) {
4738 final String ppwperm = pp.getWritePermission();
4739 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking write perm "
4740 + ppwperm + " for " + pp.getPath()
4741 + ": match=" + pp.match(path)
4742 + " check=" + pm.checkUidPermission(ppwperm, uid));
4743 if (ppwperm != null) {
4744 if (pm.checkUidPermission(ppwperm, uid) == PERMISSION_GRANTED) {
4745 writeMet = true;
4746 } else {
4747 allowDefaultWrite = false;
4748 }
4749 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004750 }
4751 }
4752 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07004753 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004754
4755 // grant unprotected <provider> read/write, if not blocked by
4756 // <path-permission> above
4757 if (allowDefaultRead) readMet = true;
4758 if (allowDefaultWrite) writeMet = true;
4759
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004760 } catch (RemoteException e) {
4761 return false;
4762 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004763
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004764 return readMet && writeMet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004765 }
4766
4767 private final boolean checkUriPermissionLocked(Uri uri, int uid,
4768 int modeFlags) {
4769 // Root gets to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07004770 if (uid == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004771 return true;
4772 }
4773 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(uid);
4774 if (perms == null) return false;
4775 UriPermission perm = perms.get(uri);
4776 if (perm == null) return false;
4777 return (modeFlags&perm.modeFlags) == modeFlags;
4778 }
4779
4780 public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004781 enforceNotIsolatedCaller("checkUriPermission");
4782
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004783 // Another redirected-binder-call permissions check as in
4784 // {@link checkComponentPermission}.
4785 Identity tlsIdentity = sCallerIdentity.get();
4786 if (tlsIdentity != null) {
4787 uid = tlsIdentity.uid;
4788 pid = tlsIdentity.pid;
4789 }
4790
Amith Yamasani742a6712011-05-04 14:49:28 -07004791 uid = UserId.getAppId(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004792 // Our own process gets to do everything.
4793 if (pid == MY_PID) {
4794 return PackageManager.PERMISSION_GRANTED;
4795 }
4796 synchronized(this) {
4797 return checkUriPermissionLocked(uri, uid, modeFlags)
4798 ? PackageManager.PERMISSION_GRANTED
4799 : PackageManager.PERMISSION_DENIED;
4800 }
4801 }
4802
Dianne Hackborn39792d22010-08-19 18:01:52 -07004803 /**
4804 * Check if the targetPkg can be granted permission to access uri by
4805 * the callingUid using the given modeFlags. Throws a security exception
4806 * if callingUid is not allowed to do this. Returns the uid of the target
4807 * if the URI permission grant should be performed; returns -1 if it is not
4808 * needed (for example targetPkg already has permission to access the URI).
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004809 * If you already know the uid of the target, you can supply it in
4810 * lastTargetUid else set that to -1.
Dianne Hackborn39792d22010-08-19 18:01:52 -07004811 */
4812 int checkGrantUriPermissionLocked(int callingUid, String targetPkg,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004813 Uri uri, int modeFlags, int lastTargetUid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004814 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4815 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4816 if (modeFlags == 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004817 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004818 }
4819
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004820 if (targetPkg != null) {
4821 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4822 "Checking grant " + targetPkg + " permission to " + uri);
4823 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004824
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004825 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004826
4827 // If this is not a content: uri, we can't do anything with it.
4828 if (!ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004829 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004830 "Can't grant URI permission for non-content URI: " + uri);
Dianne Hackborn39792d22010-08-19 18:01:52 -07004831 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004832 }
4833
4834 String name = uri.getAuthority();
4835 ProviderInfo pi = null;
Amith Yamasani742a6712011-05-04 14:49:28 -07004836 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
4837 UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004838 if (cpr != null) {
4839 pi = cpr.info;
4840 } else {
4841 try {
4842 pi = pm.resolveContentProvider(name,
Amith Yamasani483f3b02012-03-13 16:08:00 -07004843 PackageManager.GET_URI_PERMISSION_PATTERNS, UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004844 } catch (RemoteException ex) {
4845 }
4846 }
4847 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07004848 Slog.w(TAG, "No content provider found for permission check: " + uri.toSafeString());
Dianne Hackborn39792d22010-08-19 18:01:52 -07004849 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004850 }
4851
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004852 int targetUid = lastTargetUid;
4853 if (targetUid < 0 && targetPkg != null) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004854 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07004855 targetUid = pm.getPackageUid(targetPkg, UserId.getUserId(callingUid));
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004856 if (targetUid < 0) {
4857 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4858 "Can't grant URI permission no uid for: " + targetPkg);
4859 return -1;
4860 }
4861 } catch (RemoteException ex) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004862 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004863 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004864 }
4865
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004866 if (targetUid >= 0) {
4867 // First... does the target actually need this permission?
4868 if (checkHoldingPermissionsLocked(pm, pi, uri, targetUid, modeFlags)) {
4869 // No need to grant the target this permission.
4870 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4871 "Target " + targetPkg + " already has full permission to " + uri);
4872 return -1;
4873 }
4874 } else {
4875 // First... there is no target package, so can anyone access it?
4876 boolean allowed = pi.exported;
4877 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
4878 if (pi.readPermission != null) {
4879 allowed = false;
4880 }
4881 }
4882 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
4883 if (pi.writePermission != null) {
4884 allowed = false;
4885 }
4886 }
4887 if (allowed) {
4888 return -1;
4889 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004890 }
4891
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004892 // Second... is the provider allowing granting of URI permissions?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004893 if (!pi.grantUriPermissions) {
4894 throw new SecurityException("Provider " + pi.packageName
4895 + "/" + pi.name
4896 + " does not allow granting of Uri permissions (uri "
4897 + uri + ")");
4898 }
4899 if (pi.uriPermissionPatterns != null) {
4900 final int N = pi.uriPermissionPatterns.length;
4901 boolean allowed = false;
4902 for (int i=0; i<N; i++) {
4903 if (pi.uriPermissionPatterns[i] != null
4904 && pi.uriPermissionPatterns[i].match(uri.getPath())) {
4905 allowed = true;
4906 break;
4907 }
4908 }
4909 if (!allowed) {
4910 throw new SecurityException("Provider " + pi.packageName
4911 + "/" + pi.name
4912 + " does not allow granting of permission to path of Uri "
4913 + uri);
4914 }
4915 }
4916
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004917 // Third... does the caller itself have permission to access
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004918 // this uri?
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004919 if (callingUid != Process.myUid()) {
4920 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
4921 if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
4922 throw new SecurityException("Uid " + callingUid
4923 + " does not have permission to uri " + uri);
4924 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004925 }
4926 }
4927
Dianne Hackborn39792d22010-08-19 18:01:52 -07004928 return targetUid;
4929 }
4930
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004931 public int checkGrantUriPermission(int callingUid, String targetPkg,
4932 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004933 enforceNotIsolatedCaller("checkGrantUriPermission");
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004934 synchronized(this) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004935 return checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004936 }
4937 }
4938
Dianne Hackborn39792d22010-08-19 18:01:52 -07004939 void grantUriPermissionUncheckedLocked(int targetUid, String targetPkg,
4940 Uri uri, int modeFlags, UriPermissionOwner owner) {
4941 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4942 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4943 if (modeFlags == 0) {
4944 return;
4945 }
4946
4947 // So here we are: the caller has the assumed permission
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004948 // to the uri, and the target doesn't. Let's now give this to
4949 // the target.
4950
Joe Onorato8a9b2202010-02-26 18:56:32 -08004951 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn39792d22010-08-19 18:01:52 -07004952 "Granting " + targetPkg + "/" + targetUid + " permission to " + uri);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004953
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004954 HashMap<Uri, UriPermission> targetUris
4955 = mGrantedUriPermissions.get(targetUid);
4956 if (targetUris == null) {
4957 targetUris = new HashMap<Uri, UriPermission>();
4958 mGrantedUriPermissions.put(targetUid, targetUris);
4959 }
4960
4961 UriPermission perm = targetUris.get(uri);
4962 if (perm == null) {
4963 perm = new UriPermission(targetUid, uri);
4964 targetUris.put(uri, perm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004965 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07004966
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004967 perm.modeFlags |= modeFlags;
Dianne Hackborn39792d22010-08-19 18:01:52 -07004968 if (owner == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004969 perm.globalModeFlags |= modeFlags;
Vairavan Srinivasan91c12c22011-01-21 18:26:06 -08004970 } else {
4971 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
4972 perm.readOwners.add(owner);
4973 owner.addReadPermission(perm);
4974 }
4975 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
4976 perm.writeOwners.add(owner);
4977 owner.addWritePermission(perm);
4978 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004979 }
4980 }
4981
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004982 void grantUriPermissionLocked(int callingUid, String targetPkg, Uri uri,
4983 int modeFlags, UriPermissionOwner owner) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004984 if (targetPkg == null) {
4985 throw new NullPointerException("targetPkg");
4986 }
4987
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004988 int targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn39792d22010-08-19 18:01:52 -07004989 if (targetUid < 0) {
4990 return;
4991 }
4992
4993 grantUriPermissionUncheckedLocked(targetUid, targetPkg, uri, modeFlags, owner);
4994 }
4995
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004996 static class NeededUriGrants extends ArrayList<Uri> {
4997 final String targetPkg;
4998 final int targetUid;
4999 final int flags;
5000
5001 NeededUriGrants(String _targetPkg, int _targetUid, int _flags) {
5002 targetPkg = _targetPkg;
5003 targetUid = _targetUid;
5004 flags = _flags;
5005 }
5006 }
5007
Dianne Hackborn39792d22010-08-19 18:01:52 -07005008 /**
5009 * Like checkGrantUriPermissionLocked, but takes an Intent.
5010 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005011 NeededUriGrants checkGrantUriPermissionFromIntentLocked(int callingUid,
5012 String targetPkg, Intent intent, int mode, NeededUriGrants needed) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07005013 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005014 "Checking URI perm to data=" + (intent != null ? intent.getData() : null)
5015 + " clip=" + (intent != null ? intent.getClipData() : null)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005016 + " from " + intent + "; flags=0x"
5017 + Integer.toHexString(intent != null ? intent.getFlags() : 0));
5018
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005019 if (targetPkg == null) {
5020 throw new NullPointerException("targetPkg");
5021 }
5022
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005023 if (intent == null) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005024 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005025 }
5026 Uri data = intent.getData();
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005027 ClipData clip = intent.getClipData();
5028 if (data == null && clip == null) {
5029 return null;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005030 }
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005031 if (data != null) {
5032 int target = checkGrantUriPermissionLocked(callingUid, targetPkg, data,
5033 mode, needed != null ? needed.targetUid : -1);
5034 if (target > 0) {
5035 if (needed == null) {
5036 needed = new NeededUriGrants(targetPkg, target, mode);
5037 }
5038 needed.add(data);
5039 }
5040 }
5041 if (clip != null) {
5042 for (int i=0; i<clip.getItemCount(); i++) {
5043 Uri uri = clip.getItemAt(i).getUri();
5044 if (uri != null) {
5045 int target = -1;
5046 target = checkGrantUriPermissionLocked(callingUid, targetPkg, uri,
5047 mode, needed != null ? needed.targetUid : -1);
5048 if (target > 0) {
5049 if (needed == null) {
5050 needed = new NeededUriGrants(targetPkg, target, mode);
5051 }
5052 needed.add(uri);
5053 }
5054 } else {
5055 Intent clipIntent = clip.getItemAt(i).getIntent();
5056 if (clipIntent != null) {
5057 NeededUriGrants newNeeded = checkGrantUriPermissionFromIntentLocked(
5058 callingUid, targetPkg, clipIntent, mode, needed);
5059 if (newNeeded != null) {
5060 needed = newNeeded;
5061 }
5062 }
5063 }
5064 }
5065 }
5066
5067 return needed;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005068 }
5069
5070 /**
5071 * Like grantUriPermissionUncheckedLocked, but takes an Intent.
5072 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005073 void grantUriPermissionUncheckedFromIntentLocked(NeededUriGrants needed,
5074 UriPermissionOwner owner) {
5075 if (needed != null) {
5076 for (int i=0; i<needed.size(); i++) {
5077 grantUriPermissionUncheckedLocked(needed.targetUid, needed.targetPkg,
5078 needed.get(i), needed.flags, owner);
5079 }
5080 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005081 }
5082
5083 void grantUriPermissionFromIntentLocked(int callingUid,
5084 String targetPkg, Intent intent, UriPermissionOwner owner) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005085 NeededUriGrants needed = checkGrantUriPermissionFromIntentLocked(callingUid, targetPkg,
Dianne Hackbornd9781fe2012-03-08 18:04:18 -08005086 intent, intent != null ? intent.getFlags() : 0, null);
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005087 if (needed == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005088 return;
5089 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005090
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005091 grantUriPermissionUncheckedFromIntentLocked(needed, owner);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005092 }
5093
5094 public void grantUriPermission(IApplicationThread caller, String targetPkg,
5095 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005096 enforceNotIsolatedCaller("grantUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005097 synchronized(this) {
5098 final ProcessRecord r = getRecordForAppLocked(caller);
5099 if (r == null) {
5100 throw new SecurityException("Unable to find app for caller "
5101 + caller
5102 + " when granting permission to uri " + uri);
5103 }
5104 if (targetPkg == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005105 throw new IllegalArgumentException("null target");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005106 }
5107 if (uri == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005108 throw new IllegalArgumentException("null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005109 }
5110
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005111 grantUriPermissionLocked(r.uid, targetPkg, uri, modeFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005112 null);
5113 }
5114 }
5115
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005116 void removeUriPermissionIfNeededLocked(UriPermission perm) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005117 if ((perm.modeFlags&(Intent.FLAG_GRANT_READ_URI_PERMISSION
5118 |Intent.FLAG_GRANT_WRITE_URI_PERMISSION)) == 0) {
5119 HashMap<Uri, UriPermission> perms
5120 = mGrantedUriPermissions.get(perm.uid);
5121 if (perms != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005122 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005123 "Removing " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005124 perms.remove(perm.uri);
5125 if (perms.size() == 0) {
5126 mGrantedUriPermissions.remove(perm.uid);
5127 }
5128 }
5129 }
5130 }
5131
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005132 private void revokeUriPermissionLocked(int callingUid, Uri uri,
5133 int modeFlags) {
5134 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5135 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5136 if (modeFlags == 0) {
5137 return;
5138 }
5139
Joe Onorato8a9b2202010-02-26 18:56:32 -08005140 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005141 "Revoking all granted permissions to " + uri);
5142
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005143 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005144
5145 final String authority = uri.getAuthority();
5146 ProviderInfo pi = null;
Amith Yamasani483f3b02012-03-13 16:08:00 -07005147 int userId = UserId.getUserId(callingUid);
5148 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005149 if (cpr != null) {
5150 pi = cpr.info;
5151 } else {
5152 try {
5153 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005154 PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005155 } catch (RemoteException ex) {
5156 }
5157 }
5158 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005159 Slog.w(TAG, "No content provider found for permission revoke: " + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005160 return;
5161 }
5162
5163 // Does the caller have this permission on the URI?
Dianne Hackborn48058e82010-09-27 16:53:23 -07005164 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005165 // Right now, if you are not the original owner of the permission,
5166 // you are not allowed to revoke it.
5167 //if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5168 throw new SecurityException("Uid " + callingUid
5169 + " does not have permission to uri " + uri);
5170 //}
5171 }
5172
5173 // Go through all of the permissions and remove any that match.
5174 final List<String> SEGMENTS = uri.getPathSegments();
5175 if (SEGMENTS != null) {
5176 final int NS = SEGMENTS.size();
5177 int N = mGrantedUriPermissions.size();
5178 for (int i=0; i<N; i++) {
5179 HashMap<Uri, UriPermission> perms
5180 = mGrantedUriPermissions.valueAt(i);
5181 Iterator<UriPermission> it = perms.values().iterator();
5182 toploop:
5183 while (it.hasNext()) {
5184 UriPermission perm = it.next();
5185 Uri targetUri = perm.uri;
5186 if (!authority.equals(targetUri.getAuthority())) {
5187 continue;
5188 }
5189 List<String> targetSegments = targetUri.getPathSegments();
5190 if (targetSegments == null) {
5191 continue;
5192 }
5193 if (targetSegments.size() < NS) {
5194 continue;
5195 }
5196 for (int j=0; j<NS; j++) {
5197 if (!SEGMENTS.get(j).equals(targetSegments.get(j))) {
5198 continue toploop;
5199 }
5200 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08005201 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005202 "Revoking " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005203 perm.clearModes(modeFlags);
5204 if (perm.modeFlags == 0) {
5205 it.remove();
5206 }
5207 }
5208 if (perms.size() == 0) {
5209 mGrantedUriPermissions.remove(
5210 mGrantedUriPermissions.keyAt(i));
5211 N--;
5212 i--;
5213 }
5214 }
5215 }
5216 }
5217
5218 public void revokeUriPermission(IApplicationThread caller, Uri uri,
5219 int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005220 enforceNotIsolatedCaller("revokeUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005221 synchronized(this) {
5222 final ProcessRecord r = getRecordForAppLocked(caller);
5223 if (r == null) {
5224 throw new SecurityException("Unable to find app for caller "
5225 + caller
5226 + " when revoking permission to uri " + uri);
5227 }
5228 if (uri == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005229 Slog.w(TAG, "revokeUriPermission: null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005230 return;
5231 }
5232
5233 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5234 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5235 if (modeFlags == 0) {
5236 return;
5237 }
5238
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005239 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005240
5241 final String authority = uri.getAuthority();
5242 ProviderInfo pi = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005243 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005244 if (cpr != null) {
5245 pi = cpr.info;
5246 } else {
5247 try {
5248 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005249 PackageManager.GET_URI_PERMISSION_PATTERNS, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005250 } catch (RemoteException ex) {
5251 }
5252 }
5253 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005254 Slog.w(TAG, "No content provider found for permission revoke: "
5255 + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005256 return;
5257 }
5258
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005259 revokeUriPermissionLocked(r.uid, uri, modeFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005260 }
5261 }
5262
Dianne Hackborn7e269642010-08-25 19:50:20 -07005263 @Override
5264 public IBinder newUriPermissionOwner(String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005265 enforceNotIsolatedCaller("newUriPermissionOwner");
Dianne Hackborn7e269642010-08-25 19:50:20 -07005266 synchronized(this) {
5267 UriPermissionOwner owner = new UriPermissionOwner(this, name);
5268 return owner.getExternalTokenLocked();
5269 }
5270 }
5271
5272 @Override
5273 public void grantUriPermissionFromOwner(IBinder token, int fromUid, String targetPkg,
5274 Uri uri, int modeFlags) {
5275 synchronized(this) {
5276 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5277 if (owner == null) {
5278 throw new IllegalArgumentException("Unknown owner: " + token);
5279 }
5280 if (fromUid != Binder.getCallingUid()) {
5281 if (Binder.getCallingUid() != Process.myUid()) {
5282 // Only system code can grant URI permissions on behalf
5283 // of other users.
5284 throw new SecurityException("nice try");
5285 }
5286 }
5287 if (targetPkg == null) {
5288 throw new IllegalArgumentException("null target");
5289 }
5290 if (uri == null) {
5291 throw new IllegalArgumentException("null uri");
5292 }
5293
5294 grantUriPermissionLocked(fromUid, targetPkg, uri, modeFlags, owner);
5295 }
5296 }
5297
5298 @Override
5299 public void revokeUriPermissionFromOwner(IBinder token, Uri uri, int mode) {
5300 synchronized(this) {
5301 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5302 if (owner == null) {
5303 throw new IllegalArgumentException("Unknown owner: " + token);
5304 }
5305
5306 if (uri == null) {
5307 owner.removeUriPermissionsLocked(mode);
5308 } else {
5309 owner.removeUriPermissionLocked(uri, mode);
5310 }
5311 }
5312 }
5313
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005314 public void showWaitingForDebugger(IApplicationThread who, boolean waiting) {
5315 synchronized (this) {
5316 ProcessRecord app =
5317 who != null ? getRecordForAppLocked(who) : null;
5318 if (app == null) return;
5319
5320 Message msg = Message.obtain();
5321 msg.what = WAIT_FOR_DEBUGGER_MSG;
5322 msg.obj = app;
5323 msg.arg1 = waiting ? 1 : 0;
5324 mHandler.sendMessage(msg);
5325 }
5326 }
5327
5328 public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07005329 final long homeAppMem = mProcessList.getMemLevel(ProcessList.HOME_APP_ADJ);
5330 final long hiddenAppMem = mProcessList.getMemLevel(ProcessList.HIDDEN_APP_MIN_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005331 outInfo.availMem = Process.getFreeMemory();
Dianne Hackborn7d608422011-08-07 16:24:18 -07005332 outInfo.threshold = homeAppMem;
5333 outInfo.lowMemory = outInfo.availMem < (homeAppMem + ((hiddenAppMem-homeAppMem)/2));
5334 outInfo.hiddenAppThreshold = hiddenAppMem;
5335 outInfo.secondaryServerThreshold = mProcessList.getMemLevel(
Dianne Hackborne02c88a2011-10-28 13:58:15 -07005336 ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07005337 outInfo.visibleAppThreshold = mProcessList.getMemLevel(
5338 ProcessList.VISIBLE_APP_ADJ);
5339 outInfo.foregroundAppThreshold = mProcessList.getMemLevel(
5340 ProcessList.FOREGROUND_APP_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005341 }
5342
5343 // =========================================================
5344 // TASK MANAGEMENT
5345 // =========================================================
5346
5347 public List getTasks(int maxNum, int flags,
5348 IThumbnailReceiver receiver) {
5349 ArrayList list = new ArrayList();
5350
5351 PendingThumbnailsRecord pending = null;
5352 IApplicationThread topThumbnail = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005353 ActivityRecord topRecord = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005354
5355 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005356 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005357 TAG, "getTasks: max=" + maxNum + ", flags=" + flags
5358 + ", receiver=" + receiver);
5359
5360 if (checkCallingPermission(android.Manifest.permission.GET_TASKS)
5361 != PackageManager.PERMISSION_GRANTED) {
5362 if (receiver != null) {
5363 // If the caller wants to wait for pending thumbnails,
5364 // it ain't gonna get them.
5365 try {
5366 receiver.finished();
5367 } catch (RemoteException ex) {
5368 }
5369 }
5370 String msg = "Permission Denial: getTasks() from pid="
5371 + Binder.getCallingPid()
5372 + ", uid=" + Binder.getCallingUid()
5373 + " requires " + android.Manifest.permission.GET_TASKS;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005374 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005375 throw new SecurityException(msg);
5376 }
5377
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005378 int pos = mMainStack.mHistory.size()-1;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005379 ActivityRecord next =
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005380 pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005381 ActivityRecord top = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005382 TaskRecord curTask = null;
5383 int numActivities = 0;
5384 int numRunning = 0;
5385 while (pos >= 0 && maxNum > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005386 final ActivityRecord r = next;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005387 pos--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005388 next = pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005389
5390 // Initialize state for next task if needed.
5391 if (top == null ||
5392 (top.state == ActivityState.INITIALIZING
5393 && top.task == r.task)) {
5394 top = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005395 curTask = r.task;
5396 numActivities = numRunning = 0;
5397 }
5398
5399 // Add 'r' into the current task.
5400 numActivities++;
5401 if (r.app != null && r.app.thread != null) {
5402 numRunning++;
5403 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005404
Joe Onorato8a9b2202010-02-26 18:56:32 -08005405 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005406 TAG, r.intent.getComponent().flattenToShortString()
5407 + ": task=" + r.task);
5408
5409 // If the next one is a different task, generate a new
5410 // TaskInfo entry for what we have.
5411 if (next == null || next.task != curTask) {
5412 ActivityManager.RunningTaskInfo ci
5413 = new ActivityManager.RunningTaskInfo();
5414 ci.id = curTask.taskId;
5415 ci.baseActivity = r.intent.getComponent();
5416 ci.topActivity = top.intent.getComponent();
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005417 if (top.thumbHolder != null) {
5418 ci.description = top.thumbHolder.lastDescription;
5419 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005420 ci.numActivities = numActivities;
5421 ci.numRunning = numRunning;
5422 //System.out.println(
5423 // "#" + maxNum + ": " + " descr=" + ci.description);
5424 if (ci.thumbnail == null && receiver != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005425 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005426 TAG, "State=" + top.state + "Idle=" + top.idle
5427 + " app=" + top.app
5428 + " thr=" + (top.app != null ? top.app.thread : null));
5429 if (top.state == ActivityState.RESUMED
5430 || top.state == ActivityState.PAUSING) {
5431 if (top.idle && top.app != null
5432 && top.app.thread != null) {
5433 topRecord = top;
5434 topThumbnail = top.app.thread;
5435 } else {
5436 top.thumbnailNeeded = true;
5437 }
5438 }
5439 if (pending == null) {
5440 pending = new PendingThumbnailsRecord(receiver);
5441 }
5442 pending.pendingRecords.add(top);
5443 }
5444 list.add(ci);
5445 maxNum--;
5446 top = null;
5447 }
5448 }
5449
5450 if (pending != null) {
5451 mPendingThumbnails.add(pending);
5452 }
5453 }
5454
Joe Onorato8a9b2202010-02-26 18:56:32 -08005455 if (localLOGV) Slog.v(TAG, "We have pending thumbnails: " + pending);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005456
5457 if (topThumbnail != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005458 if (localLOGV) Slog.v(TAG, "Requesting top thumbnail");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005459 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08005460 topThumbnail.requestThumbnail(topRecord.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005461 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005462 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005463 sendPendingThumbnail(null, topRecord.appToken, null, null, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005464 }
5465 }
5466
5467 if (pending == null && receiver != null) {
5468 // In this case all thumbnails were available and the client
5469 // is being asked to be told when the remaining ones come in...
5470 // which is unusually, since the top-most currently running
5471 // activity should never have a canned thumbnail! Oh well.
5472 try {
5473 receiver.finished();
5474 } catch (RemoteException ex) {
5475 }
5476 }
5477
5478 return list;
5479 }
5480
5481 public List<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum,
5482 int flags) {
Amith Yamasani742a6712011-05-04 14:49:28 -07005483 final int callingUid = Binder.getCallingUid();
5484 // If it's the system uid asking, then use the current user id.
5485 // TODO: Make sure that there aren't any other legitimate calls from the system uid that
5486 // require the entire list.
5487 final int callingUserId = callingUid == Process.SYSTEM_UID
5488 ? mCurrentUserId : UserId.getUserId(callingUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005489 synchronized (this) {
5490 enforceCallingPermission(android.Manifest.permission.GET_TASKS,
5491 "getRecentTasks()");
5492
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005493 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005494
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005495 final int N = mRecentTasks.size();
5496 ArrayList<ActivityManager.RecentTaskInfo> res
5497 = new ArrayList<ActivityManager.RecentTaskInfo>(
5498 maxNum < N ? maxNum : N);
5499 for (int i=0; i<N && maxNum > 0; i++) {
5500 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005501 // Only add calling user's recent tasks
5502 if (tr.userId != callingUserId) continue;
Dianne Hackborn905577f2011-09-07 18:31:28 -07005503 // Return the entry if desired by the caller. We always return
5504 // the first entry, because callers always expect this to be the
Amith Yamasani742a6712011-05-04 14:49:28 -07005505 // foreground app. We may filter others if the caller has
Dianne Hackborn905577f2011-09-07 18:31:28 -07005506 // not supplied RECENT_WITH_EXCLUDED and there is some reason
5507 // we should exclude the entry.
Amith Yamasani742a6712011-05-04 14:49:28 -07005508
Dianne Hackborn905577f2011-09-07 18:31:28 -07005509 if (i == 0
5510 || ((flags&ActivityManager.RECENT_WITH_EXCLUDED) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005511 || (tr.intent == null)
5512 || ((tr.intent.getFlags()
5513 &Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) == 0)) {
5514 ActivityManager.RecentTaskInfo rti
5515 = new ActivityManager.RecentTaskInfo();
5516 rti.id = tr.numActivities > 0 ? tr.taskId : -1;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005517 rti.persistentId = tr.taskId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005518 rti.baseIntent = new Intent(
5519 tr.intent != null ? tr.intent : tr.affinityIntent);
5520 rti.origActivity = tr.origActivity;
Dianne Hackbornd2835932010-12-13 16:28:46 -08005521 rti.description = tr.lastDescription;
5522
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005523 if ((flags&ActivityManager.RECENT_IGNORE_UNAVAILABLE) != 0) {
5524 // Check whether this activity is currently available.
5525 try {
5526 if (rti.origActivity != null) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07005527 if (pm.getActivityInfo(rti.origActivity, 0, callingUserId)
5528 == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005529 continue;
5530 }
5531 } else if (rti.baseIntent != null) {
5532 if (pm.queryIntentActivities(rti.baseIntent,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005533 null, 0, callingUserId) == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005534 continue;
5535 }
5536 }
5537 } catch (RemoteException e) {
5538 // Will never happen.
5539 }
5540 }
5541
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005542 res.add(rti);
5543 maxNum--;
5544 }
5545 }
5546 return res;
5547 }
5548 }
5549
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005550 private TaskRecord taskForIdLocked(int id) {
5551 final int N = mRecentTasks.size();
5552 for (int i=0; i<N; i++) {
5553 TaskRecord tr = mRecentTasks.get(i);
5554 if (tr.taskId == id) {
5555 return tr;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005556 }
5557 }
5558 return null;
5559 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005560
5561 public ActivityManager.TaskThumbnails getTaskThumbnails(int id) {
5562 synchronized (this) {
5563 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
5564 "getTaskThumbnails()");
5565 TaskRecord tr = taskForIdLocked(id);
5566 if (tr != null) {
5567 return mMainStack.getTaskThumbnailsLocked(tr);
5568 }
5569 }
5570 return null;
5571 }
5572
5573 public boolean removeSubTask(int taskId, int subTaskIndex) {
5574 synchronized (this) {
5575 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5576 "removeSubTask()");
5577 long ident = Binder.clearCallingIdentity();
5578 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005579 return mMainStack.removeTaskActivitiesLocked(taskId, subTaskIndex,
5580 true) != null;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005581 } finally {
5582 Binder.restoreCallingIdentity(ident);
5583 }
5584 }
5585 }
5586
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005587 private void cleanUpRemovedTaskLocked(TaskRecord tr, int flags) {
5588 final boolean killProcesses = (flags&ActivityManager.REMOVE_TASK_KILL_PROCESS) != 0;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005589 Intent baseIntent = new Intent(
5590 tr.intent != null ? tr.intent : tr.affinityIntent);
5591 ComponentName component = baseIntent.getComponent();
5592 if (component == null) {
5593 Slog.w(TAG, "Now component for base intent of task: " + tr);
5594 return;
5595 }
5596
5597 // Find any running services associated with this app.
5598 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005599 for (ServiceRecord sr : mServiceMap.getAllServices(tr.userId)) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005600 if (sr.packageName.equals(component.getPackageName())) {
5601 services.add(sr);
5602 }
5603 }
5604
5605 // Take care of any running services associated with the app.
5606 for (int i=0; i<services.size(); i++) {
5607 ServiceRecord sr = services.get(i);
5608 if (sr.startRequested) {
5609 if ((sr.serviceInfo.flags&ServiceInfo.FLAG_STOP_WITH_TASK) != 0) {
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005610 Slog.i(TAG, "Stopping service " + sr.shortName + ": remove task");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005611 stopServiceLocked(sr);
5612 } else {
5613 sr.pendingStarts.add(new ServiceRecord.StartItem(sr, true,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005614 sr.makeNextStartId(), baseIntent, null));
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005615 if (sr.app != null && sr.app.thread != null) {
5616 sendServiceArgsLocked(sr, false);
5617 }
5618 }
5619 }
5620 }
5621
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005622 if (killProcesses) {
5623 // Find any running processes associated with this app.
5624 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
5625 SparseArray<ProcessRecord> appProcs
5626 = mProcessNames.getMap().get(component.getPackageName());
5627 if (appProcs != null) {
5628 for (int i=0; i<appProcs.size(); i++) {
5629 procs.add(appProcs.valueAt(i));
5630 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005631 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005632
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005633 // Kill the running processes.
5634 for (int i=0; i<procs.size(); i++) {
5635 ProcessRecord pr = procs.get(i);
5636 if (pr.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
5637 Slog.i(TAG, "Killing " + pr.toShortString() + ": remove task");
5638 EventLog.writeEvent(EventLogTags.AM_KILL, pr.pid,
5639 pr.processName, pr.setAdj, "remove task");
5640 Process.killProcessQuiet(pr.pid);
5641 } else {
5642 pr.waitingToKill = "remove task";
5643 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005644 }
5645 }
5646 }
5647
5648 public boolean removeTask(int taskId, int flags) {
5649 synchronized (this) {
5650 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5651 "removeTask()");
5652 long ident = Binder.clearCallingIdentity();
5653 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005654 ActivityRecord r = mMainStack.removeTaskActivitiesLocked(taskId, -1,
5655 false);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005656 if (r != null) {
5657 mRecentTasks.remove(r.task);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005658 cleanUpRemovedTaskLocked(r.task, flags);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005659 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005660 } else {
5661 TaskRecord tr = null;
5662 int i=0;
5663 while (i < mRecentTasks.size()) {
5664 TaskRecord t = mRecentTasks.get(i);
5665 if (t.taskId == taskId) {
5666 tr = t;
5667 break;
5668 }
5669 i++;
5670 }
5671 if (tr != null) {
5672 if (tr.numActivities <= 0) {
5673 // Caller is just removing a recent task that is
5674 // not actively running. That is easy!
5675 mRecentTasks.remove(i);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005676 cleanUpRemovedTaskLocked(tr, flags);
5677 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005678 } else {
5679 Slog.w(TAG, "removeTask: task " + taskId
5680 + " does not have activities to remove, "
5681 + " but numActivities=" + tr.numActivities
5682 + ": " + tr);
5683 }
5684 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005685 }
5686 } finally {
5687 Binder.restoreCallingIdentity(ident);
5688 }
5689 }
5690 return false;
5691 }
Dianne Hackbornd94df452011-02-16 18:53:31 -08005692
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005693 private final int findAffinityTaskTopLocked(int startIndex, String affinity) {
5694 int j;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005695 TaskRecord startTask = ((ActivityRecord)mMainStack.mHistory.get(startIndex)).task;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005696 TaskRecord jt = startTask;
5697
5698 // First look backwards
5699 for (j=startIndex-1; j>=0; j--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005700 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005701 if (r.task != jt) {
5702 jt = r.task;
5703 if (affinity.equals(jt.affinity)) {
5704 return j;
5705 }
5706 }
5707 }
5708
5709 // Now look forwards
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005710 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005711 jt = startTask;
5712 for (j=startIndex+1; j<N; j++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005713 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005714 if (r.task != jt) {
5715 if (affinity.equals(jt.affinity)) {
5716 return j;
5717 }
5718 jt = r.task;
5719 }
5720 }
5721
5722 // Might it be at the top?
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005723 if (affinity.equals(((ActivityRecord)mMainStack.mHistory.get(N-1)).task.affinity)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005724 return N-1;
5725 }
5726
5727 return -1;
5728 }
5729
5730 /**
Dianne Hackbornb06ea702009-07-13 13:07:51 -07005731 * TODO: Add mController hook
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005732 */
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005733 public void moveTaskToFront(int task, int flags, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005734 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5735 "moveTaskToFront()");
5736
5737 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005738 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5739 Binder.getCallingUid(), "Task to front")) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005740 ActivityOptions.abort(options);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005741 return;
5742 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005743 final long origId = Binder.clearCallingIdentity();
5744 try {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005745 TaskRecord tr = taskForIdLocked(task);
5746 if (tr != null) {
5747 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5748 mMainStack.mUserLeaving = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005749 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005750 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5751 // Caller wants the home activity moved with it. To accomplish this,
5752 // we'll just move the home task to the top first.
5753 mMainStack.moveHomeToFrontLocked();
5754 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005755 mMainStack.moveTaskToFrontLocked(tr, null, options);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005756 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005757 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005758 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
5759 ActivityRecord hr = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005760 if (hr.task.taskId == task) {
Dianne Hackbornd94df452011-02-16 18:53:31 -08005761 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5762 mMainStack.mUserLeaving = true;
5763 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005764 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5765 // Caller wants the home activity moved with it. To accomplish this,
5766 // we'll just move the home task to the top first.
5767 mMainStack.moveHomeToFrontLocked();
5768 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005769 mMainStack.moveTaskToFrontLocked(hr.task, null, options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005770 return;
5771 }
5772 }
5773 } finally {
5774 Binder.restoreCallingIdentity(origId);
5775 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005776 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005777 }
5778 }
5779
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005780 public void moveTaskToBack(int task) {
5781 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5782 "moveTaskToBack()");
5783
5784 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005785 if (mMainStack.mResumedActivity != null
5786 && mMainStack.mResumedActivity.task.taskId == task) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005787 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5788 Binder.getCallingUid(), "Task to back")) {
5789 return;
5790 }
5791 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005792 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005793 mMainStack.moveTaskToBackLocked(task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005794 Binder.restoreCallingIdentity(origId);
5795 }
5796 }
5797
5798 /**
5799 * Moves an activity, and all of the other activities within the same task, to the bottom
5800 * of the history stack. The activity's order within the task is unchanged.
5801 *
5802 * @param token A reference to the activity we wish to move
5803 * @param nonRoot If false then this only works if the activity is the root
5804 * of a task; if true it will work for any activity in a task.
5805 * @return Returns true if the move completed, false if not.
5806 */
5807 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005808 enforceNotIsolatedCaller("moveActivityTaskToBack");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005809 synchronized(this) {
5810 final long origId = Binder.clearCallingIdentity();
5811 int taskId = getTaskForActivityLocked(token, !nonRoot);
5812 if (taskId >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005813 return mMainStack.moveTaskToBackLocked(taskId, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005814 }
5815 Binder.restoreCallingIdentity(origId);
5816 }
5817 return false;
5818 }
5819
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005820 public void moveTaskBackwards(int task) {
5821 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5822 "moveTaskBackwards()");
5823
5824 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005825 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5826 Binder.getCallingUid(), "Task backwards")) {
5827 return;
5828 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005829 final long origId = Binder.clearCallingIdentity();
5830 moveTaskBackwardsLocked(task);
5831 Binder.restoreCallingIdentity(origId);
5832 }
5833 }
5834
5835 private final void moveTaskBackwardsLocked(int task) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005836 Slog.e(TAG, "moveTaskBackwards not yet implemented!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005837 }
5838
5839 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
5840 synchronized(this) {
5841 return getTaskForActivityLocked(token, onlyRoot);
5842 }
5843 }
5844
5845 int getTaskForActivityLocked(IBinder token, boolean onlyRoot) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005846 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005847 TaskRecord lastTask = null;
5848 for (int i=0; i<N; i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005849 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005850 if (r.appToken == token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005851 if (!onlyRoot || lastTask != r.task) {
5852 return r.task.taskId;
5853 }
5854 return -1;
5855 }
5856 lastTask = r.task;
5857 }
5858
5859 return -1;
5860 }
5861
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005862 // =========================================================
5863 // THUMBNAILS
5864 // =========================================================
5865
5866 public void reportThumbnail(IBinder token,
5867 Bitmap thumbnail, CharSequence description) {
5868 //System.out.println("Report thumbnail for " + token + ": " + thumbnail);
5869 final long origId = Binder.clearCallingIdentity();
5870 sendPendingThumbnail(null, token, thumbnail, description, true);
5871 Binder.restoreCallingIdentity(origId);
5872 }
5873
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005874 final void sendPendingThumbnail(ActivityRecord r, IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005875 Bitmap thumbnail, CharSequence description, boolean always) {
5876 TaskRecord task = null;
5877 ArrayList receivers = null;
5878
5879 //System.out.println("Send pending thumbnail: " + r);
5880
5881 synchronized(this) {
5882 if (r == null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07005883 r = mMainStack.isInStackLocked(token);
5884 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005885 return;
5886 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005887 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005888 if (thumbnail == null && r.thumbHolder != null) {
5889 thumbnail = r.thumbHolder.lastThumbnail;
5890 description = r.thumbHolder.lastDescription;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005891 }
5892 if (thumbnail == null && !always) {
5893 // If there is no thumbnail, and this entry is not actually
5894 // going away, then abort for now and pick up the next
5895 // thumbnail we get.
5896 return;
5897 }
5898 task = r.task;
5899
5900 int N = mPendingThumbnails.size();
5901 int i=0;
5902 while (i<N) {
5903 PendingThumbnailsRecord pr =
5904 (PendingThumbnailsRecord)mPendingThumbnails.get(i);
5905 //System.out.println("Looking in " + pr.pendingRecords);
5906 if (pr.pendingRecords.remove(r)) {
5907 if (receivers == null) {
5908 receivers = new ArrayList();
5909 }
5910 receivers.add(pr);
5911 if (pr.pendingRecords.size() == 0) {
5912 pr.finished = true;
5913 mPendingThumbnails.remove(i);
5914 N--;
5915 continue;
5916 }
5917 }
5918 i++;
5919 }
5920 }
5921
5922 if (receivers != null) {
5923 final int N = receivers.size();
5924 for (int i=0; i<N; i++) {
5925 try {
5926 PendingThumbnailsRecord pr =
5927 (PendingThumbnailsRecord)receivers.get(i);
5928 pr.receiver.newThumbnail(
5929 task != null ? task.taskId : -1, thumbnail, description);
5930 if (pr.finished) {
5931 pr.receiver.finished();
5932 }
5933 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005934 Slog.w(TAG, "Exception thrown when sending thumbnail", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005935 }
5936 }
5937 }
5938 }
5939
5940 // =========================================================
5941 // CONTENT PROVIDERS
5942 // =========================================================
5943
Jeff Brown10e89712011-07-08 18:52:57 -07005944 private final List<ProviderInfo> generateApplicationProvidersLocked(ProcessRecord app) {
5945 List<ProviderInfo> providers = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005946 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005947 providers = AppGlobals.getPackageManager().
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005948 queryContentProviders(app.processName, app.uid,
Dianne Hackborn1655be42009-05-08 14:29:01 -07005949 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005950 } catch (RemoteException ex) {
5951 }
Amith Yamasani742a6712011-05-04 14:49:28 -07005952 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005953 Slog.v(TAG_MU, "generateApplicationProvidersLocked, app.info.uid = " + app.uid);
5954 int userId = app.userId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005955 if (providers != null) {
5956 final int N = providers.size();
5957 for (int i=0; i<N; i++) {
5958 ProviderInfo cpi =
5959 (ProviderInfo)providers.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005960
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07005961 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07005962 ContentProviderRecord cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005963 if (cpr == null) {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08005964 cpr = new ContentProviderRecord(this, cpi, app.info, comp);
Amith Yamasani742a6712011-05-04 14:49:28 -07005965 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005966 }
Amith Yamasani742a6712011-05-04 14:49:28 -07005967 if (DEBUG_MU)
5968 Slog.v(TAG_MU, "generateApplicationProvidersLocked, cpi.uid = " + cpr.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005969 app.pubProviders.put(cpi.name, cpr);
5970 app.addPackage(cpi.applicationInfo.packageName);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07005971 ensurePackageDexOpt(cpi.applicationInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005972 }
5973 }
5974 return providers;
5975 }
5976
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005977 /**
5978 * Check if {@link ProcessRecord} has a possible chance at accessing the
5979 * given {@link ProviderInfo}. Final permission checking is always done
5980 * in {@link ContentProvider}.
5981 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005982 private final String checkContentProviderPermissionLocked(
Dianne Hackbornb424b632010-08-18 15:59:05 -07005983 ProviderInfo cpi, ProcessRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005984 final int callingPid = (r != null) ? r.pid : Binder.getCallingPid();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005985 final int callingUid = (r != null) ? r.uid : Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005986 if (checkComponentPermission(cpi.readPermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005987 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005988 == PackageManager.PERMISSION_GRANTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005989 return null;
5990 }
5991 if (checkComponentPermission(cpi.writePermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005992 cpi.applicationInfo.uid, cpi.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005993 == PackageManager.PERMISSION_GRANTED) {
5994 return null;
5995 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07005996
5997 PathPermission[] pps = cpi.pathPermissions;
5998 if (pps != null) {
5999 int i = pps.length;
6000 while (i > 0) {
6001 i--;
6002 PathPermission pp = pps[i];
6003 if (checkComponentPermission(pp.getReadPermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006004 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006005 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006006 return null;
6007 }
6008 if (checkComponentPermission(pp.getWritePermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006009 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006010 == PackageManager.PERMISSION_GRANTED) {
6011 return null;
6012 }
6013 }
6014 }
6015
Dianne Hackbornb424b632010-08-18 15:59:05 -07006016 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(callingUid);
6017 if (perms != null) {
6018 for (Map.Entry<Uri, UriPermission> uri : perms.entrySet()) {
6019 if (uri.getKey().getAuthority().equals(cpi.authority)) {
6020 return null;
6021 }
6022 }
6023 }
6024
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006025 String msg;
6026 if (!cpi.exported) {
6027 msg = "Permission Denial: opening provider " + cpi.name
6028 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6029 + ", uid=" + callingUid + ") that is not exported from uid "
6030 + cpi.applicationInfo.uid;
6031 } else {
6032 msg = "Permission Denial: opening provider " + cpi.name
6033 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6034 + ", uid=" + callingUid + ") requires "
6035 + cpi.readPermission + " or " + cpi.writePermission;
6036 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08006037 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006038 return msg;
6039 }
6040
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006041 boolean incProviderCount(ProcessRecord r, final ContentProviderRecord cpr,
6042 IBinder externalProcessToken) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006043 if (r != null) {
6044 Integer cnt = r.conProviders.get(cpr);
6045 if (DEBUG_PROVIDER) Slog.v(TAG,
6046 "Adding provider requested by "
6047 + r.processName + " from process "
6048 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
6049 + " cnt=" + (cnt == null ? 1 : cnt));
6050 if (cnt == null) {
6051 cpr.clients.add(r);
6052 r.conProviders.put(cpr, new Integer(1));
6053 return true;
6054 } else {
6055 r.conProviders.put(cpr, new Integer(cnt.intValue()+1));
6056 }
6057 } else {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006058 cpr.addExternalProcessHandleLocked(externalProcessToken);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006059 }
6060 return false;
6061 }
6062
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006063 boolean decProviderCount(ProcessRecord r, final ContentProviderRecord cpr,
6064 IBinder externalProcessToken) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006065 if (r != null) {
6066 Integer cnt = r.conProviders.get(cpr);
6067 if (DEBUG_PROVIDER) Slog.v(TAG,
6068 "Removing provider requested by "
6069 + r.processName + " from process "
6070 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
6071 + " cnt=" + cnt);
6072 if (cnt == null || cnt.intValue() <= 1) {
6073 cpr.clients.remove(r);
6074 r.conProviders.remove(cpr);
6075 return true;
6076 } else {
6077 r.conProviders.put(cpr, new Integer(cnt.intValue()-1));
6078 }
6079 } else {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006080 cpr.removeExternalProcessHandleLocked(externalProcessToken);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006081 }
6082 return false;
6083 }
6084
Amith Yamasani742a6712011-05-04 14:49:28 -07006085 private final ContentProviderHolder getContentProviderImpl(IApplicationThread caller,
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006086 String name, IBinder token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006087 ContentProviderRecord cpr;
6088 ProviderInfo cpi = null;
6089
6090 synchronized(this) {
6091 ProcessRecord r = null;
6092 if (caller != null) {
6093 r = getRecordForAppLocked(caller);
6094 if (r == null) {
6095 throw new SecurityException(
6096 "Unable to find app for caller " + caller
6097 + " (pid=" + Binder.getCallingPid()
6098 + ") when getting content provider " + name);
6099 }
6100 }
6101
6102 // First check if this content provider has been published...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006103 int userId = UserId.getUserId(r != null ? r.uid : Binder.getCallingUid());
Amith Yamasani742a6712011-05-04 14:49:28 -07006104 cpr = mProviderMap.getProviderByName(name, userId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006105 boolean providerRunning = cpr != null;
6106 if (providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006107 cpi = cpr.info;
Dianne Hackbornb424b632010-08-18 15:59:05 -07006108 String msg;
6109 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6110 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006111 }
6112
6113 if (r != null && cpr.canRunHere(r)) {
6114 // This provider has been published or is in the process
6115 // of being published... but it is also allowed to run
6116 // in the caller's process, so don't make a connection
6117 // and just let the caller instantiate its own instance.
6118 if (cpr.provider != null) {
6119 // don't give caller the provider object, it needs
6120 // to make its own.
6121 cpr = new ContentProviderRecord(cpr);
6122 }
6123 return cpr;
6124 }
6125
6126 final long origId = Binder.clearCallingIdentity();
6127
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006128 // In this case the provider instance already exists, so we can
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006129 // return it right away.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006130 final boolean countChanged = incProviderCount(r, cpr, token);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006131 if (countChanged) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006132 if (cpr.proc != null && r.setAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006133 // If this is a perceptible app accessing the provider,
Dianne Hackborn906497c2010-05-10 15:57:38 -07006134 // make sure to count it as being accessed and thus
6135 // back up on the LRU list. This is good because
6136 // content providers are often expensive to start.
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006137 updateLruProcessLocked(cpr.proc, false, true);
Dianne Hackborn906497c2010-05-10 15:57:38 -07006138 }
Dianne Hackborn6f86c0e2010-05-11 14:20:52 -07006139 }
6140
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006141 if (cpr.proc != null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006142 if (false) {
6143 if (cpr.name.flattenToShortString().equals(
6144 "com.android.providers.calendar/.CalendarProvider2")) {
6145 Slog.v(TAG, "****************** KILLING "
6146 + cpr.name.flattenToShortString());
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006147 Process.killProcess(cpr.proc.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006148 }
6149 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006150 boolean success = updateOomAdjLocked(cpr.proc);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006151 if (DEBUG_PROVIDER) Slog.i(TAG, "Adjust success: " + success);
6152 // NOTE: there is still a race here where a signal could be
6153 // pending on the process even though we managed to update its
6154 // adj level. Not sure what to do about this, but at least
6155 // the race is now smaller.
6156 if (!success) {
6157 // Uh oh... it looks like the provider's process
6158 // has been killed on us. We need to wait for a new
6159 // process to be started, and make sure its death
6160 // doesn't kill our process.
6161 Slog.i(TAG,
6162 "Existing provider " + cpr.name.flattenToShortString()
6163 + " is crashing; detaching " + r);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006164 boolean lastRef = decProviderCount(r, cpr, token);
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006165 appDiedLocked(cpr.proc, cpr.proc.pid, cpr.proc.thread);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006166 if (!lastRef) {
6167 // This wasn't the last ref our process had on
6168 // the provider... we have now been killed, bail.
6169 return null;
6170 }
6171 providerRunning = false;
6172 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006173 }
6174
6175 Binder.restoreCallingIdentity(origId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006176 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006177
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006178 if (!providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006179 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006180 cpi = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07006181 resolveContentProvider(name,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006182 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006183 } catch (RemoteException ex) {
6184 }
6185 if (cpi == null) {
6186 return null;
6187 }
Amith Yamasania4a54e22012-04-16 15:44:19 -07006188 if (isSingleton(cpi.processName, cpi.applicationInfo)) {
6189 userId = 0;
6190 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006191 cpi.applicationInfo = getAppInfoForUser(cpi.applicationInfo, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07006192
Dianne Hackbornb424b632010-08-18 15:59:05 -07006193 String msg;
6194 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6195 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006196 }
6197
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07006198 if (!mProcessesReady && !mDidUpdate && !mWaitingUpdate
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006199 && !cpi.processName.equals("system")) {
6200 // If this content provider does not run in the system
6201 // process, and the system is not yet ready to run other
6202 // processes, then fail fast instead of hanging.
6203 throw new IllegalArgumentException(
6204 "Attempt to launch content provider before system ready");
6205 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006206
6207 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani483f3b02012-03-13 16:08:00 -07006208 cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006209 final boolean firstClass = cpr == null;
6210 if (firstClass) {
6211 try {
6212 ApplicationInfo ai =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006213 AppGlobals.getPackageManager().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006214 getApplicationInfo(
6215 cpi.applicationInfo.packageName,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006216 STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006217 if (ai == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006218 Slog.w(TAG, "No package info for content provider "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006219 + cpi.name);
6220 return null;
6221 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006222 ai = getAppInfoForUser(ai, userId);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006223 cpr = new ContentProviderRecord(this, cpi, ai, comp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006224 } catch (RemoteException ex) {
6225 // pm is in same process, this will never happen.
6226 }
6227 }
6228
6229 if (r != null && cpr.canRunHere(r)) {
6230 // If this is a multiprocess provider, then just return its
6231 // info and allow the caller to instantiate it. Only do
6232 // this if the provider is the same user as the caller's
6233 // process, or can run as root (so can be in any process).
6234 return cpr;
6235 }
6236
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006237 if (DEBUG_PROVIDER) {
6238 RuntimeException e = new RuntimeException("here");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006239 Slog.w(TAG, "LAUNCHING REMOTE PROVIDER (myuid " + r.uid
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006240 + " pruid " + cpr.appInfo.uid + "): " + cpr.info.name, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006241 }
6242
6243 // This is single process, and our app is now connecting to it.
6244 // See if we are already in the process of launching this
6245 // provider.
6246 final int N = mLaunchingProviders.size();
6247 int i;
6248 for (i=0; i<N; i++) {
6249 if (mLaunchingProviders.get(i) == cpr) {
6250 break;
6251 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006252 }
6253
6254 // If the provider is not already being launched, then get it
6255 // started.
6256 if (i >= N) {
6257 final long origId = Binder.clearCallingIdentity();
Dianne Hackborne7f97212011-02-24 14:40:20 -08006258
6259 try {
6260 // Content provider is now in use, its package can't be stopped.
6261 try {
6262 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07006263 cpr.appInfo.packageName, false, userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006264 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006265 } catch (IllegalArgumentException e) {
6266 Slog.w(TAG, "Failed trying to unstop package "
6267 + cpr.appInfo.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006268 }
6269
6270 ProcessRecord proc = startProcessLocked(cpi.processName,
6271 cpr.appInfo, false, 0, "content provider",
6272 new ComponentName(cpi.applicationInfo.packageName,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006273 cpi.name), false, false);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006274 if (proc == null) {
6275 Slog.w(TAG, "Unable to launch app "
6276 + cpi.applicationInfo.packageName + "/"
6277 + cpi.applicationInfo.uid + " for provider "
6278 + name + ": process is bad");
6279 return null;
6280 }
6281 cpr.launchingApp = proc;
6282 mLaunchingProviders.add(cpr);
6283 } finally {
6284 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006285 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006286 }
6287
6288 // Make sure the provider is published (the same provider class
6289 // may be published under multiple names).
6290 if (firstClass) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006291 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006292 }
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006293
Amith Yamasani742a6712011-05-04 14:49:28 -07006294 mProviderMap.putProviderByName(name, cpr);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006295 incProviderCount(r, cpr, token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006296 }
6297 }
6298
6299 // Wait for the provider to be published...
6300 synchronized (cpr) {
6301 while (cpr.provider == null) {
6302 if (cpr.launchingApp == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006303 Slog.w(TAG, "Unable to launch app "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006304 + cpi.applicationInfo.packageName + "/"
6305 + cpi.applicationInfo.uid + " for provider "
6306 + name + ": launching app became null");
Doug Zongker2bec3d42009-12-04 12:52:44 -08006307 EventLog.writeEvent(EventLogTags.AM_PROVIDER_LOST_PROCESS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006308 cpi.applicationInfo.packageName,
6309 cpi.applicationInfo.uid, name);
6310 return null;
6311 }
6312 try {
Amith Yamasani742a6712011-05-04 14:49:28 -07006313 if (DEBUG_MU) {
6314 Slog.v(TAG_MU, "Waiting to start provider " + cpr + " launchingApp="
6315 + cpr.launchingApp);
6316 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006317 cpr.wait();
6318 } catch (InterruptedException ex) {
6319 }
6320 }
6321 }
6322 return cpr;
6323 }
6324
6325 public final ContentProviderHolder getContentProvider(
6326 IApplicationThread caller, String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006327 enforceNotIsolatedCaller("getContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006328 if (caller == null) {
6329 String msg = "null IApplicationThread when getting content provider "
6330 + name;
Joe Onorato8a9b2202010-02-26 18:56:32 -08006331 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006332 throw new SecurityException(msg);
6333 }
6334
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006335 return getContentProviderImpl(caller, name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006336 }
6337
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006338 public ContentProviderHolder getContentProviderExternal(String name, IBinder token) {
6339 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6340 "Do not have permission in call getContentProviderExternal()");
6341 return getContentProviderExternalUnchecked(name, token);
6342 }
6343
6344 private ContentProviderHolder getContentProviderExternalUnchecked(String name,IBinder token) {
6345 return getContentProviderImpl(null, name, token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006346 }
6347
6348 /**
6349 * Drop a content provider from a ProcessRecord's bookkeeping
6350 * @param cpr
6351 */
6352 public void removeContentProvider(IApplicationThread caller, String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006353 enforceNotIsolatedCaller("removeContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006354 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006355 int userId = UserId.getUserId(Binder.getCallingUid());
6356 ContentProviderRecord cpr = mProviderMap.getProviderByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006357 if(cpr == null) {
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006358 // remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006359 if (DEBUG_PROVIDER) Slog.v(TAG, name +
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006360 " provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006361 return;
6362 }
6363 final ProcessRecord r = getRecordForAppLocked(caller);
6364 if (r == null) {
6365 throw new SecurityException(
6366 "Unable to find app for caller " + caller +
6367 " when removing content provider " + name);
6368 }
6369 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006370 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006371 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp, userId);
6372 if (DEBUG_PROVIDER) Slog.v(TAG, "Removing provider requested by "
6373 + r.info.processName + " from process "
6374 + localCpr.appInfo.processName);
6375 if (localCpr.launchingApp == r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006376 //should not happen. taken care of as a local provider
Joe Onorato8a9b2202010-02-26 18:56:32 -08006377 Slog.w(TAG, "removeContentProvider called on local provider: "
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006378 + cpr.info.name + " in process " + r.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006379 return;
6380 } else {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006381 if (decProviderCount(r, localCpr, null)) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006382 updateOomAdjLocked();
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07006383 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006384 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006385 }
6386 }
6387
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006388 public void removeContentProviderExternal(String name, IBinder token) {
6389 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6390 "Do not have permission in call removeContentProviderExternal()");
6391 removeContentProviderExternalUnchecked(name, token);
6392 }
6393
6394 private void removeContentProviderExternalUnchecked(String name, IBinder token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006395 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006396 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
6397 Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006398 if(cpr == null) {
6399 //remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006400 if(localLOGV) Slog.v(TAG, name+" content provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006401 return;
6402 }
6403
6404 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006405 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006406 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp,
6407 Binder.getOrigCallingUser());
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006408 if (localCpr.hasExternalProcessHandles()) {
6409 if (localCpr.removeExternalProcessHandleLocked(token)) {
6410 updateOomAdjLocked();
6411 } else {
6412 Slog.e(TAG, "Attmpt to remove content provider " + localCpr
6413 + " with no external reference for token: "
6414 + token + ".");
6415 }
6416 } else {
6417 Slog.e(TAG, "Attmpt to remove content provider: " + localCpr
6418 + " with no external references.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006419 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006420 }
6421 }
6422
6423 public final void publishContentProviders(IApplicationThread caller,
6424 List<ContentProviderHolder> providers) {
6425 if (providers == null) {
6426 return;
6427 }
6428
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006429 enforceNotIsolatedCaller("publishContentProviders");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006430 synchronized(this) {
6431 final ProcessRecord r = getRecordForAppLocked(caller);
Amith Yamasani742a6712011-05-04 14:49:28 -07006432 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006433 Slog.v(TAG_MU, "ProcessRecord uid = " + r.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006434 if (r == null) {
6435 throw new SecurityException(
6436 "Unable to find app for caller " + caller
6437 + " (pid=" + Binder.getCallingPid()
6438 + ") when publishing content providers");
6439 }
6440
6441 final long origId = Binder.clearCallingIdentity();
6442
6443 final int N = providers.size();
6444 for (int i=0; i<N; i++) {
6445 ContentProviderHolder src = providers.get(i);
6446 if (src == null || src.info == null || src.provider == null) {
6447 continue;
6448 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07006449 ContentProviderRecord dst = r.pubProviders.get(src.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006450 if (DEBUG_MU)
6451 Slog.v(TAG_MU, "ContentProviderRecord uid = " + dst.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006452 if (dst != null) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006453 ComponentName comp = new ComponentName(dst.info.packageName, dst.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006454 mProviderMap.putProviderByClass(comp, dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006455 String names[] = dst.info.authority.split(";");
6456 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006457 mProviderMap.putProviderByName(names[j], dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006458 }
6459
6460 int NL = mLaunchingProviders.size();
6461 int j;
6462 for (j=0; j<NL; j++) {
6463 if (mLaunchingProviders.get(j) == dst) {
6464 mLaunchingProviders.remove(j);
6465 j--;
6466 NL--;
6467 }
6468 }
6469 synchronized (dst) {
6470 dst.provider = src.provider;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006471 dst.proc = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006472 dst.notifyAll();
6473 }
6474 updateOomAdjLocked(r);
6475 }
6476 }
6477
6478 Binder.restoreCallingIdentity(origId);
6479 }
6480 }
6481
6482 public static final void installSystemProviders() {
Jeff Brown10e89712011-07-08 18:52:57 -07006483 List<ProviderInfo> providers;
Josh Bartel2ecce342010-02-25 10:55:48 -06006484 synchronized (mSelf) {
6485 ProcessRecord app = mSelf.mProcessNames.get("system", Process.SYSTEM_UID);
6486 providers = mSelf.generateApplicationProvidersLocked(app);
Dianne Hackborn5c83a5f2010-03-12 16:46:46 -08006487 if (providers != null) {
6488 for (int i=providers.size()-1; i>=0; i--) {
6489 ProviderInfo pi = (ProviderInfo)providers.get(i);
6490 if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6491 Slog.w(TAG, "Not installing system proc provider " + pi.name
6492 + ": not system .apk");
6493 providers.remove(i);
6494 }
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006495 }
6496 }
6497 }
Josh Bartel2ecce342010-02-25 10:55:48 -06006498 if (providers != null) {
6499 mSystemThread.installSystemProviders(providers);
6500 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08006501
6502 mSelf.mCoreSettingsObserver = new CoreSettingsObserver(mSelf);
Mark Brophyc6350272011-08-05 16:16:39 +01006503
6504 mSelf.mUsageStatsService.monitorPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006505 }
6506
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006507 /**
6508 * Allows app to retrieve the MIME type of a URI without having permission
6509 * to access its content provider.
6510 *
6511 * CTS tests for this functionality can be run with "runtest cts-appsecurity".
6512 *
6513 * Test cases are at cts/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/
6514 * src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java
6515 */
6516 public String getProviderMimeType(Uri uri) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006517 enforceNotIsolatedCaller("getProviderMimeType");
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006518 final String name = uri.getAuthority();
6519 final long ident = Binder.clearCallingIdentity();
6520 ContentProviderHolder holder = null;
6521
6522 try {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006523 holder = getContentProviderExternalUnchecked(name, null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006524 if (holder != null) {
6525 return holder.provider.getType(uri);
6526 }
6527 } catch (RemoteException e) {
6528 Log.w(TAG, "Content provider dead retrieving " + uri, e);
6529 return null;
6530 } finally {
6531 if (holder != null) {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006532 removeContentProviderExternalUnchecked(name, null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006533 }
6534 Binder.restoreCallingIdentity(ident);
6535 }
6536
6537 return null;
6538 }
6539
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006540 // =========================================================
6541 // GLOBAL MANAGEMENT
6542 // =========================================================
6543
6544 final ProcessRecord newProcessRecordLocked(IApplicationThread thread,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006545 ApplicationInfo info, String customProcess, boolean isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006546 String proc = customProcess != null ? customProcess : info.processName;
6547 BatteryStatsImpl.Uid.Proc ps = null;
6548 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006549 int uid = info.uid;
6550 if (isolated) {
6551 int userId = UserId.getUserId(uid);
6552 int stepsLeft = Process.LAST_ISOLATED_UID - Process.FIRST_ISOLATED_UID + 1;
6553 uid = 0;
6554 while (true) {
6555 if (mNextIsolatedProcessUid < Process.FIRST_ISOLATED_UID
6556 || mNextIsolatedProcessUid > Process.LAST_ISOLATED_UID) {
6557 mNextIsolatedProcessUid = Process.FIRST_ISOLATED_UID;
6558 }
6559 uid = UserId.getUid(userId, mNextIsolatedProcessUid);
6560 mNextIsolatedProcessUid++;
6561 if (mIsolatedProcesses.indexOfKey(uid) < 0) {
6562 // No process for this uid, use it.
6563 break;
6564 }
6565 stepsLeft--;
6566 if (stepsLeft <= 0) {
6567 return null;
6568 }
6569 }
6570 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006571 synchronized (stats) {
6572 ps = stats.getProcessStatsLocked(info.uid, proc);
6573 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006574 return new ProcessRecord(ps, thread, info, proc, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006575 }
6576
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006577 final ProcessRecord addAppLocked(ApplicationInfo info, boolean isolated) {
6578 ProcessRecord app;
6579 if (!isolated) {
6580 app = getProcessRecordLocked(info.processName, info.uid);
6581 } else {
6582 app = null;
6583 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006584
6585 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006586 app = newProcessRecordLocked(null, info, null, isolated);
6587 mProcessNames.put(info.processName, app.uid, app);
6588 if (isolated) {
6589 mIsolatedProcesses.put(app.uid, app);
6590 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08006591 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006592 }
6593
Dianne Hackborne7f97212011-02-24 14:40:20 -08006594 // This package really, really can not be stopped.
6595 try {
6596 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07006597 info.packageName, false, UserId.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -08006598 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006599 } catch (IllegalArgumentException e) {
6600 Slog.w(TAG, "Failed trying to unstop package "
6601 + info.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006602 }
6603
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006604 if ((info.flags&(ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT))
6605 == (ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT)) {
6606 app.persistent = true;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07006607 app.maxAdj = ProcessList.PERSISTENT_PROC_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006608 }
6609 if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) {
6610 mPersistentStartingProcesses.add(app);
6611 startProcessLocked(app, "added application", app.processName);
6612 }
6613
6614 return app;
6615 }
6616
6617 public void unhandledBack() {
6618 enforceCallingPermission(android.Manifest.permission.FORCE_BACK,
6619 "unhandledBack()");
6620
6621 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006622 int count = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08006623 if (DEBUG_SWITCH) Slog.d(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006624 TAG, "Performing unhandledBack(): stack size = " + count);
6625 if (count > 1) {
6626 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006627 mMainStack.finishActivityLocked((ActivityRecord)mMainStack.mHistory.get(count-1),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006628 count-1, Activity.RESULT_CANCELED, null, "unhandled-back");
6629 Binder.restoreCallingIdentity(origId);
6630 }
6631 }
6632 }
6633
6634 public ParcelFileDescriptor openContentUri(Uri uri) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006635 enforceNotIsolatedCaller("openContentUri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006636 String name = uri.getAuthority();
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006637 ContentProviderHolder cph = getContentProviderExternalUnchecked(name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006638 ParcelFileDescriptor pfd = null;
6639 if (cph != null) {
6640 // We record the binder invoker's uid in thread-local storage before
6641 // going to the content provider to open the file. Later, in the code
6642 // that handles all permissions checks, we look for this uid and use
6643 // that rather than the Activity Manager's own uid. The effect is that
6644 // we do the check against the caller's permissions even though it looks
6645 // to the content provider like the Activity Manager itself is making
6646 // the request.
6647 sCallerIdentity.set(new Identity(
6648 Binder.getCallingPid(), Binder.getCallingUid()));
6649 try {
6650 pfd = cph.provider.openFile(uri, "r");
6651 } catch (FileNotFoundException e) {
6652 // do nothing; pfd will be returned null
6653 } finally {
6654 // Ensure that whatever happens, we clean up the identity state
6655 sCallerIdentity.remove();
6656 }
6657
6658 // We've got the fd now, so we're done with the provider.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006659 removeContentProviderExternalUnchecked(name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006660 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006661 Slog.d(TAG, "Failed to get provider for authority '" + name + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006662 }
6663 return pfd;
6664 }
6665
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006666 // Actually is sleeping or shutting down or whatever else in the future
6667 // is an inactive state.
6668 public boolean isSleeping() {
6669 return mSleeping || mShuttingDown;
6670 }
6671
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006672 public void goingToSleep() {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006673 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
6674 != PackageManager.PERMISSION_GRANTED) {
6675 throw new SecurityException("Requires permission "
6676 + android.Manifest.permission.DEVICE_POWER);
6677 }
6678
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006679 synchronized(this) {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006680 mWentToSleep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006681 mWindowManager.setEventDispatching(false);
6682
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006683 if (!mSleeping) {
6684 mSleeping = true;
6685 mMainStack.stopIfSleepingLocked();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006686
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006687 // Initialize the wake times of all processes.
6688 checkExcessivePowerUsageLocked(false);
6689 mHandler.removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
6690 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
6691 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
6692 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006693 }
6694 }
6695
Dianne Hackborn55280a92009-05-07 15:53:46 -07006696 public boolean shutdown(int timeout) {
6697 if (checkCallingPermission(android.Manifest.permission.SHUTDOWN)
6698 != PackageManager.PERMISSION_GRANTED) {
6699 throw new SecurityException("Requires permission "
6700 + android.Manifest.permission.SHUTDOWN);
6701 }
6702
6703 boolean timedout = false;
6704
6705 synchronized(this) {
6706 mShuttingDown = true;
6707 mWindowManager.setEventDispatching(false);
6708
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006709 if (mMainStack.mResumedActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006710 mMainStack.stopIfSleepingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07006711 final long endTime = System.currentTimeMillis() + timeout;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006712 while (mMainStack.mResumedActivity != null
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08006713 || mMainStack.mPausingActivity != null) {
Dianne Hackborn55280a92009-05-07 15:53:46 -07006714 long delay = endTime - System.currentTimeMillis();
6715 if (delay <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006716 Slog.w(TAG, "Activity manager shutdown timed out");
Dianne Hackborn55280a92009-05-07 15:53:46 -07006717 timedout = true;
6718 break;
6719 }
6720 try {
6721 this.wait();
6722 } catch (InterruptedException e) {
6723 }
6724 }
6725 }
6726 }
6727
6728 mUsageStatsService.shutdown();
6729 mBatteryStatsService.shutdown();
6730
6731 return timedout;
6732 }
6733
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006734 public final void activitySlept(IBinder token) {
6735 if (localLOGV) Slog.v(
6736 TAG, "Activity slept: token=" + token);
6737
6738 ActivityRecord r = null;
6739
6740 final long origId = Binder.clearCallingIdentity();
6741
6742 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006743 r = mMainStack.isInStackLocked(token);
6744 if (r != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006745 mMainStack.activitySleptLocked(r);
6746 }
6747 }
6748
6749 Binder.restoreCallingIdentity(origId);
6750 }
6751
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006752 private void comeOutOfSleepIfNeededLocked() {
6753 if (!mWentToSleep && !mLockScreenShown) {
6754 if (mSleeping) {
6755 mSleeping = false;
6756 mMainStack.awakeFromSleepingLocked();
6757 mMainStack.resumeTopActivityLocked(null);
6758 }
6759 }
6760 }
6761
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006762 public void wakingUp() {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006763 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
6764 != PackageManager.PERMISSION_GRANTED) {
6765 throw new SecurityException("Requires permission "
6766 + android.Manifest.permission.DEVICE_POWER);
6767 }
6768
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006769 synchronized(this) {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006770 mWentToSleep = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006771 mWindowManager.setEventDispatching(true);
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006772 comeOutOfSleepIfNeededLocked();
6773 }
6774 }
6775
6776 public void setLockScreenShown(boolean shown) {
6777 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
6778 != PackageManager.PERMISSION_GRANTED) {
6779 throw new SecurityException("Requires permission "
6780 + android.Manifest.permission.DEVICE_POWER);
6781 }
6782
6783 synchronized(this) {
6784 mLockScreenShown = shown;
6785 comeOutOfSleepIfNeededLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006786 }
6787 }
6788
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006789 public void stopAppSwitches() {
6790 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
6791 != PackageManager.PERMISSION_GRANTED) {
6792 throw new SecurityException("Requires permission "
6793 + android.Manifest.permission.STOP_APP_SWITCHES);
6794 }
6795
6796 synchronized(this) {
6797 mAppSwitchesAllowedTime = SystemClock.uptimeMillis()
6798 + APP_SWITCH_DELAY_TIME;
6799 mDidAppSwitch = false;
6800 mHandler.removeMessages(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
6801 Message msg = mHandler.obtainMessage(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
6802 mHandler.sendMessageDelayed(msg, APP_SWITCH_DELAY_TIME);
6803 }
6804 }
6805
6806 public void resumeAppSwitches() {
6807 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
6808 != PackageManager.PERMISSION_GRANTED) {
6809 throw new SecurityException("Requires permission "
6810 + android.Manifest.permission.STOP_APP_SWITCHES);
6811 }
6812
6813 synchronized(this) {
6814 // Note that we don't execute any pending app switches... we will
6815 // let those wait until either the timeout, or the next start
6816 // activity request.
6817 mAppSwitchesAllowedTime = 0;
6818 }
6819 }
6820
6821 boolean checkAppSwitchAllowedLocked(int callingPid, int callingUid,
6822 String name) {
6823 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
6824 return true;
6825 }
6826
6827 final int perm = checkComponentPermission(
6828 android.Manifest.permission.STOP_APP_SWITCHES, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006829 callingUid, -1, true);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006830 if (perm == PackageManager.PERMISSION_GRANTED) {
6831 return true;
6832 }
6833
Joe Onorato8a9b2202010-02-26 18:56:32 -08006834 Slog.w(TAG, name + " request from " + callingUid + " stopped");
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006835 return false;
6836 }
6837
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006838 public void setDebugApp(String packageName, boolean waitForDebugger,
6839 boolean persistent) {
6840 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
6841 "setDebugApp()");
6842
6843 // Note that this is not really thread safe if there are multiple
6844 // callers into it at the same time, but that's not a situation we
6845 // care about.
6846 if (persistent) {
6847 final ContentResolver resolver = mContext.getContentResolver();
6848 Settings.System.putString(
6849 resolver, Settings.System.DEBUG_APP,
6850 packageName);
6851 Settings.System.putInt(
6852 resolver, Settings.System.WAIT_FOR_DEBUGGER,
6853 waitForDebugger ? 1 : 0);
6854 }
6855
6856 synchronized (this) {
6857 if (!persistent) {
6858 mOrigDebugApp = mDebugApp;
6859 mOrigWaitForDebugger = mWaitForDebugger;
6860 }
6861 mDebugApp = packageName;
6862 mWaitForDebugger = waitForDebugger;
6863 mDebugTransient = !persistent;
6864 if (packageName != null) {
6865 final long origId = Binder.clearCallingIdentity();
Amith Yamasani483f3b02012-03-13 16:08:00 -07006866 forceStopPackageLocked(packageName, -1, false, false, true, true, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006867 Binder.restoreCallingIdentity(origId);
6868 }
6869 }
6870 }
6871
Siva Velusamy92a8b222012-03-09 16:24:04 -08006872 void setOpenGlTraceApp(ApplicationInfo app, String processName) {
6873 synchronized (this) {
6874 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
6875 if (!isDebuggable) {
6876 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
6877 throw new SecurityException("Process not debuggable: " + app.packageName);
6878 }
6879 }
6880
6881 mOpenGlTraceApp = processName;
6882 }
6883 }
6884
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07006885 void setProfileApp(ApplicationInfo app, String processName, String profileFile,
6886 ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
6887 synchronized (this) {
6888 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
6889 if (!isDebuggable) {
6890 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
6891 throw new SecurityException("Process not debuggable: " + app.packageName);
6892 }
6893 }
6894 mProfileApp = processName;
6895 mProfileFile = profileFile;
6896 if (mProfileFd != null) {
6897 try {
6898 mProfileFd.close();
6899 } catch (IOException e) {
6900 }
6901 mProfileFd = null;
6902 }
6903 mProfileFd = profileFd;
6904 mProfileType = 0;
6905 mAutoStopProfiler = autoStopProfiler;
6906 }
6907 }
6908
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006909 public void setAlwaysFinish(boolean enabled) {
6910 enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH,
6911 "setAlwaysFinish()");
6912
6913 Settings.System.putInt(
6914 mContext.getContentResolver(),
6915 Settings.System.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0);
6916
6917 synchronized (this) {
6918 mAlwaysFinishActivities = enabled;
6919 }
6920 }
6921
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006922 public void setActivityController(IActivityController controller) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006923 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006924 "setActivityController()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006925 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006926 mController = controller;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006927 }
6928 }
6929
Dianne Hackborn9327f4f2010-01-29 10:38:29 -08006930 public boolean isUserAMonkey() {
6931 // For now the fact that there is a controller implies
6932 // we have a monkey.
6933 synchronized (this) {
6934 return mController != null;
6935 }
6936 }
6937
Jeff Sharkeya4620792011-05-20 15:29:23 -07006938 public void registerProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08006939 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
6940 "registerProcessObserver()");
6941 synchronized (this) {
6942 mProcessObservers.register(observer);
6943 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07006944 }
6945
6946 public void unregisterProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08006947 synchronized (this) {
6948 mProcessObservers.unregister(observer);
6949 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07006950 }
6951
Daniel Sandler69a48172010-06-23 16:29:36 -04006952 public void setImmersive(IBinder token, boolean immersive) {
6953 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006954 ActivityRecord r = mMainStack.isInStackLocked(token);
6955 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04006956 throw new IllegalArgumentException();
6957 }
Daniel Sandler69a48172010-06-23 16:29:36 -04006958 r.immersive = immersive;
6959 }
6960 }
6961
6962 public boolean isImmersive(IBinder token) {
6963 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006964 ActivityRecord r = mMainStack.isInStackLocked(token);
6965 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04006966 throw new IllegalArgumentException();
6967 }
Daniel Sandler69a48172010-06-23 16:29:36 -04006968 return r.immersive;
6969 }
6970 }
6971
6972 public boolean isTopActivityImmersive() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006973 enforceNotIsolatedCaller("startActivity");
Daniel Sandler69a48172010-06-23 16:29:36 -04006974 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006975 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Daniel Sandler69a48172010-06-23 16:29:36 -04006976 return (r != null) ? r.immersive : false;
6977 }
6978 }
6979
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006980 public final void enterSafeMode() {
6981 synchronized(this) {
6982 // It only makes sense to do this before the system is ready
6983 // and started launching other packages.
6984 if (!mSystemReady) {
6985 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006986 AppGlobals.getPackageManager().enterSafeMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006987 } catch (RemoteException e) {
6988 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006989 }
6990 }
6991 }
6992
Jeff Brownb09abc12011-01-13 21:08:27 -08006993 public final void showSafeModeOverlay() {
6994 View v = LayoutInflater.from(mContext).inflate(
6995 com.android.internal.R.layout.safe_mode, null);
6996 WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
6997 lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
6998 lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
6999 lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
7000 lp.gravity = Gravity.BOTTOM | Gravity.LEFT;
7001 lp.format = v.getBackground().getOpacity();
7002 lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
7003 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
7004 ((WindowManager)mContext.getSystemService(
7005 Context.WINDOW_SERVICE)).addView(v, lp);
7006 }
7007
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007008 public void noteWakeupAlarm(IIntentSender sender) {
7009 if (!(sender instanceof PendingIntentRecord)) {
7010 return;
7011 }
7012 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
7013 synchronized (stats) {
7014 if (mBatteryStatsService.isOnBattery()) {
7015 mBatteryStatsService.enforceCallingPermission();
7016 PendingIntentRecord rec = (PendingIntentRecord)sender;
7017 int MY_UID = Binder.getCallingUid();
7018 int uid = rec.uid == MY_UID ? Process.SYSTEM_UID : rec.uid;
7019 BatteryStatsImpl.Uid.Pkg pkg =
7020 stats.getPackageStatsLocked(uid, rec.key.packageName);
7021 pkg.incWakeupsLocked();
7022 }
7023 }
7024 }
7025
Dianne Hackborn64825172011-03-02 21:32:58 -08007026 public boolean killPids(int[] pids, String pReason, boolean secure) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007027 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007028 throw new SecurityException("killPids only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007029 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007030 String reason = (pReason == null) ? "Unknown" : pReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007031 // XXX Note: don't acquire main activity lock here, because the window
7032 // manager calls in with its locks held.
7033
7034 boolean killed = false;
7035 synchronized (mPidsSelfLocked) {
7036 int[] types = new int[pids.length];
7037 int worstType = 0;
7038 for (int i=0; i<pids.length; i++) {
7039 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7040 if (proc != null) {
7041 int type = proc.setAdj;
7042 types[i] = type;
7043 if (type > worstType) {
7044 worstType = type;
7045 }
7046 }
7047 }
7048
Dianne Hackborn64825172011-03-02 21:32:58 -08007049 // If the worst oom_adj is somewhere in the hidden proc LRU range,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007050 // then constrain it so we will kill all hidden procs.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007051 if (worstType < ProcessList.HIDDEN_APP_MAX_ADJ
7052 && worstType > ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07007053 worstType = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007054 }
Dianne Hackborn64825172011-03-02 21:32:58 -08007055
7056 // If this is not a secure call, don't let it kill processes that
7057 // are important.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007058 if (!secure && worstType < ProcessList.SERVICE_ADJ) {
7059 worstType = ProcessList.SERVICE_ADJ;
Dianne Hackborn64825172011-03-02 21:32:58 -08007060 }
7061
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007062 Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007063 for (int i=0; i<pids.length; i++) {
7064 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7065 if (proc == null) {
7066 continue;
7067 }
7068 int adj = proc.setAdj;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007069 if (adj >= worstType && !proc.killedBackground) {
Dianne Hackborn8633e682010-04-22 16:03:41 -07007070 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007071 EventLog.writeEvent(EventLogTags.AM_KILL, proc.pid,
7072 proc.processName, adj, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007073 killed = true;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007074 proc.killedBackground = true;
7075 Process.killProcessQuiet(pids[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007076 }
7077 }
7078 }
7079 return killed;
7080 }
Jeff Sharkeyb9a07012012-03-22 17:00:04 -07007081
7082 @Override
7083 public boolean killProcessesBelowForeground(String reason) {
7084 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7085 throw new SecurityException("killProcessesBelowForeground() only available to system");
7086 }
7087
7088 return killProcessesBelowAdj(ProcessList.FOREGROUND_APP_ADJ, reason);
7089 }
7090
7091 private boolean killProcessesBelowAdj(int belowAdj, String reason) {
7092 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7093 throw new SecurityException("killProcessesBelowAdj() only available to system");
7094 }
7095
7096 boolean killed = false;
7097 synchronized (mPidsSelfLocked) {
7098 final int size = mPidsSelfLocked.size();
7099 for (int i = 0; i < size; i++) {
7100 final int pid = mPidsSelfLocked.keyAt(i);
7101 final ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7102 if (proc == null) continue;
7103
7104 final int adj = proc.setAdj;
7105 if (adj > belowAdj && !proc.killedBackground) {
7106 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
7107 EventLog.writeEvent(
7108 EventLogTags.AM_KILL, proc.pid, proc.processName, adj, reason);
7109 killed = true;
7110 proc.killedBackground = true;
7111 Process.killProcessQuiet(pid);
7112 }
7113 }
7114 }
7115 return killed;
7116 }
7117
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007118 public final void startRunning(String pkg, String cls, String action,
7119 String data) {
7120 synchronized(this) {
7121 if (mStartRunning) {
7122 return;
7123 }
7124 mStartRunning = true;
7125 mTopComponent = pkg != null && cls != null
7126 ? new ComponentName(pkg, cls) : null;
7127 mTopAction = action != null ? action : Intent.ACTION_MAIN;
7128 mTopData = data;
7129 if (!mSystemReady) {
7130 return;
7131 }
7132 }
7133
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007134 systemReady(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007135 }
7136
7137 private void retrieveSettings() {
7138 final ContentResolver resolver = mContext.getContentResolver();
7139 String debugApp = Settings.System.getString(
7140 resolver, Settings.System.DEBUG_APP);
7141 boolean waitForDebugger = Settings.System.getInt(
7142 resolver, Settings.System.WAIT_FOR_DEBUGGER, 0) != 0;
7143 boolean alwaysFinishActivities = Settings.System.getInt(
7144 resolver, Settings.System.ALWAYS_FINISH_ACTIVITIES, 0) != 0;
7145
7146 Configuration configuration = new Configuration();
7147 Settings.System.getConfiguration(resolver, configuration);
7148
7149 synchronized (this) {
7150 mDebugApp = mOrigDebugApp = debugApp;
7151 mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger;
7152 mAlwaysFinishActivities = alwaysFinishActivities;
7153 // This happens before any activities are started, so we can
7154 // change mConfiguration in-place.
Dianne Hackborn813075a62011-11-14 17:45:19 -08007155 updateConfigurationLocked(configuration, null, false, true);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007156 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Initial config: " + mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007157 }
7158 }
7159
7160 public boolean testIsSystemReady() {
7161 // no need to synchronize(this) just to read & return the value
7162 return mSystemReady;
7163 }
7164
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007165 private static File getCalledPreBootReceiversFile() {
7166 File dataDir = Environment.getDataDirectory();
7167 File systemDir = new File(dataDir, "system");
7168 File fname = new File(systemDir, "called_pre_boots.dat");
7169 return fname;
7170 }
Dianne Hackborn661cd522011-08-22 00:26:20 -07007171
7172 static final int LAST_DONE_VERSION = 10000;
7173
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007174 private static ArrayList<ComponentName> readLastDonePreBootReceivers() {
7175 ArrayList<ComponentName> lastDoneReceivers = new ArrayList<ComponentName>();
7176 File file = getCalledPreBootReceiversFile();
7177 FileInputStream fis = null;
7178 try {
7179 fis = new FileInputStream(file);
7180 DataInputStream dis = new DataInputStream(new BufferedInputStream(fis, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007181 int fvers = dis.readInt();
7182 if (fvers == LAST_DONE_VERSION) {
7183 String vers = dis.readUTF();
7184 String codename = dis.readUTF();
7185 String build = dis.readUTF();
7186 if (android.os.Build.VERSION.RELEASE.equals(vers)
7187 && android.os.Build.VERSION.CODENAME.equals(codename)
7188 && android.os.Build.VERSION.INCREMENTAL.equals(build)) {
7189 int num = dis.readInt();
7190 while (num > 0) {
7191 num--;
7192 String pkg = dis.readUTF();
7193 String cls = dis.readUTF();
7194 lastDoneReceivers.add(new ComponentName(pkg, cls));
7195 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007196 }
7197 }
7198 } catch (FileNotFoundException e) {
7199 } catch (IOException e) {
7200 Slog.w(TAG, "Failure reading last done pre-boot receivers", e);
7201 } finally {
7202 if (fis != null) {
7203 try {
7204 fis.close();
7205 } catch (IOException e) {
7206 }
7207 }
7208 }
7209 return lastDoneReceivers;
7210 }
7211
7212 private static void writeLastDonePreBootReceivers(ArrayList<ComponentName> list) {
7213 File file = getCalledPreBootReceiversFile();
7214 FileOutputStream fos = null;
7215 DataOutputStream dos = null;
7216 try {
7217 Slog.i(TAG, "Writing new set of last done pre-boot receivers...");
7218 fos = new FileOutputStream(file);
7219 dos = new DataOutputStream(new BufferedOutputStream(fos, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007220 dos.writeInt(LAST_DONE_VERSION);
7221 dos.writeUTF(android.os.Build.VERSION.RELEASE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007222 dos.writeUTF(android.os.Build.VERSION.CODENAME);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007223 dos.writeUTF(android.os.Build.VERSION.INCREMENTAL);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007224 dos.writeInt(list.size());
7225 for (int i=0; i<list.size(); i++) {
7226 dos.writeUTF(list.get(i).getPackageName());
7227 dos.writeUTF(list.get(i).getClassName());
7228 }
7229 } catch (IOException e) {
7230 Slog.w(TAG, "Failure writing last done pre-boot receivers", e);
7231 file.delete();
7232 } finally {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07007233 FileUtils.sync(fos);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007234 if (dos != null) {
7235 try {
7236 dos.close();
7237 } catch (IOException e) {
7238 // TODO Auto-generated catch block
7239 e.printStackTrace();
7240 }
7241 }
7242 }
7243 }
7244
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007245 public void systemReady(final Runnable goingCallback) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007246 synchronized(this) {
7247 if (mSystemReady) {
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007248 if (goingCallback != null) goingCallback.run();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007249 return;
7250 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007251
7252 // Check to see if there are any update receivers to run.
7253 if (!mDidUpdate) {
7254 if (mWaitingUpdate) {
7255 return;
7256 }
7257 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
7258 List<ResolveInfo> ris = null;
7259 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007260 ris = AppGlobals.getPackageManager().queryIntentReceivers(
Amith Yamasani483f3b02012-03-13 16:08:00 -07007261 intent, null, 0, 0);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007262 } catch (RemoteException e) {
7263 }
7264 if (ris != null) {
7265 for (int i=ris.size()-1; i>=0; i--) {
7266 if ((ris.get(i).activityInfo.applicationInfo.flags
7267 &ApplicationInfo.FLAG_SYSTEM) == 0) {
7268 ris.remove(i);
7269 }
7270 }
7271 intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007272
7273 ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers();
7274
7275 final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007276 for (int i=0; i<ris.size(); i++) {
7277 ActivityInfo ai = ris.get(i).activityInfo;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007278 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7279 if (lastDoneReceivers.contains(comp)) {
7280 ris.remove(i);
7281 i--;
7282 }
7283 }
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07007284
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007285 for (int i=0; i<ris.size(); i++) {
7286 ActivityInfo ai = ris.get(i).activityInfo;
7287 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7288 doneReceivers.add(comp);
7289 intent.setComponent(comp);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007290 IIntentReceiver finisher = null;
Dianne Hackbornd6847842010-01-12 18:14:19 -08007291 if (i == ris.size()-1) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007292 finisher = new IIntentReceiver.Stub() {
7293 public void performReceive(Intent intent, int resultCode,
Dianne Hackborn68d881c2009-10-05 13:58:17 -07007294 String data, Bundle extras, boolean ordered,
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007295 boolean sticky) {
7296 // The raw IIntentReceiver interface is called
7297 // with the AM lock held, so redispatch to
7298 // execute our code without the lock.
7299 mHandler.post(new Runnable() {
7300 public void run() {
7301 synchronized (ActivityManagerService.this) {
7302 mDidUpdate = true;
7303 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007304 writeLastDonePreBootReceivers(doneReceivers);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007305 showBootMessage(mContext.getText(
7306 R.string.android_upgrading_complete),
7307 false);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007308 systemReady(goingCallback);
7309 }
7310 });
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007311 }
7312 };
7313 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08007314 Slog.i(TAG, "Sending system update to: " + intent.getComponent());
Amith Yamasani742a6712011-05-04 14:49:28 -07007315 /* TODO: Send this to all users */
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007316 broadcastIntentLocked(null, null, intent, null, finisher,
Amith Yamasani742a6712011-05-04 14:49:28 -07007317 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID,
Amith Yamasanic600e21f2012-02-14 16:08:07 -08007318 0 /* UserId zero */);
Dianne Hackbornd6847842010-01-12 18:14:19 -08007319 if (finisher != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007320 mWaitingUpdate = true;
7321 }
7322 }
7323 }
7324 if (mWaitingUpdate) {
7325 return;
7326 }
7327 mDidUpdate = true;
7328 }
7329
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007330 mSystemReady = true;
7331 if (!mStartRunning) {
7332 return;
7333 }
7334 }
7335
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007336 ArrayList<ProcessRecord> procsToKill = null;
7337 synchronized(mPidsSelfLocked) {
7338 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
7339 ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7340 if (!isAllowedWhileBooting(proc.info)){
7341 if (procsToKill == null) {
7342 procsToKill = new ArrayList<ProcessRecord>();
7343 }
7344 procsToKill.add(proc);
7345 }
7346 }
7347 }
7348
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007349 synchronized(this) {
7350 if (procsToKill != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007351 for (int i=procsToKill.size()-1; i>=0; i--) {
7352 ProcessRecord proc = procsToKill.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007353 Slog.i(TAG, "Removing system update proc: " + proc);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007354 removeProcessLocked(proc, true, false, "system update done");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007355 }
7356 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007357
7358 // Now that we have cleaned up any update processes, we
7359 // are ready to start launching real processes and know that
7360 // we won't trample on them any more.
7361 mProcessesReady = true;
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007362 }
7363
Joe Onorato8a9b2202010-02-26 18:56:32 -08007364 Slog.i(TAG, "System now ready");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007365 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007366 SystemClock.uptimeMillis());
7367
7368 synchronized(this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007369 // Make sure we have no pre-ready processes sitting around.
7370
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007371 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
7372 ResolveInfo ri = mContext.getPackageManager()
7373 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST),
Dianne Hackborn1655be42009-05-08 14:29:01 -07007374 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007375 CharSequence errorMsg = null;
7376 if (ri != null) {
7377 ActivityInfo ai = ri.activityInfo;
7378 ApplicationInfo app = ai.applicationInfo;
7379 if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7380 mTopAction = Intent.ACTION_FACTORY_TEST;
7381 mTopData = null;
7382 mTopComponent = new ComponentName(app.packageName,
7383 ai.name);
7384 } else {
7385 errorMsg = mContext.getResources().getText(
7386 com.android.internal.R.string.factorytest_not_system);
7387 }
7388 } else {
7389 errorMsg = mContext.getResources().getText(
7390 com.android.internal.R.string.factorytest_no_action);
7391 }
7392 if (errorMsg != null) {
7393 mTopAction = null;
7394 mTopData = null;
7395 mTopComponent = null;
7396 Message msg = Message.obtain();
7397 msg.what = SHOW_FACTORY_ERROR_MSG;
7398 msg.getData().putCharSequence("msg", errorMsg);
7399 mHandler.sendMessage(msg);
7400 }
7401 }
7402 }
7403
7404 retrieveSettings();
7405
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007406 if (goingCallback != null) goingCallback.run();
7407
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007408 synchronized (this) {
7409 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
7410 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007411 List apps = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07007412 getPersistentApplications(STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007413 if (apps != null) {
7414 int N = apps.size();
7415 int i;
7416 for (i=0; i<N; i++) {
7417 ApplicationInfo info
7418 = (ApplicationInfo)apps.get(i);
7419 if (info != null &&
7420 !info.packageName.equals("android")) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007421 addAppLocked(info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007422 }
7423 }
7424 }
7425 } catch (RemoteException ex) {
7426 // pm is in same process, this will never happen.
7427 }
7428 }
7429
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007430 // Start up initial activity.
7431 mBooting = true;
7432
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007433 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007434 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007435 Message msg = Message.obtain();
7436 msg.what = SHOW_UID_ERROR_MSG;
7437 mHandler.sendMessage(msg);
7438 }
7439 } catch (RemoteException e) {
7440 }
7441
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007442 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007443 }
7444 }
7445
Dan Egnorb7f03672009-12-09 16:22:32 -08007446 private boolean makeAppCrashingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007447 String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007448 app.crashing = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007449 app.crashingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007450 ActivityManager.ProcessErrorStateInfo.CRASHED, null, shortMsg, longMsg, stackTrace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007451 startAppProblemLocked(app);
7452 app.stopFreezingAllLocked();
7453 return handleAppCrashLocked(app);
7454 }
7455
Dan Egnorb7f03672009-12-09 16:22:32 -08007456 private void makeAppNotRespondingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007457 String activity, String shortMsg, String longMsg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007458 app.notResponding = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007459 app.notRespondingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007460 ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING,
7461 activity, shortMsg, longMsg, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007462 startAppProblemLocked(app);
7463 app.stopFreezingAllLocked();
7464 }
7465
7466 /**
7467 * Generate a process error record, suitable for attachment to a ProcessRecord.
7468 *
7469 * @param app The ProcessRecord in which the error occurred.
7470 * @param condition Crashing, Application Not Responding, etc. Values are defined in
7471 * ActivityManager.AppErrorStateInfo
Dan Egnor60d87622009-12-16 16:32:58 -08007472 * @param activity The activity associated with the crash, if known.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007473 * @param shortMsg Short message describing the crash.
7474 * @param longMsg Long message describing the crash.
Dan Egnorb7f03672009-12-09 16:22:32 -08007475 * @param stackTrace Full crash stack trace, may be null.
7476 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007477 * @return Returns a fully-formed AppErrorStateInfo record.
7478 */
7479 private ActivityManager.ProcessErrorStateInfo generateProcessError(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007480 int condition, String activity, String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007481 ActivityManager.ProcessErrorStateInfo report = new ActivityManager.ProcessErrorStateInfo();
Dan Egnorb7f03672009-12-09 16:22:32 -08007482
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007483 report.condition = condition;
7484 report.processName = app.processName;
7485 report.pid = app.pid;
7486 report.uid = app.info.uid;
Dan Egnor60d87622009-12-16 16:32:58 -08007487 report.tag = activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007488 report.shortMsg = shortMsg;
7489 report.longMsg = longMsg;
Dan Egnorb7f03672009-12-09 16:22:32 -08007490 report.stackTrace = stackTrace;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007491
7492 return report;
7493 }
7494
Dan Egnor42471dd2010-01-07 17:25:22 -08007495 void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007496 synchronized (this) {
7497 app.crashing = false;
7498 app.crashingReport = null;
7499 app.notResponding = false;
7500 app.notRespondingReport = null;
7501 if (app.anrDialog == fromDialog) {
7502 app.anrDialog = null;
7503 }
7504 if (app.waitDialog == fromDialog) {
7505 app.waitDialog = null;
7506 }
7507 if (app.pid > 0 && app.pid != MY_PID) {
Dan Egnor42471dd2010-01-07 17:25:22 -08007508 handleAppCrashLocked(app);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007509 Slog.i(ActivityManagerService.TAG, "Killing " + app + ": user's request");
Dianne Hackborn8633e682010-04-22 16:03:41 -07007510 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
7511 app.processName, app.setAdj, "user's request after error");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007512 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007513 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007514 }
7515 }
Dan Egnor42471dd2010-01-07 17:25:22 -08007516
Dan Egnorb7f03672009-12-09 16:22:32 -08007517 private boolean handleAppCrashLocked(ProcessRecord app) {
Mike Lockwood86548c42011-09-13 17:21:46 -04007518 if (mHeadless) {
7519 Log.e(TAG, "handleAppCrashLocked: " + app.processName);
7520 return false;
7521 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007522 long now = SystemClock.uptimeMillis();
7523
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007524 Long crashTime;
7525 if (!app.isolated) {
7526 crashTime = mProcessCrashTimes.get(app.info.processName, app.uid);
7527 } else {
7528 crashTime = null;
7529 }
Dianne Hackborn7d608422011-08-07 16:24:18 -07007530 if (crashTime != null && now < crashTime+ProcessList.MIN_CRASH_INTERVAL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007531 // This process loses!
Joe Onorato8a9b2202010-02-26 18:56:32 -08007532 Slog.w(TAG, "Process " + app.info.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007533 + " has crashed too many times: killing!");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007534 EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007535 app.info.processName, app.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007536 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
7537 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007538 if (r.app == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007539 Slog.w(TAG, " Force finishing activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007540 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007541 r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED, null, "crashed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007542 }
7543 }
7544 if (!app.persistent) {
7545 // We don't want to start this process again until the user
7546 // explicitly does so... but for persistent process, we really
7547 // need to keep it running. If a persistent process is actually
7548 // repeatedly crashing, then badness for everyone.
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007549 EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007550 app.info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007551 if (!app.isolated) {
7552 // XXX We don't have a way to mark isolated processes
7553 // as bad, since they don't have a peristent identity.
7554 mBadProcesses.put(app.info.processName, app.uid, now);
7555 mProcessCrashTimes.remove(app.info.processName, app.uid);
7556 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007557 app.bad = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007558 app.removed = true;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07007559 // Don't let services in this process be restarted and potentially
7560 // annoy the user repeatedly. Unless it is persistent, since those
7561 // processes run critical code.
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007562 removeProcessLocked(app, false, false, "crash");
Dianne Hackborncb44d962011-03-10 17:02:27 -08007563 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007564 return false;
7565 }
Dianne Hackborncb44d962011-03-10 17:02:27 -08007566 mMainStack.resumeTopActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007567 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007568 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Kevin Hester-Chowd87a9be2012-03-05 08:01:00 -08007569 if (r != null && r.app == app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007570 // If the top running activity is from this crashing
7571 // process, then terminate it to avoid getting in a loop.
7572 Slog.w(TAG, " Force finishing activity "
7573 + r.intent.getComponent().flattenToShortString());
Dianne Hackbornbe707852011-11-11 14:32:10 -08007574 int index = mMainStack.indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007575 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007576 Activity.RESULT_CANCELED, null, "crashed");
Dianne Hackborn070783f2010-12-29 16:46:28 -08007577 // Also terminate any activities below it that aren't yet
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007578 // stopped, to avoid a situation where one will get
7579 // re-start our crashing activity once it gets resumed again.
7580 index--;
7581 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007582 r = (ActivityRecord)mMainStack.mHistory.get(index);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007583 if (r.state == ActivityState.RESUMED
7584 || r.state == ActivityState.PAUSING
7585 || r.state == ActivityState.PAUSED) {
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08007586 if (!r.isHomeActivity || mHomeProcess != r.app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007587 Slog.w(TAG, " Force finishing activity "
7588 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007589 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007590 Activity.RESULT_CANCELED, null, "crashed");
7591 }
7592 }
7593 }
7594 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007595 }
7596
7597 // Bump up the crash count of any services currently running in the proc.
7598 if (app.services.size() != 0) {
7599 // Any services running in the application need to be placed
7600 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -07007601 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007602 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07007603 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007604 sr.crashCount++;
7605 }
7606 }
Mattias Larssona4fd0072010-06-22 22:37:03 +02007607
7608 // If the crashing process is what we consider to be the "home process" and it has been
7609 // replaced by a third-party app, clear the package preferred activities from packages
7610 // with a home activity running in the process to prevent a repeatedly crashing app
7611 // from blocking the user to manually clear the list.
7612 if (app == mHomeProcess && mHomeProcess.activities.size() > 0
7613 && (mHomeProcess.info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
7614 Iterator it = mHomeProcess.activities.iterator();
7615 while (it.hasNext()) {
Jean-Baptiste Queru5ea89f72010-07-30 09:30:31 -07007616 ActivityRecord r = (ActivityRecord)it.next();
Mattias Larssona4fd0072010-06-22 22:37:03 +02007617 if (r.isHomeActivity) {
7618 Log.i(TAG, "Clearing package preferred activities from " + r.packageName);
7619 try {
7620 ActivityThread.getPackageManager()
7621 .clearPackagePreferredActivities(r.packageName);
7622 } catch (RemoteException c) {
7623 // pm is in same process, this will never happen.
7624 }
7625 }
7626 }
7627 }
7628
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007629 if (!app.isolated) {
7630 // XXX Can't keep track of crash times for isolated processes,
7631 // because they don't have a perisistent identity.
7632 mProcessCrashTimes.put(app.info.processName, app.uid, now);
7633 }
7634
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007635 return true;
7636 }
7637
7638 void startAppProblemLocked(ProcessRecord app) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08007639 app.errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver(
7640 mContext, app.info.packageName, app.info.flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007641 skipCurrentReceiverLocked(app);
7642 }
7643
7644 void skipCurrentReceiverLocked(ProcessRecord app) {
Christopher Tatef46723b2012-01-26 14:19:24 -08007645 for (BroadcastQueue queue : mBroadcastQueues) {
7646 queue.skipCurrentReceiverLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007647 }
7648 }
7649
Dan Egnor60d87622009-12-16 16:32:58 -08007650 /**
7651 * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes.
7652 * The application process will exit immediately after this call returns.
7653 * @param app object of the crashing app, null for the system server
7654 * @param crashInfo describing the exception
7655 */
7656 public void handleApplicationCrash(IBinder app, ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007657 ProcessRecord r = findAppProcess(app, "Crash");
Jeff Sharkeya353d262011-10-28 11:12:06 -07007658 final String processName = app == null ? "system_server"
7659 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08007660
7661 EventLog.writeEvent(EventLogTags.AM_CRASH, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07007662 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08007663 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08007664 crashInfo.exceptionClassName,
7665 crashInfo.exceptionMessage,
7666 crashInfo.throwFileName,
7667 crashInfo.throwLineNumber);
7668
Jeff Sharkeya353d262011-10-28 11:12:06 -07007669 addErrorToDropBox("crash", r, processName, null, null, null, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08007670
7671 crashApplication(r, crashInfo);
7672 }
7673
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007674 public void handleApplicationStrictModeViolation(
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007675 IBinder app,
7676 int violationMask,
7677 StrictMode.ViolationInfo info) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007678 ProcessRecord r = findAppProcess(app, "StrictMode");
7679 if (r == null) {
7680 return;
7681 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007682
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007683 if ((violationMask & StrictMode.PENALTY_DROPBOX) != 0) {
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08007684 Integer stackFingerprint = info.hashCode();
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007685 boolean logIt = true;
7686 synchronized (mAlreadyLoggedViolatedStacks) {
7687 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) {
7688 logIt = false;
7689 // TODO: sub-sample into EventLog for these, with
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007690 // the info.durationMillis? Then we'd get
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007691 // the relative pain numbers, without logging all
7692 // the stack traces repeatedly. We'd want to do
7693 // likewise in the client code, which also does
7694 // dup suppression, before the Binder call.
7695 } else {
7696 if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) {
7697 mAlreadyLoggedViolatedStacks.clear();
7698 }
7699 mAlreadyLoggedViolatedStacks.add(stackFingerprint);
7700 }
7701 }
7702 if (logIt) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007703 logStrictModeViolationToDropBox(r, info);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007704 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007705 }
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007706
7707 if ((violationMask & StrictMode.PENALTY_DIALOG) != 0) {
7708 AppErrorResult result = new AppErrorResult();
7709 synchronized (this) {
7710 final long origId = Binder.clearCallingIdentity();
7711
7712 Message msg = Message.obtain();
7713 msg.what = SHOW_STRICT_MODE_VIOLATION_MSG;
7714 HashMap<String, Object> data = new HashMap<String, Object>();
7715 data.put("result", result);
7716 data.put("app", r);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007717 data.put("violationMask", violationMask);
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007718 data.put("info", info);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007719 msg.obj = data;
7720 mHandler.sendMessage(msg);
7721
7722 Binder.restoreCallingIdentity(origId);
7723 }
7724 int res = result.get();
Dianne Hackbornb424b632010-08-18 15:59:05 -07007725 Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007726 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007727 }
7728
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007729 // Depending on the policy in effect, there could be a bunch of
7730 // these in quick succession so we try to batch these together to
7731 // minimize disk writes, number of dropbox entries, and maximize
7732 // compression, by having more fewer, larger records.
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007733 private void logStrictModeViolationToDropBox(
7734 ProcessRecord process,
7735 StrictMode.ViolationInfo info) {
7736 if (info == null) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007737 return;
7738 }
7739 final boolean isSystemApp = process == null ||
7740 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM |
7741 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07007742 final String processName = process == null ? "unknown" : process.processName;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007743 final String dropboxTag = isSystemApp ? "system_app_strictmode" : "data_app_strictmode";
7744 final DropBoxManager dbox = (DropBoxManager)
7745 mContext.getSystemService(Context.DROPBOX_SERVICE);
7746
7747 // Exit early if the dropbox isn't configured to accept this report type.
7748 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
7749
7750 boolean bufferWasEmpty;
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007751 boolean needsFlush;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007752 final StringBuilder sb = isSystemApp ? mStrictModeBuffer : new StringBuilder(1024);
7753 synchronized (sb) {
7754 bufferWasEmpty = sb.length() == 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07007755 appendDropBoxProcessHeaders(process, processName, sb);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007756 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
7757 sb.append("System-App: ").append(isSystemApp).append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007758 sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n");
7759 if (info.violationNumThisLoop != 0) {
7760 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n");
7761 }
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07007762 if (info.numAnimationsRunning != 0) {
7763 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n");
7764 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07007765 if (info.broadcastIntentAction != null) {
7766 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n");
7767 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08007768 if (info.durationMillis != -1) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007769 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n");
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007770 }
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08007771 if (info.numInstances != -1) {
7772 sb.append("Instance-Count: ").append(info.numInstances).append("\n");
7773 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08007774 if (info.tags != null) {
7775 for (String tag : info.tags) {
7776 sb.append("Span-Tag: ").append(tag).append("\n");
7777 }
7778 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007779 sb.append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007780 if (info.crashInfo != null && info.crashInfo.stackTrace != null) {
7781 sb.append(info.crashInfo.stackTrace);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007782 }
7783 sb.append("\n");
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007784
7785 // Only buffer up to ~64k. Various logging bits truncate
7786 // things at 128k.
7787 needsFlush = (sb.length() > 64 * 1024);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007788 }
7789
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007790 // Flush immediately if the buffer's grown too large, or this
7791 // is a non-system app. Non-system apps are isolated with a
7792 // different tag & policy and not batched.
7793 //
7794 // Batching is useful during internal testing with
7795 // StrictMode settings turned up high. Without batching,
7796 // thousands of separate files could be created on boot.
7797 if (!isSystemApp || needsFlush) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007798 new Thread("Error dump: " + dropboxTag) {
7799 @Override
7800 public void run() {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007801 String report;
7802 synchronized (sb) {
7803 report = sb.toString();
7804 sb.delete(0, sb.length());
7805 sb.trimToSize();
7806 }
7807 if (report.length() != 0) {
7808 dbox.addText(dropboxTag, report);
7809 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007810 }
7811 }.start();
7812 return;
7813 }
7814
7815 // System app batching:
7816 if (!bufferWasEmpty) {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007817 // An existing dropbox-writing thread is outstanding, so
7818 // we don't need to start it up. The existing thread will
7819 // catch the buffer appends we just did.
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007820 return;
7821 }
7822
7823 // Worker thread to both batch writes and to avoid blocking the caller on I/O.
7824 // (After this point, we shouldn't access AMS internal data structures.)
7825 new Thread("Error dump: " + dropboxTag) {
7826 @Override
7827 public void run() {
7828 // 5 second sleep to let stacks arrive and be batched together
7829 try {
7830 Thread.sleep(5000); // 5 seconds
7831 } catch (InterruptedException e) {}
7832
7833 String errorReport;
7834 synchronized (mStrictModeBuffer) {
7835 errorReport = mStrictModeBuffer.toString();
7836 if (errorReport.length() == 0) {
7837 return;
7838 }
7839 mStrictModeBuffer.delete(0, mStrictModeBuffer.length());
7840 mStrictModeBuffer.trimToSize();
7841 }
7842 dbox.addText(dropboxTag, errorReport);
7843 }
7844 }.start();
7845 }
7846
Dan Egnor60d87622009-12-16 16:32:58 -08007847 /**
7848 * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors.
7849 * @param app object of the crashing app, null for the system server
7850 * @param tag reported by the caller
7851 * @param crashInfo describing the context of the error
7852 * @return true if the process should exit immediately (WTF is fatal)
7853 */
7854 public boolean handleApplicationWtf(IBinder app, String tag,
Dan Egnorb7f03672009-12-09 16:22:32 -08007855 ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007856 ProcessRecord r = findAppProcess(app, "WTF");
Jeff Sharkeya353d262011-10-28 11:12:06 -07007857 final String processName = app == null ? "system_server"
7858 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08007859
7860 EventLog.writeEvent(EventLogTags.AM_WTF, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07007861 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08007862 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08007863 tag, crashInfo.exceptionMessage);
7864
Jeff Sharkeya353d262011-10-28 11:12:06 -07007865 addErrorToDropBox("wtf", r, processName, null, null, tag, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08007866
Dianne Hackborn1ab43772011-03-15 14:38:02 -07007867 if (r != null && r.pid != Process.myPid() &&
7868 Settings.Secure.getInt(mContext.getContentResolver(),
7869 Settings.Secure.WTF_IS_FATAL, 0) != 0) {
Dan Egnor60d87622009-12-16 16:32:58 -08007870 crashApplication(r, crashInfo);
7871 return true;
7872 } else {
7873 return false;
7874 }
7875 }
7876
7877 /**
7878 * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit})
7879 * @return the corresponding {@link ProcessRecord} object, or null if none could be found
7880 */
Dianne Hackborncb44d962011-03-10 17:02:27 -08007881 private ProcessRecord findAppProcess(IBinder app, String reason) {
Dan Egnor60d87622009-12-16 16:32:58 -08007882 if (app == null) {
7883 return null;
7884 }
7885
7886 synchronized (this) {
7887 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
7888 final int NA = apps.size();
7889 for (int ia=0; ia<NA; ia++) {
7890 ProcessRecord p = apps.valueAt(ia);
7891 if (p.thread != null && p.thread.asBinder() == app) {
7892 return p;
7893 }
7894 }
7895 }
7896
Dianne Hackborncb44d962011-03-10 17:02:27 -08007897 Slog.w(TAG, "Can't find mystery application for " + reason
7898 + " from pid=" + Binder.getCallingPid()
7899 + " uid=" + Binder.getCallingUid() + ": " + app);
Dan Egnor60d87622009-12-16 16:32:58 -08007900 return null;
7901 }
7902 }
7903
7904 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007905 * Utility function for addErrorToDropBox and handleStrictModeViolation's logging
7906 * to append various headers to the dropbox log text.
Dan Egnor60d87622009-12-16 16:32:58 -08007907 */
Jeff Sharkeya353d262011-10-28 11:12:06 -07007908 private void appendDropBoxProcessHeaders(ProcessRecord process, String processName,
7909 StringBuilder sb) {
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08007910 // Watchdog thread ends up invoking this function (with
7911 // a null ProcessRecord) to add the stack file to dropbox.
7912 // Do not acquire a lock on this (am) in such cases, as it
7913 // could cause a potential deadlock, if and when watchdog
7914 // is invoked due to unavailability of lock on am and it
7915 // would prevent watchdog from killing system_server.
7916 if (process == null) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07007917 sb.append("Process: ").append(processName).append("\n");
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08007918 return;
7919 }
Brad Fitzpatrick1e02d362010-09-10 09:19:50 -07007920 // Note: ProcessRecord 'process' is guarded by the service
7921 // instance. (notably process.pkgList, which could otherwise change
7922 // concurrently during execution of this method)
7923 synchronized (this) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07007924 sb.append("Process: ").append(processName).append("\n");
Dan Egnora455d192010-03-12 08:52:28 -08007925 int flags = process.info.flags;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007926 IPackageManager pm = AppGlobals.getPackageManager();
Dan Egnora455d192010-03-12 08:52:28 -08007927 sb.append("Flags: 0x").append(Integer.toString(flags, 16)).append("\n");
7928 for (String pkg : process.pkgList) {
7929 sb.append("Package: ").append(pkg);
Dan Egnor42471dd2010-01-07 17:25:22 -08007930 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07007931 PackageInfo pi = pm.getPackageInfo(pkg, 0, 0);
Dan Egnora455d192010-03-12 08:52:28 -08007932 if (pi != null) {
7933 sb.append(" v").append(pi.versionCode);
7934 if (pi.versionName != null) {
7935 sb.append(" (").append(pi.versionName).append(")");
7936 }
7937 }
7938 } catch (RemoteException e) {
7939 Slog.e(TAG, "Error getting package info: " + pkg, e);
Dan Egnor60d87622009-12-16 16:32:58 -08007940 }
Dan Egnora455d192010-03-12 08:52:28 -08007941 sb.append("\n");
Dan Egnor60d87622009-12-16 16:32:58 -08007942 }
Dan Egnora455d192010-03-12 08:52:28 -08007943 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007944 }
7945
7946 private static String processClass(ProcessRecord process) {
7947 if (process == null || process.pid == MY_PID) {
7948 return "system_server";
7949 } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
7950 return "system_app";
7951 } else {
7952 return "data_app";
7953 }
7954 }
7955
7956 /**
7957 * Write a description of an error (crash, WTF, ANR) to the drop box.
7958 * @param eventType to include in the drop box tag ("crash", "wtf", etc.)
7959 * @param process which caused the error, null means the system server
7960 * @param activity which triggered the error, null if unknown
7961 * @param parent activity related to the error, null if unknown
7962 * @param subject line related to the error, null if absent
7963 * @param report in long form describing the error, null if absent
7964 * @param logFile to include in the report, null if none
7965 * @param crashInfo giving an application stack trace, null if absent
7966 */
7967 public void addErrorToDropBox(String eventType,
Jeff Sharkeya353d262011-10-28 11:12:06 -07007968 ProcessRecord process, String processName, ActivityRecord activity,
7969 ActivityRecord parent, String subject,
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007970 final String report, final File logFile,
7971 final ApplicationErrorReport.CrashInfo crashInfo) {
7972 // NOTE -- this must never acquire the ActivityManagerService lock,
7973 // otherwise the watchdog may be prevented from resetting the system.
7974
7975 final String dropboxTag = processClass(process) + "_" + eventType;
7976 final DropBoxManager dbox = (DropBoxManager)
7977 mContext.getSystemService(Context.DROPBOX_SERVICE);
7978
7979 // Exit early if the dropbox isn't configured to accept this report type.
7980 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
7981
7982 final StringBuilder sb = new StringBuilder(1024);
Jeff Sharkeya353d262011-10-28 11:12:06 -07007983 appendDropBoxProcessHeaders(process, processName, sb);
Dan Egnora455d192010-03-12 08:52:28 -08007984 if (activity != null) {
7985 sb.append("Activity: ").append(activity.shortComponentName).append("\n");
7986 }
7987 if (parent != null && parent.app != null && parent.app.pid != process.pid) {
7988 sb.append("Parent-Process: ").append(parent.app.processName).append("\n");
7989 }
7990 if (parent != null && parent != activity) {
7991 sb.append("Parent-Activity: ").append(parent.shortComponentName).append("\n");
7992 }
7993 if (subject != null) {
7994 sb.append("Subject: ").append(subject).append("\n");
7995 }
7996 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
Christian Lindeberg03d2ca62010-09-28 14:52:20 +02007997 if (Debug.isDebuggerConnected()) {
7998 sb.append("Debugger: Connected\n");
7999 }
Dan Egnora455d192010-03-12 08:52:28 -08008000 sb.append("\n");
8001
8002 // Do the rest in a worker thread to avoid blocking the caller on I/O
8003 // (After this point, we shouldn't access AMS internal data structures.)
8004 Thread worker = new Thread("Error dump: " + dropboxTag) {
8005 @Override
8006 public void run() {
8007 if (report != null) {
8008 sb.append(report);
8009 }
8010 if (logFile != null) {
8011 try {
8012 sb.append(FileUtils.readTextFile(logFile, 128 * 1024, "\n\n[[TRUNCATED]]"));
8013 } catch (IOException e) {
8014 Slog.e(TAG, "Error reading " + logFile, e);
8015 }
8016 }
8017 if (crashInfo != null && crashInfo.stackTrace != null) {
8018 sb.append(crashInfo.stackTrace);
8019 }
8020
8021 String setting = Settings.Secure.ERROR_LOGCAT_PREFIX + dropboxTag;
8022 int lines = Settings.Secure.getInt(mContext.getContentResolver(), setting, 0);
8023 if (lines > 0) {
8024 sb.append("\n");
8025
8026 // Merge several logcat streams, and take the last N lines
8027 InputStreamReader input = null;
8028 try {
8029 java.lang.Process logcat = new ProcessBuilder("/system/bin/logcat",
8030 "-v", "time", "-b", "events", "-b", "system", "-b", "main",
8031 "-t", String.valueOf(lines)).redirectErrorStream(true).start();
8032
8033 try { logcat.getOutputStream().close(); } catch (IOException e) {}
8034 try { logcat.getErrorStream().close(); } catch (IOException e) {}
8035 input = new InputStreamReader(logcat.getInputStream());
8036
8037 int num;
8038 char[] buf = new char[8192];
8039 while ((num = input.read(buf)) > 0) sb.append(buf, 0, num);
8040 } catch (IOException e) {
8041 Slog.e(TAG, "Error running logcat", e);
8042 } finally {
8043 if (input != null) try { input.close(); } catch (IOException e) {}
8044 }
8045 }
8046
8047 dbox.addText(dropboxTag, sb.toString());
Dan Egnor60d87622009-12-16 16:32:58 -08008048 }
Dan Egnora455d192010-03-12 08:52:28 -08008049 };
8050
8051 if (process == null || process.pid == MY_PID) {
8052 worker.run(); // We may be about to die -- need to run this synchronously
8053 } else {
8054 worker.start();
Dan Egnor60d87622009-12-16 16:32:58 -08008055 }
8056 }
8057
8058 /**
8059 * Bring up the "unexpected error" dialog box for a crashing app.
8060 * Deal with edge cases (intercepts from instrumented applications,
8061 * ActivityController, error intent receivers, that sort of thing).
8062 * @param r the application crashing
8063 * @param crashInfo describing the failure
8064 */
8065 private void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008066 long timeMillis = System.currentTimeMillis();
8067 String shortMsg = crashInfo.exceptionClassName;
8068 String longMsg = crashInfo.exceptionMessage;
8069 String stackTrace = crashInfo.stackTrace;
8070 if (shortMsg != null && longMsg != null) {
8071 longMsg = shortMsg + ": " + longMsg;
8072 } else if (shortMsg != null) {
8073 longMsg = shortMsg;
8074 }
8075
Dan Egnor60d87622009-12-16 16:32:58 -08008076 AppErrorResult result = new AppErrorResult();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008077 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008078 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008079 try {
8080 String name = r != null ? r.processName : null;
8081 int pid = r != null ? r.pid : Binder.getCallingPid();
Dan Egnor60d87622009-12-16 16:32:58 -08008082 if (!mController.appCrashed(name, pid,
Dan Egnorb7f03672009-12-09 16:22:32 -08008083 shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008084 Slog.w(TAG, "Force-killing crashed app " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008085 + " at watcher's request");
8086 Process.killProcess(pid);
Dan Egnorb7f03672009-12-09 16:22:32 -08008087 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008088 }
8089 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008090 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008091 }
8092 }
8093
8094 final long origId = Binder.clearCallingIdentity();
8095
8096 // If this process is running instrumentation, finish it.
8097 if (r != null && r.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008098 Slog.w(TAG, "Error in app " + r.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008099 + " running instrumentation " + r.instrumentationClass + ":");
Joe Onorato8a9b2202010-02-26 18:56:32 -08008100 if (shortMsg != null) Slog.w(TAG, " " + shortMsg);
8101 if (longMsg != null) Slog.w(TAG, " " + longMsg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008102 Bundle info = new Bundle();
8103 info.putString("shortMsg", shortMsg);
8104 info.putString("longMsg", longMsg);
8105 finishInstrumentationLocked(r, Activity.RESULT_CANCELED, info);
8106 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008107 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008108 }
8109
Dan Egnor60d87622009-12-16 16:32:58 -08008110 // If we can't identify the process or it's already exceeded its crash quota,
8111 // quit right away without showing a crash dialog.
8112 if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008113 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008114 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008115 }
8116
8117 Message msg = Message.obtain();
8118 msg.what = SHOW_ERROR_MSG;
8119 HashMap data = new HashMap();
8120 data.put("result", result);
8121 data.put("app", r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008122 msg.obj = data;
8123 mHandler.sendMessage(msg);
8124
8125 Binder.restoreCallingIdentity(origId);
8126 }
8127
8128 int res = result.get();
8129
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008130 Intent appErrorIntent = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008131 synchronized (this) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008132 if (r != null && !r.isolated) {
8133 // XXX Can't keep track of crash time for isolated processes,
8134 // since they don't have a persistent identity.
8135 mProcessCrashTimes.put(r.info.processName, r.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008136 SystemClock.uptimeMillis());
8137 }
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008138 if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008139 appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008140 }
8141 }
8142
8143 if (appErrorIntent != null) {
8144 try {
8145 mContext.startActivity(appErrorIntent);
8146 } catch (ActivityNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008147 Slog.w(TAG, "bug report receiver dissappeared", e);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008148 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008149 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008150 }
Dan Egnorb7f03672009-12-09 16:22:32 -08008151
8152 Intent createAppErrorIntentLocked(ProcessRecord r,
8153 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
8154 ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008155 if (report == null) {
8156 return null;
8157 }
8158 Intent result = new Intent(Intent.ACTION_APP_ERROR);
8159 result.setComponent(r.errorReportReceiver);
8160 result.putExtra(Intent.EXTRA_BUG_REPORT, report);
8161 result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
8162 return result;
8163 }
8164
Dan Egnorb7f03672009-12-09 16:22:32 -08008165 private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r,
8166 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008167 if (r.errorReportReceiver == null) {
8168 return null;
8169 }
8170
8171 if (!r.crashing && !r.notResponding) {
8172 return null;
8173 }
8174
Dan Egnorb7f03672009-12-09 16:22:32 -08008175 ApplicationErrorReport report = new ApplicationErrorReport();
8176 report.packageName = r.info.packageName;
8177 report.installerPackageName = r.errorReportReceiver.getPackageName();
8178 report.processName = r.processName;
8179 report.time = timeMillis;
Jacek Surazskie0ee6ef2010-01-07 16:23:03 +01008180 report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008181
Dan Egnorb7f03672009-12-09 16:22:32 -08008182 if (r.crashing) {
8183 report.type = ApplicationErrorReport.TYPE_CRASH;
8184 report.crashInfo = crashInfo;
8185 } else if (r.notResponding) {
8186 report.type = ApplicationErrorReport.TYPE_ANR;
8187 report.anrInfo = new ApplicationErrorReport.AnrInfo();
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008188
Dan Egnorb7f03672009-12-09 16:22:32 -08008189 report.anrInfo.activity = r.notRespondingReport.tag;
8190 report.anrInfo.cause = r.notRespondingReport.shortMsg;
8191 report.anrInfo.info = r.notRespondingReport.longMsg;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008192 }
8193
Dan Egnorb7f03672009-12-09 16:22:32 -08008194 return report;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008195 }
8196
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008197 public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008198 enforceNotIsolatedCaller("getProcessesInErrorState");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008199 // assume our apps are happy - lazy create the list
8200 List<ActivityManager.ProcessErrorStateInfo> errList = null;
8201
8202 synchronized (this) {
8203
8204 // iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008205 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8206 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008207 if ((app.thread != null) && (app.crashing || app.notResponding)) {
8208 // This one's in trouble, so we'll generate a report for it
8209 // crashes are higher priority (in case there's a crash *and* an anr)
8210 ActivityManager.ProcessErrorStateInfo report = null;
8211 if (app.crashing) {
8212 report = app.crashingReport;
8213 } else if (app.notResponding) {
8214 report = app.notRespondingReport;
8215 }
8216
8217 if (report != null) {
8218 if (errList == null) {
8219 errList = new ArrayList<ActivityManager.ProcessErrorStateInfo>(1);
8220 }
8221 errList.add(report);
8222 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008223 Slog.w(TAG, "Missing app error report, app = " + app.processName +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008224 " crashing = " + app.crashing +
8225 " notResponding = " + app.notResponding);
8226 }
8227 }
8228 }
8229 }
8230
8231 return errList;
8232 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07008233
8234 static int oomAdjToImportance(int adj, ActivityManager.RunningAppProcessInfo currApp) {
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008235 if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008236 if (currApp != null) {
8237 currApp.lru = adj - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
8238 }
8239 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008240 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
8241 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008242 } else if (adj >= ProcessList.HOME_APP_ADJ) {
8243 if (currApp != null) {
8244 currApp.lru = 0;
8245 }
8246 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008247 } else if (adj >= ProcessList.SERVICE_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008248 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
8249 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
8250 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
8251 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
8252 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
8253 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
8254 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
8255 } else {
8256 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
8257 }
8258 }
8259
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008260 private void fillInProcMemInfo(ProcessRecord app,
8261 ActivityManager.RunningAppProcessInfo outInfo) {
8262 outInfo.pid = app.pid;
8263 outInfo.uid = app.info.uid;
8264 if (mHeavyWeightProcess == app) {
8265 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_CANT_SAVE_STATE;
8266 }
8267 if (app.persistent) {
8268 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_PERSISTENT;
8269 }
8270 outInfo.lastTrimLevel = app.trimMemoryLevel;
8271 int adj = app.curAdj;
8272 outInfo.importance = oomAdjToImportance(adj, outInfo);
8273 outInfo.importanceReasonCode = app.adjTypeCode;
8274 }
8275
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008276 public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008277 enforceNotIsolatedCaller("getRunningAppProcesses");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008278 // Lazy instantiation of list
8279 List<ActivityManager.RunningAppProcessInfo> runList = null;
8280 synchronized (this) {
8281 // Iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008282 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8283 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008284 if ((app.thread != null) && (!app.crashing && !app.notResponding)) {
8285 // Generate process state info for running application
8286 ActivityManager.RunningAppProcessInfo currApp =
8287 new ActivityManager.RunningAppProcessInfo(app.processName,
8288 app.pid, app.getPackageList());
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008289 fillInProcMemInfo(app, currApp);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008290 if (app.adjSource instanceof ProcessRecord) {
8291 currApp.importanceReasonPid = ((ProcessRecord)app.adjSource).pid;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008292 currApp.importanceReasonImportance = oomAdjToImportance(
8293 app.adjSourceOom, null);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008294 } else if (app.adjSource instanceof ActivityRecord) {
8295 ActivityRecord r = (ActivityRecord)app.adjSource;
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008296 if (r.app != null) currApp.importanceReasonPid = r.app.pid;
8297 }
8298 if (app.adjTarget instanceof ComponentName) {
8299 currApp.importanceReasonComponent = (ComponentName)app.adjTarget;
8300 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08008301 //Slog.v(TAG, "Proc " + app.processName + ": imp=" + currApp.importance
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008302 // + " lru=" + currApp.lru);
8303 if (runList == null) {
8304 runList = new ArrayList<ActivityManager.RunningAppProcessInfo>();
8305 }
8306 runList.add(currApp);
8307 }
8308 }
8309 }
8310 return runList;
8311 }
8312
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008313 public List<ApplicationInfo> getRunningExternalApplications() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008314 enforceNotIsolatedCaller("getRunningExternalApplications");
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008315 List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses();
8316 List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>();
8317 if (runningApps != null && runningApps.size() > 0) {
8318 Set<String> extList = new HashSet<String>();
8319 for (ActivityManager.RunningAppProcessInfo app : runningApps) {
8320 if (app.pkgList != null) {
8321 for (String pkg : app.pkgList) {
8322 extList.add(pkg);
8323 }
8324 }
8325 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008326 IPackageManager pm = AppGlobals.getPackageManager();
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008327 for (String pkg : extList) {
8328 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07008329 ApplicationInfo info = pm.getApplicationInfo(pkg, 0, UserId.getCallingUserId());
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008330 if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
8331 retList.add(info);
8332 }
8333 } catch (RemoteException e) {
8334 }
8335 }
8336 }
8337 return retList;
8338 }
8339
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008340 @Override
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008341 public void getMyMemoryState(ActivityManager.RunningAppProcessInfo outInfo) {
8342 enforceNotIsolatedCaller("getMyMemoryState");
8343 synchronized (this) {
8344 ProcessRecord proc;
8345 synchronized (mPidsSelfLocked) {
8346 proc = mPidsSelfLocked.get(Binder.getCallingPid());
8347 }
8348 fillInProcMemInfo(proc, outInfo);
8349 }
8350 }
8351
8352 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008353 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008354 if (checkCallingPermission(android.Manifest.permission.DUMP)
8355 != PackageManager.PERMISSION_GRANTED) {
8356 pw.println("Permission Denial: can't dump ActivityManager from from pid="
8357 + Binder.getCallingPid()
8358 + ", uid=" + Binder.getCallingUid()
8359 + " without permission "
8360 + android.Manifest.permission.DUMP);
8361 return;
8362 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008363
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008364 boolean dumpAll = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008365 boolean dumpClient = false;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008366 String dumpPackage = null;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008367
8368 int opti = 0;
8369 while (opti < args.length) {
8370 String opt = args[opti];
8371 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
8372 break;
8373 }
8374 opti++;
8375 if ("-a".equals(opt)) {
8376 dumpAll = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008377 } else if ("-c".equals(opt)) {
8378 dumpClient = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008379 } else if ("-h".equals(opt)) {
8380 pw.println("Activity manager dump options:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008381 pw.println(" [-a] [-c] [-h] [cmd] ...");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008382 pw.println(" cmd may be one of:");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008383 pw.println(" a[ctivities]: activity stack state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008384 pw.println(" b[roadcasts] [PACKAGE_NAME]: broadcast state");
8385 pw.println(" i[ntents] [PACKAGE_NAME]: pending intent state");
8386 pw.println(" p[rocesses] [PACKAGE_NAME]: process state");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008387 pw.println(" o[om]: out of memory management");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008388 pw.println(" prov[iders] [COMP_SPEC ...]: content provider state");
Marco Nelissen18cb2872011-11-15 11:19:53 -08008389 pw.println(" provider [COMP_SPEC]: provider client-side state");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008390 pw.println(" s[ervices] [COMP_SPEC ...]: service state");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008391 pw.println(" service [COMP_SPEC]: service client-side state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008392 pw.println(" package [PACKAGE_NAME]: all state related to given package");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008393 pw.println(" all: dump all activities");
8394 pw.println(" top: dump the top activity");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008395 pw.println(" cmd may also be a COMP_SPEC to dump activities.");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008396 pw.println(" COMP_SPEC may be a component name (com.foo/.myApp),");
8397 pw.println(" a partial substring in a component name, a");
8398 pw.println(" hex object identifier.");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008399 pw.println(" -a: include all available server state.");
8400 pw.println(" -c: include client state.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008401 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008402 } else {
8403 pw.println("Unknown argument: " + opt + "; use -h for help");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008404 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008405 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008406
8407 long origId = Binder.clearCallingIdentity();
8408 boolean more = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008409 // Is the caller requesting to dump a particular piece of data?
8410 if (opti < args.length) {
8411 String cmd = args[opti];
8412 opti++;
8413 if ("activities".equals(cmd) || "a".equals(cmd)) {
8414 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008415 dumpActivitiesLocked(fd, pw, args, opti, true, dumpClient, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008416 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008417 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008418 String[] newArgs;
8419 String name;
8420 if (opti >= args.length) {
8421 name = null;
8422 newArgs = EMPTY_STRING_ARRAY;
8423 } else {
8424 name = args[opti];
8425 opti++;
8426 newArgs = new String[args.length - opti];
8427 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8428 args.length - opti);
8429 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008430 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008431 dumpBroadcastsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008432 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008433 } else if ("intents".equals(cmd) || "i".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008434 String[] newArgs;
8435 String name;
8436 if (opti >= args.length) {
8437 name = null;
8438 newArgs = EMPTY_STRING_ARRAY;
8439 } else {
8440 name = args[opti];
8441 opti++;
8442 newArgs = new String[args.length - opti];
8443 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8444 args.length - opti);
8445 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008446 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008447 dumpPendingIntentsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008448 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008449 } else if ("processes".equals(cmd) || "p".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008450 String[] newArgs;
8451 String name;
8452 if (opti >= args.length) {
8453 name = null;
8454 newArgs = EMPTY_STRING_ARRAY;
8455 } else {
8456 name = args[opti];
8457 opti++;
8458 newArgs = new String[args.length - opti];
8459 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8460 args.length - opti);
8461 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008462 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008463 dumpProcessesLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008464 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008465 } else if ("oom".equals(cmd) || "o".equals(cmd)) {
8466 synchronized (this) {
8467 dumpOomLocked(fd, pw, args, opti, true);
8468 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08008469 } else if ("provider".equals(cmd)) {
8470 String[] newArgs;
8471 String name;
8472 if (opti >= args.length) {
8473 name = null;
8474 newArgs = EMPTY_STRING_ARRAY;
8475 } else {
8476 name = args[opti];
8477 opti++;
8478 newArgs = new String[args.length - opti];
8479 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
8480 }
8481 if (!dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) {
8482 pw.println("No providers match: " + name);
8483 pw.println("Use -h for help.");
8484 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008485 } else if ("providers".equals(cmd) || "prov".equals(cmd)) {
8486 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008487 dumpProvidersLocked(fd, pw, args, opti, true, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008488 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008489 } else if ("service".equals(cmd)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008490 String[] newArgs;
8491 String name;
8492 if (opti >= args.length) {
8493 name = null;
8494 newArgs = EMPTY_STRING_ARRAY;
8495 } else {
8496 name = args[opti];
8497 opti++;
8498 newArgs = new String[args.length - opti];
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008499 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8500 args.length - opti);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008501 }
8502 if (!dumpService(fd, pw, name, newArgs, 0, dumpAll)) {
8503 pw.println("No services match: " + name);
8504 pw.println("Use -h for help.");
8505 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008506 } else if ("package".equals(cmd)) {
8507 String[] newArgs;
8508 if (opti >= args.length) {
8509 pw.println("package: no package name specified");
8510 pw.println("Use -h for help.");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008511 } else {
8512 dumpPackage = args[opti];
8513 opti++;
8514 newArgs = new String[args.length - opti];
8515 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8516 args.length - opti);
8517 args = newArgs;
8518 opti = 0;
Amith Yamasani7463ada2012-04-11 15:02:39 -07008519 more = true;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008520 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008521 } else if ("services".equals(cmd) || "s".equals(cmd)) {
8522 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008523 dumpServicesLocked(fd, pw, args, opti, true, dumpClient, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008524 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07008525 } else {
8526 // Dumping a single activity?
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008527 if (!dumpActivity(fd, pw, cmd, args, opti, dumpAll)) {
8528 pw.println("Bad activity command, or no activities match: " + cmd);
8529 pw.println("Use -h for help.");
Dianne Hackborn625ac272010-09-17 18:29:22 -07008530 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008531 }
8532 if (!more) {
8533 Binder.restoreCallingIdentity(origId);
Dianne Hackborn30d71892010-12-11 10:37:55 -08008534 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008535 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008536 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008537
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008538 // No piece of data specified, dump everything.
8539 synchronized (this) {
8540 boolean needSep;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008541 needSep = dumpPendingIntentsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008542 if (needSep) {
8543 pw.println(" ");
8544 }
8545 if (dumpAll) {
8546 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008547 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008548 needSep = dumpBroadcastsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008549 if (needSep) {
8550 pw.println(" ");
8551 }
8552 if (dumpAll) {
8553 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008554 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008555 needSep = dumpProvidersLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008556 if (needSep) {
8557 pw.println(" ");
8558 }
8559 if (dumpAll) {
8560 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008561 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008562 needSep = dumpServicesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008563 if (needSep) {
8564 pw.println(" ");
8565 }
8566 if (dumpAll) {
8567 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008568 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008569 needSep = dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008570 if (needSep) {
8571 pw.println(" ");
8572 }
8573 if (dumpAll) {
8574 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008575 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008576 dumpProcessesLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008577 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008578 Binder.restoreCallingIdentity(origId);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008579 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008580
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008581 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008582 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008583 pw.println("ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
8584 pw.println(" Main stack:");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008585 dumpHistoryList(fd, pw, mMainStack.mHistory, " ", "Hist", true, !dumpAll, dumpClient,
8586 dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008587 pw.println(" ");
8588 pw.println(" Running activities (most recent first):");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008589 dumpHistoryList(fd, pw, mMainStack.mLRUActivities, " ", "Run", false, !dumpAll, false,
8590 dumpPackage);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008591 if (mMainStack.mWaitingVisibleActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008592 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008593 pw.println(" Activities waiting for another to become visible:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008594 dumpHistoryList(fd, pw, mMainStack.mWaitingVisibleActivities, " ", "Wait", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008595 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008596 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008597 if (mMainStack.mStoppingActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008598 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008599 pw.println(" Activities waiting to stop:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008600 dumpHistoryList(fd, pw, mMainStack.mStoppingActivities, " ", "Stop", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008601 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008602 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008603 if (mMainStack.mGoingToSleepActivities.size() > 0) {
8604 pw.println(" ");
8605 pw.println(" Activities waiting to sleep:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008606 dumpHistoryList(fd, pw, mMainStack.mGoingToSleepActivities, " ", "Sleep", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008607 !dumpAll, false, dumpPackage);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008608 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008609 if (mMainStack.mFinishingActivities.size() > 0) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008610 pw.println(" ");
8611 pw.println(" Activities waiting to finish:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008612 dumpHistoryList(fd, pw, mMainStack.mFinishingActivities, " ", "Fin", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008613 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008614 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008615
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008616 pw.println(" ");
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08008617 if (mMainStack.mPausingActivity != null) {
8618 pw.println(" mPausingActivity: " + mMainStack.mPausingActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008619 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008620 pw.println(" mResumedActivity: " + mMainStack.mResumedActivity);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008621 pw.println(" mFocusedActivity: " + mFocusedActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008622 if (dumpAll) {
8623 pw.println(" mLastPausedActivity: " + mMainStack.mLastPausedActivity);
8624 pw.println(" mSleepTimeout: " + mMainStack.mSleepTimeout);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07008625 pw.println(" mDismissKeyguardOnNextActivity: "
8626 + mMainStack.mDismissKeyguardOnNextActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008627 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008628
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008629 if (mRecentTasks.size() > 0) {
8630 pw.println();
8631 pw.println(" Recent tasks:");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008632
8633 final int N = mRecentTasks.size();
8634 for (int i=0; i<N; i++) {
8635 TaskRecord tr = mRecentTasks.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008636 if (dumpPackage != null) {
8637 if (tr.realActivity == null ||
8638 !dumpPackage.equals(tr.realActivity)) {
8639 continue;
8640 }
8641 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008642 pw.print(" * Recent #"); pw.print(i); pw.print(": ");
8643 pw.println(tr);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008644 if (dumpAll) {
8645 mRecentTasks.get(i).dump(pw, " ");
8646 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008647 }
8648 }
8649
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008650 if (dumpAll) {
8651 pw.println(" ");
8652 pw.println(" mCurTask: " + mCurTask);
8653 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008654
8655 return true;
8656 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008657
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008658 boolean dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008659 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008660 boolean needSep = false;
8661 int numPers = 0;
8662
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008663 pw.println("ACTIVITY MANAGER RUNNING PROCESSES (dumpsys activity processes)");
8664
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008665 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008666 for (SparseArray<ProcessRecord> procs : mProcessNames.getMap().values()) {
8667 final int NA = procs.size();
8668 for (int ia=0; ia<NA; ia++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008669 ProcessRecord r = procs.valueAt(ia);
8670 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8671 continue;
8672 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008673 if (!needSep) {
8674 pw.println(" All known processes:");
8675 needSep = true;
8676 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008677 pw.print(r.persistent ? " *PERS*" : " *APP*");
8678 pw.print(" UID "); pw.print(procs.keyAt(ia));
8679 pw.print(" "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008680 r.dump(pw, " ");
8681 if (r.persistent) {
8682 numPers++;
8683 }
8684 }
8685 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008686 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008687
8688 if (mIsolatedProcesses.size() > 0) {
8689 if (needSep) pw.println(" ");
8690 needSep = true;
8691 pw.println(" Isolated process list (sorted by uid):");
8692 for (int i=0; i<mIsolatedProcesses.size(); i++) {
8693 ProcessRecord r = mIsolatedProcesses.valueAt(i);
8694 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8695 continue;
8696 }
8697 pw.println(String.format("%sIsolated #%2d: %s",
8698 " ", i, r.toString()));
8699 }
8700 }
8701
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008702 if (mLruProcesses.size() > 0) {
8703 if (needSep) pw.println(" ");
8704 needSep = true;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008705 pw.println(" Process LRU list (sorted by oom_adj):");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008706 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008707 "Proc", "PERS", false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008708 needSep = true;
8709 }
8710
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008711 if (dumpAll) {
8712 synchronized (mPidsSelfLocked) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008713 boolean printed = false;
8714 for (int i=0; i<mPidsSelfLocked.size(); i++) {
8715 ProcessRecord r = mPidsSelfLocked.valueAt(i);
8716 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8717 continue;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008718 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008719 if (!printed) {
8720 if (needSep) pw.println(" ");
8721 needSep = true;
8722 pw.println(" PID mappings:");
8723 printed = true;
8724 }
8725 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i));
8726 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008727 }
8728 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008729 }
8730
8731 if (mForegroundProcesses.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008732 synchronized (mPidsSelfLocked) {
8733 boolean printed = false;
8734 for (int i=0; i<mForegroundProcesses.size(); i++) {
8735 ProcessRecord r = mPidsSelfLocked.get(
8736 mForegroundProcesses.valueAt(i).pid);
8737 if (dumpPackage != null && (r == null
8738 || !dumpPackage.equals(r.info.packageName))) {
8739 continue;
8740 }
8741 if (!printed) {
8742 if (needSep) pw.println(" ");
8743 needSep = true;
8744 pw.println(" Foreground Processes:");
8745 printed = true;
8746 }
8747 pw.print(" PID #"); pw.print(mForegroundProcesses.keyAt(i));
8748 pw.print(": "); pw.println(mForegroundProcesses.valueAt(i));
8749 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008750 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008751 }
8752
8753 if (mPersistentStartingProcesses.size() > 0) {
8754 if (needSep) pw.println(" ");
8755 needSep = true;
8756 pw.println(" Persisent processes that are starting:");
8757 dumpProcessList(pw, this, mPersistentStartingProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008758 "Starting Norm", "Restarting PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008759 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008760
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008761 if (mRemovedProcesses.size() > 0) {
8762 if (needSep) pw.println(" ");
8763 needSep = true;
8764 pw.println(" Processes that are being removed:");
8765 dumpProcessList(pw, this, mRemovedProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008766 "Removed Norm", "Removed PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008767 }
8768
8769 if (mProcessesOnHold.size() > 0) {
8770 if (needSep) pw.println(" ");
8771 needSep = true;
8772 pw.println(" Processes that are on old until the system is ready:");
8773 dumpProcessList(pw, this, mProcessesOnHold, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008774 "OnHold Norm", "OnHold PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008775 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008776
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008777 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008778
8779 if (mProcessCrashTimes.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008780 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008781 long now = SystemClock.uptimeMillis();
8782 for (Map.Entry<String, SparseArray<Long>> procs
8783 : mProcessCrashTimes.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008784 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008785 SparseArray<Long> uids = procs.getValue();
8786 final int N = uids.size();
8787 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008788 int puid = uids.keyAt(i);
8789 ProcessRecord r = mProcessNames.get(pname, puid);
8790 if (dumpPackage != null && (r == null
8791 || !dumpPackage.equals(r.info.packageName))) {
8792 continue;
8793 }
8794 if (!printed) {
8795 if (needSep) pw.println(" ");
8796 needSep = true;
8797 pw.println(" Time since processes crashed:");
8798 printed = true;
8799 }
8800 pw.print(" Process "); pw.print(pname);
8801 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008802 pw.print(": last crashed ");
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008803 TimeUtils.formatDuration(now-uids.valueAt(i), pw);
8804 pw.println(" ago");
Dianne Hackbornfd12af42009-08-27 00:44:33 -07008805 }
8806 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008807 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008808
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008809 if (mBadProcesses.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008810 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008811 for (Map.Entry<String, SparseArray<Long>> procs
8812 : mBadProcesses.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008813 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008814 SparseArray<Long> uids = procs.getValue();
8815 final int N = uids.size();
8816 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008817 int puid = uids.keyAt(i);
8818 ProcessRecord r = mProcessNames.get(pname, puid);
8819 if (dumpPackage != null && (r == null
8820 || !dumpPackage.equals(r.info.packageName))) {
8821 continue;
8822 }
8823 if (!printed) {
8824 if (needSep) pw.println(" ");
8825 needSep = true;
8826 pw.println(" Bad processes:");
8827 }
8828 pw.print(" Bad process "); pw.print(pname);
8829 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008830 pw.print(": crashed at time ");
8831 pw.println(uids.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008832 }
8833 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008834 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008835
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008836 pw.println();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008837 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07008838 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn50685602011-12-01 12:23:37 -08008839 if (dumpAll) {
8840 StringBuilder sb = new StringBuilder(128);
8841 sb.append(" mPreviousProcessVisibleTime: ");
8842 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
8843 pw.println(sb);
8844 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07008845 if (mHeavyWeightProcess != null) {
8846 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
8847 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008848 pw.println(" mConfiguration: " + mConfiguration);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008849 if (dumpAll) {
8850 pw.println(" mConfigWillChange: " + mMainStack.mConfigWillChange);
Dianne Hackborn3d0724d2011-05-12 15:39:41 -07008851 if (mCompatModePackages.getPackages().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008852 boolean printed = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07008853 for (Map.Entry<String, Integer> entry
8854 : mCompatModePackages.getPackages().entrySet()) {
8855 String pkg = entry.getKey();
8856 int mode = entry.getValue();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008857 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
8858 continue;
8859 }
8860 if (!printed) {
8861 pw.println(" mScreenCompatPackages:");
8862 printed = true;
8863 }
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07008864 pw.print(" "); pw.print(pkg); pw.print(": ");
8865 pw.print(mode); pw.println();
8866 }
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07008867 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008868 }
Dianne Hackbornff5b1582012-04-12 17:24:07 -07008869 if (mSleeping || mWentToSleep || mLockScreenShown) {
8870 pw.println(" mSleeping=" + mSleeping + " mWentToSleep=" + mWentToSleep
8871 + " mLockScreenShown " + mLockScreenShown);
8872 }
8873 if (mShuttingDown) {
8874 pw.println(" mShuttingDown=" + mShuttingDown);
8875 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008876 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
8877 || mOrigWaitForDebugger) {
8878 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp
8879 + " mDebugTransient=" + mDebugTransient
8880 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger);
8881 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08008882 if (mOpenGlTraceApp != null) {
8883 pw.println(" mOpenGlTraceApp=" + mOpenGlTraceApp);
8884 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07008885 if (mProfileApp != null || mProfileProc != null || mProfileFile != null
8886 || mProfileFd != null) {
8887 pw.println(" mProfileApp=" + mProfileApp + " mProfileProc=" + mProfileProc);
8888 pw.println(" mProfileFile=" + mProfileFile + " mProfileFd=" + mProfileFd);
8889 pw.println(" mProfileType=" + mProfileType + " mAutoStopProfiler="
8890 + mAutoStopProfiler);
8891 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008892 if (mAlwaysFinishActivities || mController != null) {
8893 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities
8894 + " mController=" + mController);
8895 }
8896 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008897 pw.println(" Total persistent processes: " + numPers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008898 pw.println(" mStartRunning=" + mStartRunning
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07008899 + " mProcessesReady=" + mProcessesReady
8900 + " mSystemReady=" + mSystemReady);
8901 pw.println(" mBooting=" + mBooting
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008902 + " mBooted=" + mBooted
8903 + " mFactoryTest=" + mFactoryTest);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008904 pw.print(" mLastPowerCheckRealtime=");
8905 TimeUtils.formatDuration(mLastPowerCheckRealtime, pw);
8906 pw.println("");
8907 pw.print(" mLastPowerCheckUptime=");
8908 TimeUtils.formatDuration(mLastPowerCheckUptime, pw);
8909 pw.println("");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008910 pw.println(" mGoingToSleep=" + mMainStack.mGoingToSleep);
8911 pw.println(" mLaunchingActivity=" + mMainStack.mLaunchingActivity);
Dianne Hackborn906497c2010-05-10 15:57:38 -07008912 pw.println(" mAdjSeq=" + mAdjSeq + " mLruSeq=" + mLruSeq);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008913 pw.println(" mNumServiceProcs=" + mNumServiceProcs
8914 + " mNewNumServiceProcs=" + mNewNumServiceProcs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008915 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008916
8917 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008918 }
8919
Dianne Hackborn287952c2010-09-22 22:34:31 -07008920 boolean dumpProcessesToGc(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008921 int opti, boolean needSep, boolean dumpAll, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07008922 if (mProcessesToGc.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008923 boolean printed = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -07008924 long now = SystemClock.uptimeMillis();
8925 for (int i=0; i<mProcessesToGc.size(); i++) {
8926 ProcessRecord proc = mProcessesToGc.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008927 if (dumpPackage != null && !dumpPackage.equals(proc.info.packageName)) {
8928 continue;
8929 }
8930 if (!printed) {
8931 if (needSep) pw.println(" ");
8932 needSep = true;
8933 pw.println(" Processes that are waiting to GC:");
8934 printed = true;
8935 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008936 pw.print(" Process "); pw.println(proc);
8937 pw.print(" lowMem="); pw.print(proc.reportLowMemory);
8938 pw.print(", last gced=");
8939 pw.print(now-proc.lastRequestedGc);
8940 pw.print(" ms ago, last lowMem=");
8941 pw.print(now-proc.lastLowMemory);
8942 pw.println(" ms ago");
8943
8944 }
8945 }
8946 return needSep;
8947 }
8948
8949 boolean dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args,
8950 int opti, boolean dumpAll) {
8951 boolean needSep = false;
8952
8953 if (mLruProcesses.size() > 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07008954 if (needSep) pw.println(" ");
8955 needSep = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -07008956 pw.println(" OOM levels:");
Dianne Hackborn7d608422011-08-07 16:24:18 -07008957 pw.print(" SYSTEM_ADJ: "); pw.println(ProcessList.SYSTEM_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008958 pw.print(" PERSISTENT_PROC_ADJ: "); pw.println(ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07008959 pw.print(" FOREGROUND_APP_ADJ: "); pw.println(ProcessList.FOREGROUND_APP_ADJ);
8960 pw.print(" VISIBLE_APP_ADJ: "); pw.println(ProcessList.VISIBLE_APP_ADJ);
8961 pw.print(" PERCEPTIBLE_APP_ADJ: "); pw.println(ProcessList.PERCEPTIBLE_APP_ADJ);
8962 pw.print(" HEAVY_WEIGHT_APP_ADJ: "); pw.println(ProcessList.HEAVY_WEIGHT_APP_ADJ);
8963 pw.print(" BACKUP_APP_ADJ: "); pw.println(ProcessList.BACKUP_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008964 pw.print(" SERVICE_ADJ: "); pw.println(ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07008965 pw.print(" HOME_APP_ADJ: "); pw.println(ProcessList.HOME_APP_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07008966 pw.print(" PREVIOUS_APP_ADJ: "); pw.println(ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008967 pw.print(" SERVICE_B_ADJ: "); pw.println(ProcessList.SERVICE_B_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07008968 pw.print(" HIDDEN_APP_MIN_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008969 pw.print(" HIDDEN_APP_MAX_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MAX_ADJ);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07008970
8971 if (needSep) pw.println(" ");
8972 needSep = true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07008973 pw.println(" Process OOM control:");
Dianne Hackborn905577f2011-09-07 18:31:28 -07008974 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008975 "Proc", "PERS", true, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008976 needSep = true;
8977 }
8978
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008979 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008980
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008981 pw.println();
Dianne Hackborn287952c2010-09-22 22:34:31 -07008982 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07008983 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008984 if (mHeavyWeightProcess != null) {
8985 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
8986 }
8987
8988 return true;
8989 }
8990
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008991 /**
8992 * There are three ways to call this:
8993 * - no service specified: dump all the services
8994 * - a flattened component name that matched an existing service was specified as the
8995 * first arg: dump that one service
8996 * - the first arg isn't the flattened component name of an existing service:
8997 * dump all services whose component contains the first arg as a substring
8998 */
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008999 protected boolean dumpService(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9000 int opti, boolean dumpAll) {
9001 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009002
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009003 if ("all".equals(name)) {
Dianne Hackborn14bfa392010-07-24 19:58:06 -07009004 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07009005 try {
9006 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
9007 for (UserInfo user : users) {
9008 for (ServiceRecord r1 : mServiceMap.getAllServices(user.id)) {
9009 services.add(r1);
9010 }
9011 }
9012 } catch (RemoteException re) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009013 }
9014 }
9015 } else {
9016 ComponentName componentName = name != null
9017 ? ComponentName.unflattenFromString(name) : null;
9018 int objectId = 0;
9019 if (componentName == null) {
9020 // Not a '/' separated full component name; maybe an object ID?
9021 try {
9022 objectId = Integer.parseInt(name, 16);
9023 name = null;
9024 componentName = null;
9025 } catch (RuntimeException e) {
9026 }
9027 }
9028
9029 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07009030 try {
9031 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
9032 for (UserInfo user : users) {
9033 for (ServiceRecord r1 : mServiceMap.getAllServices(user.id)) {
9034 if (componentName != null) {
9035 if (r1.name.equals(componentName)) {
9036 services.add(r1);
9037 }
9038 } else if (name != null) {
9039 if (r1.name.flattenToString().contains(name)) {
9040 services.add(r1);
9041 }
9042 } else if (System.identityHashCode(r1) == objectId) {
9043 services.add(r1);
9044 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009045 }
Dianne Hackborn14bfa392010-07-24 19:58:06 -07009046 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009047 } catch (RemoteException re) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009048 }
9049 }
9050 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009051
9052 if (services.size() <= 0) {
9053 return false;
9054 }
9055
9056 boolean needSep = false;
9057 for (int i=0; i<services.size(); i++) {
9058 if (needSep) {
9059 pw.println();
9060 }
9061 needSep = true;
9062 dumpService("", fd, pw, services.get(i), args, dumpAll);
9063 }
9064 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009065 }
9066
9067 /**
9068 * Invokes IApplicationThread.dumpService() on the thread of the specified service if
9069 * there is a thread associated with the service.
9070 */
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009071 private void dumpService(String prefix, FileDescriptor fd, PrintWriter pw,
9072 final ServiceRecord r, String[] args, boolean dumpAll) {
9073 String innerPrefix = prefix + " ";
9074 synchronized (this) {
9075 pw.print(prefix); pw.print("SERVICE ");
9076 pw.print(r.shortName); pw.print(" ");
9077 pw.print(Integer.toHexString(System.identityHashCode(r)));
9078 pw.print(" pid=");
9079 if (r.app != null) pw.println(r.app.pid);
9080 else pw.println("(not running)");
9081 if (dumpAll) {
9082 r.dump(pw, innerPrefix);
9083 }
9084 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009085 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009086 pw.print(prefix); pw.println(" Client:");
9087 pw.flush();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009088 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009089 TransferPipe tp = new TransferPipe();
9090 try {
9091 r.app.thread.dumpService(tp.getWriteFd().getFileDescriptor(), r, args);
9092 tp.setBufferPrefix(prefix + " ");
9093 tp.go(fd);
9094 } finally {
9095 tp.kill();
9096 }
9097 } catch (IOException e) {
9098 pw.println(prefix + " Failure while dumping the service: " + e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009099 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009100 pw.println(prefix + " Got a RemoteException while dumping the service");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009101 }
9102 }
9103 }
9104
Marco Nelissen18cb2872011-11-15 11:19:53 -08009105 /**
9106 * There are three ways to call this:
9107 * - no provider specified: dump all the providers
9108 * - a flattened component name that matched an existing provider was specified as the
9109 * first arg: dump that one provider
9110 * - the first arg isn't the flattened component name of an existing provider:
9111 * dump all providers whose component contains the first arg as a substring
9112 */
9113 protected boolean dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9114 int opti, boolean dumpAll) {
Marco Nelissende7408c2012-02-08 14:57:38 -08009115 return mProviderMap.dumpProvider(fd, pw, name, args, opti, dumpAll);
Marco Nelissen18cb2872011-11-15 11:19:53 -08009116 }
9117
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009118 static class ItemMatcher {
9119 ArrayList<ComponentName> components;
9120 ArrayList<String> strings;
9121 ArrayList<Integer> objects;
9122 boolean all;
9123
9124 ItemMatcher() {
9125 all = true;
9126 }
9127
9128 void build(String name) {
9129 ComponentName componentName = ComponentName.unflattenFromString(name);
9130 if (componentName != null) {
9131 if (components == null) {
9132 components = new ArrayList<ComponentName>();
9133 }
9134 components.add(componentName);
9135 all = false;
9136 } else {
9137 int objectId = 0;
9138 // Not a '/' separated full component name; maybe an object ID?
9139 try {
9140 objectId = Integer.parseInt(name, 16);
9141 if (objects == null) {
9142 objects = new ArrayList<Integer>();
9143 }
9144 objects.add(objectId);
9145 all = false;
9146 } catch (RuntimeException e) {
9147 // Not an integer; just do string match.
9148 if (strings == null) {
9149 strings = new ArrayList<String>();
9150 }
9151 strings.add(name);
9152 all = false;
9153 }
9154 }
9155 }
9156
9157 int build(String[] args, int opti) {
9158 for (; opti<args.length; opti++) {
9159 String name = args[opti];
9160 if ("--".equals(name)) {
9161 return opti+1;
9162 }
9163 build(name);
9164 }
9165 return opti;
9166 }
9167
9168 boolean match(Object object, ComponentName comp) {
9169 if (all) {
9170 return true;
9171 }
9172 if (components != null) {
9173 for (int i=0; i<components.size(); i++) {
9174 if (components.get(i).equals(comp)) {
9175 return true;
9176 }
9177 }
9178 }
9179 if (objects != null) {
9180 for (int i=0; i<objects.size(); i++) {
9181 if (System.identityHashCode(object) == objects.get(i)) {
9182 return true;
9183 }
9184 }
9185 }
9186 if (strings != null) {
9187 String flat = comp.flattenToString();
9188 for (int i=0; i<strings.size(); i++) {
9189 if (flat.contains(strings.get(i))) {
9190 return true;
9191 }
9192 }
9193 }
9194 return false;
9195 }
9196 }
9197
Dianne Hackborn625ac272010-09-17 18:29:22 -07009198 /**
9199 * There are three things that cmd can be:
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009200 * - a flattened component name that matches an existing activity
Dianne Hackborn625ac272010-09-17 18:29:22 -07009201 * - the cmd arg isn't the flattened component name of an existing activity:
9202 * dump all activity whose component contains the cmd as a substring
9203 * - A hex number of the ActivityRecord object instance.
9204 */
9205 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9206 int opti, boolean dumpAll) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009207 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009208
9209 if ("all".equals(name)) {
9210 synchronized (this) {
9211 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009212 activities.add(r1);
9213 }
9214 }
Dianne Hackbornf9302322011-06-14 18:36:14 -07009215 } else if ("top".equals(name)) {
9216 synchronized (this) {
9217 final int N = mMainStack.mHistory.size();
9218 if (N > 0) {
9219 activities.add((ActivityRecord)mMainStack.mHistory.get(N-1));
9220 }
9221 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009222 } else {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009223 ItemMatcher matcher = new ItemMatcher();
9224 matcher.build(name);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009225
9226 synchronized (this) {
9227 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009228 if (matcher.match(r1, r1.intent.getComponent())) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009229 activities.add(r1);
9230 }
9231 }
9232 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009233 }
9234
9235 if (activities.size() <= 0) {
9236 return false;
9237 }
9238
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009239 String[] newArgs = new String[args.length - opti];
9240 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
9241
Dianne Hackborn30d71892010-12-11 10:37:55 -08009242 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009243 boolean needSep = false;
Dianne Hackborn30d71892010-12-11 10:37:55 -08009244 for (int i=activities.size()-1; i>=0; i--) {
9245 ActivityRecord r = (ActivityRecord)activities.get(i);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009246 if (needSep) {
9247 pw.println();
9248 }
9249 needSep = true;
9250 synchronized (this) {
9251 if (lastTask != r.task) {
9252 lastTask = r.task;
9253 pw.print("TASK "); pw.print(lastTask.affinity);
9254 pw.print(" id="); pw.println(lastTask.taskId);
9255 if (dumpAll) {
9256 lastTask.dump(pw, " ");
9257 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08009258 }
9259 }
9260 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009261 }
9262 return true;
9263 }
9264
9265 /**
9266 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
9267 * there is a thread associated with the activity.
9268 */
Dianne Hackborn30d71892010-12-11 10:37:55 -08009269 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009270 final ActivityRecord r, String[] args, boolean dumpAll) {
9271 String innerPrefix = prefix + " ";
Dianne Hackborn30d71892010-12-11 10:37:55 -08009272 synchronized (this) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009273 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
9274 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
9275 pw.print(" pid=");
Dianne Hackborn30d71892010-12-11 10:37:55 -08009276 if (r.app != null) pw.println(r.app.pid);
9277 else pw.println("(not running)");
9278 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009279 r.dump(pw, innerPrefix);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009280 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009281 }
9282 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009283 // flush anything that is already in the PrintWriter since the thread is going
9284 // to write to the file descriptor directly
9285 pw.flush();
Dianne Hackborn625ac272010-09-17 18:29:22 -07009286 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009287 TransferPipe tp = new TransferPipe();
9288 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009289 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9290 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009291 tp.go(fd);
9292 } finally {
9293 tp.kill();
9294 }
9295 } catch (IOException e) {
9296 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009297 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009298 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
Dianne Hackborn625ac272010-09-17 18:29:22 -07009299 }
9300 }
9301 }
9302
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009303 boolean dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009304 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009305 boolean needSep = false;
9306
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009307 pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009308 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009309 if (mRegisteredReceivers.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009310 boolean printed = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009311 Iterator it = mRegisteredReceivers.values().iterator();
9312 while (it.hasNext()) {
9313 ReceiverList r = (ReceiverList)it.next();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009314 if (dumpPackage != null && (r.app == null ||
9315 !dumpPackage.equals(r.app.info.packageName))) {
9316 continue;
9317 }
9318 if (!printed) {
9319 pw.println(" Registered Receivers:");
9320 needSep = true;
9321 printed = true;
9322 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009323 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009324 r.dump(pw, " ");
9325 }
9326 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009327
9328 if (mReceiverResolver.dump(pw, needSep ?
9329 "\n Receiver Resolver Table:" : " Receiver Resolver Table:",
9330 " ", dumpPackage, false)) {
9331 needSep = true;
9332 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009333 }
Christopher Tatef46723b2012-01-26 14:19:24 -08009334
9335 for (BroadcastQueue q : mBroadcastQueues) {
9336 needSep = q.dumpLocked(fd, pw, args, opti, dumpAll, dumpPackage, needSep);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009337 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009338
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009339 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009340
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009341 if (mStickyBroadcasts != null && dumpPackage == null) {
9342 if (needSep) {
9343 pw.println();
9344 }
9345 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009346 pw.println(" Sticky broadcasts:");
9347 StringBuilder sb = new StringBuilder(128);
9348 for (Map.Entry<String, ArrayList<Intent>> ent
9349 : mStickyBroadcasts.entrySet()) {
9350 pw.print(" * Sticky action "); pw.print(ent.getKey());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009351 if (dumpAll) {
9352 pw.println(":");
9353 ArrayList<Intent> intents = ent.getValue();
9354 final int N = intents.size();
9355 for (int i=0; i<N; i++) {
9356 sb.setLength(0);
9357 sb.append(" Intent: ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009358 intents.get(i).toShortString(sb, false, true, false, false);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009359 pw.println(sb.toString());
9360 Bundle bundle = intents.get(i).getExtras();
9361 if (bundle != null) {
9362 pw.print(" ");
9363 pw.println(bundle.toString());
9364 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009365 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009366 } else {
9367 pw.println("");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009368 }
9369 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009370 needSep = true;
9371 }
9372
9373 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009374 pw.println();
Christopher Tatef46723b2012-01-26 14:19:24 -08009375 for (BroadcastQueue queue : mBroadcastQueues) {
9376 pw.println(" mBroadcastsScheduled [" + queue.mQueueName + "]="
9377 + queue.mBroadcastsScheduled);
9378 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009379 pw.println(" mHandler:");
9380 mHandler.dump(new PrintWriterPrinter(pw), " ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009381 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009382 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009383
9384 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009385 }
9386
Marco Nelissen18cb2872011-11-15 11:19:53 -08009387 /**
9388 * Prints a list of ServiceRecords (dumpsys activity services)
9389 */
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009390 boolean dumpServicesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009391 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009392 boolean needSep = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009393
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009394 ItemMatcher matcher = new ItemMatcher();
9395 matcher.build(args, opti);
9396
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009397 pw.println("ACTIVITY MANAGER SERVICES (dumpsys activity services)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009398 try {
9399 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
9400 for (UserInfo user : users) {
9401 if (mServiceMap.getAllServices(user.id).size() > 0) {
9402 boolean printed = false;
9403 long nowReal = SystemClock.elapsedRealtime();
9404 Iterator<ServiceRecord> it = mServiceMap.getAllServices(
9405 user.id).iterator();
9406 needSep = false;
9407 while (it.hasNext()) {
9408 ServiceRecord r = it.next();
9409 if (!matcher.match(r, r.name)) {
9410 continue;
9411 }
9412 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9413 continue;
9414 }
9415 if (!printed) {
9416 pw.println(" Active services:");
9417 printed = true;
9418 }
9419 if (needSep) {
9420 pw.println();
9421 }
9422 pw.print(" * ");
9423 pw.println(r);
9424 if (dumpAll) {
9425 r.dump(pw, " ");
9426 needSep = true;
9427 } else {
9428 pw.print(" app=");
9429 pw.println(r.app);
9430 pw.print(" created=");
9431 TimeUtils.formatDuration(r.createTime, nowReal, pw);
9432 pw.print(" started=");
9433 pw.print(r.startRequested);
9434 pw.print(" connections=");
9435 pw.println(r.connections.size());
9436 if (r.connections.size() > 0) {
9437 pw.println(" Connections:");
9438 for (ArrayList<ConnectionRecord> clist : r.connections.values()) {
9439 for (int i = 0; i < clist.size(); i++) {
9440 ConnectionRecord conn = clist.get(i);
9441 pw.print(" ");
9442 pw.print(conn.binding.intent.intent.getIntent()
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009443 .toShortString(false, false, false, false));
Amith Yamasani742a6712011-05-04 14:49:28 -07009444 pw.print(" -> ");
9445 ProcessRecord proc = conn.binding.client;
9446 pw.println(proc != null ? proc.toShortString() : "null");
9447 }
9448 }
Dianne Hackborn8ec8d412011-11-14 18:27:24 -08009449 }
9450 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009451 if (dumpClient && r.app != null && r.app.thread != null) {
9452 pw.println(" Client:");
9453 pw.flush();
9454 try {
9455 TransferPipe tp = new TransferPipe();
9456 try {
9457 r.app.thread.dumpService(tp.getWriteFd().getFileDescriptor(),
9458 r, args);
9459 tp.setBufferPrefix(" ");
9460 // Short timeout, since blocking here can
9461 // deadlock with the application.
9462 tp.go(fd, 2000);
9463 } finally {
9464 tp.kill();
9465 }
9466 } catch (IOException e) {
9467 pw.println(" Failure while dumping the service: " + e);
9468 } catch (RemoteException e) {
9469 pw.println(" Got a RemoteException while dumping the service");
9470 }
9471 needSep = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009472 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009473 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009474 needSep = printed;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009475 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009476 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009477 } catch (RemoteException re) {
9478
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009479 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009480
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009481 if (mPendingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009482 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009483 for (int i=0; i<mPendingServices.size(); i++) {
9484 ServiceRecord r = mPendingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009485 if (!matcher.match(r, r.name)) {
9486 continue;
9487 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009488 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9489 continue;
9490 }
9491 if (!printed) {
9492 if (needSep) pw.println(" ");
9493 needSep = true;
9494 pw.println(" Pending services:");
9495 printed = true;
9496 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009497 pw.print(" * Pending "); pw.println(r);
9498 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009499 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009500 needSep = true;
9501 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009502
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009503 if (mRestartingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009504 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009505 for (int i=0; i<mRestartingServices.size(); i++) {
9506 ServiceRecord r = mRestartingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009507 if (!matcher.match(r, r.name)) {
9508 continue;
9509 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009510 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9511 continue;
9512 }
9513 if (!printed) {
9514 if (needSep) pw.println(" ");
9515 needSep = true;
9516 pw.println(" Restarting services:");
9517 printed = true;
9518 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009519 pw.print(" * Restarting "); pw.println(r);
9520 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009521 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009522 needSep = true;
9523 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009524
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009525 if (mStoppingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009526 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009527 for (int i=0; i<mStoppingServices.size(); i++) {
9528 ServiceRecord r = mStoppingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009529 if (!matcher.match(r, r.name)) {
9530 continue;
9531 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009532 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9533 continue;
9534 }
9535 if (!printed) {
9536 if (needSep) pw.println(" ");
9537 needSep = true;
9538 pw.println(" Stopping services:");
9539 printed = true;
9540 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009541 pw.print(" * Stopping "); pw.println(r);
9542 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009543 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009544 needSep = true;
9545 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009546
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009547 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009548 if (mServiceConnections.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009549 boolean printed = false;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009550 Iterator<ArrayList<ConnectionRecord>> it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009551 = mServiceConnections.values().iterator();
9552 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009553 ArrayList<ConnectionRecord> r = it.next();
9554 for (int i=0; i<r.size(); i++) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009555 ConnectionRecord cr = r.get(i);
9556 if (!matcher.match(cr.binding.service, cr.binding.service.name)) {
9557 continue;
9558 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009559 if (dumpPackage != null && (cr.binding.client == null
9560 || !dumpPackage.equals(cr.binding.client.info.packageName))) {
9561 continue;
9562 }
9563 if (!printed) {
9564 if (needSep) pw.println(" ");
9565 needSep = true;
9566 pw.println(" Connection bindings to services:");
9567 printed = true;
9568 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009569 pw.print(" * "); pw.println(cr);
9570 cr.dump(pw, " ");
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009571 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009572 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009573 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009574 }
9575 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009576
9577 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009578 }
9579
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009580 boolean dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009581 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07009582 boolean needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009583
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009584 ItemMatcher matcher = new ItemMatcher();
9585 matcher.build(args, opti);
9586
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009587 pw.println("ACTIVITY MANAGER CONTENT PROVIDERS (dumpsys activity providers)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009588
9589 mProviderMap.dumpProvidersLocked(pw, dumpAll);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009590
9591 if (mLaunchingProviders.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009592 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009593 for (int i=mLaunchingProviders.size()-1; i>=0; i--) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009594 ContentProviderRecord r = mLaunchingProviders.get(i);
9595 if (dumpPackage != null && !dumpPackage.equals(r.name.getPackageName())) {
9596 continue;
9597 }
9598 if (!printed) {
9599 if (needSep) pw.println(" ");
9600 needSep = true;
9601 pw.println(" Launching content providers:");
9602 printed = true;
9603 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009604 pw.print(" Launching #"); pw.print(i); pw.print(": ");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009605 pw.println(r);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009606 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009607 }
9608
9609 if (mGrantedUriPermissions.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009610 if (needSep) pw.println();
9611 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009612 pw.println("Granted Uri Permissions:");
9613 for (int i=0; i<mGrantedUriPermissions.size(); i++) {
9614 int uid = mGrantedUriPermissions.keyAt(i);
9615 HashMap<Uri, UriPermission> perms
9616 = mGrantedUriPermissions.valueAt(i);
9617 pw.print(" * UID "); pw.print(uid);
9618 pw.println(" holds:");
9619 for (UriPermission perm : perms.values()) {
9620 pw.print(" "); pw.println(perm);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009621 if (dumpAll) {
9622 perm.dump(pw, " ");
9623 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009624 }
9625 }
9626 needSep = true;
9627 }
9628
9629 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009630 }
9631
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009632 boolean dumpPendingIntentsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009633 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009634 boolean needSep = false;
9635
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009636 if (mIntentSenderRecords.size() > 0) {
9637 boolean printed = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009638 Iterator<WeakReference<PendingIntentRecord>> it
9639 = mIntentSenderRecords.values().iterator();
9640 while (it.hasNext()) {
9641 WeakReference<PendingIntentRecord> ref = it.next();
9642 PendingIntentRecord rec = ref != null ? ref.get(): null;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009643 if (dumpPackage != null && (rec == null
9644 || !dumpPackage.equals(rec.key.packageName))) {
9645 continue;
9646 }
9647 if (!printed) {
9648 pw.println("ACTIVITY MANAGER PENDING INTENTS (dumpsys activity intents)");
9649 printed = true;
9650 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009651 needSep = true;
9652 if (rec != null) {
9653 pw.print(" * "); pw.println(rec);
9654 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009655 rec.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009656 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009657 } else {
9658 pw.print(" * "); pw.println(ref);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009659 }
9660 }
9661 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009662
9663 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009664 }
9665
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009666 private static final void dumpHistoryList(FileDescriptor fd, PrintWriter pw, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009667 String prefix, String label, boolean complete, boolean brief, boolean client,
9668 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009669 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009670 boolean needNL = false;
9671 final String innerPrefix = prefix + " ";
9672 final String[] args = new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009673 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009674 final ActivityRecord r = (ActivityRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009675 if (dumpPackage != null && !dumpPackage.equals(r.packageName)) {
9676 continue;
9677 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07009678 final boolean full = !brief && (complete || !r.isInHistory());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009679 if (needNL) {
9680 pw.println(" ");
9681 needNL = false;
9682 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009683 if (lastTask != r.task) {
9684 lastTask = r.task;
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009685 pw.print(prefix);
9686 pw.print(full ? "* " : " ");
9687 pw.println(lastTask);
9688 if (full) {
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009689 lastTask.dump(pw, prefix + " ");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009690 } else if (complete) {
9691 // Complete + brief == give a summary. Isn't that obvious?!?
9692 if (lastTask.intent != null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009693 pw.print(prefix); pw.print(" ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009694 pw.println(lastTask.intent.toInsecureStringWithClip());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009695 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009696 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009697 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009698 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label);
9699 pw.print(" #"); pw.print(i); pw.print(": ");
9700 pw.println(r);
9701 if (full) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009702 r.dump(pw, innerPrefix);
9703 } else if (complete) {
9704 // Complete + brief == give a summary. Isn't that obvious?!?
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009705 pw.print(innerPrefix); pw.println(r.intent.toInsecureString());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009706 if (r.app != null) {
9707 pw.print(innerPrefix); pw.println(r.app);
9708 }
9709 }
9710 if (client && r.app != null && r.app.thread != null) {
9711 // flush anything that is already in the PrintWriter since the thread is going
9712 // to write to the file descriptor directly
9713 pw.flush();
9714 try {
9715 TransferPipe tp = new TransferPipe();
9716 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009717 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9718 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009719 // Short timeout, since blocking here can
9720 // deadlock with the application.
9721 tp.go(fd, 2000);
9722 } finally {
9723 tp.kill();
9724 }
9725 } catch (IOException e) {
9726 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
9727 } catch (RemoteException e) {
9728 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
9729 }
9730 needNL = true;
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009731 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009732 }
9733 }
9734
Dianne Hackborn09c916b2009-12-08 14:50:51 -08009735 private static String buildOomTag(String prefix, String space, int val, int base) {
9736 if (val == base) {
9737 if (space == null) return prefix;
9738 return prefix + " ";
9739 }
9740 return prefix + "+" + Integer.toString(val-base);
9741 }
9742
9743 private static final int dumpProcessList(PrintWriter pw,
9744 ActivityManagerService service, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009745 String prefix, String normalLabel, String persistentLabel,
9746 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009747 int numPers = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07009748 final int N = list.size()-1;
9749 for (int i=N; i>=0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009750 ProcessRecord r = (ProcessRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009751 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9752 continue;
9753 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009754 pw.println(String.format("%s%s #%2d: %s",
9755 prefix, (r.persistent ? persistentLabel : normalLabel),
9756 i, r.toString()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009757 if (r.persistent) {
9758 numPers++;
9759 }
9760 }
9761 return numPers;
9762 }
9763
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009764 private static final boolean dumpProcessOomList(PrintWriter pw,
Dianne Hackborn905577f2011-09-07 18:31:28 -07009765 ActivityManagerService service, List<ProcessRecord> origList,
Dianne Hackborn287952c2010-09-22 22:34:31 -07009766 String prefix, String normalLabel, String persistentLabel,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009767 boolean inclDetails, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009768
Dianne Hackborn905577f2011-09-07 18:31:28 -07009769 ArrayList<Pair<ProcessRecord, Integer>> list
9770 = new ArrayList<Pair<ProcessRecord, Integer>>(origList.size());
9771 for (int i=0; i<origList.size(); i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009772 ProcessRecord r = origList.get(i);
9773 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9774 continue;
9775 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07009776 list.add(new Pair<ProcessRecord, Integer>(origList.get(i), i));
9777 }
9778
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009779 if (list.size() <= 0) {
9780 return false;
9781 }
9782
Dianne Hackborn905577f2011-09-07 18:31:28 -07009783 Comparator<Pair<ProcessRecord, Integer>> comparator
9784 = new Comparator<Pair<ProcessRecord, Integer>>() {
9785 @Override
9786 public int compare(Pair<ProcessRecord, Integer> object1,
9787 Pair<ProcessRecord, Integer> object2) {
9788 if (object1.first.setAdj != object2.first.setAdj) {
9789 return object1.first.setAdj > object2.first.setAdj ? -1 : 1;
9790 }
9791 if (object1.second.intValue() != object2.second.intValue()) {
9792 return object1.second.intValue() > object2.second.intValue() ? -1 : 1;
9793 }
9794 return 0;
9795 }
9796 };
9797
9798 Collections.sort(list, comparator);
9799
Dianne Hackborn287952c2010-09-22 22:34:31 -07009800 final long curRealtime = SystemClock.elapsedRealtime();
9801 final long realtimeSince = curRealtime - service.mLastPowerCheckRealtime;
9802 final long curUptime = SystemClock.uptimeMillis();
9803 final long uptimeSince = curUptime - service.mLastPowerCheckUptime;
9804
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009805 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07009806 ProcessRecord r = list.get(i).first;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009807 String oomAdj;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009808 if (r.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07009809 oomAdj = buildOomTag("bak", " ", r.setAdj, ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009810 } else if (r.setAdj >= ProcessList.SERVICE_B_ADJ) {
9811 oomAdj = buildOomTag("svcb ", null, r.setAdj, ProcessList.SERVICE_B_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009812 } else if (r.setAdj >= ProcessList.PREVIOUS_APP_ADJ) {
9813 oomAdj = buildOomTag("prev ", null, r.setAdj, ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009814 } else if (r.setAdj >= ProcessList.HOME_APP_ADJ) {
9815 oomAdj = buildOomTag("home ", null, r.setAdj, ProcessList.HOME_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009816 } else if (r.setAdj >= ProcessList.SERVICE_ADJ) {
9817 oomAdj = buildOomTag("svc ", null, r.setAdj, ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009818 } else if (r.setAdj >= ProcessList.BACKUP_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08009819 oomAdj = buildOomTag("bkup ", null, r.setAdj, ProcessList.BACKUP_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009820 } else if (r.setAdj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
9821 oomAdj = buildOomTag("hvy ", null, r.setAdj, ProcessList.HEAVY_WEIGHT_APP_ADJ);
9822 } else if (r.setAdj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
9823 oomAdj = buildOomTag("prcp ", null, r.setAdj, ProcessList.PERCEPTIBLE_APP_ADJ);
9824 } else if (r.setAdj >= ProcessList.VISIBLE_APP_ADJ) {
9825 oomAdj = buildOomTag("vis ", null, r.setAdj, ProcessList.VISIBLE_APP_ADJ);
9826 } else if (r.setAdj >= ProcessList.FOREGROUND_APP_ADJ) {
9827 oomAdj = buildOomTag("fore ", null, r.setAdj, ProcessList.FOREGROUND_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009828 } else if (r.setAdj >= ProcessList.PERSISTENT_PROC_ADJ) {
9829 oomAdj = buildOomTag("pers ", null, r.setAdj, ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009830 } else if (r.setAdj >= ProcessList.SYSTEM_ADJ) {
9831 oomAdj = buildOomTag("sys ", null, r.setAdj, ProcessList.SYSTEM_ADJ);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009832 } else {
9833 oomAdj = Integer.toString(r.setAdj);
9834 }
9835 String schedGroup;
9836 switch (r.setSchedGroup) {
9837 case Process.THREAD_GROUP_BG_NONINTERACTIVE:
9838 schedGroup = "B";
9839 break;
9840 case Process.THREAD_GROUP_DEFAULT:
9841 schedGroup = "F";
9842 break;
9843 default:
9844 schedGroup = Integer.toString(r.setSchedGroup);
9845 break;
9846 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07009847 String foreground;
9848 if (r.foregroundActivities) {
9849 foreground = "A";
9850 } else if (r.foregroundServices) {
9851 foreground = "S";
9852 } else {
9853 foreground = " ";
9854 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07009855 pw.println(String.format("%s%s #%2d: adj=%s/%s%s trm=%2d %s (%s)",
Dianne Hackborn287952c2010-09-22 22:34:31 -07009856 prefix, (r.persistent ? persistentLabel : normalLabel),
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009857 (origList.size()-1)-list.get(i).second, oomAdj, schedGroup,
9858 foreground, r.trimMemoryLevel, r.toShortString(), r.adjType));
Dianne Hackborn287952c2010-09-22 22:34:31 -07009859 if (r.adjSource != null || r.adjTarget != null) {
9860 pw.print(prefix);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009861 pw.print(" ");
Dianne Hackborn287952c2010-09-22 22:34:31 -07009862 if (r.adjTarget instanceof ComponentName) {
9863 pw.print(((ComponentName)r.adjTarget).flattenToShortString());
9864 } else if (r.adjTarget != null) {
9865 pw.print(r.adjTarget.toString());
9866 } else {
9867 pw.print("{null}");
9868 }
9869 pw.print("<=");
9870 if (r.adjSource instanceof ProcessRecord) {
9871 pw.print("Proc{");
9872 pw.print(((ProcessRecord)r.adjSource).toShortString());
9873 pw.println("}");
9874 } else if (r.adjSource != null) {
9875 pw.println(r.adjSource.toString());
9876 } else {
9877 pw.println("{null}");
9878 }
9879 }
9880 if (inclDetails) {
9881 pw.print(prefix);
9882 pw.print(" ");
9883 pw.print("oom: max="); pw.print(r.maxAdj);
9884 pw.print(" hidden="); pw.print(r.hiddenAdj);
9885 pw.print(" curRaw="); pw.print(r.curRawAdj);
9886 pw.print(" setRaw="); pw.print(r.setRawAdj);
9887 pw.print(" cur="); pw.print(r.curAdj);
9888 pw.print(" set="); pw.println(r.setAdj);
9889 pw.print(prefix);
9890 pw.print(" ");
9891 pw.print("keeping="); pw.print(r.keeping);
9892 pw.print(" hidden="); pw.print(r.hidden);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009893 pw.print(" empty="); pw.print(r.empty);
9894 pw.print(" hasAboveClient="); pw.println(r.hasAboveClient);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009895
9896 if (!r.keeping) {
9897 if (r.lastWakeTime != 0) {
9898 long wtime;
9899 BatteryStatsImpl stats = service.mBatteryStatsService.getActiveStatistics();
9900 synchronized (stats) {
9901 wtime = stats.getProcessWakeTime(r.info.uid,
9902 r.pid, curRealtime);
9903 }
9904 long timeUsed = wtime - r.lastWakeTime;
9905 pw.print(prefix);
9906 pw.print(" ");
9907 pw.print("keep awake over ");
9908 TimeUtils.formatDuration(realtimeSince, pw);
9909 pw.print(" used ");
9910 TimeUtils.formatDuration(timeUsed, pw);
9911 pw.print(" (");
9912 pw.print((timeUsed*100)/realtimeSince);
9913 pw.println("%)");
9914 }
9915 if (r.lastCpuTime != 0) {
9916 long timeUsed = r.curCpuTime - r.lastCpuTime;
9917 pw.print(prefix);
9918 pw.print(" ");
9919 pw.print("run cpu over ");
9920 TimeUtils.formatDuration(uptimeSince, pw);
9921 pw.print(" used ");
9922 TimeUtils.formatDuration(timeUsed, pw);
9923 pw.print(" (");
9924 pw.print((timeUsed*100)/uptimeSince);
9925 pw.println("%)");
9926 }
9927 }
9928 }
9929 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009930 return true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009931 }
9932
Dianne Hackbornb437e092011-08-05 17:50:29 -07009933 ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, String[] args) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009934 ArrayList<ProcessRecord> procs;
9935 synchronized (this) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009936 if (args != null && args.length > start
9937 && args[start].charAt(0) != '-') {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009938 procs = new ArrayList<ProcessRecord>();
9939 int pid = -1;
9940 try {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009941 pid = Integer.parseInt(args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009942 } catch (NumberFormatException e) {
9943
9944 }
9945 for (int i=mLruProcesses.size()-1; i>=0; i--) {
9946 ProcessRecord proc = mLruProcesses.get(i);
9947 if (proc.pid == pid) {
9948 procs.add(proc);
Dianne Hackbornb437e092011-08-05 17:50:29 -07009949 } else if (proc.processName.equals(args[start])) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009950 procs.add(proc);
9951 }
9952 }
9953 if (procs.size() <= 0) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009954 pw.println("No process found for: " + args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009955 return null;
9956 }
9957 } else {
9958 procs = new ArrayList<ProcessRecord>(mLruProcesses);
9959 }
9960 }
9961 return procs;
9962 }
9963
9964 final void dumpGraphicsHardwareUsage(FileDescriptor fd,
9965 PrintWriter pw, String[] args) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009966 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009967 if (procs == null) {
9968 return;
9969 }
9970
9971 long uptime = SystemClock.uptimeMillis();
9972 long realtime = SystemClock.elapsedRealtime();
9973 pw.println("Applications Graphics Acceleration Info:");
9974 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
9975
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009976 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
9977 ProcessRecord r = procs.get(i);
Chet Haase9c1e23b2011-03-24 10:51:31 -07009978 if (r.thread != null) {
9979 pw.println("\n** Graphics info for pid " + r.pid + " [" + r.processName + "] **");
9980 pw.flush();
9981 try {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009982 TransferPipe tp = new TransferPipe();
9983 try {
9984 r.thread.dumpGfxInfo(tp.getWriteFd().getFileDescriptor(), args);
9985 tp.go(fd);
9986 } finally {
9987 tp.kill();
9988 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009989 } catch (IOException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009990 pw.println("Failure while dumping the app: " + r);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009991 pw.flush();
Chet Haase9c1e23b2011-03-24 10:51:31 -07009992 } catch (RemoteException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009993 pw.println("Got a RemoteException while dumping the app " + r);
Chet Haase9c1e23b2011-03-24 10:51:31 -07009994 pw.flush();
9995 }
9996 }
9997 }
Chet Haase9c1e23b2011-03-24 10:51:31 -07009998 }
9999
Jeff Brown6754ba22011-12-14 20:20:01 -080010000 final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) {
10001 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
10002 if (procs == null) {
10003 return;
10004 }
10005
10006 pw.println("Applications Database Info:");
10007
10008 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10009 ProcessRecord r = procs.get(i);
10010 if (r.thread != null) {
10011 pw.println("\n** Database info for pid " + r.pid + " [" + r.processName + "] **");
10012 pw.flush();
10013 try {
10014 TransferPipe tp = new TransferPipe();
10015 try {
10016 r.thread.dumpDbInfo(tp.getWriteFd().getFileDescriptor(), args);
10017 tp.go(fd);
10018 } finally {
10019 tp.kill();
10020 }
10021 } catch (IOException e) {
10022 pw.println("Failure while dumping the app: " + r);
10023 pw.flush();
10024 } catch (RemoteException e) {
10025 pw.println("Got a RemoteException while dumping the app " + r);
10026 pw.flush();
10027 }
10028 }
10029 }
10030 }
10031
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010032 final static class MemItem {
10033 final String label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010034 final String shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010035 final long pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010036 final int id;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010037 ArrayList<MemItem> subitems;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010038
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010039 public MemItem(String _label, String _shortLabel, long _pss, int _id) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010040 label = _label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010041 shortLabel = _shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010042 pss = _pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010043 id = _id;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010044 }
10045 }
10046
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010047 static final void dumpMemItems(PrintWriter pw, String prefix, ArrayList<MemItem> items,
Dianne Hackbornb437e092011-08-05 17:50:29 -070010048 boolean sort) {
10049 if (sort) {
10050 Collections.sort(items, new Comparator<MemItem>() {
10051 @Override
10052 public int compare(MemItem lhs, MemItem rhs) {
10053 if (lhs.pss < rhs.pss) {
10054 return 1;
10055 } else if (lhs.pss > rhs.pss) {
10056 return -1;
10057 }
10058 return 0;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010059 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010060 });
10061 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010062
10063 for (int i=0; i<items.size(); i++) {
10064 MemItem mi = items.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010065 pw.print(prefix); pw.printf("%7d kB: ", mi.pss); pw.println(mi.label);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010066 if (mi.subitems != null) {
10067 dumpMemItems(pw, prefix + " ", mi.subitems, true);
10068 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010069 }
10070 }
10071
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010072 // These are in KB.
10073 static final long[] DUMP_MEM_BUCKETS = new long[] {
10074 5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024,
10075 120*1024, 160*1024, 200*1024,
10076 250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024,
10077 1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024
10078 };
10079
Dianne Hackborn672342c2011-11-29 11:29:02 -080010080 static final void appendMemBucket(StringBuilder out, long memKB, String label,
10081 boolean stackLike) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010082 int start = label.lastIndexOf('.');
10083 if (start >= 0) start++;
10084 else start = 0;
10085 int end = label.length();
10086 for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) {
10087 if (DUMP_MEM_BUCKETS[i] >= memKB) {
10088 long bucket = DUMP_MEM_BUCKETS[i]/1024;
10089 out.append(bucket);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010090 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010091 out.append(label, start, end);
10092 return;
10093 }
10094 }
10095 out.append(memKB/1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010096 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010097 out.append(label, start, end);
10098 }
10099
10100 static final int[] DUMP_MEM_OOM_ADJ = new int[] {
10101 ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ, ProcessList.FOREGROUND_APP_ADJ,
10102 ProcessList.VISIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ,
10103 ProcessList.BACKUP_APP_ADJ, ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ,
10104 ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.HIDDEN_APP_MAX_ADJ
10105 };
10106 static final String[] DUMP_MEM_OOM_LABEL = new String[] {
10107 "System", "Persistent", "Foreground",
10108 "Visible", "Perceptible", "Heavy Weight",
10109 "Backup", "A Services", "Home", "Previous",
10110 "B Services", "Background"
10111 };
10112
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010113 final void dumpApplicationMemoryUsage(FileDescriptor fd,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010114 PrintWriter pw, String prefix, String[] args, boolean brief,
Dianne Hackborn672342c2011-11-29 11:29:02 -080010115 PrintWriter categoryPw, StringBuilder outTag, StringBuilder outStack) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010116 boolean dumpAll = false;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010117 boolean oomOnly = false;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010118
10119 int opti = 0;
10120 while (opti < args.length) {
10121 String opt = args[opti];
10122 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
10123 break;
10124 }
10125 opti++;
10126 if ("-a".equals(opt)) {
10127 dumpAll = true;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010128 } else if ("--oom".equals(opt)) {
10129 oomOnly = true;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010130 } else if ("-h".equals(opt)) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010131 pw.println("meminfo dump options: [-a] [--oom] [process]");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010132 pw.println(" -a: include all available information for each process.");
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010133 pw.println(" --oom: only show processes organized by oom adj.");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010134 pw.println("If [process] is specified it can be the name or ");
10135 pw.println("pid of a specific process to dump.");
10136 return;
10137 } else {
10138 pw.println("Unknown argument: " + opt + "; use -h for help");
10139 }
10140 }
10141
10142 ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010143 if (procs == null) {
10144 return;
10145 }
10146
Dianne Hackborn6447ca32009-04-07 19:50:08 -070010147 final boolean isCheckinRequest = scanArgs(args, "--checkin");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010148 long uptime = SystemClock.uptimeMillis();
10149 long realtime = SystemClock.elapsedRealtime();
Dianne Hackbornb437e092011-08-05 17:50:29 -070010150
10151 if (procs.size() == 1 || isCheckinRequest) {
10152 dumpAll = true;
10153 }
10154
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010155 if (isCheckinRequest) {
10156 // short checkin version
10157 pw.println(uptime + "," + realtime);
10158 pw.flush();
10159 } else {
10160 pw.println("Applications Memory Usage (kB):");
10161 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10162 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010163
Dianne Hackbornb437e092011-08-05 17:50:29 -070010164 String[] innerArgs = new String[args.length-opti];
10165 System.arraycopy(args, opti, innerArgs, 0, args.length-opti);
10166
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010167 ArrayList<MemItem> procMems = new ArrayList<MemItem>();
10168 long nativePss=0, dalvikPss=0, otherPss=0;
10169 long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
10170
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010171 long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length];
10172 ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[])
10173 new ArrayList[DUMP_MEM_OOM_LABEL.length];
Dianne Hackbornb437e092011-08-05 17:50:29 -070010174
10175 long totalPss = 0;
10176
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010177 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10178 ProcessRecord r = procs.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010179 if (r.thread != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010180 if (!isCheckinRequest && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010181 pw.println("\n** MEMINFO in pid " + r.pid + " [" + r.processName + "] **");
10182 pw.flush();
10183 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010184 Debug.MemoryInfo mi = null;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010185 if (dumpAll) {
10186 try {
10187 mi = r.thread.dumpMemInfo(fd, isCheckinRequest, dumpAll, innerArgs);
10188 } catch (RemoteException e) {
10189 if (!isCheckinRequest) {
10190 pw.println("Got RemoteException!");
10191 pw.flush();
10192 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010193 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010194 } else {
10195 mi = new Debug.MemoryInfo();
10196 Debug.getMemoryInfo(r.pid, mi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010197 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010198
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010199 if (!isCheckinRequest && mi != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010200 long myTotalPss = mi.getTotalPss();
10201 totalPss += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010202 MemItem pssItem = new MemItem(r.processName + " (pid " + r.pid + ")",
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010203 r.processName, myTotalPss, 0);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010204 procMems.add(pssItem);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010205
10206 nativePss += mi.nativePss;
10207 dalvikPss += mi.dalvikPss;
10208 otherPss += mi.otherPss;
10209 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
10210 long mem = mi.getOtherPss(j);
10211 miscPss[j] += mem;
10212 otherPss -= mem;
10213 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010214
10215 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010216 if (r.setAdj <= DUMP_MEM_OOM_ADJ[oomIndex]
10217 || oomIndex == (oomPss.length-1)) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010218 oomPss[oomIndex] += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010219 if (oomProcs[oomIndex] == null) {
10220 oomProcs[oomIndex] = new ArrayList<MemItem>();
10221 }
10222 oomProcs[oomIndex].add(pssItem);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010223 break;
10224 }
10225 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010226 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010227 }
10228 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010229
10230 if (!isCheckinRequest && procs.size() > 1) {
10231 ArrayList<MemItem> catMems = new ArrayList<MemItem>();
10232
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010233 catMems.add(new MemItem("Native", "Native", nativePss, -1));
10234 catMems.add(new MemItem("Dalvik", "Dalvik", dalvikPss, -2));
10235 catMems.add(new MemItem("Unknown", "Unknown", otherPss, -3));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010236 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010237 String label = Debug.MemoryInfo.getOtherLabel(j);
10238 catMems.add(new MemItem(label, label, miscPss[j], j));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010239 }
10240
Dianne Hackbornb437e092011-08-05 17:50:29 -070010241 ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
10242 for (int j=0; j<oomPss.length; j++) {
10243 if (oomPss[j] != 0) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010244 String label = DUMP_MEM_OOM_LABEL[j];
10245 MemItem item = new MemItem(label, label, oomPss[j],
10246 DUMP_MEM_OOM_ADJ[j]);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010247 item.subitems = oomProcs[j];
10248 oomMems.add(item);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010249 }
10250 }
10251
Dianne Hackborn672342c2011-11-29 11:29:02 -080010252 if (outTag != null || outStack != null) {
10253 if (outTag != null) {
10254 appendMemBucket(outTag, totalPss, "total", false);
10255 }
10256 if (outStack != null) {
10257 appendMemBucket(outStack, totalPss, "total", true);
10258 }
10259 boolean firstLine = true;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010260 for (int i=0; i<oomMems.size(); i++) {
10261 MemItem miCat = oomMems.get(i);
10262 if (miCat.subitems == null || miCat.subitems.size() < 1) {
10263 continue;
10264 }
10265 if (miCat.id < ProcessList.SERVICE_ADJ
10266 || miCat.id == ProcessList.HOME_APP_ADJ
10267 || miCat.id == ProcessList.PREVIOUS_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010268 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10269 outTag.append(" / ");
10270 }
10271 if (outStack != null) {
10272 if (miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10273 if (firstLine) {
10274 outStack.append(":");
10275 firstLine = false;
10276 }
10277 outStack.append("\n\t at ");
10278 } else {
10279 outStack.append("$");
10280 }
10281 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010282 for (int j=0; j<miCat.subitems.size(); j++) {
10283 MemItem mi = miCat.subitems.get(j);
10284 if (j > 0) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010285 if (outTag != null) {
10286 outTag.append(" ");
10287 }
10288 if (outStack != null) {
10289 outStack.append("$");
10290 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010291 }
Dianne Hackborn672342c2011-11-29 11:29:02 -080010292 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10293 appendMemBucket(outTag, mi.pss, mi.shortLabel, false);
10294 }
10295 if (outStack != null) {
10296 appendMemBucket(outStack, mi.pss, mi.shortLabel, true);
10297 }
10298 }
10299 if (outStack != null && miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10300 outStack.append("(");
10301 for (int k=0; k<DUMP_MEM_OOM_ADJ.length; k++) {
10302 if (DUMP_MEM_OOM_ADJ[k] == miCat.id) {
10303 outStack.append(DUMP_MEM_OOM_LABEL[k]);
10304 outStack.append(":");
10305 outStack.append(DUMP_MEM_OOM_ADJ[k]);
10306 }
10307 }
10308 outStack.append(")");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010309 }
10310 }
10311 }
10312 }
10313
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010314 if (!brief && !oomOnly) {
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010315 pw.println();
10316 pw.println("Total PSS by process:");
10317 dumpMemItems(pw, " ", procMems, true);
10318 pw.println();
10319 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010320 pw.println("Total PSS by OOM adjustment:");
10321 dumpMemItems(pw, " ", oomMems, false);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010322 if (!oomOnly) {
10323 PrintWriter out = categoryPw != null ? categoryPw : pw;
10324 out.println();
10325 out.println("Total PSS by category:");
10326 dumpMemItems(out, " ", catMems, true);
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010327 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010328 pw.println();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010329 pw.print("Total PSS: "); pw.print(totalPss); pw.println(" kB");
Dianne Hackbornd3e677b2012-04-05 14:58:18 -070010330 final int[] SINGLE_LONG_FORMAT = new int[] {
10331 Process.PROC_SPACE_TERM|Process.PROC_OUT_LONG
10332 };
10333 long[] longOut = new long[1];
10334 Process.readProcFile("/sys/kernel/mm/ksm/pages_shared",
10335 SINGLE_LONG_FORMAT, null, longOut, null);
10336 long shared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10337 longOut[0] = 0;
10338 Process.readProcFile("/sys/kernel/mm/ksm/pages_sharing",
10339 SINGLE_LONG_FORMAT, null, longOut, null);
10340 long sharing = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10341 longOut[0] = 0;
10342 Process.readProcFile("/sys/kernel/mm/ksm/pages_unshared",
10343 SINGLE_LONG_FORMAT, null, longOut, null);
10344 long unshared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10345 longOut[0] = 0;
10346 Process.readProcFile("/sys/kernel/mm/ksm/pages_volatile",
10347 SINGLE_LONG_FORMAT, null, longOut, null);
10348 long voltile = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10349 pw.print(" KSM: "); pw.print(sharing); pw.print(" kB saved from shared ");
10350 pw.print(shared); pw.println(" kB");
10351 pw.print(" "); pw.print(unshared); pw.print(" kB unshared; ");
10352 pw.print(voltile); pw.println(" kB volatile");
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010353 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010354 }
10355
10356 /**
10357 * Searches array of arguments for the specified string
10358 * @param args array of argument strings
10359 * @param value value to search for
10360 * @return true if the value is contained in the array
10361 */
10362 private static boolean scanArgs(String[] args, String value) {
10363 if (args != null) {
10364 for (String arg : args) {
10365 if (value.equals(arg)) {
10366 return true;
10367 }
10368 }
10369 }
10370 return false;
10371 }
10372
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010373 private final void killServicesLocked(ProcessRecord app,
10374 boolean allowRestart) {
10375 // Report disconnected services.
10376 if (false) {
10377 // XXX we are letting the client link to the service for
10378 // death notifications.
10379 if (app.services.size() > 0) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010380 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010381 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010382 ServiceRecord r = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010383 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010384 Iterator<ArrayList<ConnectionRecord>> jt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010385 = r.connections.values().iterator();
10386 while (jt.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010387 ArrayList<ConnectionRecord> cl = jt.next();
10388 for (int i=0; i<cl.size(); i++) {
10389 ConnectionRecord c = cl.get(i);
10390 if (c.binding.client != app) {
10391 try {
10392 //c.conn.connected(r.className, null);
10393 } catch (Exception e) {
10394 // todo: this should be asynchronous!
10395 Slog.w(TAG, "Exception thrown disconnected servce "
10396 + r.shortName
10397 + " from app " + app.processName, e);
10398 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010399 }
10400 }
10401 }
10402 }
10403 }
10404 }
10405 }
10406
10407 // Clean up any connections this application has to other services.
10408 if (app.connections.size() > 0) {
10409 Iterator<ConnectionRecord> it = app.connections.iterator();
10410 while (it.hasNext()) {
10411 ConnectionRecord r = it.next();
10412 removeConnectionLocked(r, app, null);
10413 }
10414 }
10415 app.connections.clear();
10416
10417 if (app.services.size() != 0) {
10418 // Any services running in the application need to be placed
10419 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -070010420 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010421 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010422 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010423 synchronized (sr.stats.getBatteryStats()) {
10424 sr.stats.stopLaunchedLocked();
10425 }
10426 sr.app = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010427 sr.isolatedProc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010428 sr.executeNesting = 0;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010429 if (mStoppingServices.remove(sr)) {
10430 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
10431 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010432
10433 boolean hasClients = sr.bindings.size() > 0;
10434 if (hasClients) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010435 Iterator<IntentBindRecord> bindings
10436 = sr.bindings.values().iterator();
10437 while (bindings.hasNext()) {
10438 IntentBindRecord b = bindings.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -080010439 if (DEBUG_SERVICE) Slog.v(TAG, "Killing binding " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010440 + ": shouldUnbind=" + b.hasBound);
10441 b.binder = null;
10442 b.requested = b.received = b.hasBound = false;
10443 }
10444 }
10445
Dianne Hackborn070783f2010-12-29 16:46:28 -080010446 if (sr.crashCount >= 2 && (sr.serviceInfo.applicationInfo.flags
10447 &ApplicationInfo.FLAG_PERSISTENT) == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010448 Slog.w(TAG, "Service crashed " + sr.crashCount
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010449 + " times, stopping: " + sr);
Doug Zongker2bec3d42009-12-04 12:52:44 -080010450 EventLog.writeEvent(EventLogTags.AM_SERVICE_CRASHED_TOO_MUCH,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010451 sr.crashCount, sr.shortName, app.pid);
10452 bringDownServiceLocked(sr, true);
10453 } else if (!allowRestart) {
10454 bringDownServiceLocked(sr, true);
10455 } else {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010456 boolean canceled = scheduleServiceRestartLocked(sr, true);
10457
10458 // Should the service remain running? Note that in the
10459 // extreme case of so many attempts to deliver a command
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010460 // that it failed we also will stop it here.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010461 if (sr.startRequested && (sr.stopIfKilled || canceled)) {
10462 if (sr.pendingStarts.size() == 0) {
10463 sr.startRequested = false;
10464 if (!hasClients) {
10465 // Whoops, no reason to restart!
10466 bringDownServiceLocked(sr, true);
10467 }
10468 }
10469 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010470 }
10471 }
10472
10473 if (!allowRestart) {
10474 app.services.clear();
10475 }
10476 }
10477
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010478 // Make sure we have no more records on the stopping list.
10479 int i = mStoppingServices.size();
10480 while (i > 0) {
10481 i--;
10482 ServiceRecord sr = mStoppingServices.get(i);
10483 if (sr.app == app) {
10484 mStoppingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010485 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010486 }
10487 }
10488
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010489 app.executingServices.clear();
10490 }
10491
10492 private final void removeDyingProviderLocked(ProcessRecord proc,
10493 ContentProviderRecord cpr) {
10494 synchronized (cpr) {
10495 cpr.launchingApp = null;
10496 cpr.notifyAll();
10497 }
10498
Amith Yamasani742a6712011-05-04 14:49:28 -070010499 mProviderMap.removeProviderByClass(cpr.name, UserId.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010500 String names[] = cpr.info.authority.split(";");
10501 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010502 mProviderMap.removeProviderByName(names[j], UserId.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010503 }
10504
10505 Iterator<ProcessRecord> cit = cpr.clients.iterator();
10506 while (cit.hasNext()) {
10507 ProcessRecord capp = cit.next();
10508 if (!capp.persistent && capp.thread != null
10509 && capp.pid != 0
10510 && capp.pid != MY_PID) {
Dianne Hackborn8633e682010-04-22 16:03:41 -070010511 Slog.i(TAG, "Kill " + capp.processName
10512 + " (pid " + capp.pid + "): provider " + cpr.info.name
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010513 + " in dying process " + (proc != null ? proc.processName : "??"));
Dianne Hackborn8633e682010-04-22 16:03:41 -070010514 EventLog.writeEvent(EventLogTags.AM_KILL, capp.pid,
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010515 capp.processName, capp.setAdj, "dying provider "
10516 + cpr.name.toShortString());
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070010517 Process.killProcessQuiet(capp.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010518 }
10519 }
10520
10521 mLaunchingProviders.remove(cpr);
10522 }
10523
10524 /**
10525 * Main code for cleaning up a process when it has gone away. This is
10526 * called both as a result of the process dying, or directly when stopping
10527 * a process when running in single process mode.
10528 */
10529 private final void cleanUpApplicationRecordLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010530 boolean restarting, boolean allowRestart, int index) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010531 if (index >= 0) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010532 mLruProcesses.remove(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010533 }
10534
Dianne Hackborn36124872009-10-08 16:22:03 -070010535 mProcessesToGc.remove(app);
10536
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010537 // Dismiss any open dialogs.
10538 if (app.crashDialog != null) {
10539 app.crashDialog.dismiss();
10540 app.crashDialog = null;
10541 }
10542 if (app.anrDialog != null) {
10543 app.anrDialog.dismiss();
10544 app.anrDialog = null;
10545 }
10546 if (app.waitDialog != null) {
10547 app.waitDialog.dismiss();
10548 app.waitDialog = null;
10549 }
10550
10551 app.crashing = false;
10552 app.notResponding = false;
10553
10554 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -070010555 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010556 app.thread = null;
10557 app.forcingToForeground = null;
10558 app.foregroundServices = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010559 app.foregroundActivities = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070010560 app.hasShownUi = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010561 app.hasAboveClient = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010562
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010563 killServicesLocked(app, allowRestart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010564
10565 boolean restart = false;
10566
10567 int NL = mLaunchingProviders.size();
10568
10569 // Remove published content providers.
10570 if (!app.pubProviders.isEmpty()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010571 Iterator<ContentProviderRecord> it = app.pubProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010572 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010573 ContentProviderRecord cpr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010574 cpr.provider = null;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010575 cpr.proc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010576
10577 // See if someone is waiting for this provider... in which
10578 // case we don't remove it, but just let it restart.
10579 int i = 0;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010580 if (!app.bad && allowRestart) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010581 for (; i<NL; i++) {
10582 if (mLaunchingProviders.get(i) == cpr) {
10583 restart = true;
10584 break;
10585 }
10586 }
10587 } else {
10588 i = NL;
10589 }
10590
10591 if (i >= NL) {
10592 removeDyingProviderLocked(app, cpr);
10593 NL = mLaunchingProviders.size();
10594 }
10595 }
10596 app.pubProviders.clear();
10597 }
10598
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010599 // Take care of any launching providers waiting for this process.
10600 if (checkAppInLaunchingProvidersLocked(app, false)) {
10601 restart = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010602 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010603
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010604 // Unregister from connected content providers.
10605 if (!app.conProviders.isEmpty()) {
Dianne Hackborn0c3154d2009-10-06 17:18:05 -070010606 Iterator it = app.conProviders.keySet().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010607 while (it.hasNext()) {
10608 ContentProviderRecord cpr = (ContentProviderRecord)it.next();
10609 cpr.clients.remove(app);
10610 }
10611 app.conProviders.clear();
10612 }
10613
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010614 // At this point there may be remaining entries in mLaunchingProviders
10615 // where we were the only one waiting, so they are no longer of use.
10616 // Look for these and clean up if found.
10617 // XXX Commented out for now. Trying to figure out a way to reproduce
10618 // the actual situation to identify what is actually going on.
10619 if (false) {
10620 for (int i=0; i<NL; i++) {
10621 ContentProviderRecord cpr = (ContentProviderRecord)
10622 mLaunchingProviders.get(i);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080010623 if (cpr.clients.size() <= 0 && !cpr.hasExternalProcessHandles()) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010624 synchronized (cpr) {
10625 cpr.launchingApp = null;
10626 cpr.notifyAll();
10627 }
10628 }
10629 }
10630 }
10631
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010632 skipCurrentReceiverLocked(app);
10633
10634 // Unregister any receivers.
10635 if (app.receivers.size() > 0) {
10636 Iterator<ReceiverList> it = app.receivers.iterator();
10637 while (it.hasNext()) {
10638 removeReceiverLocked(it.next());
10639 }
10640 app.receivers.clear();
10641 }
10642
Christopher Tate181fafa2009-05-14 11:12:14 -070010643 // If the app is undergoing backup, tell the backup manager about it
10644 if (mBackupTarget != null && app.pid == mBackupTarget.app.pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010645 if (DEBUG_BACKUP) Slog.d(TAG, "App " + mBackupTarget.appInfo + " died during backup");
Christopher Tate181fafa2009-05-14 11:12:14 -070010646 try {
10647 IBackupManager bm = IBackupManager.Stub.asInterface(
10648 ServiceManager.getService(Context.BACKUP_SERVICE));
10649 bm.agentDisconnected(app.info.packageName);
10650 } catch (RemoteException e) {
10651 // can't happen; backup manager is local
10652 }
10653 }
10654
Jeff Sharkey287bd832011-05-28 19:36:26 -070010655 mHandler.obtainMessage(DISPATCH_PROCESS_DIED, app.pid, app.info.uid, null).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010656
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010657 // If the caller is restarting this app, then leave it in its
10658 // current lists and let the caller take care of it.
10659 if (restarting) {
10660 return;
10661 }
10662
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010663 if (!app.persistent || app.isolated) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010664 if (DEBUG_PROCESSES) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010665 "Removing non-persistent process during cleanup: " + app);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010666 mProcessNames.remove(app.processName, app.uid);
10667 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -070010668 if (mHeavyWeightProcess == app) {
10669 mHeavyWeightProcess = null;
10670 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
10671 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010672 } else if (!app.removed) {
10673 // This app is persistent, so we need to keep its record around.
10674 // If it is not already on the pending app list, add it there
10675 // and start a new process for it.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010676 if (mPersistentStartingProcesses.indexOf(app) < 0) {
10677 mPersistentStartingProcesses.add(app);
10678 restart = true;
10679 }
10680 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070010681 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
10682 "Clean-up removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010683 mProcessesOnHold.remove(app);
10684
The Android Open Source Project4df24232009-03-05 14:34:35 -080010685 if (app == mHomeProcess) {
10686 mHomeProcess = null;
10687 }
Dianne Hackbornf35fe232011-11-01 19:25:20 -070010688 if (app == mPreviousProcess) {
10689 mPreviousProcess = null;
10690 }
10691
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010692 if (restart && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010693 // We have components that still need to be running in the
10694 // process, so re-launch it.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010695 mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010696 startProcessLocked(app, "restart", app.processName);
10697 } else if (app.pid > 0 && app.pid != MY_PID) {
10698 // Goodbye!
10699 synchronized (mPidsSelfLocked) {
10700 mPidsSelfLocked.remove(app.pid);
10701 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
10702 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010703 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010704 }
10705 }
10706
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010707 boolean checkAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) {
10708 // Look through the content providers we are waiting to have launched,
10709 // and if any run in this process then either schedule a restart of
10710 // the process or kill the client waiting for it if this process has
10711 // gone bad.
10712 int NL = mLaunchingProviders.size();
10713 boolean restart = false;
10714 for (int i=0; i<NL; i++) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010715 ContentProviderRecord cpr = mLaunchingProviders.get(i);
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010716 if (cpr.launchingApp == app) {
10717 if (!alwaysBad && !app.bad) {
10718 restart = true;
10719 } else {
10720 removeDyingProviderLocked(app, cpr);
10721 NL = mLaunchingProviders.size();
10722 }
10723 }
10724 }
10725 return restart;
10726 }
10727
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010728 // =========================================================
10729 // SERVICES
10730 // =========================================================
10731
10732 ActivityManager.RunningServiceInfo makeRunningServiceInfoLocked(ServiceRecord r) {
10733 ActivityManager.RunningServiceInfo info =
10734 new ActivityManager.RunningServiceInfo();
10735 info.service = r.name;
10736 if (r.app != null) {
10737 info.pid = r.app.pid;
10738 }
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010739 info.uid = r.appInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010740 info.process = r.processName;
10741 info.foreground = r.isForeground;
10742 info.activeSince = r.createTime;
10743 info.started = r.startRequested;
10744 info.clientCount = r.connections.size();
10745 info.crashCount = r.crashCount;
10746 info.lastActivityTime = r.lastActivity;
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010747 if (r.isForeground) {
10748 info.flags |= ActivityManager.RunningServiceInfo.FLAG_FOREGROUND;
10749 }
10750 if (r.startRequested) {
10751 info.flags |= ActivityManager.RunningServiceInfo.FLAG_STARTED;
10752 }
Dan Egnor42471dd2010-01-07 17:25:22 -080010753 if (r.app != null && r.app.pid == MY_PID) {
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010754 info.flags |= ActivityManager.RunningServiceInfo.FLAG_SYSTEM_PROCESS;
10755 }
10756 if (r.app != null && r.app.persistent) {
10757 info.flags |= ActivityManager.RunningServiceInfo.FLAG_PERSISTENT_PROCESS;
10758 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010759
10760 for (ArrayList<ConnectionRecord> connl : r.connections.values()) {
10761 for (int i=0; i<connl.size(); i++) {
10762 ConnectionRecord conn = connl.get(i);
10763 if (conn.clientLabel != 0) {
10764 info.clientPackage = conn.binding.client.info.packageName;
10765 info.clientLabel = conn.clientLabel;
10766 return info;
10767 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010768 }
10769 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010770 return info;
10771 }
10772
10773 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum,
10774 int flags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010775 enforceNotIsolatedCaller("getServices");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010776 synchronized (this) {
10777 ArrayList<ActivityManager.RunningServiceInfo> res
10778 = new ArrayList<ActivityManager.RunningServiceInfo>();
10779
Amith Yamasani742a6712011-05-04 14:49:28 -070010780 int userId = UserId.getUserId(Binder.getCallingUid());
10781 if (mServiceMap.getAllServices(userId).size() > 0) {
10782 Iterator<ServiceRecord> it
10783 = mServiceMap.getAllServices(userId).iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010784 while (it.hasNext() && res.size() < maxNum) {
10785 res.add(makeRunningServiceInfoLocked(it.next()));
10786 }
10787 }
10788
10789 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
10790 ServiceRecord r = mRestartingServices.get(i);
10791 ActivityManager.RunningServiceInfo info =
10792 makeRunningServiceInfoLocked(r);
10793 info.restarting = r.nextRestartTime;
10794 res.add(info);
10795 }
10796
10797 return res;
10798 }
10799 }
10800
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010801 public PendingIntent getRunningServiceControlPanel(ComponentName name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010802 enforceNotIsolatedCaller("getRunningServiceControlPanel");
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010803 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010804 int userId = UserId.getUserId(Binder.getCallingUid());
10805 ServiceRecord r = mServiceMap.getServiceByName(name, userId);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010806 if (r != null) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010807 for (ArrayList<ConnectionRecord> conn : r.connections.values()) {
10808 for (int i=0; i<conn.size(); i++) {
10809 if (conn.get(i).clientIntent != null) {
10810 return conn.get(i).clientIntent;
10811 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010812 }
10813 }
10814 }
10815 }
10816 return null;
10817 }
10818
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010819 private final ServiceRecord findServiceLocked(ComponentName name,
10820 IBinder token) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010821 ServiceRecord r = mServiceMap.getServiceByName(name, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010822 return r == token ? r : null;
10823 }
10824
10825 private final class ServiceLookupResult {
10826 final ServiceRecord record;
10827 final String permission;
10828
10829 ServiceLookupResult(ServiceRecord _record, String _permission) {
10830 record = _record;
10831 permission = _permission;
10832 }
10833 };
10834
10835 private ServiceLookupResult findServiceLocked(Intent service,
Amith Yamasani483f3b02012-03-13 16:08:00 -070010836 String resolvedType, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010837 ServiceRecord r = null;
10838 if (service.getComponent() != null) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070010839 r = mServiceMap.getServiceByName(service.getComponent(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010840 }
10841 if (r == null) {
10842 Intent.FilterComparison filter = new Intent.FilterComparison(service);
Amith Yamasani483f3b02012-03-13 16:08:00 -070010843 r = mServiceMap.getServiceByIntent(filter, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010844 }
10845
10846 if (r == null) {
10847 try {
10848 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070010849 AppGlobals.getPackageManager().resolveService(
Amith Yamasani483f3b02012-03-13 16:08:00 -070010850 service, resolvedType, 0, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010851 ServiceInfo sInfo =
10852 rInfo != null ? rInfo.serviceInfo : null;
10853 if (sInfo == null) {
10854 return null;
10855 }
10856
10857 ComponentName name = new ComponentName(
10858 sInfo.applicationInfo.packageName, sInfo.name);
Amith Yamasani742a6712011-05-04 14:49:28 -070010859 r = mServiceMap.getServiceByName(name, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010860 } catch (RemoteException ex) {
10861 // pm is in same process, this will never happen.
10862 }
10863 }
10864 if (r != null) {
10865 int callingPid = Binder.getCallingPid();
10866 int callingUid = Binder.getCallingUid();
10867 if (checkComponentPermission(r.permission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010868 callingPid, callingUid, r.appInfo.uid, r.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010869 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010870 if (!r.exported) {
10871 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
10872 + " from pid=" + callingPid
10873 + ", uid=" + callingUid
10874 + " that is not exported from uid " + r.appInfo.uid);
10875 return new ServiceLookupResult(null, "not exported from uid "
10876 + r.appInfo.uid);
10877 }
Joe Onorato8a9b2202010-02-26 18:56:32 -080010878 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010879 + " from pid=" + callingPid
10880 + ", uid=" + callingUid
10881 + " requires " + r.permission);
10882 return new ServiceLookupResult(null, r.permission);
10883 }
10884 return new ServiceLookupResult(r, null);
10885 }
10886 return null;
10887 }
10888
10889 private class ServiceRestarter implements Runnable {
10890 private ServiceRecord mService;
10891
10892 void setService(ServiceRecord service) {
10893 mService = service;
10894 }
10895
10896 public void run() {
10897 synchronized(ActivityManagerService.this) {
10898 performServiceRestartLocked(mService);
10899 }
10900 }
10901 }
10902
10903 private ServiceLookupResult retrieveServiceLocked(Intent service,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010904 String resolvedType, int callingPid, int callingUid, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010905 ServiceRecord r = null;
Amith Yamasani742a6712011-05-04 14:49:28 -070010906 if (DEBUG_SERVICE)
10907 Slog.v(TAG, "retrieveServiceLocked: " + service + " type=" + resolvedType
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010908 + " callingUid=" + callingUid);
Amith Yamasani742a6712011-05-04 14:49:28 -070010909
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010910 if (service.getComponent() != null) {
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010911 r = mServiceMap.getServiceByName(service.getComponent(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010912 }
Amith Yamasani742a6712011-05-04 14:49:28 -070010913 if (r == null) {
10914 Intent.FilterComparison filter = new Intent.FilterComparison(service);
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010915 r = mServiceMap.getServiceByIntent(filter, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -070010916 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010917 if (r == null) {
10918 try {
10919 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070010920 AppGlobals.getPackageManager().resolveService(
Amith Yamasani483f3b02012-03-13 16:08:00 -070010921 service, resolvedType, STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010922 ServiceInfo sInfo =
10923 rInfo != null ? rInfo.serviceInfo : null;
10924 if (sInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010925 Slog.w(TAG, "Unable to start service " + service +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010926 ": not found");
10927 return null;
10928 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010929 if (userId > 0) {
Amith Yamasania4a54e22012-04-16 15:44:19 -070010930 if (isSingleton(sInfo.processName, sInfo.applicationInfo)) {
10931 userId = 0;
10932 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010933 sInfo.applicationInfo = getAppInfoForUser(sInfo.applicationInfo, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -070010934 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010935 ComponentName name = new ComponentName(
10936 sInfo.applicationInfo.packageName, sInfo.name);
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010937 r = mServiceMap.getServiceByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010938 if (r == null) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010939 Intent.FilterComparison filter = new Intent.FilterComparison(
10940 service.cloneFilter());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010941 ServiceRestarter res = new ServiceRestarter();
10942 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
10943 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
10944 synchronized (stats) {
10945 ss = stats.getServiceStatsLocked(
10946 sInfo.applicationInfo.uid, sInfo.packageName,
10947 sInfo.name);
10948 }
Dianne Hackbornb1c4a2a2010-01-19 15:36:42 -080010949 r = new ServiceRecord(this, ss, name, filter, sInfo, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010950 res.setService(r);
Amith Yamasani742a6712011-05-04 14:49:28 -070010951 mServiceMap.putServiceByName(name, UserId.getUserId(r.appInfo.uid), r);
10952 mServiceMap.putServiceByIntent(filter, UserId.getUserId(r.appInfo.uid), r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010953
10954 // Make sure this component isn't in the pending list.
10955 int N = mPendingServices.size();
10956 for (int i=0; i<N; i++) {
10957 ServiceRecord pr = mPendingServices.get(i);
10958 if (pr.name.equals(name)) {
10959 mPendingServices.remove(i);
10960 i--;
10961 N--;
10962 }
10963 }
10964 }
10965 } catch (RemoteException ex) {
10966 // pm is in same process, this will never happen.
10967 }
10968 }
10969 if (r != null) {
10970 if (checkComponentPermission(r.permission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010971 callingPid, callingUid, r.appInfo.uid, r.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010972 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010973 if (!r.exported) {
10974 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
10975 + " from pid=" + callingPid
10976 + ", uid=" + callingUid
10977 + " that is not exported from uid " + r.appInfo.uid);
10978 return new ServiceLookupResult(null, "not exported from uid "
10979 + r.appInfo.uid);
10980 }
Joe Onorato8a9b2202010-02-26 18:56:32 -080010981 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010982 + " from pid=" + callingPid
10983 + ", uid=" + callingUid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010984 + " requires " + r.permission);
10985 return new ServiceLookupResult(null, r.permission);
10986 }
10987 return new ServiceLookupResult(r, null);
10988 }
10989 return null;
10990 }
10991
Dianne Hackborn287952c2010-09-22 22:34:31 -070010992 private final void bumpServiceExecutingLocked(ServiceRecord r, String why) {
10993 if (DEBUG_SERVICE) Log.v(TAG, ">>> EXECUTING "
10994 + why + " of " + r + " in app " + r.app);
10995 else if (DEBUG_SERVICE_EXECUTING) Log.v(TAG, ">>> EXECUTING "
10996 + why + " of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010997 long now = SystemClock.uptimeMillis();
10998 if (r.executeNesting == 0 && r.app != null) {
10999 if (r.app.executingServices.size() == 0) {
11000 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
11001 msg.obj = r.app;
11002 mHandler.sendMessageAtTime(msg, now+SERVICE_TIMEOUT);
11003 }
11004 r.app.executingServices.add(r);
11005 }
11006 r.executeNesting++;
11007 r.executingStart = now;
11008 }
11009
11010 private final void sendServiceArgsLocked(ServiceRecord r,
11011 boolean oomAdjusted) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011012 final int N = r.pendingStarts.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011013 if (N == 0) {
11014 return;
11015 }
11016
Dianne Hackborn39792d22010-08-19 18:01:52 -070011017 while (r.pendingStarts.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011018 try {
Dianne Hackborn39792d22010-08-19 18:01:52 -070011019 ServiceRecord.StartItem si = r.pendingStarts.remove(0);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011020 if (DEBUG_SERVICE) Slog.v(TAG, "Sending arguments to: "
11021 + r + " " + r.intent + " args=" + si.intent);
Dianne Hackborn3a28f222011-03-01 12:25:54 -080011022 if (si.intent == null && N > 1) {
11023 // If somehow we got a dummy null intent in the middle,
11024 // then skip it. DO NOT skip a null intent when it is
11025 // the only one in the list -- this is to support the
11026 // onStartCommand(null) case.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011027 continue;
11028 }
Dianne Hackborn39792d22010-08-19 18:01:52 -070011029 si.deliveredTime = SystemClock.uptimeMillis();
11030 r.deliveredStarts.add(si);
11031 si.deliveryCount++;
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011032 if (si.neededGrants != null) {
11033 grantUriPermissionUncheckedFromIntentLocked(si.neededGrants,
11034 si.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -070011035 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070011036 bumpServiceExecutingLocked(r, "start");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011037 if (!oomAdjusted) {
11038 oomAdjusted = true;
11039 updateOomAdjLocked(r.app);
11040 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011041 int flags = 0;
11042 if (si.deliveryCount > 0) {
11043 flags |= Service.START_FLAG_RETRY;
11044 }
11045 if (si.doneExecutingCount > 0) {
11046 flags |= Service.START_FLAG_REDELIVERY;
11047 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011048 r.app.thread.scheduleServiceArgs(r, si.taskRemoved, si.id, flags, si.intent);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011049 } catch (RemoteException e) {
11050 // Remote process gone... we'll let the normal cleanup take
11051 // care of this.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011052 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while scheduling start: " + r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011053 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011054 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011055 Slog.w(TAG, "Unexpected exception", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011056 break;
11057 }
11058 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011059 }
11060
11061 private final boolean requestServiceBindingLocked(ServiceRecord r,
11062 IntentBindRecord i, boolean rebind) {
11063 if (r.app == null || r.app.thread == null) {
11064 // If service is not currently running, can't yet bind.
11065 return false;
11066 }
11067 if ((!i.requested || rebind) && i.apps.size() > 0) {
11068 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011069 bumpServiceExecutingLocked(r, "bind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011070 r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind);
11071 if (!rebind) {
11072 i.requested = true;
11073 }
11074 i.hasBound = true;
11075 i.doRebind = false;
11076 } catch (RemoteException e) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011077 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while binding " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011078 return false;
11079 }
11080 }
11081 return true;
11082 }
11083
11084 private final void requestServiceBindingsLocked(ServiceRecord r) {
11085 Iterator<IntentBindRecord> bindings = r.bindings.values().iterator();
11086 while (bindings.hasNext()) {
11087 IntentBindRecord i = bindings.next();
11088 if (!requestServiceBindingLocked(r, i, false)) {
11089 break;
11090 }
11091 }
11092 }
11093
11094 private final void realStartServiceLocked(ServiceRecord r,
11095 ProcessRecord app) throws RemoteException {
11096 if (app.thread == null) {
11097 throw new RemoteException();
11098 }
Amith Yamasani742a6712011-05-04 14:49:28 -070011099 if (DEBUG_MU)
11100 Slog.v(TAG_MU, "realStartServiceLocked, ServiceRecord.uid = " + r.appInfo.uid
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011101 + ", ProcessRecord.uid = " + app.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011102 r.app = app;
The Android Open Source Project10592532009-03-18 17:39:46 -070011103 r.restartTime = r.lastActivity = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011104
11105 app.services.add(r);
Dianne Hackborn287952c2010-09-22 22:34:31 -070011106 bumpServiceExecutingLocked(r, "create");
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011107 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011108
11109 boolean created = false;
11110 try {
Dianne Hackborna33e3f72009-09-29 17:28:24 -070011111 mStringBuilder.setLength(0);
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011112 r.intent.getIntent().toShortString(mStringBuilder, true, false, true, false);
Doug Zongker2bec3d42009-12-04 12:52:44 -080011113 EventLog.writeEvent(EventLogTags.AM_CREATE_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011114 System.identityHashCode(r), r.shortName,
Dianne Hackborna33e3f72009-09-29 17:28:24 -070011115 mStringBuilder.toString(), r.app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011116 synchronized (r.stats.getBatteryStats()) {
11117 r.stats.startLaunchedLocked();
11118 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -070011119 ensurePackageDexOpt(r.serviceInfo.packageName);
Dianne Hackborne2515ee2011-04-27 18:52:56 -040011120 app.thread.scheduleCreateService(r, r.serviceInfo,
11121 compatibilityInfoForPackageLocked(r.serviceInfo.applicationInfo));
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011122 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011123 created = true;
11124 } finally {
11125 if (!created) {
11126 app.services.remove(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011127 scheduleServiceRestartLocked(r, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011128 }
11129 }
11130
11131 requestServiceBindingsLocked(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011132
11133 // If the service is in the started state, and there are no
11134 // pending arguments, then fake up one so its onStartCommand() will
11135 // be called.
11136 if (r.startRequested && r.callStart && r.pendingStarts.size() == 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011137 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011138 null, null));
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011139 }
11140
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011141 sendServiceArgsLocked(r, true);
11142 }
11143
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011144 private final boolean scheduleServiceRestartLocked(ServiceRecord r,
11145 boolean allowCancel) {
11146 boolean canceled = false;
11147
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011148 final long now = SystemClock.uptimeMillis();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011149 long minDuration = SERVICE_RESTART_DURATION;
Dianne Hackborn6ccd2af2009-08-27 12:26:44 -070011150 long resetTime = SERVICE_RESET_RUN_DURATION;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011151
Dianne Hackborn070783f2010-12-29 16:46:28 -080011152 if ((r.serviceInfo.applicationInfo.flags
11153 &ApplicationInfo.FLAG_PERSISTENT) != 0) {
11154 minDuration /= 4;
11155 }
11156
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011157 // Any delivered but not yet finished starts should be put back
11158 // on the pending list.
11159 final int N = r.deliveredStarts.size();
11160 if (N > 0) {
11161 for (int i=N-1; i>=0; i--) {
11162 ServiceRecord.StartItem si = r.deliveredStarts.get(i);
Dianne Hackborn39792d22010-08-19 18:01:52 -070011163 si.removeUriPermissionsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011164 if (si.intent == null) {
11165 // We'll generate this again if needed.
11166 } else if (!allowCancel || (si.deliveryCount < ServiceRecord.MAX_DELIVERY_COUNT
11167 && si.doneExecutingCount < ServiceRecord.MAX_DONE_EXECUTING_COUNT)) {
11168 r.pendingStarts.add(0, si);
11169 long dur = SystemClock.uptimeMillis() - si.deliveredTime;
11170 dur *= 2;
11171 if (minDuration < dur) minDuration = dur;
11172 if (resetTime < dur) resetTime = dur;
11173 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011174 Slog.w(TAG, "Canceling start item " + si.intent + " in service "
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011175 + r.name);
11176 canceled = true;
11177 }
11178 }
11179 r.deliveredStarts.clear();
11180 }
11181
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011182 r.totalRestartCount++;
11183 if (r.restartDelay == 0) {
11184 r.restartCount++;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011185 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011186 } else {
11187 // If it has been a "reasonably long time" since the service
11188 // was started, then reset our restart duration back to
11189 // the beginning, so we don't infinitely increase the duration
11190 // on a service that just occasionally gets killed (which is
11191 // a normal case, due to process being killed to reclaim memory).
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011192 if (now > (r.restartTime+resetTime)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011193 r.restartCount = 1;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011194 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011195 } else {
Dianne Hackborn070783f2010-12-29 16:46:28 -080011196 if ((r.serviceInfo.applicationInfo.flags
11197 &ApplicationInfo.FLAG_PERSISTENT) != 0) {
11198 // Services in peristent processes will restart much more
11199 // quickly, since they are pretty important. (Think SystemUI).
11200 r.restartDelay += minDuration/2;
11201 } else {
11202 r.restartDelay *= SERVICE_RESTART_DURATION_FACTOR;
11203 if (r.restartDelay < minDuration) {
11204 r.restartDelay = minDuration;
11205 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011206 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011207 }
11208 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011209
11210 r.nextRestartTime = now + r.restartDelay;
11211
11212 // Make sure that we don't end up restarting a bunch of services
11213 // all at the same time.
11214 boolean repeat;
11215 do {
11216 repeat = false;
11217 for (int i=mRestartingServices.size()-1; i>=0; i--) {
11218 ServiceRecord r2 = mRestartingServices.get(i);
11219 if (r2 != r && r.nextRestartTime
11220 >= (r2.nextRestartTime-SERVICE_MIN_RESTART_TIME_BETWEEN)
11221 && r.nextRestartTime
11222 < (r2.nextRestartTime+SERVICE_MIN_RESTART_TIME_BETWEEN)) {
11223 r.nextRestartTime = r2.nextRestartTime + SERVICE_MIN_RESTART_TIME_BETWEEN;
11224 r.restartDelay = r.nextRestartTime - now;
11225 repeat = true;
11226 break;
11227 }
11228 }
11229 } while (repeat);
11230
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011231 if (!mRestartingServices.contains(r)) {
11232 mRestartingServices.add(r);
11233 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011234
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011235 r.cancelNotification();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011236
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011237 mHandler.removeCallbacks(r.restarter);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011238 mHandler.postAtTime(r.restarter, r.nextRestartTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011239 r.nextRestartTime = SystemClock.uptimeMillis() + r.restartDelay;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011240 Slog.w(TAG, "Scheduling restart of crashed service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011241 + r.shortName + " in " + r.restartDelay + "ms");
Doug Zongker2bec3d42009-12-04 12:52:44 -080011242 EventLog.writeEvent(EventLogTags.AM_SCHEDULE_SERVICE_RESTART,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011243 r.shortName, r.restartDelay);
11244
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011245 return canceled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011246 }
11247
11248 final void performServiceRestartLocked(ServiceRecord r) {
11249 if (!mRestartingServices.contains(r)) {
11250 return;
11251 }
11252 bringUpServiceLocked(r, r.intent.getIntent().getFlags(), true);
11253 }
11254
11255 private final boolean unscheduleServiceRestartLocked(ServiceRecord r) {
11256 if (r.restartDelay == 0) {
11257 return false;
11258 }
11259 r.resetRestartCounter();
11260 mRestartingServices.remove(r);
11261 mHandler.removeCallbacks(r.restarter);
11262 return true;
11263 }
11264
11265 private final boolean bringUpServiceLocked(ServiceRecord r,
11266 int intentFlags, boolean whileRestarting) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011267 //Slog.i(TAG, "Bring up service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011268 //r.dump(" ");
11269
Dianne Hackborn36124872009-10-08 16:22:03 -070011270 if (r.app != null && r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011271 sendServiceArgsLocked(r, false);
11272 return true;
11273 }
11274
11275 if (!whileRestarting && r.restartDelay > 0) {
11276 // If waiting for a restart, then do nothing.
11277 return true;
11278 }
11279
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011280 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing up " + r + " " + r.intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011281
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011282 // We are now bringing the service up, so no longer in the
11283 // restarting state.
11284 mRestartingServices.remove(r);
11285
Dianne Hackborne7f97212011-02-24 14:40:20 -080011286 // Service is now being launched, its package can't be stopped.
11287 try {
11288 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -070011289 r.packageName, false, r.userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -080011290 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080011291 } catch (IllegalArgumentException e) {
11292 Slog.w(TAG, "Failed trying to unstop package "
11293 + r.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080011294 }
11295
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011296 final boolean isolated = (r.serviceInfo.flags&ServiceInfo.FLAG_ISOLATED_PROCESS) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011297 final String appName = r.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011298 ProcessRecord app;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011299
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011300 if (!isolated) {
11301 app = getProcessRecordLocked(appName, r.appInfo.uid);
11302 if (DEBUG_MU)
11303 Slog.v(TAG_MU, "bringUpServiceLocked: appInfo.uid=" + r.appInfo.uid + " app=" + app);
11304 if (app != null && app.thread != null) {
11305 try {
11306 app.addPackage(r.appInfo.packageName);
11307 realStartServiceLocked(r, app);
11308 return true;
11309 } catch (RemoteException e) {
11310 Slog.w(TAG, "Exception when starting service " + r.shortName, e);
11311 }
11312
11313 // If a dead object exception was thrown -- fall through to
11314 // restart the application.
11315 }
11316 } else {
11317 // If this service runs in an isolated process, then each time
11318 // we call startProcessLocked() we will get a new isolated
11319 // process, starting another process if we are currently waiting
11320 // for a previous process to come up. To deal with this, we store
11321 // in the service any current isolated process it is running in or
11322 // waiting to have come up.
11323 app = r.isolatedProc;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011324 }
11325
Dianne Hackborn36124872009-10-08 16:22:03 -070011326 // Not running -- get it started, and enqueue this service record
11327 // to be executed when the app comes up.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011328 if (app == null) {
11329 if ((app=startProcessLocked(appName, r.appInfo, true, intentFlags,
11330 "service", r.name, false, isolated)) == null) {
11331 Slog.w(TAG, "Unable to launch app "
11332 + r.appInfo.packageName + "/"
11333 + r.appInfo.uid + " for service "
11334 + r.intent.getIntent() + ": process is bad");
11335 bringDownServiceLocked(r, true);
11336 return false;
11337 }
11338 if (isolated) {
11339 r.isolatedProc = app;
11340 }
Dianne Hackborn36124872009-10-08 16:22:03 -070011341 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011342
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011343 if (!mPendingServices.contains(r)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011344 mPendingServices.add(r);
11345 }
Dianne Hackborn36124872009-10-08 16:22:03 -070011346
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011347 return true;
11348 }
11349
11350 private final void bringDownServiceLocked(ServiceRecord r, boolean force) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011351 //Slog.i(TAG, "Bring down service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011352 //r.dump(" ");
11353
11354 // Does it still need to run?
11355 if (!force && r.startRequested) {
11356 return;
11357 }
11358 if (r.connections.size() > 0) {
11359 if (!force) {
11360 // XXX should probably keep a count of the number of auto-create
11361 // connections directly in the service.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011362 Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011363 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011364 ArrayList<ConnectionRecord> cr = it.next();
11365 for (int i=0; i<cr.size(); i++) {
11366 if ((cr.get(i).flags&Context.BIND_AUTO_CREATE) != 0) {
11367 return;
11368 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011369 }
11370 }
11371 }
11372
11373 // Report to all of the connections that the service is no longer
11374 // available.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011375 Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011376 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011377 ArrayList<ConnectionRecord> c = it.next();
11378 for (int i=0; i<c.size(); i++) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011379 ConnectionRecord cr = c.get(i);
11380 // There is still a connection to the service that is
11381 // being brought down. Mark it as dead.
11382 cr.serviceDead = true;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011383 try {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011384 cr.conn.connected(r.name, null);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011385 } catch (Exception e) {
11386 Slog.w(TAG, "Failure disconnecting service " + r.name +
11387 " to connection " + c.get(i).conn.asBinder() +
11388 " (in " + c.get(i).binding.client.processName + ")", e);
11389 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011390 }
11391 }
11392 }
11393
11394 // Tell the service that it has been unbound.
11395 if (r.bindings.size() > 0 && r.app != null && r.app.thread != null) {
11396 Iterator<IntentBindRecord> it = r.bindings.values().iterator();
11397 while (it.hasNext()) {
11398 IntentBindRecord ibr = it.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -080011399 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down binding " + ibr
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011400 + ": hasBound=" + ibr.hasBound);
11401 if (r.app != null && r.app.thread != null && ibr.hasBound) {
11402 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011403 bumpServiceExecutingLocked(r, "bring down unbind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011404 updateOomAdjLocked(r.app);
11405 ibr.hasBound = false;
11406 r.app.thread.scheduleUnbindService(r,
11407 ibr.intent.getIntent());
11408 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011409 Slog.w(TAG, "Exception when unbinding service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011410 + r.shortName, e);
11411 serviceDoneExecutingLocked(r, true);
11412 }
11413 }
11414 }
11415 }
11416
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011417 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down " + r + " " + r.intent);
Doug Zongker2bec3d42009-12-04 12:52:44 -080011418 EventLog.writeEvent(EventLogTags.AM_DESTROY_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011419 System.identityHashCode(r), r.shortName,
11420 (r.app != null) ? r.app.pid : -1);
11421
Amith Yamasani742a6712011-05-04 14:49:28 -070011422 mServiceMap.removeServiceByName(r.name, r.userId);
11423 mServiceMap.removeServiceByIntent(r.intent, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011424 r.totalRestartCount = 0;
11425 unscheduleServiceRestartLocked(r);
11426
11427 // Also make sure it is not on the pending list.
11428 int N = mPendingServices.size();
11429 for (int i=0; i<N; i++) {
11430 if (mPendingServices.get(i) == r) {
11431 mPendingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011432 if (DEBUG_SERVICE) Slog.v(TAG, "Removed pending: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011433 i--;
11434 N--;
11435 }
11436 }
11437
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011438 r.cancelNotification();
11439 r.isForeground = false;
11440 r.foregroundId = 0;
11441 r.foregroundNoti = null;
11442
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011443 // Clear start entries.
Dianne Hackborn39792d22010-08-19 18:01:52 -070011444 r.clearDeliveredStartsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011445 r.pendingStarts.clear();
11446
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011447 if (r.app != null) {
11448 synchronized (r.stats.getBatteryStats()) {
11449 r.stats.stopLaunchedLocked();
11450 }
11451 r.app.services.remove(r);
11452 if (r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011453 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011454 bumpServiceExecutingLocked(r, "stop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011455 mStoppingServices.add(r);
11456 updateOomAdjLocked(r.app);
11457 r.app.thread.scheduleStopService(r);
11458 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011459 Slog.w(TAG, "Exception when stopping service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011460 + r.shortName, e);
11461 serviceDoneExecutingLocked(r, true);
11462 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011463 updateServiceForegroundLocked(r.app, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011464 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011465 if (DEBUG_SERVICE) Slog.v(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011466 TAG, "Removed service that has no process: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011467 }
11468 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011469 if (DEBUG_SERVICE) Slog.v(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011470 TAG, "Removed service that is not running: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011471 }
Vairavan Srinivasana207ce22010-12-23 13:51:48 -080011472
11473 if (r.bindings.size() > 0) {
11474 r.bindings.clear();
11475 }
11476
11477 if (r.restarter instanceof ServiceRestarter) {
11478 ((ServiceRestarter)r.restarter).setService(null);
11479 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011480 }
11481
11482 ComponentName startServiceLocked(IApplicationThread caller,
11483 Intent service, String resolvedType,
11484 int callingPid, int callingUid) {
11485 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011486 if (DEBUG_SERVICE) Slog.v(TAG, "startService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011487 + " type=" + resolvedType + " args=" + service.getExtras());
11488
11489 if (caller != null) {
11490 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11491 if (callerApp == null) {
11492 throw new SecurityException(
11493 "Unable to find app for caller " + caller
11494 + " (pid=" + Binder.getCallingPid()
11495 + ") when starting service " + service);
11496 }
11497 }
11498
11499 ServiceLookupResult res =
11500 retrieveServiceLocked(service, resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011501 callingPid, callingUid, UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011502 if (res == null) {
11503 return null;
11504 }
11505 if (res.record == null) {
11506 return new ComponentName("!", res.permission != null
11507 ? res.permission : "private to package");
11508 }
11509 ServiceRecord r = res.record;
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011510 NeededUriGrants neededGrants = checkGrantUriPermissionFromIntentLocked(
11511 callingUid, r.packageName, service, service.getFlags(), null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011512 if (unscheduleServiceRestartLocked(r)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011513 if (DEBUG_SERVICE) Slog.v(TAG, "START SERVICE WHILE RESTART PENDING: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011514 }
11515 r.startRequested = true;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011516 r.callStart = false;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011517 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011518 service, neededGrants));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011519 r.lastActivity = SystemClock.uptimeMillis();
11520 synchronized (r.stats.getBatteryStats()) {
11521 r.stats.startRunningLocked();
11522 }
11523 if (!bringUpServiceLocked(r, service.getFlags(), false)) {
11524 return new ComponentName("!", "Service process is bad");
11525 }
11526 return r.name;
11527 }
11528 }
11529
11530 public ComponentName startService(IApplicationThread caller, Intent service,
11531 String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011532 enforceNotIsolatedCaller("startService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011533 // Refuse possible leaked file descriptors
11534 if (service != null && service.hasFileDescriptors() == true) {
11535 throw new IllegalArgumentException("File descriptors passed in Intent");
11536 }
11537
Amith Yamasani742a6712011-05-04 14:49:28 -070011538 if (DEBUG_SERVICE)
11539 Slog.v(TAG, "startService: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011540 synchronized(this) {
11541 final int callingPid = Binder.getCallingPid();
11542 final int callingUid = Binder.getCallingUid();
11543 final long origId = Binder.clearCallingIdentity();
11544 ComponentName res = startServiceLocked(caller, service,
11545 resolvedType, callingPid, callingUid);
11546 Binder.restoreCallingIdentity(origId);
11547 return res;
11548 }
11549 }
11550
11551 ComponentName startServiceInPackage(int uid,
11552 Intent service, String resolvedType) {
11553 synchronized(this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070011554 if (DEBUG_SERVICE)
11555 Slog.v(TAG, "startServiceInPackage: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011556 final long origId = Binder.clearCallingIdentity();
11557 ComponentName res = startServiceLocked(null, service,
11558 resolvedType, -1, uid);
11559 Binder.restoreCallingIdentity(origId);
11560 return res;
11561 }
11562 }
11563
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011564 private void stopServiceLocked(ServiceRecord service) {
11565 synchronized (service.stats.getBatteryStats()) {
11566 service.stats.stopRunningLocked();
11567 }
11568 service.startRequested = false;
11569 service.callStart = false;
11570 bringDownServiceLocked(service, false);
11571 }
11572
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011573 public int stopService(IApplicationThread caller, Intent service,
11574 String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011575 enforceNotIsolatedCaller("stopService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011576 // Refuse possible leaked file descriptors
11577 if (service != null && service.hasFileDescriptors() == true) {
11578 throw new IllegalArgumentException("File descriptors passed in Intent");
11579 }
11580
11581 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011582 if (DEBUG_SERVICE) Slog.v(TAG, "stopService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011583 + " type=" + resolvedType);
11584
11585 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11586 if (caller != null && callerApp == null) {
11587 throw new SecurityException(
11588 "Unable to find app for caller " + caller
11589 + " (pid=" + Binder.getCallingPid()
11590 + ") when stopping service " + service);
11591 }
11592
11593 // If this service is active, make sure it is stopped.
Amith Yamasani483f3b02012-03-13 16:08:00 -070011594 ServiceLookupResult r = findServiceLocked(service, resolvedType,
11595 callerApp == null ? UserId.getCallingUserId() : callerApp.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011596 if (r != null) {
11597 if (r.record != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011598 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011599 try {
11600 stopServiceLocked(r.record);
11601 } finally {
11602 Binder.restoreCallingIdentity(origId);
11603 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011604 return 1;
11605 }
11606 return -1;
11607 }
11608 }
11609
11610 return 0;
11611 }
11612
11613 public IBinder peekService(Intent service, String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011614 enforceNotIsolatedCaller("peekService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011615 // Refuse possible leaked file descriptors
11616 if (service != null && service.hasFileDescriptors() == true) {
11617 throw new IllegalArgumentException("File descriptors passed in Intent");
11618 }
11619
11620 IBinder ret = null;
11621
11622 synchronized(this) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070011623 ServiceLookupResult r = findServiceLocked(service, resolvedType,
11624 UserId.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011625
11626 if (r != null) {
11627 // r.record is null if findServiceLocked() failed the caller permission check
11628 if (r.record == null) {
11629 throw new SecurityException(
11630 "Permission Denial: Accessing service " + r.record.name
11631 + " from pid=" + Binder.getCallingPid()
11632 + ", uid=" + Binder.getCallingUid()
11633 + " requires " + r.permission);
11634 }
11635 IntentBindRecord ib = r.record.bindings.get(r.record.intent);
11636 if (ib != null) {
11637 ret = ib.binder;
11638 }
11639 }
11640 }
11641
11642 return ret;
11643 }
11644
11645 public boolean stopServiceToken(ComponentName className, IBinder token,
11646 int startId) {
11647 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011648 if (DEBUG_SERVICE) Slog.v(TAG, "stopServiceToken: " + className
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011649 + " " + token + " startId=" + startId);
11650 ServiceRecord r = findServiceLocked(className, token);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011651 if (r != null) {
11652 if (startId >= 0) {
11653 // Asked to only stop if done with all work. Note that
11654 // to avoid leaks, we will take this as dropping all
11655 // start items up to and including this one.
11656 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
11657 if (si != null) {
11658 while (r.deliveredStarts.size() > 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -070011659 ServiceRecord.StartItem cur = r.deliveredStarts.remove(0);
11660 cur.removeUriPermissionsLocked();
11661 if (cur == si) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011662 break;
11663 }
11664 }
11665 }
11666
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011667 if (r.getLastStartId() != startId) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011668 return false;
11669 }
11670
11671 if (r.deliveredStarts.size() > 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011672 Slog.w(TAG, "stopServiceToken startId " + startId
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011673 + " is last, but have " + r.deliveredStarts.size()
11674 + " remaining args");
11675 }
11676 }
11677
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011678 synchronized (r.stats.getBatteryStats()) {
11679 r.stats.stopRunningLocked();
11680 r.startRequested = false;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011681 r.callStart = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011682 }
11683 final long origId = Binder.clearCallingIdentity();
11684 bringDownServiceLocked(r, false);
11685 Binder.restoreCallingIdentity(origId);
11686 return true;
11687 }
11688 }
11689 return false;
11690 }
11691
11692 public void setServiceForeground(ComponentName className, IBinder token,
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011693 int id, Notification notification, boolean removeNotification) {
11694 final long origId = Binder.clearCallingIdentity();
11695 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011696 synchronized(this) {
11697 ServiceRecord r = findServiceLocked(className, token);
11698 if (r != null) {
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011699 if (id != 0) {
11700 if (notification == null) {
11701 throw new IllegalArgumentException("null notification");
11702 }
11703 if (r.foregroundId != id) {
11704 r.cancelNotification();
11705 r.foregroundId = id;
11706 }
11707 notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
11708 r.foregroundNoti = notification;
11709 r.isForeground = true;
11710 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011711 if (r.app != null) {
11712 updateServiceForegroundLocked(r.app, true);
11713 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011714 } else {
11715 if (r.isForeground) {
11716 r.isForeground = false;
11717 if (r.app != null) {
Dianne Hackborn8633e682010-04-22 16:03:41 -070011718 updateLruProcessLocked(r.app, false, true);
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011719 updateServiceForegroundLocked(r.app, true);
11720 }
11721 }
11722 if (removeNotification) {
11723 r.cancelNotification();
11724 r.foregroundId = 0;
11725 r.foregroundNoti = null;
11726 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011727 }
11728 }
11729 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011730 } finally {
11731 Binder.restoreCallingIdentity(origId);
11732 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011733 }
11734
11735 public void updateServiceForegroundLocked(ProcessRecord proc, boolean oomAdj) {
11736 boolean anyForeground = false;
Dianne Hackborn860755f2010-06-03 18:47:52 -070011737 for (ServiceRecord sr : proc.services) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011738 if (sr.isForeground) {
11739 anyForeground = true;
11740 break;
11741 }
11742 }
11743 if (anyForeground != proc.foregroundServices) {
11744 proc.foregroundServices = anyForeground;
11745 if (oomAdj) {
11746 updateOomAdjLocked();
11747 }
11748 }
11749 }
Amith Yamasania4a54e22012-04-16 15:44:19 -070011750
11751 boolean isSingleton(String componentProcessName, ApplicationInfo aInfo) {
11752 boolean result = false;
11753 if (UserId.getAppId(aInfo.uid) >= Process.FIRST_APPLICATION_UID) {
11754 result = false;
11755 } else if (componentProcessName == aInfo.packageName) {
11756 result = (aInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0;
11757 } else if ("system".equals(componentProcessName)) {
11758 result = true;
11759 }
11760 if (DEBUG_MU) {
11761 Slog.v(TAG, "isSingleton(" + componentProcessName + ", " + aInfo + ") = " + result);
11762 }
11763 return result;
11764 }
11765
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011766 public int bindService(IApplicationThread caller, IBinder token,
11767 Intent service, String resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011768 IServiceConnection connection, int flags, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011769 enforceNotIsolatedCaller("bindService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011770 // Refuse possible leaked file descriptors
11771 if (service != null && service.hasFileDescriptors() == true) {
11772 throw new IllegalArgumentException("File descriptors passed in Intent");
11773 }
11774
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011775 checkValidCaller(Binder.getCallingUid(), userId);
11776
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011777 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011778 if (DEBUG_SERVICE) Slog.v(TAG, "bindService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011779 + " type=" + resolvedType + " conn=" + connection.asBinder()
11780 + " flags=0x" + Integer.toHexString(flags));
Amith Yamasani742a6712011-05-04 14:49:28 -070011781 if (DEBUG_MU)
11782 Slog.i(TAG_MU, "bindService uid=" + Binder.getCallingUid() + " origUid="
11783 + Binder.getOrigCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011784 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11785 if (callerApp == null) {
11786 throw new SecurityException(
11787 "Unable to find app for caller " + caller
11788 + " (pid=" + Binder.getCallingPid()
11789 + ") when binding service " + service);
11790 }
11791
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011792 ActivityRecord activity = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011793 if (token != null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070011794 activity = mMainStack.isInStackLocked(token);
11795 if (activity == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011796 Slog.w(TAG, "Binding with unknown activity: " + token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011797 return 0;
11798 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011799 }
11800
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011801 int clientLabel = 0;
11802 PendingIntent clientIntent = null;
11803
11804 if (callerApp.info.uid == Process.SYSTEM_UID) {
11805 // Hacky kind of thing -- allow system stuff to tell us
11806 // what they are, so we can report this elsewhere for
11807 // others to know why certain services are running.
11808 try {
11809 clientIntent = (PendingIntent)service.getParcelableExtra(
11810 Intent.EXTRA_CLIENT_INTENT);
11811 } catch (RuntimeException e) {
11812 }
11813 if (clientIntent != null) {
11814 clientLabel = service.getIntExtra(Intent.EXTRA_CLIENT_LABEL, 0);
11815 if (clientLabel != 0) {
11816 // There are no useful extras in the intent, trash them.
11817 // System code calling with this stuff just needs to know
11818 // this will happen.
11819 service = service.cloneFilter();
11820 }
11821 }
11822 }
11823
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011824 ServiceLookupResult res =
11825 retrieveServiceLocked(service, resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011826 Binder.getCallingPid(), Binder.getCallingUid(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011827 if (res == null) {
11828 return 0;
11829 }
11830 if (res.record == null) {
11831 return -1;
11832 }
Amith Yamasania4a54e22012-04-16 15:44:19 -070011833 if (isSingleton(res.record.processName, res.record.appInfo)) {
11834 userId = 0;
11835 res = retrieveServiceLocked(service, resolvedType, Binder.getCallingPid(),
11836 Binder.getCallingUid(), 0);
11837 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011838 ServiceRecord s = res.record;
11839
11840 final long origId = Binder.clearCallingIdentity();
11841
11842 if (unscheduleServiceRestartLocked(s)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011843 if (DEBUG_SERVICE) Slog.v(TAG, "BIND SERVICE WHILE RESTART PENDING: "
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011844 + s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011845 }
11846
11847 AppBindRecord b = s.retrieveAppBindingLocked(service, callerApp);
11848 ConnectionRecord c = new ConnectionRecord(b, activity,
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011849 connection, flags, clientLabel, clientIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011850
11851 IBinder binder = connection.asBinder();
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011852 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
11853 if (clist == null) {
11854 clist = new ArrayList<ConnectionRecord>();
11855 s.connections.put(binder, clist);
11856 }
11857 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011858 b.connections.add(c);
11859 if (activity != null) {
11860 if (activity.connections == null) {
11861 activity.connections = new HashSet<ConnectionRecord>();
11862 }
11863 activity.connections.add(c);
11864 }
11865 b.client.connections.add(c);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070011866 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
11867 b.client.hasAboveClient = true;
11868 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011869 clist = mServiceConnections.get(binder);
11870 if (clist == null) {
11871 clist = new ArrayList<ConnectionRecord>();
11872 mServiceConnections.put(binder, clist);
11873 }
11874 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011875
11876 if ((flags&Context.BIND_AUTO_CREATE) != 0) {
11877 s.lastActivity = SystemClock.uptimeMillis();
11878 if (!bringUpServiceLocked(s, service.getFlags(), false)) {
11879 return 0;
11880 }
11881 }
11882
11883 if (s.app != null) {
11884 // This could have made the service more important.
11885 updateOomAdjLocked(s.app);
11886 }
11887
Joe Onorato8a9b2202010-02-26 18:56:32 -080011888 if (DEBUG_SERVICE) Slog.v(TAG, "Bind " + s + " with " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011889 + ": received=" + b.intent.received
11890 + " apps=" + b.intent.apps.size()
11891 + " doRebind=" + b.intent.doRebind);
11892
11893 if (s.app != null && b.intent.received) {
11894 // Service is already running, so we can immediately
11895 // publish the connection.
11896 try {
11897 c.conn.connected(s.name, b.intent.binder);
11898 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011899 Slog.w(TAG, "Failure sending service " + s.shortName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011900 + " to connection " + c.conn.asBinder()
11901 + " (in " + c.binding.client.processName + ")", e);
11902 }
11903
11904 // If this is the first app connected back to this binding,
11905 // and the service had previously asked to be told when
11906 // rebound, then do so.
11907 if (b.intent.apps.size() == 1 && b.intent.doRebind) {
11908 requestServiceBindingLocked(s, b.intent, true);
11909 }
11910 } else if (!b.intent.requested) {
11911 requestServiceBindingLocked(s, b.intent, false);
11912 }
11913
11914 Binder.restoreCallingIdentity(origId);
11915 }
11916
11917 return 1;
11918 }
11919
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070011920 void removeConnectionLocked(
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011921 ConnectionRecord c, ProcessRecord skipApp, ActivityRecord skipAct) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011922 IBinder binder = c.conn.asBinder();
11923 AppBindRecord b = c.binding;
11924 ServiceRecord s = b.service;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011925 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
11926 if (clist != null) {
11927 clist.remove(c);
11928 if (clist.size() == 0) {
11929 s.connections.remove(binder);
11930 }
11931 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011932 b.connections.remove(c);
11933 if (c.activity != null && c.activity != skipAct) {
11934 if (c.activity.connections != null) {
11935 c.activity.connections.remove(c);
11936 }
11937 }
11938 if (b.client != skipApp) {
11939 b.client.connections.remove(c);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070011940 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
11941 b.client.updateHasAboveClientLocked();
11942 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011943 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011944 clist = mServiceConnections.get(binder);
11945 if (clist != null) {
11946 clist.remove(c);
11947 if (clist.size() == 0) {
11948 mServiceConnections.remove(binder);
11949 }
11950 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011951
11952 if (b.connections.size() == 0) {
11953 b.intent.apps.remove(b.client);
11954 }
11955
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011956 if (!c.serviceDead) {
11957 if (DEBUG_SERVICE) Slog.v(TAG, "Disconnecting binding " + b.intent
11958 + ": shouldUnbind=" + b.intent.hasBound);
11959 if (s.app != null && s.app.thread != null && b.intent.apps.size() == 0
11960 && b.intent.hasBound) {
11961 try {
11962 bumpServiceExecutingLocked(s, "unbind");
11963 updateOomAdjLocked(s.app);
11964 b.intent.hasBound = false;
11965 // Assume the client doesn't want to know about a rebind;
11966 // we will deal with that later if it asks for one.
11967 b.intent.doRebind = false;
11968 s.app.thread.scheduleUnbindService(s, b.intent.intent.getIntent());
11969 } catch (Exception e) {
11970 Slog.w(TAG, "Exception when unbinding service " + s.shortName, e);
11971 serviceDoneExecutingLocked(s, true);
11972 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011973 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011974
11975 if ((c.flags&Context.BIND_AUTO_CREATE) != 0) {
11976 bringDownServiceLocked(s, false);
11977 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011978 }
11979 }
11980
11981 public boolean unbindService(IServiceConnection connection) {
11982 synchronized (this) {
11983 IBinder binder = connection.asBinder();
Joe Onorato8a9b2202010-02-26 18:56:32 -080011984 if (DEBUG_SERVICE) Slog.v(TAG, "unbindService: conn=" + binder);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011985 ArrayList<ConnectionRecord> clist = mServiceConnections.get(binder);
11986 if (clist == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011987 Slog.w(TAG, "Unbind failed: could not find connection for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011988 + connection.asBinder());
11989 return false;
11990 }
11991
11992 final long origId = Binder.clearCallingIdentity();
11993
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011994 while (clist.size() > 0) {
11995 ConnectionRecord r = clist.get(0);
11996 removeConnectionLocked(r, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011997
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011998 if (r.binding.service.app != null) {
11999 // This could have made the service less important.
12000 updateOomAdjLocked(r.binding.service.app);
12001 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012002 }
12003
12004 Binder.restoreCallingIdentity(origId);
12005 }
12006
12007 return true;
12008 }
12009
12010 public void publishService(IBinder token, Intent intent, IBinder service) {
12011 // Refuse possible leaked file descriptors
12012 if (intent != null && intent.hasFileDescriptors() == true) {
12013 throw new IllegalArgumentException("File descriptors passed in Intent");
12014 }
12015
12016 synchronized(this) {
12017 if (!(token instanceof ServiceRecord)) {
12018 throw new IllegalArgumentException("Invalid service token");
12019 }
12020 ServiceRecord r = (ServiceRecord)token;
12021
12022 final long origId = Binder.clearCallingIdentity();
12023
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012024 if (DEBUG_SERVICE) Slog.v(TAG, "PUBLISHING " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012025 + " " + intent + ": " + service);
12026 if (r != null) {
12027 Intent.FilterComparison filter
12028 = new Intent.FilterComparison(intent);
12029 IntentBindRecord b = r.bindings.get(filter);
12030 if (b != null && !b.received) {
12031 b.binder = service;
12032 b.requested = true;
12033 b.received = true;
12034 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012035 Iterator<ArrayList<ConnectionRecord>> it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012036 = r.connections.values().iterator();
12037 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012038 ArrayList<ConnectionRecord> clist = it.next();
12039 for (int i=0; i<clist.size(); i++) {
12040 ConnectionRecord c = clist.get(i);
12041 if (!filter.equals(c.binding.intent.intent)) {
12042 if (DEBUG_SERVICE) Slog.v(
12043 TAG, "Not publishing to: " + c);
12044 if (DEBUG_SERVICE) Slog.v(
12045 TAG, "Bound intent: " + c.binding.intent.intent);
12046 if (DEBUG_SERVICE) Slog.v(
12047 TAG, "Published intent: " + intent);
12048 continue;
12049 }
12050 if (DEBUG_SERVICE) Slog.v(TAG, "Publishing to: " + c);
12051 try {
12052 c.conn.connected(r.name, service);
12053 } catch (Exception e) {
12054 Slog.w(TAG, "Failure sending service " + r.name +
12055 " to connection " + c.conn.asBinder() +
12056 " (in " + c.binding.client.processName + ")", e);
12057 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012058 }
12059 }
12060 }
12061 }
12062
12063 serviceDoneExecutingLocked(r, mStoppingServices.contains(r));
12064
12065 Binder.restoreCallingIdentity(origId);
12066 }
12067 }
12068 }
12069
12070 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
12071 // Refuse possible leaked file descriptors
12072 if (intent != null && intent.hasFileDescriptors() == true) {
12073 throw new IllegalArgumentException("File descriptors passed in Intent");
12074 }
12075
12076 synchronized(this) {
12077 if (!(token instanceof ServiceRecord)) {
12078 throw new IllegalArgumentException("Invalid service token");
12079 }
12080 ServiceRecord r = (ServiceRecord)token;
12081
12082 final long origId = Binder.clearCallingIdentity();
12083
12084 if (r != null) {
12085 Intent.FilterComparison filter
12086 = new Intent.FilterComparison(intent);
12087 IntentBindRecord b = r.bindings.get(filter);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012088 if (DEBUG_SERVICE) Slog.v(TAG, "unbindFinished in " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012089 + " at " + b + ": apps="
12090 + (b != null ? b.apps.size() : 0));
Per Edelberg78f9fff2010-08-30 20:01:35 +020012091
12092 boolean inStopping = mStoppingServices.contains(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012093 if (b != null) {
Per Edelberg78f9fff2010-08-30 20:01:35 +020012094 if (b.apps.size() > 0 && !inStopping) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012095 // Applications have already bound since the last
12096 // unbind, so just rebind right here.
12097 requestServiceBindingLocked(r, b, true);
12098 } else {
12099 // Note to tell the service the next time there is
12100 // a new client.
12101 b.doRebind = true;
12102 }
12103 }
12104
Per Edelberg78f9fff2010-08-30 20:01:35 +020012105 serviceDoneExecutingLocked(r, inStopping);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012106
12107 Binder.restoreCallingIdentity(origId);
12108 }
12109 }
12110 }
12111
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012112 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012113 synchronized(this) {
12114 if (!(token instanceof ServiceRecord)) {
12115 throw new IllegalArgumentException("Invalid service token");
12116 }
12117 ServiceRecord r = (ServiceRecord)token;
12118 boolean inStopping = mStoppingServices.contains(token);
12119 if (r != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012120 if (r != token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012121 Slog.w(TAG, "Done executing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012122 + " with incorrect token: given " + token
12123 + ", expected " + r);
12124 return;
12125 }
12126
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012127 if (type == 1) {
12128 // This is a call from a service start... take care of
12129 // book-keeping.
12130 r.callStart = true;
12131 switch (res) {
12132 case Service.START_STICKY_COMPATIBILITY:
12133 case Service.START_STICKY: {
12134 // We are done with the associated start arguments.
12135 r.findDeliveredStart(startId, true);
12136 // Don't stop if killed.
12137 r.stopIfKilled = false;
12138 break;
12139 }
12140 case Service.START_NOT_STICKY: {
12141 // We are done with the associated start arguments.
12142 r.findDeliveredStart(startId, true);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070012143 if (r.getLastStartId() == startId) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012144 // There is no more work, and this service
12145 // doesn't want to hang around if killed.
12146 r.stopIfKilled = true;
12147 }
12148 break;
12149 }
12150 case Service.START_REDELIVER_INTENT: {
12151 // We'll keep this item until they explicitly
12152 // call stop for it, but keep track of the fact
12153 // that it was delivered.
12154 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
12155 if (si != null) {
12156 si.deliveryCount = 0;
12157 si.doneExecutingCount++;
12158 // Don't stop if killed.
12159 r.stopIfKilled = true;
12160 }
12161 break;
12162 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070012163 case Service.START_TASK_REMOVED_COMPLETE: {
12164 // Special processing for onTaskRemoved(). Don't
12165 // impact normal onStartCommand() processing.
12166 r.findDeliveredStart(startId, true);
12167 break;
12168 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012169 default:
12170 throw new IllegalArgumentException(
12171 "Unknown service start result: " + res);
12172 }
12173 if (res == Service.START_STICKY_COMPATIBILITY) {
12174 r.callStart = false;
12175 }
12176 }
Amith Yamasani742a6712011-05-04 14:49:28 -070012177 if (DEBUG_MU)
12178 Slog.v(TAG_MU, "before serviceDontExecutingLocked, uid="
12179 + Binder.getOrigCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012180 final long origId = Binder.clearCallingIdentity();
12181 serviceDoneExecutingLocked(r, inStopping);
12182 Binder.restoreCallingIdentity(origId);
12183 } else {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012184 Slog.w(TAG, "Done executing unknown service from pid "
12185 + Binder.getCallingPid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012186 }
12187 }
12188 }
12189
12190 public void serviceDoneExecutingLocked(ServiceRecord r, boolean inStopping) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012191 if (DEBUG_SERVICE) Slog.v(TAG, "<<< DONE EXECUTING " + r
12192 + ": nesting=" + r.executeNesting
12193 + ", inStopping=" + inStopping + ", app=" + r.app);
Dianne Hackborn287952c2010-09-22 22:34:31 -070012194 else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG, "<<< DONE EXECUTING " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012195 r.executeNesting--;
12196 if (r.executeNesting <= 0 && r.app != null) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012197 if (DEBUG_SERVICE) Slog.v(TAG,
12198 "Nesting at 0 of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012199 r.app.executingServices.remove(r);
12200 if (r.app.executingServices.size() == 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012201 if (DEBUG_SERVICE || DEBUG_SERVICE_EXECUTING) Slog.v(TAG,
12202 "No more executingServices of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012203 mHandler.removeMessages(SERVICE_TIMEOUT_MSG, r.app);
12204 }
12205 if (inStopping) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012206 if (DEBUG_SERVICE) Slog.v(TAG,
12207 "doneExecuting remove stopping " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012208 mStoppingServices.remove(r);
Mattias Petersson3996b412010-10-27 09:32:51 +020012209 r.bindings.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012210 }
12211 updateOomAdjLocked(r.app);
12212 }
12213 }
12214
12215 void serviceTimeout(ProcessRecord proc) {
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012216 String anrMessage = null;
12217
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012218 synchronized(this) {
12219 if (proc.executingServices.size() == 0 || proc.thread == null) {
12220 return;
12221 }
12222 long maxTime = SystemClock.uptimeMillis() - SERVICE_TIMEOUT;
12223 Iterator<ServiceRecord> it = proc.executingServices.iterator();
12224 ServiceRecord timeout = null;
12225 long nextTime = 0;
12226 while (it.hasNext()) {
12227 ServiceRecord sr = it.next();
12228 if (sr.executingStart < maxTime) {
12229 timeout = sr;
12230 break;
12231 }
12232 if (sr.executingStart > nextTime) {
12233 nextTime = sr.executingStart;
12234 }
12235 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012236 if (timeout != null && mLruProcesses.contains(proc)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012237 Slog.w(TAG, "Timeout executing service: " + timeout);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012238 anrMessage = "Executing service " + timeout.shortName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012239 } else {
12240 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
12241 msg.obj = proc;
12242 mHandler.sendMessageAtTime(msg, nextTime+SERVICE_TIMEOUT);
12243 }
12244 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012245
12246 if (anrMessage != null) {
12247 appNotResponding(proc, null, null, anrMessage);
12248 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012249 }
12250
12251 // =========================================================
Christopher Tate181fafa2009-05-14 11:12:14 -070012252 // BACKUP AND RESTORE
12253 // =========================================================
12254
12255 // Cause the target app to be launched if necessary and its backup agent
12256 // instantiated. The backup agent will invoke backupAgentCreated() on the
12257 // activity manager to announce its creation.
12258 public boolean bindBackupAgent(ApplicationInfo app, int backupMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012259 if (DEBUG_BACKUP) Slog.v(TAG, "startBackupAgent: app=" + app + " mode=" + backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070012260 enforceCallingPermission("android.permission.BACKUP", "startBackupAgent");
12261
12262 synchronized(this) {
12263 // !!! TODO: currently no check here that we're already bound
12264 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
12265 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
12266 synchronized (stats) {
12267 ss = stats.getServiceStatsLocked(app.uid, app.packageName, app.name);
12268 }
12269
Dianne Hackborne7f97212011-02-24 14:40:20 -080012270 // Backup agent is now in use, its package can't be stopped.
12271 try {
12272 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -070012273 app.packageName, false, UserId.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -080012274 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080012275 } catch (IllegalArgumentException e) {
12276 Slog.w(TAG, "Failed trying to unstop package "
12277 + app.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080012278 }
12279
Christopher Tate181fafa2009-05-14 11:12:14 -070012280 BackupRecord r = new BackupRecord(ss, app, backupMode);
Christopher Tate4a627c72011-04-01 14:43:32 -070012281 ComponentName hostingName = (backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL)
12282 ? new ComponentName(app.packageName, app.backupAgentName)
12283 : new ComponentName("android", "FullBackupAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -070012284 // startProcessLocked() returns existing proc's record if it's already running
12285 ProcessRecord proc = startProcessLocked(app.processName, app,
Dianne Hackborna0c283e2012-02-09 10:47:01 -080012286 false, 0, "backup", hostingName, false, false);
Christopher Tate181fafa2009-05-14 11:12:14 -070012287 if (proc == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012288 Slog.e(TAG, "Unable to start backup agent process " + r);
Christopher Tate181fafa2009-05-14 11:12:14 -070012289 return false;
12290 }
12291
12292 r.app = proc;
12293 mBackupTarget = r;
12294 mBackupAppName = app.packageName;
12295
Christopher Tate6fa95972009-06-05 18:43:55 -070012296 // Try not to kill the process during backup
12297 updateOomAdjLocked(proc);
12298
Christopher Tate181fafa2009-05-14 11:12:14 -070012299 // If the process is already attached, schedule the creation of the backup agent now.
12300 // If it is not yet live, this will be done when it attaches to the framework.
12301 if (proc.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012302 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc already running: " + proc);
Christopher Tate181fafa2009-05-14 11:12:14 -070012303 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040012304 proc.thread.scheduleCreateBackupAgent(app,
12305 compatibilityInfoForPackageLocked(app), backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070012306 } catch (RemoteException e) {
Christopher Tate436344a2009-09-30 16:17:37 -070012307 // Will time out on the backup manager side
Christopher Tate181fafa2009-05-14 11:12:14 -070012308 }
12309 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012310 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc not running, waiting for attach");
Christopher Tate181fafa2009-05-14 11:12:14 -070012311 }
12312 // Invariants: at this point, the target app process exists and the application
12313 // is either already running or in the process of coming up. mBackupTarget and
12314 // mBackupAppName describe the app, so that when it binds back to the AM we
12315 // know that it's scheduled for a backup-agent operation.
12316 }
12317
12318 return true;
12319 }
12320
12321 // A backup agent has just come up
12322 public void backupAgentCreated(String agentPackageName, IBinder agent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012323 if (DEBUG_BACKUP) Slog.v(TAG, "backupAgentCreated: " + agentPackageName
Christopher Tate181fafa2009-05-14 11:12:14 -070012324 + " = " + agent);
12325
12326 synchronized(this) {
12327 if (!agentPackageName.equals(mBackupAppName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012328 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
Christopher Tate181fafa2009-05-14 11:12:14 -070012329 return;
12330 }
Dianne Hackborn06740692010-09-22 22:46:21 -070012331 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012332
Dianne Hackborn06740692010-09-22 22:46:21 -070012333 long oldIdent = Binder.clearCallingIdentity();
12334 try {
12335 IBackupManager bm = IBackupManager.Stub.asInterface(
12336 ServiceManager.getService(Context.BACKUP_SERVICE));
12337 bm.agentConnected(agentPackageName, agent);
12338 } catch (RemoteException e) {
12339 // can't happen; the backup manager service is local
12340 } catch (Exception e) {
12341 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: ");
12342 e.printStackTrace();
12343 } finally {
12344 Binder.restoreCallingIdentity(oldIdent);
Christopher Tate181fafa2009-05-14 11:12:14 -070012345 }
12346 }
12347
12348 // done with this agent
12349 public void unbindBackupAgent(ApplicationInfo appInfo) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012350 if (DEBUG_BACKUP) Slog.v(TAG, "unbindBackupAgent: " + appInfo);
Christopher Tate8a27f922009-06-26 11:49:18 -070012351 if (appInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012352 Slog.w(TAG, "unbind backup agent for null app");
Christopher Tate8a27f922009-06-26 11:49:18 -070012353 return;
12354 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012355
12356 synchronized(this) {
Christopher Tate8a27f922009-06-26 11:49:18 -070012357 if (mBackupAppName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012358 Slog.w(TAG, "Unbinding backup agent with no active backup");
Christopher Tate8a27f922009-06-26 11:49:18 -070012359 return;
12360 }
12361
Christopher Tate181fafa2009-05-14 11:12:14 -070012362 if (!mBackupAppName.equals(appInfo.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012363 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
Christopher Tate181fafa2009-05-14 11:12:14 -070012364 return;
12365 }
12366
Christopher Tate6fa95972009-06-05 18:43:55 -070012367 ProcessRecord proc = mBackupTarget.app;
12368 mBackupTarget = null;
12369 mBackupAppName = null;
12370
12371 // Not backing this app up any more; reset its OOM adjustment
12372 updateOomAdjLocked(proc);
12373
Christopher Tatec7b31e32009-06-10 15:49:30 -070012374 // If the app crashed during backup, 'thread' will be null here
12375 if (proc.thread != null) {
12376 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040012377 proc.thread.scheduleDestroyBackupAgent(appInfo,
12378 compatibilityInfoForPackageLocked(appInfo));
Christopher Tatec7b31e32009-06-10 15:49:30 -070012379 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012380 Slog.e(TAG, "Exception when unbinding backup agent:");
Christopher Tatec7b31e32009-06-10 15:49:30 -070012381 e.printStackTrace();
12382 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012383 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012384 }
12385 }
12386 // =========================================================
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012387 // BROADCASTS
12388 // =========================================================
12389
Josh Bartel7f208742010-02-25 11:01:44 -060012390 private final List getStickiesLocked(String action, IntentFilter filter,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012391 List cur) {
12392 final ContentResolver resolver = mContext.getContentResolver();
12393 final ArrayList<Intent> list = mStickyBroadcasts.get(action);
12394 if (list == null) {
12395 return cur;
12396 }
12397 int N = list.size();
12398 for (int i=0; i<N; i++) {
12399 Intent intent = list.get(i);
12400 if (filter.match(resolver, intent, true, TAG) >= 0) {
12401 if (cur == null) {
12402 cur = new ArrayList<Intent>();
12403 }
12404 cur.add(intent);
12405 }
12406 }
12407 return cur;
12408 }
12409
Christopher Tatef46723b2012-01-26 14:19:24 -080012410 boolean isPendingBroadcastProcessLocked(int pid) {
12411 return mFgBroadcastQueue.isPendingBroadcastProcessLocked(pid)
12412 || mBgBroadcastQueue.isPendingBroadcastProcessLocked(pid);
12413 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012414
Christopher Tatef46723b2012-01-26 14:19:24 -080012415 void skipPendingBroadcastLocked(int pid) {
12416 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
12417 for (BroadcastQueue queue : mBroadcastQueues) {
12418 queue.skipPendingBroadcastLocked(pid);
12419 }
12420 }
12421
12422 // The app just attached; send any pending broadcasts that it should receive
12423 boolean sendPendingBroadcastsLocked(ProcessRecord app) {
12424 boolean didSomething = false;
12425 for (BroadcastQueue queue : mBroadcastQueues) {
12426 didSomething |= queue.sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012427 }
Christopher Tatef46723b2012-01-26 14:19:24 -080012428 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012429 }
12430
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012431 public Intent registerReceiver(IApplicationThread caller, String callerPackage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012432 IIntentReceiver receiver, IntentFilter filter, String permission) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012433 enforceNotIsolatedCaller("registerReceiver");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012434 synchronized(this) {
12435 ProcessRecord callerApp = null;
12436 if (caller != null) {
12437 callerApp = getRecordForAppLocked(caller);
12438 if (callerApp == null) {
12439 throw new SecurityException(
12440 "Unable to find app for caller " + caller
12441 + " (pid=" + Binder.getCallingPid()
12442 + ") when registering receiver " + receiver);
12443 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012444 if (callerApp.info.uid != Process.SYSTEM_UID &&
12445 !callerApp.pkgList.contains(callerPackage)) {
12446 throw new SecurityException("Given caller package " + callerPackage
12447 + " is not running in process " + callerApp);
12448 }
12449 } else {
12450 callerPackage = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012451 }
12452
12453 List allSticky = null;
12454
12455 // Look for any matching sticky broadcasts...
12456 Iterator actions = filter.actionsIterator();
12457 if (actions != null) {
12458 while (actions.hasNext()) {
12459 String action = (String)actions.next();
Josh Bartel7f208742010-02-25 11:01:44 -060012460 allSticky = getStickiesLocked(action, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012461 }
12462 } else {
Josh Bartel7f208742010-02-25 11:01:44 -060012463 allSticky = getStickiesLocked(null, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012464 }
12465
12466 // The first sticky in the list is returned directly back to
12467 // the client.
12468 Intent sticky = allSticky != null ? (Intent)allSticky.get(0) : null;
12469
Joe Onorato8a9b2202010-02-26 18:56:32 -080012470 if (DEBUG_BROADCAST) Slog.v(TAG, "Register receiver " + filter
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012471 + ": " + sticky);
12472
12473 if (receiver == null) {
12474 return sticky;
12475 }
12476
12477 ReceiverList rl
12478 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
12479 if (rl == null) {
12480 rl = new ReceiverList(this, callerApp,
12481 Binder.getCallingPid(),
12482 Binder.getCallingUid(), receiver);
12483 if (rl.app != null) {
12484 rl.app.receivers.add(rl);
12485 } else {
12486 try {
12487 receiver.asBinder().linkToDeath(rl, 0);
12488 } catch (RemoteException e) {
12489 return sticky;
12490 }
12491 rl.linkedToDeath = true;
12492 }
12493 mRegisteredReceivers.put(receiver.asBinder(), rl);
12494 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012495 BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage, permission);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012496 rl.add(bf);
12497 if (!bf.debugCheck()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012498 Slog.w(TAG, "==> For Dynamic broadast");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012499 }
12500 mReceiverResolver.addFilter(bf);
12501
12502 // Enqueue broadcasts for all existing stickies that match
12503 // this filter.
12504 if (allSticky != null) {
12505 ArrayList receivers = new ArrayList();
12506 receivers.add(bf);
12507
12508 int N = allSticky.size();
12509 for (int i=0; i<N; i++) {
12510 Intent intent = (Intent)allSticky.get(i);
Christopher Tatef46723b2012-01-26 14:19:24 -080012511 BroadcastQueue queue = broadcastQueueForIntent(intent);
12512 BroadcastRecord r = new BroadcastRecord(queue, intent, null,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012513 null, -1, -1, null, receivers, null, 0, null, null,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012514 false, true, true);
Christopher Tatef46723b2012-01-26 14:19:24 -080012515 queue.enqueueParallelBroadcastLocked(r);
12516 queue.scheduleBroadcastsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012517 }
12518 }
12519
12520 return sticky;
12521 }
12522 }
12523
12524 public void unregisterReceiver(IIntentReceiver receiver) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012525 if (DEBUG_BROADCAST) Slog.v(TAG, "Unregister receiver: " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012526
Christopher Tatef46723b2012-01-26 14:19:24 -080012527 final long origId = Binder.clearCallingIdentity();
12528 try {
12529 boolean doTrim = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012530
Christopher Tatef46723b2012-01-26 14:19:24 -080012531 synchronized(this) {
12532 ReceiverList rl
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012533 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
Christopher Tatef46723b2012-01-26 14:19:24 -080012534 if (rl != null) {
12535 if (rl.curBroadcast != null) {
12536 BroadcastRecord r = rl.curBroadcast;
12537 final boolean doNext = finishReceiverLocked(
12538 receiver.asBinder(), r.resultCode, r.resultData,
12539 r.resultExtras, r.resultAbort, true);
12540 if (doNext) {
12541 doTrim = true;
12542 r.queue.processNextBroadcast(false);
12543 }
12544 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012545
Christopher Tatef46723b2012-01-26 14:19:24 -080012546 if (rl.app != null) {
12547 rl.app.receivers.remove(rl);
12548 }
12549 removeReceiverLocked(rl);
12550 if (rl.linkedToDeath) {
12551 rl.linkedToDeath = false;
12552 rl.receiver.asBinder().unlinkToDeath(rl, 0);
12553 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012554 }
12555 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012556
Christopher Tatef46723b2012-01-26 14:19:24 -080012557 // If we actually concluded any broadcasts, we might now be able
12558 // to trim the recipients' apps from our working set
12559 if (doTrim) {
12560 trimApplications();
12561 return;
12562 }
12563
12564 } finally {
12565 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012566 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012567 }
12568
12569 void removeReceiverLocked(ReceiverList rl) {
12570 mRegisteredReceivers.remove(rl.receiver.asBinder());
12571 int N = rl.size();
12572 for (int i=0; i<N; i++) {
12573 mReceiverResolver.removeFilter(rl.get(i));
12574 }
12575 }
12576
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012577 private final void sendPackageBroadcastLocked(int cmd, String[] packages) {
12578 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
12579 ProcessRecord r = mLruProcesses.get(i);
12580 if (r.thread != null) {
12581 try {
12582 r.thread.dispatchPackageBroadcast(cmd, packages);
12583 } catch (RemoteException ex) {
12584 }
12585 }
12586 }
12587 }
12588
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012589 private final int broadcastIntentLocked(ProcessRecord callerApp,
12590 String callerPackage, Intent intent, String resolvedType,
12591 IIntentReceiver resultTo, int resultCode, String resultData,
12592 Bundle map, String requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070012593 boolean ordered, boolean sticky, int callingPid, int callingUid,
12594 int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012595 intent = new Intent(intent);
12596
Dianne Hackborne7f97212011-02-24 14:40:20 -080012597 // By default broadcasts do not go to stopped apps.
12598 intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
12599
Joe Onorato8a9b2202010-02-26 18:56:32 -080012600 if (DEBUG_BROADCAST_LIGHT) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012601 TAG, (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
Amith Yamasani13593602012-03-22 16:16:17 -070012602 + " ordered=" + ordered + " userid=" + userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012603 if ((resultTo != null) && !ordered) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012604 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012605 }
12606
12607 // Handle special intents: if this broadcast is from the package
12608 // manager about a package being removed, we need to remove all of
12609 // its activities from the history stack.
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012610 final boolean uidRemoved = Intent.ACTION_UID_REMOVED.equals(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012611 intent.getAction());
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012612 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())
12613 || Intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction())
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080012614 || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012615 || uidRemoved) {
12616 if (checkComponentPermission(
12617 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080012618 callingPid, callingUid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012619 == PackageManager.PERMISSION_GRANTED) {
12620 if (uidRemoved) {
12621 final Bundle intentExtras = intent.getExtras();
12622 final int uid = intentExtras != null
12623 ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
12624 if (uid >= 0) {
12625 BatteryStatsImpl bs = mBatteryStatsService.getActiveStatistics();
12626 synchronized (bs) {
12627 bs.removeUidStatsLocked(uid);
12628 }
12629 }
12630 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012631 // If resources are unvailble just force stop all
12632 // those packages and flush the attribute cache as well.
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080012633 if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012634 String list[] = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
12635 if (list != null && (list.length > 0)) {
12636 for (String pkg : list) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070012637 forceStopPackageLocked(pkg, -1, false, true, true, false, userId);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012638 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012639 sendPackageBroadcastLocked(
12640 IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE, list);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012641 }
12642 } else {
12643 Uri data = intent.getData();
12644 String ssp;
12645 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
12646 if (!intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false)) {
12647 forceStopPackageLocked(ssp,
Amith Yamasani483f3b02012-03-13 16:08:00 -070012648 intent.getIntExtra(Intent.EXTRA_UID, -1), false, true, true,
12649 false, userId);
Dianne Hackbornde7faf62009-06-30 13:27:30 -070012650 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012651 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012652 sendPackageBroadcastLocked(IApplicationThread.PACKAGE_REMOVED,
12653 new String[] {ssp});
12654 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012655 }
12656 }
12657 }
12658 } else {
12659 String msg = "Permission Denial: " + intent.getAction()
12660 + " broadcast from " + callerPackage + " (pid=" + callingPid
12661 + ", uid=" + callingUid + ")"
12662 + " requires "
12663 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012664 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012665 throw new SecurityException(msg);
12666 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012667
12668 // Special case for adding a package: by default turn on compatibility
12669 // mode.
12670 } else if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -070012671 Uri data = intent.getData();
12672 String ssp;
12673 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
12674 mCompatModePackages.handlePackageAddedLocked(ssp,
12675 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false));
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012676 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012677 }
12678
12679 /*
12680 * If this is the time zone changed action, queue up a message that will reset the timezone
12681 * of all currently running processes. This message will get queued up before the broadcast
12682 * happens.
12683 */
12684 if (intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) {
12685 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
12686 }
12687
Robert Greenwalt03595d02010-11-02 14:08:23 -070012688 if (intent.ACTION_CLEAR_DNS_CACHE.equals(intent.getAction())) {
12689 mHandler.sendEmptyMessage(CLEAR_DNS_CACHE);
12690 }
12691
Robert Greenwalt434203a2010-10-11 16:00:27 -070012692 if (Proxy.PROXY_CHANGE_ACTION.equals(intent.getAction())) {
12693 ProxyProperties proxy = intent.getParcelableExtra("proxy");
12694 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY, proxy));
12695 }
12696
Dianne Hackborn854060af2009-07-09 18:14:31 -070012697 /*
12698 * Prevent non-system code (defined here to be non-persistent
12699 * processes) from sending protected broadcasts.
12700 */
12701 if (callingUid == Process.SYSTEM_UID || callingUid == Process.PHONE_UID
12702 || callingUid == Process.SHELL_UID || callingUid == 0) {
12703 // Always okay.
12704 } else if (callerApp == null || !callerApp.persistent) {
12705 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012706 if (AppGlobals.getPackageManager().isProtectedBroadcast(
Dianne Hackborn854060af2009-07-09 18:14:31 -070012707 intent.getAction())) {
12708 String msg = "Permission Denial: not allowed to send broadcast "
12709 + intent.getAction() + " from pid="
12710 + callingPid + ", uid=" + callingUid;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012711 Slog.w(TAG, msg);
Dianne Hackborn854060af2009-07-09 18:14:31 -070012712 throw new SecurityException(msg);
12713 }
12714 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012715 Slog.w(TAG, "Remote exception", e);
Dianne Hackborna4972e92012-03-14 10:38:05 -070012716 return ActivityManager.BROADCAST_SUCCESS;
Dianne Hackborn854060af2009-07-09 18:14:31 -070012717 }
12718 }
12719
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012720 // Add to the sticky list if requested.
12721 if (sticky) {
12722 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
12723 callingPid, callingUid)
12724 != PackageManager.PERMISSION_GRANTED) {
12725 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
12726 + callingPid + ", uid=" + callingUid
12727 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012728 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012729 throw new SecurityException(msg);
12730 }
12731 if (requiredPermission != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012732 Slog.w(TAG, "Can't broadcast sticky intent " + intent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012733 + " and enforce permission " + requiredPermission);
Dianne Hackborna4972e92012-03-14 10:38:05 -070012734 return ActivityManager.BROADCAST_STICKY_CANT_HAVE_PERMISSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012735 }
12736 if (intent.getComponent() != null) {
12737 throw new SecurityException(
12738 "Sticky broadcasts can't target a specific component");
12739 }
12740 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
12741 if (list == null) {
12742 list = new ArrayList<Intent>();
12743 mStickyBroadcasts.put(intent.getAction(), list);
12744 }
12745 int N = list.size();
12746 int i;
12747 for (i=0; i<N; i++) {
12748 if (intent.filterEquals(list.get(i))) {
12749 // This sticky already exists, replace it.
12750 list.set(i, new Intent(intent));
12751 break;
12752 }
12753 }
12754 if (i >= N) {
12755 list.add(new Intent(intent));
12756 }
12757 }
12758
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012759 // Figure out who all will receive this broadcast.
12760 List receivers = null;
12761 List<BroadcastFilter> registeredReceivers = null;
12762 try {
12763 if (intent.getComponent() != null) {
12764 // Broadcast is going to one specific receiver class...
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012765 ActivityInfo ai = AppGlobals.getPackageManager().
Amith Yamasani483f3b02012-03-13 16:08:00 -070012766 getReceiverInfo(intent.getComponent(), STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012767 if (ai != null) {
12768 receivers = new ArrayList();
12769 ResolveInfo ri = new ResolveInfo();
Amith Yamasania4a54e22012-04-16 15:44:19 -070012770 if (isSingleton(ai.processName, ai.applicationInfo)) {
12771 ri.activityInfo = getActivityInfoForUser(ai, 0);
12772 } else {
12773 ri.activityInfo = getActivityInfoForUser(ai, userId);
12774 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012775 receivers.add(ri);
12776 }
12777 } else {
12778 // Need to resolve the intent to interested receivers...
12779 if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
12780 == 0) {
12781 receivers =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012782 AppGlobals.getPackageManager().queryIntentReceivers(
Amith Yamasani483f3b02012-03-13 16:08:00 -070012783 intent, resolvedType, STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012784 }
Amith Yamasani483f3b02012-03-13 16:08:00 -070012785 registeredReceivers = mReceiverResolver.queryIntent(intent, resolvedType, false,
12786 userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012787 }
12788 } catch (RemoteException ex) {
12789 // pm is in same process, this will never happen.
12790 }
12791
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012792 final boolean replacePending =
12793 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
12794
Joe Onorato8a9b2202010-02-26 18:56:32 -080012795 if (DEBUG_BROADCAST) Slog.v(TAG, "Enqueing broadcast: " + intent.getAction()
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012796 + " replacePending=" + replacePending);
12797
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012798 int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
12799 if (!ordered && NR > 0) {
12800 // If we are not serializing this broadcast, then send the
12801 // registered receivers separately so they don't wait for the
12802 // components to be launched.
Christopher Tatef46723b2012-01-26 14:19:24 -080012803 final BroadcastQueue queue = broadcastQueueForIntent(intent);
12804 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012805 callerPackage, callingPid, callingUid, requiredPermission,
12806 registeredReceivers, resultTo, resultCode, resultData, map,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012807 ordered, sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012808 if (DEBUG_BROADCAST) Slog.v(
Christopher Tatef46723b2012-01-26 14:19:24 -080012809 TAG, "Enqueueing parallel broadcast " + r);
12810 final boolean replaced = replacePending && queue.replaceParallelBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012811 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012812 queue.enqueueParallelBroadcastLocked(r);
12813 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012814 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012815 registeredReceivers = null;
12816 NR = 0;
12817 }
12818
12819 // Merge into one list.
12820 int ir = 0;
12821 if (receivers != null) {
12822 // A special case for PACKAGE_ADDED: do not allow the package
12823 // being added to see this broadcast. This prevents them from
12824 // using this as a back door to get run as soon as they are
12825 // installed. Maybe in the future we want to have a special install
12826 // broadcast or such for apps, but we'd like to deliberately make
12827 // this decision.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012828 String skipPackages[] = null;
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012829 if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
12830 || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
12831 || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012832 Uri data = intent.getData();
12833 if (data != null) {
12834 String pkgName = data.getSchemeSpecificPart();
12835 if (pkgName != null) {
12836 skipPackages = new String[] { pkgName };
12837 }
12838 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012839 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012840 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
The Android Open Source Project10592532009-03-18 17:39:46 -070012841 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012842 if (skipPackages != null && (skipPackages.length > 0)) {
12843 for (String skipPackage : skipPackages) {
12844 if (skipPackage != null) {
12845 int NT = receivers.size();
12846 for (int it=0; it<NT; it++) {
12847 ResolveInfo curt = (ResolveInfo)receivers.get(it);
12848 if (curt.activityInfo.packageName.equals(skipPackage)) {
12849 receivers.remove(it);
12850 it--;
12851 NT--;
12852 }
12853 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012854 }
12855 }
12856 }
12857
12858 int NT = receivers != null ? receivers.size() : 0;
12859 int it = 0;
12860 ResolveInfo curt = null;
12861 BroadcastFilter curr = null;
12862 while (it < NT && ir < NR) {
12863 if (curt == null) {
12864 curt = (ResolveInfo)receivers.get(it);
12865 }
12866 if (curr == null) {
12867 curr = registeredReceivers.get(ir);
12868 }
12869 if (curr.getPriority() >= curt.priority) {
12870 // Insert this broadcast record into the final list.
12871 receivers.add(it, curr);
12872 ir++;
12873 curr = null;
12874 it++;
12875 NT++;
12876 } else {
12877 // Skip to the next ResolveInfo in the final list.
12878 it++;
12879 curt = null;
12880 }
12881 }
12882 }
12883 while (ir < NR) {
12884 if (receivers == null) {
12885 receivers = new ArrayList();
12886 }
12887 receivers.add(registeredReceivers.get(ir));
12888 ir++;
12889 }
12890
12891 if ((receivers != null && receivers.size() > 0)
12892 || resultTo != null) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012893 BroadcastQueue queue = broadcastQueueForIntent(intent);
12894 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012895 callerPackage, callingPid, callingUid, requiredPermission,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012896 receivers, resultTo, resultCode, resultData, map, ordered,
12897 sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012898 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012899 TAG, "Enqueueing ordered broadcast " + r
Christopher Tatef46723b2012-01-26 14:19:24 -080012900 + ": prev had " + queue.mOrderedBroadcasts.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012901 if (DEBUG_BROADCAST) {
12902 int seq = r.intent.getIntExtra("seq", -1);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012903 Slog.i(TAG, "Enqueueing broadcast " + r.intent.getAction() + " seq=" + seq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012904 }
Christopher Tatef46723b2012-01-26 14:19:24 -080012905 boolean replaced = replacePending && queue.replaceOrderedBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012906 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012907 queue.enqueueOrderedBroadcastLocked(r);
12908 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012909 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012910 }
12911
Dianne Hackborna4972e92012-03-14 10:38:05 -070012912 return ActivityManager.BROADCAST_SUCCESS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012913 }
12914
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012915 final Intent verifyBroadcastLocked(Intent intent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012916 // Refuse possible leaked file descriptors
12917 if (intent != null && intent.hasFileDescriptors() == true) {
12918 throw new IllegalArgumentException("File descriptors passed in Intent");
12919 }
12920
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012921 int flags = intent.getFlags();
12922
12923 if (!mProcessesReady) {
12924 // if the caller really truly claims to know what they're doing, go
12925 // ahead and allow the broadcast without launching any receivers
12926 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
12927 intent = new Intent(intent);
12928 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
12929 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
12930 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
12931 + " before boot completion");
12932 throw new IllegalStateException("Cannot broadcast before boot completed");
12933 }
12934 }
12935
12936 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
12937 throw new IllegalArgumentException(
12938 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
12939 }
12940
12941 return intent;
12942 }
12943
12944 public final int broadcastIntent(IApplicationThread caller,
12945 Intent intent, String resolvedType, IIntentReceiver resultTo,
12946 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070012947 String requiredPermission, boolean serialized, boolean sticky, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012948 enforceNotIsolatedCaller("broadcastIntent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012949 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012950 intent = verifyBroadcastLocked(intent);
Dianne Hackborn9acc0302009-08-25 00:27:12 -070012951
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012952 final ProcessRecord callerApp = getRecordForAppLocked(caller);
12953 final int callingPid = Binder.getCallingPid();
12954 final int callingUid = Binder.getCallingUid();
12955 final long origId = Binder.clearCallingIdentity();
12956 int res = broadcastIntentLocked(callerApp,
12957 callerApp != null ? callerApp.info.packageName : null,
12958 intent, resolvedType, resultTo,
Amith Yamasani742a6712011-05-04 14:49:28 -070012959 resultCode, resultData, map, requiredPermission, serialized, sticky,
12960 callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012961 Binder.restoreCallingIdentity(origId);
12962 return res;
12963 }
12964 }
12965
12966 int broadcastIntentInPackage(String packageName, int uid,
12967 Intent intent, String resolvedType, IIntentReceiver resultTo,
12968 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070012969 String requiredPermission, boolean serialized, boolean sticky, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012970 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012971 intent = verifyBroadcastLocked(intent);
12972
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012973 final long origId = Binder.clearCallingIdentity();
12974 int res = broadcastIntentLocked(null, packageName, intent, resolvedType,
12975 resultTo, resultCode, resultData, map, requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070012976 serialized, sticky, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012977 Binder.restoreCallingIdentity(origId);
12978 return res;
12979 }
12980 }
12981
Amith Yamasani742a6712011-05-04 14:49:28 -070012982 // TODO: Use the userId; maybe mStickyBroadcasts need to be tied to the user.
12983 public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012984 // Refuse possible leaked file descriptors
12985 if (intent != null && intent.hasFileDescriptors() == true) {
12986 throw new IllegalArgumentException("File descriptors passed in Intent");
12987 }
12988
12989 synchronized(this) {
12990 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
12991 != PackageManager.PERMISSION_GRANTED) {
12992 String msg = "Permission Denial: unbroadcastIntent() from pid="
12993 + Binder.getCallingPid()
12994 + ", uid=" + Binder.getCallingUid()
12995 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012996 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012997 throw new SecurityException(msg);
12998 }
12999 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
13000 if (list != null) {
13001 int N = list.size();
13002 int i;
13003 for (i=0; i<N; i++) {
13004 if (intent.filterEquals(list.get(i))) {
13005 list.remove(i);
13006 break;
13007 }
13008 }
13009 }
13010 }
13011 }
13012
13013 private final boolean finishReceiverLocked(IBinder receiver, int resultCode,
13014 String resultData, Bundle resultExtras, boolean resultAbort,
13015 boolean explicit) {
Christopher Tatef46723b2012-01-26 14:19:24 -080013016 final BroadcastRecord r = broadcastRecordForReceiverLocked(receiver);
13017 if (r == null) {
13018 Slog.w(TAG, "finishReceiver called but not found on queue");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013019 return false;
13020 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013021
Christopher Tatef46723b2012-01-26 14:19:24 -080013022 return r.queue.finishReceiverLocked(r, resultCode, resultData, resultExtras, resultAbort,
13023 explicit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013024 }
13025
13026 public void finishReceiver(IBinder who, int resultCode, String resultData,
13027 Bundle resultExtras, boolean resultAbort) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013028 if (DEBUG_BROADCAST) Slog.v(TAG, "Finish receiver: " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013029
13030 // Refuse possible leaked file descriptors
13031 if (resultExtras != null && resultExtras.hasFileDescriptors()) {
13032 throw new IllegalArgumentException("File descriptors passed in Bundle");
13033 }
13034
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013035 final long origId = Binder.clearCallingIdentity();
Christopher Tatef46723b2012-01-26 14:19:24 -080013036 try {
13037 boolean doNext = false;
13038 BroadcastRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013039
Christopher Tatef46723b2012-01-26 14:19:24 -080013040 synchronized(this) {
13041 r = broadcastRecordForReceiverLocked(who);
13042 if (r != null) {
13043 doNext = r.queue.finishReceiverLocked(r, resultCode,
13044 resultData, resultExtras, resultAbort, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013045 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013046 }
Jeff Brown4d94a762010-09-23 11:33:28 -070013047
Christopher Tatef46723b2012-01-26 14:19:24 -080013048 if (doNext) {
13049 r.queue.processNextBroadcast(false);
13050 }
13051 trimApplications();
13052 } finally {
13053 Binder.restoreCallingIdentity(origId);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070013054 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013055 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013056
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013057 // =========================================================
13058 // INSTRUMENTATION
13059 // =========================================================
13060
13061 public boolean startInstrumentation(ComponentName className,
13062 String profileFile, int flags, Bundle arguments,
13063 IInstrumentationWatcher watcher) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080013064 enforceNotIsolatedCaller("startInstrumentation");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013065 // Refuse possible leaked file descriptors
13066 if (arguments != null && arguments.hasFileDescriptors()) {
13067 throw new IllegalArgumentException("File descriptors passed in Bundle");
13068 }
13069
13070 synchronized(this) {
13071 InstrumentationInfo ii = null;
13072 ApplicationInfo ai = null;
13073 try {
13074 ii = mContext.getPackageManager().getInstrumentationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070013075 className, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013076 ai = mContext.getPackageManager().getApplicationInfo(
Amith Yamasani483f3b02012-03-13 16:08:00 -070013077 ii.targetPackage, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013078 } catch (PackageManager.NameNotFoundException e) {
13079 }
13080 if (ii == null) {
13081 reportStartInstrumentationFailure(watcher, className,
13082 "Unable to find instrumentation info for: " + className);
13083 return false;
13084 }
13085 if (ai == null) {
13086 reportStartInstrumentationFailure(watcher, className,
13087 "Unable to find instrumentation target package: " + ii.targetPackage);
13088 return false;
13089 }
13090
13091 int match = mContext.getPackageManager().checkSignatures(
13092 ii.targetPackage, ii.packageName);
13093 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
13094 String msg = "Permission Denial: starting instrumentation "
13095 + className + " from pid="
13096 + Binder.getCallingPid()
13097 + ", uid=" + Binder.getCallingPid()
13098 + " not allowed because package " + ii.packageName
13099 + " does not have a signature matching the target "
13100 + ii.targetPackage;
13101 reportStartInstrumentationFailure(watcher, className, msg);
13102 throw new SecurityException(msg);
13103 }
13104
Amith Yamasani483f3b02012-03-13 16:08:00 -070013105 int userId = UserId.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013106 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -070013107 // Instrumentation can kill and relaunch even persistent processes
Amith Yamasani483f3b02012-03-13 16:08:00 -070013108 forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true, userId);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013109 ProcessRecord app = addAppLocked(ai, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013110 app.instrumentationClass = className;
Dianne Hackborn1655be42009-05-08 14:29:01 -070013111 app.instrumentationInfo = ai;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013112 app.instrumentationProfileFile = profileFile;
13113 app.instrumentationArguments = arguments;
13114 app.instrumentationWatcher = watcher;
13115 app.instrumentationResultClass = className;
13116 Binder.restoreCallingIdentity(origId);
13117 }
13118
13119 return true;
13120 }
13121
13122 /**
13123 * Report errors that occur while attempting to start Instrumentation. Always writes the
13124 * error to the logs, but if somebody is watching, send the report there too. This enables
13125 * the "am" command to report errors with more information.
13126 *
13127 * @param watcher The IInstrumentationWatcher. Null if there isn't one.
13128 * @param cn The component name of the instrumentation.
13129 * @param report The error report.
13130 */
13131 private void reportStartInstrumentationFailure(IInstrumentationWatcher watcher,
13132 ComponentName cn, String report) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013133 Slog.w(TAG, report);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013134 try {
13135 if (watcher != null) {
13136 Bundle results = new Bundle();
13137 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
13138 results.putString("Error", report);
13139 watcher.instrumentationStatus(cn, -1, results);
13140 }
13141 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013142 Slog.w(TAG, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013143 }
13144 }
13145
13146 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
13147 if (app.instrumentationWatcher != null) {
13148 try {
13149 // NOTE: IInstrumentationWatcher *must* be oneway here
13150 app.instrumentationWatcher.instrumentationFinished(
13151 app.instrumentationClass,
13152 resultCode,
13153 results);
13154 } catch (RemoteException e) {
13155 }
13156 }
13157 app.instrumentationWatcher = null;
13158 app.instrumentationClass = null;
Dianne Hackborn1655be42009-05-08 14:29:01 -070013159 app.instrumentationInfo = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013160 app.instrumentationProfileFile = null;
13161 app.instrumentationArguments = null;
13162
Amith Yamasani483f3b02012-03-13 16:08:00 -070013163 forceStopPackageLocked(app.processName, -1, false, false, true, true, app.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013164 }
13165
13166 public void finishInstrumentation(IApplicationThread target,
13167 int resultCode, Bundle results) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070013168 int userId = UserId.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013169 // Refuse possible leaked file descriptors
13170 if (results != null && results.hasFileDescriptors()) {
13171 throw new IllegalArgumentException("File descriptors passed in Intent");
13172 }
13173
13174 synchronized(this) {
13175 ProcessRecord app = getRecordForAppLocked(target);
13176 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013177 Slog.w(TAG, "finishInstrumentation: no app for " + target);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013178 return;
13179 }
13180 final long origId = Binder.clearCallingIdentity();
13181 finishInstrumentationLocked(app, resultCode, results);
13182 Binder.restoreCallingIdentity(origId);
13183 }
13184 }
13185
13186 // =========================================================
13187 // CONFIGURATION
13188 // =========================================================
13189
13190 public ConfigurationInfo getDeviceConfigurationInfo() {
13191 ConfigurationInfo config = new ConfigurationInfo();
13192 synchronized (this) {
13193 config.reqTouchScreen = mConfiguration.touchscreen;
13194 config.reqKeyboardType = mConfiguration.keyboard;
13195 config.reqNavigation = mConfiguration.navigation;
Dianne Hackbornfae76f52009-07-16 13:41:23 -070013196 if (mConfiguration.navigation == Configuration.NAVIGATION_DPAD
13197 || mConfiguration.navigation == Configuration.NAVIGATION_TRACKBALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013198 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
13199 }
Dianne Hackbornfae76f52009-07-16 13:41:23 -070013200 if (mConfiguration.keyboard != Configuration.KEYBOARD_UNDEFINED
13201 && mConfiguration.keyboard != Configuration.KEYBOARD_NOKEYS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013202 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
13203 }
Jack Palevichb90d28c2009-07-22 15:35:24 -070013204 config.reqGlEsVersion = GL_ES_VERSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013205 }
13206 return config;
13207 }
13208
13209 public Configuration getConfiguration() {
13210 Configuration ci;
13211 synchronized(this) {
13212 ci = new Configuration(mConfiguration);
13213 }
13214 return ci;
13215 }
13216
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013217 public void updatePersistentConfiguration(Configuration values) {
13218 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
13219 "updateConfiguration()");
13220 enforceCallingPermission(android.Manifest.permission.WRITE_SETTINGS,
13221 "updateConfiguration()");
13222 if (values == null) {
13223 throw new NullPointerException("Configuration must not be null");
13224 }
13225
13226 synchronized(this) {
13227 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn813075a62011-11-14 17:45:19 -080013228 updateConfigurationLocked(values, null, true, false);
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013229 Binder.restoreCallingIdentity(origId);
13230 }
13231 }
13232
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013233 public void updateConfiguration(Configuration values) {
13234 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
13235 "updateConfiguration()");
13236
13237 synchronized(this) {
13238 if (values == null && mWindowManager != null) {
13239 // sentinel: fetch the current configuration from the window manager
13240 values = mWindowManager.computeNewConfiguration();
13241 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013242
13243 if (mWindowManager != null) {
13244 mProcessList.applyDisplaySize(mWindowManager);
13245 }
13246
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013247 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013248 if (values != null) {
13249 Settings.System.clearConfiguration(values);
13250 }
Dianne Hackborn813075a62011-11-14 17:45:19 -080013251 updateConfigurationLocked(values, null, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013252 Binder.restoreCallingIdentity(origId);
13253 }
13254 }
13255
13256 /**
13257 * Do either or both things: (1) change the current configuration, and (2)
13258 * make sure the given activity is running with the (now) current
13259 * configuration. Returns true if the activity has been left running, or
13260 * false if <var>starting</var> is being destroyed to match the new
13261 * configuration.
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013262 * @param persistent TODO
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013263 */
Dianne Hackborna573f6a2012-02-09 16:12:18 -080013264 boolean updateConfigurationLocked(Configuration values,
Dianne Hackborn813075a62011-11-14 17:45:19 -080013265 ActivityRecord starting, boolean persistent, boolean initLocale) {
Mike Lockwood3a74bd32011-08-12 13:55:22 -070013266 // do nothing if we are headless
13267 if (mHeadless) return true;
13268
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013269 int changes = 0;
13270
13271 boolean kept = true;
13272
13273 if (values != null) {
13274 Configuration newConfig = new Configuration(mConfiguration);
13275 changes = newConfig.updateFrom(values);
13276 if (changes != 0) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013277 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013278 Slog.i(TAG, "Updating configuration to: " + values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013279 }
13280
Doug Zongker2bec3d42009-12-04 12:52:44 -080013281 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013282
Dianne Hackborn813075a62011-11-14 17:45:19 -080013283 if (values.locale != null && !initLocale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013284 saveLocaleLocked(values.locale,
13285 !values.locale.equals(mConfiguration.locale),
13286 values.userSetLocale);
13287 }
13288
Dianne Hackborne36d6e22010-02-17 19:46:25 -080013289 mConfigurationSeq++;
13290 if (mConfigurationSeq <= 0) {
13291 mConfigurationSeq = 1;
13292 }
13293 newConfig.seq = mConfigurationSeq;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013294 mConfiguration = newConfig;
Joe Onorato8a9b2202010-02-26 18:56:32 -080013295 Slog.i(TAG, "Config changed: " + newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013296
13297 final Configuration configCopy = new Configuration(mConfiguration);
Joe Onorato54a4a412011-11-02 20:50:08 -070013298
13299 // TODO: If our config changes, should we auto dismiss any currently
13300 // showing dialogs?
13301 mShowDialogs = shouldShowDialogs(newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013302
Dianne Hackborn826d17c2009-11-12 12:55:51 -080013303 AttributeCache ac = AttributeCache.instance();
13304 if (ac != null) {
Dianne Hackborn813075a62011-11-14 17:45:19 -080013305 ac.updateConfiguration(configCopy);
Dianne Hackborn826d17c2009-11-12 12:55:51 -080013306 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013307
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070013308 // Make sure all resources in our process are updated
13309 // right now, so that anyone who is going to retrieve
13310 // resource values after we return will be sure to get
13311 // the new ones. This is especially important during
13312 // boot, where the first config change needs to guarantee
13313 // all resources have that config before following boot
13314 // code is executed.
Dianne Hackborn813075a62011-11-14 17:45:19 -080013315 mSystemThread.applyConfigurationToResources(configCopy);
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070013316
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013317 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080013318 Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013319 msg.obj = new Configuration(configCopy);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080013320 mHandler.sendMessage(msg);
13321 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013322
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013323 for (int i=mLruProcesses.size()-1; i>=0; i--) {
13324 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013325 try {
13326 if (app.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013327 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending to proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013328 + app.processName + " new config " + mConfiguration);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013329 app.thread.scheduleConfigurationChanged(configCopy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013330 }
13331 } catch (Exception e) {
13332 }
13333 }
13334 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080013335 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
13336 | Intent.FLAG_RECEIVER_REPLACE_PENDING);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013337 broadcastIntentLocked(null, null, intent, null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070013338 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080013339 if ((changes&ActivityInfo.CONFIG_LOCALE) != 0) {
13340 broadcastIntentLocked(null, null,
13341 new Intent(Intent.ACTION_LOCALE_CHANGED),
13342 null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070013343 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080013344 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013345 }
13346 }
13347
13348 if (changes != 0 && starting == null) {
13349 // If the configuration changed, and the caller is not already
13350 // in the process of starting an activity, then find the top
13351 // activity to check if its configuration needs to change.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013352 starting = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013353 }
13354
13355 if (starting != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013356 kept = mMainStack.ensureActivityConfigurationLocked(starting, changes);
Dianne Hackborn5f4d6432010-12-21 20:40:11 -080013357 // And we need to make sure at this point that all other activities
13358 // are made visible with the correct configuration.
13359 mMainStack.ensureActivitiesVisibleLocked(starting, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013360 }
13361
Dianne Hackborne36d6e22010-02-17 19:46:25 -080013362 if (values != null && mWindowManager != null) {
13363 mWindowManager.setNewConfiguration(mConfiguration);
13364 }
13365
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013366 return kept;
13367 }
Joe Onorato54a4a412011-11-02 20:50:08 -070013368
13369 /**
13370 * Decide based on the configuration whether we should shouw the ANR,
13371 * crash, etc dialogs. The idea is that if there is no affordnace to
13372 * press the on-screen buttons, we shouldn't show the dialog.
13373 *
13374 * A thought: SystemUI might also want to get told about this, the Power
13375 * dialog / global actions also might want different behaviors.
13376 */
13377 private static final boolean shouldShowDialogs(Configuration config) {
13378 return !(config.keyboard == Configuration.KEYBOARD_NOKEYS
13379 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH);
13380 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013381
13382 /**
13383 * Save the locale. You must be inside a synchronized (this) block.
13384 */
13385 private void saveLocaleLocked(Locale l, boolean isDiff, boolean isPersist) {
13386 if(isDiff) {
13387 SystemProperties.set("user.language", l.getLanguage());
13388 SystemProperties.set("user.region", l.getCountry());
13389 }
13390
13391 if(isPersist) {
13392 SystemProperties.set("persist.sys.language", l.getLanguage());
13393 SystemProperties.set("persist.sys.country", l.getCountry());
13394 SystemProperties.set("persist.sys.localevar", l.getVariant());
13395 }
13396 }
13397
Adam Powelldd8fab22012-03-22 17:47:27 -070013398 @Override
13399 public boolean targetTaskAffinityMatchesActivity(IBinder token, String destAffinity) {
13400 ActivityRecord srec = ActivityRecord.forToken(token);
13401 return srec.task.affinity != null && srec.task.affinity.equals(destAffinity);
13402 }
13403
13404 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
13405 Intent resultData) {
13406 ComponentName dest = destIntent.getComponent();
13407
13408 synchronized (this) {
13409 ActivityRecord srec = ActivityRecord.forToken(token);
13410 ArrayList<ActivityRecord> history = srec.stack.mHistory;
13411 final int start = history.indexOf(srec);
13412 if (start < 0) {
13413 // Current activity is not in history stack; do nothing.
13414 return false;
13415 }
13416 int finishTo = start - 1;
13417 ActivityRecord parent = null;
13418 boolean foundParentInTask = false;
13419 if (dest != null) {
13420 TaskRecord tr = srec.task;
13421 for (int i = start - 1; i >= 0; i--) {
13422 ActivityRecord r = history.get(i);
13423 if (tr != r.task) {
13424 // Couldn't find parent in the same task; stop at the one above this.
13425 // (Root of current task; in-app "home" behavior)
13426 // Always at least finish the current activity.
13427 finishTo = Math.min(start - 1, i + 1);
13428 parent = history.get(finishTo);
13429 break;
13430 } else if (r.info.packageName.equals(dest.getPackageName()) &&
13431 r.info.name.equals(dest.getClassName())) {
13432 finishTo = i;
13433 parent = r;
13434 foundParentInTask = true;
13435 break;
13436 }
13437 }
13438 }
13439
13440 if (mController != null) {
13441 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
13442 if (next != null) {
13443 // ask watcher if this is allowed
13444 boolean resumeOK = true;
13445 try {
13446 resumeOK = mController.activityResuming(next.packageName);
13447 } catch (RemoteException e) {
13448 mController = null;
13449 }
13450
13451 if (!resumeOK) {
13452 return false;
13453 }
13454 }
13455 }
13456 final long origId = Binder.clearCallingIdentity();
13457 for (int i = start; i > finishTo; i--) {
13458 ActivityRecord r = history.get(i);
13459 mMainStack.requestFinishActivityLocked(r.appToken, resultCode, resultData,
13460 "navigate-up");
13461 // Only return the supplied result for the first activity finished
13462 resultCode = Activity.RESULT_CANCELED;
13463 resultData = null;
13464 }
13465
13466 if (parent != null && foundParentInTask) {
13467 final int parentLaunchMode = parent.info.launchMode;
13468 final int destIntentFlags = destIntent.getFlags();
13469 if (parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE ||
13470 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TASK ||
13471 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TOP ||
13472 (destIntentFlags & Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
13473 parent.deliverNewIntentLocked(srec.app.uid, destIntent);
13474 } else {
13475 try {
13476 ActivityInfo aInfo = AppGlobals.getPackageManager().getActivityInfo(
13477 destIntent.getComponent(), 0, UserId.getCallingUserId());
13478 int res = mMainStack.startActivityLocked(srec.app.thread, destIntent,
13479 null, aInfo, parent.appToken, null,
13480 0, -1, parent.launchedFromUid, 0, null, true, null);
13481 foundParentInTask = res == ActivityManager.START_SUCCESS;
13482 } catch (RemoteException e) {
13483 foundParentInTask = false;
13484 }
13485 mMainStack.requestFinishActivityLocked(parent.appToken, resultCode,
13486 resultData, "navigate-up");
13487 }
13488 }
13489 Binder.restoreCallingIdentity(origId);
13490 return foundParentInTask;
13491 }
13492 }
13493
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013494 // =========================================================
13495 // LIFETIME MANAGEMENT
13496 // =========================================================
13497
Christopher Tatef46723b2012-01-26 14:19:24 -080013498 // Returns which broadcast queue the app is the current [or imminent] receiver
13499 // on, or 'null' if the app is not an active broadcast recipient.
13500 private BroadcastQueue isReceivingBroadcast(ProcessRecord app) {
13501 BroadcastRecord r = app.curReceiver;
13502 if (r != null) {
13503 return r.queue;
13504 }
13505
13506 // It's not the current receiver, but it might be starting up to become one
13507 synchronized (this) {
13508 for (BroadcastQueue queue : mBroadcastQueues) {
13509 r = queue.mPendingBroadcast;
13510 if (r != null && r.curApp == app) {
13511 // found it; report which queue it's in
13512 return queue;
13513 }
13514 }
13515 }
13516
13517 return null;
13518 }
13519
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013520 private final int computeOomAdjLocked(ProcessRecord app, int hiddenAdj,
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013521 ProcessRecord TOP_APP, boolean recursed, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013522 if (mAdjSeq == app.adjSeq) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013523 // This adjustment has already been computed. If we are calling
13524 // from the top, we may have already computed our adjustment with
13525 // an earlier hidden adjustment that isn't really for us... if
13526 // so, use the new hidden adjustment.
13527 if (!recursed && app.hidden) {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013528 app.curAdj = app.curRawAdj = app.nonStoppingAdj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013529 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013530 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013531 }
13532
13533 if (app.thread == null) {
13534 app.adjSeq = mAdjSeq;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013535 app.curSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013536 return (app.curAdj=ProcessList.HIDDEN_APP_MAX_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013537 }
13538
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013539 app.adjTypeCode = ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN;
13540 app.adjSource = null;
13541 app.adjTarget = null;
13542 app.empty = false;
13543 app.hidden = false;
13544
13545 final int activitiesSize = app.activities.size();
13546
Dianne Hackborn7d608422011-08-07 16:24:18 -070013547 if (app.maxAdj <= ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013548 // The max adjustment doesn't allow this app to be anything
13549 // below foreground, so it is not worth doing work for it.
13550 app.adjType = "fixed";
13551 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013552 app.curRawAdj = app.nonStoppingAdj = app.maxAdj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013553 app.foregroundActivities = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013554 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013555 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013556 // System process can do UI, and when they do we want to have
13557 // them trim their memory after the user leaves the UI. To
13558 // facilitate this, here we need to determine whether or not it
13559 // is currently showing UI.
13560 app.systemNoUi = true;
13561 if (app == TOP_APP) {
13562 app.systemNoUi = false;
13563 } else if (activitiesSize > 0) {
13564 for (int j = 0; j < activitiesSize; j++) {
13565 final ActivityRecord r = app.activities.get(j);
13566 if (r.visible) {
13567 app.systemNoUi = false;
13568 break;
13569 }
13570 }
13571 }
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013572 return (app.curAdj=app.maxAdj);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013573 }
13574
13575 final boolean hadForegroundActivities = app.foregroundActivities;
13576
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013577 app.foregroundActivities = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013578 app.keeping = false;
13579 app.systemNoUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013580
The Android Open Source Project4df24232009-03-05 14:34:35 -080013581 // Determine the importance of the process, starting with most
13582 // important to least, and assign an appropriate OOM adjustment.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013583 int adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013584 int schedGroup;
Christopher Tatef46723b2012-01-26 14:19:24 -080013585 BroadcastQueue queue;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013586 if (app == TOP_APP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013587 // The last app on the list is the foreground app.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013588 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013589 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013590 app.adjType = "top-activity";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013591 app.foregroundActivities = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013592 } else if (app.instrumentationClass != null) {
13593 // Don't want to kill running instrumentation.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013594 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013595 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013596 app.adjType = "instrumentation";
Christopher Tatef46723b2012-01-26 14:19:24 -080013597 } else if ((queue = isReceivingBroadcast(app)) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013598 // An app that is currently receiving a broadcast also
Christopher Tatef46723b2012-01-26 14:19:24 -080013599 // counts as being in the foreground for OOM killer purposes.
13600 // It's placed in a sched group based on the nature of the
13601 // broadcast as reflected by which queue it's active in.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013602 adj = ProcessList.FOREGROUND_APP_ADJ;
Christopher Tatef46723b2012-01-26 14:19:24 -080013603 schedGroup = (queue == mFgBroadcastQueue)
13604 ? Process.THREAD_GROUP_DEFAULT : Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013605 app.adjType = "broadcast";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013606 } else if (app.executingServices.size() > 0) {
13607 // An app that is currently executing a service callback also
13608 // counts as being in the foreground.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013609 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013610 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013611 app.adjType = "exec-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013612 } else if (activitiesSize > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013613 // This app is in the background with paused activities.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013614 // We inspect activities to potentially upgrade adjustment further below.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013615 adj = hiddenAdj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013616 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013617 app.hidden = true;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013618 app.adjType = "bg-activities";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013619 } else {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013620 // A very not-needed process. If this is lower in the lru list,
13621 // we will push it in to the empty bucket.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013622 adj = hiddenAdj;
13623 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013624 app.hidden = true;
13625 app.empty = true;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013626 app.adjType = "bg-empty";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013627 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013628
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013629 boolean hasStoppingActivities = false;
13630
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013631 // Examine all activities if not already foreground.
13632 if (!app.foregroundActivities && activitiesSize > 0) {
13633 for (int j = 0; j < activitiesSize; j++) {
13634 final ActivityRecord r = app.activities.get(j);
13635 if (r.visible) {
13636 // App has a visible activity; only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013637 if (adj > ProcessList.VISIBLE_APP_ADJ) {
13638 adj = ProcessList.VISIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013639 app.adjType = "visible";
13640 }
13641 schedGroup = Process.THREAD_GROUP_DEFAULT;
13642 app.hidden = false;
13643 app.foregroundActivities = true;
13644 break;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013645 } else if (r.state == ActivityState.PAUSING || r.state == ActivityState.PAUSED) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013646 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13647 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013648 app.adjType = "pausing";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013649 }
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -080013650 app.hidden = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013651 app.foregroundActivities = true;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013652 } else if (r.state == ActivityState.STOPPING) {
13653 // We will apply the actual adjustment later, because
13654 // we want to allow this process to immediately go through
13655 // any memory trimming that is in effect.
13656 app.hidden = false;
13657 app.foregroundActivities = true;
13658 hasStoppingActivities = true;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013659 }
13660 }
13661 }
13662
Dianne Hackborn7d608422011-08-07 16:24:18 -070013663 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013664 if (app.foregroundServices) {
13665 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013666 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013667 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013668 app.adjType = "foreground-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013669 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013670 } else if (app.forcingToForeground != null) {
13671 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013672 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013673 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013674 app.adjType = "force-foreground";
13675 app.adjSource = app.forcingToForeground;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013676 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013677 }
13678 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013679
Dianne Hackborn7d608422011-08-07 16:24:18 -070013680 if (adj > ProcessList.HEAVY_WEIGHT_APP_ADJ && app == mHeavyWeightProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013681 // We don't want to kill the current heavy-weight process.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013682 adj = ProcessList.HEAVY_WEIGHT_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013683 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013684 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013685 app.adjType = "heavy";
13686 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013687
Dianne Hackborn7d608422011-08-07 16:24:18 -070013688 if (adj > ProcessList.HOME_APP_ADJ && app == mHomeProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013689 // This process is hosting what we currently consider to be the
13690 // home app, so we don't want to let it go into the background.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013691 adj = ProcessList.HOME_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013692 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013693 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013694 app.adjType = "home";
13695 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013696
Dianne Hackbornf35fe232011-11-01 19:25:20 -070013697 if (adj > ProcessList.PREVIOUS_APP_ADJ && app == mPreviousProcess
13698 && app.activities.size() > 0) {
13699 // This was the previous process that showed UI to the user.
13700 // We want to try to keep it around more aggressively, to give
13701 // a good experience around switching between two apps.
13702 adj = ProcessList.PREVIOUS_APP_ADJ;
13703 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
13704 app.hidden = false;
13705 app.adjType = "previous";
13706 }
13707
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013708 if (false) Slog.i(TAG, "OOM " + app + ": initial adj=" + adj
13709 + " reason=" + app.adjType);
13710
The Android Open Source Project4df24232009-03-05 14:34:35 -080013711 // By default, we use the computed adjustment. It may be changed if
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013712 // there are applications dependent on our services or providers, but
13713 // this gives us a baseline and makes sure we don't get into an
13714 // infinite recursion.
13715 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013716 app.curRawAdj = app.nonStoppingAdj = adj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013717
Christopher Tate6fa95972009-06-05 18:43:55 -070013718 if (mBackupTarget != null && app == mBackupTarget.app) {
13719 // If possible we want to avoid killing apps while they're being backed up
Dianne Hackborn7d608422011-08-07 16:24:18 -070013720 if (adj > ProcessList.BACKUP_APP_ADJ) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013721 if (DEBUG_BACKUP) Slog.v(TAG, "oom BACKUP_APP_ADJ for " + app);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013722 adj = ProcessList.BACKUP_APP_ADJ;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013723 app.adjType = "backup";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013724 app.hidden = false;
Christopher Tate6fa95972009-06-05 18:43:55 -070013725 }
13726 }
13727
Dianne Hackborn7d608422011-08-07 16:24:18 -070013728 if (app.services.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013729 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013730 final long now = SystemClock.uptimeMillis();
13731 // This process is more important if the top activity is
13732 // bound to the service.
Dianne Hackborn860755f2010-06-03 18:47:52 -070013733 Iterator<ServiceRecord> jt = app.services.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013734 while (jt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013735 ServiceRecord s = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013736 if (s.startRequested) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013737 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013738 // If this process has shown some UI, let it immediately
13739 // go to the LRU list because it may be pretty heavy with
13740 // UI stuff. We'll tag it with a label just to help
13741 // debug and understand what is going on.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013742 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013743 app.adjType = "started-bg-ui-services";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013744 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013745 } else {
13746 if (now < (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
13747 // This service has seen some activity within
13748 // recent memory, so we will keep its process ahead
13749 // of the background processes.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013750 if (adj > ProcessList.SERVICE_ADJ) {
13751 adj = ProcessList.SERVICE_ADJ;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013752 app.adjType = "started-services";
13753 app.hidden = false;
13754 }
13755 }
13756 // If we have let the service slide into the background
13757 // state, still have some text describing what it is doing
13758 // even though the service no longer has an impact.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013759 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013760 app.adjType = "started-bg-services";
13761 }
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080013762 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013763 // Don't kill this process because it is doing work; it
13764 // has said it is doing work.
13765 app.keeping = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013766 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013767 if (s.connections.size() > 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013768 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013769 Iterator<ArrayList<ConnectionRecord>> kt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013770 = s.connections.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013771 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013772 ArrayList<ConnectionRecord> clist = kt.next();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013773 for (int i=0; i<clist.size() && adj > ProcessList.FOREGROUND_APP_ADJ; i++) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013774 // XXX should compute this based on the max of
13775 // all connected clients.
13776 ConnectionRecord cr = clist.get(i);
13777 if (cr.binding.client == app) {
13778 // Binding to ourself is not interesting.
13779 continue;
13780 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013781 if ((cr.flags&Context.BIND_WAIVE_PRIORITY) == 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013782 ProcessRecord client = cr.binding.client;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013783 int clientAdj = adj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013784 int myHiddenAdj = hiddenAdj;
13785 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013786 if (client.hiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013787 myHiddenAdj = client.hiddenAdj;
13788 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013789 myHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013790 }
13791 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013792 clientAdj = computeOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013793 client, myHiddenAdj, TOP_APP, true, doingAll);
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013794 String adjType = null;
13795 if ((cr.flags&Context.BIND_ALLOW_OOM_MANAGEMENT) != 0) {
13796 // Not doing bind OOM management, so treat
13797 // this guy more like a started service.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013798 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013799 // If this process has shown some UI, let it immediately
13800 // go to the LRU list because it may be pretty heavy with
13801 // UI stuff. We'll tag it with a label just to help
13802 // debug and understand what is going on.
13803 if (adj > clientAdj) {
13804 adjType = "bound-bg-ui-services";
13805 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013806 app.hidden = false;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013807 clientAdj = adj;
13808 } else {
13809 if (now >= (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
13810 // This service has not seen activity within
13811 // recent memory, so allow it to drop to the
13812 // LRU list if there is no other reason to keep
13813 // it around. We'll also tag it with a label just
13814 // to help debug and undertand what is going on.
13815 if (adj > clientAdj) {
13816 adjType = "bound-bg-services";
13817 }
13818 clientAdj = adj;
13819 }
13820 }
13821 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013822 if (adj > clientAdj) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013823 // If this process has recently shown UI, and
13824 // the process that is binding to it is less
13825 // important than being visible, then we don't
13826 // care about the binding as much as we care
13827 // about letting this process get into the LRU
13828 // list to be killed and restarted if needed for
13829 // memory.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013830 if (app.hasShownUi && app != mHomeProcess
13831 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013832 adjType = "bound-bg-ui-services";
13833 } else {
13834 if ((cr.flags&(Context.BIND_ABOVE_CLIENT
13835 |Context.BIND_IMPORTANT)) != 0) {
13836 adj = clientAdj;
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070013837 } else if ((cr.flags&Context.BIND_NOT_VISIBLE) != 0
13838 && clientAdj < ProcessList.PERCEPTIBLE_APP_ADJ
13839 && adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13840 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13841 } else if (clientAdj > ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013842 adj = clientAdj;
13843 } else {
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070013844 app.pendingUiClean = true;
13845 if (adj > ProcessList.VISIBLE_APP_ADJ) {
13846 adj = ProcessList.VISIBLE_APP_ADJ;
13847 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013848 }
13849 if (!client.hidden) {
13850 app.hidden = false;
13851 }
13852 if (client.keeping) {
13853 app.keeping = true;
13854 }
13855 adjType = "service";
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013856 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013857 }
13858 if (adjType != null) {
13859 app.adjType = adjType;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013860 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13861 .REASON_SERVICE_IN_USE;
13862 app.adjSource = cr.binding.client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013863 app.adjSourceOom = clientAdj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013864 app.adjTarget = s.name;
13865 }
13866 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
13867 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
13868 schedGroup = Process.THREAD_GROUP_DEFAULT;
13869 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013870 }
13871 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013872 if ((cr.flags&Context.BIND_ADJUST_WITH_ACTIVITY) != 0) {
13873 ActivityRecord a = cr.activity;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013874 if (a != null && adj > ProcessList.FOREGROUND_APP_ADJ &&
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013875 (a.visible || a.state == ActivityState.RESUMED
13876 || a.state == ActivityState.PAUSING)) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013877 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013878 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
13879 schedGroup = Process.THREAD_GROUP_DEFAULT;
13880 }
13881 app.hidden = false;
13882 app.adjType = "service";
13883 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13884 .REASON_SERVICE_IN_USE;
13885 app.adjSource = a;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013886 app.adjSourceOom = adj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013887 app.adjTarget = s.name;
13888 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013889 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013890 }
13891 }
13892 }
13893 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013894
Dianne Hackborn287952c2010-09-22 22:34:31 -070013895 // Finally, if this process has active services running in it, we
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013896 // would like to avoid killing it unless it would prevent the current
13897 // application from running. By default we put the process in
13898 // with the rest of the background processes; as we scan through
13899 // its services we may bump it up from there.
13900 if (adj > hiddenAdj) {
13901 adj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013902 app.hidden = false;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013903 app.adjType = "bg-services";
13904 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013905 }
13906
Dianne Hackborn7d608422011-08-07 16:24:18 -070013907 if (app.pubProviders.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013908 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013909 Iterator<ContentProviderRecord> jt = app.pubProviders.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013910 while (jt.hasNext() && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013911 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013912 ContentProviderRecord cpr = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013913 if (cpr.clients.size() != 0) {
13914 Iterator<ProcessRecord> kt = cpr.clients.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013915 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013916 ProcessRecord client = kt.next();
The Android Open Source Project10592532009-03-18 17:39:46 -070013917 if (client == app) {
13918 // Being our own client is not interesting.
13919 continue;
13920 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013921 int myHiddenAdj = hiddenAdj;
13922 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013923 if (client.hiddenAdj > ProcessList.FOREGROUND_APP_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013924 myHiddenAdj = client.hiddenAdj;
13925 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013926 myHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013927 }
13928 }
13929 int clientAdj = computeOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013930 client, myHiddenAdj, TOP_APP, true, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013931 if (adj > clientAdj) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013932 if (app.hasShownUi && app != mHomeProcess
13933 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013934 app.adjType = "bg-ui-provider";
13935 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013936 adj = clientAdj > ProcessList.FOREGROUND_APP_ADJ
13937 ? clientAdj : ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013938 app.adjType = "provider";
13939 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013940 if (!client.hidden) {
13941 app.hidden = false;
13942 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013943 if (client.keeping) {
13944 app.keeping = true;
13945 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070013946 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13947 .REASON_PROVIDER_IN_USE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013948 app.adjSource = client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013949 app.adjSourceOom = clientAdj;
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070013950 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013951 }
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013952 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
13953 schedGroup = Process.THREAD_GROUP_DEFAULT;
13954 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013955 }
13956 }
13957 // If the provider has external (non-framework) process
13958 // dependencies, ensure that its adjustment is at least
13959 // FOREGROUND_APP_ADJ.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080013960 if (cpr.hasExternalProcessHandles()) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013961 if (adj > ProcessList.FOREGROUND_APP_ADJ) {
13962 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013963 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013964 app.hidden = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013965 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013966 app.adjType = "provider";
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070013967 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013968 }
13969 }
13970 }
13971 }
13972
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013973 if (adj == ProcessList.SERVICE_ADJ) {
13974 if (doingAll) {
13975 app.serviceb = mNewNumServiceProcs > (mNumServiceProcs/3);
13976 mNewNumServiceProcs++;
13977 }
13978 if (app.serviceb) {
13979 adj = ProcessList.SERVICE_B_ADJ;
13980 }
13981 } else {
13982 app.serviceb = false;
13983 }
13984
13985 app.nonStoppingAdj = adj;
13986
13987 if (hasStoppingActivities) {
13988 // Only upgrade adjustment.
13989 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13990 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13991 app.adjType = "stopping";
13992 }
13993 }
13994
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013995 app.curRawAdj = adj;
13996
Joe Onorato8a9b2202010-02-26 18:56:32 -080013997 //Slog.i(TAG, "OOM ADJ " + app + ": pid=" + app.pid +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013998 // " adj=" + adj + " curAdj=" + app.curAdj + " maxAdj=" + app.maxAdj);
13999 if (adj > app.maxAdj) {
14000 adj = app.maxAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070014001 if (app.maxAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014002 schedGroup = Process.THREAD_GROUP_DEFAULT;
14003 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014004 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070014005 if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070014006 app.keeping = true;
14007 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014008
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014009 if (app.hasAboveClient) {
14010 // If this process has bound to any services with BIND_ABOVE_CLIENT,
14011 // then we need to drop its adjustment to be lower than the service's
14012 // in order to honor the request. We want to drop it by one adjustment
14013 // level... but there is special meaning applied to various levels so
14014 // we will skip some of them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014015 if (adj < ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014016 // System process will not get dropped, ever
Dianne Hackborn7d608422011-08-07 16:24:18 -070014017 } else if (adj < ProcessList.VISIBLE_APP_ADJ) {
14018 adj = ProcessList.VISIBLE_APP_ADJ;
14019 } else if (adj < ProcessList.PERCEPTIBLE_APP_ADJ) {
14020 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
14021 } else if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
14022 adj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014023 } else if (adj < ProcessList.HIDDEN_APP_MAX_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014024 adj++;
14025 }
14026 }
14027
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014028 app.curAdj = adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014029 app.curSchedGroup = schedGroup;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070014030
14031 if (hadForegroundActivities != app.foregroundActivities) {
Jeff Sharkey287bd832011-05-28 19:36:26 -070014032 mHandler.obtainMessage(DISPATCH_FOREGROUND_ACTIVITIES_CHANGED, app.pid, app.info.uid,
14033 app.foregroundActivities).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070014034 }
14035
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014036 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014037 }
14038
14039 /**
14040 * Ask a given process to GC right now.
14041 */
14042 final void performAppGcLocked(ProcessRecord app) {
14043 try {
14044 app.lastRequestedGc = SystemClock.uptimeMillis();
14045 if (app.thread != null) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014046 if (app.reportLowMemory) {
14047 app.reportLowMemory = false;
14048 app.thread.scheduleLowMemory();
14049 } else {
14050 app.thread.processInBackground();
14051 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014052 }
14053 } catch (Exception e) {
14054 // whatever.
14055 }
14056 }
14057
14058 /**
14059 * Returns true if things are idle enough to perform GCs.
14060 */
Josh Bartel7f208742010-02-25 11:01:44 -060014061 private final boolean canGcNowLocked() {
Christopher Tatef46723b2012-01-26 14:19:24 -080014062 boolean processingBroadcasts = false;
14063 for (BroadcastQueue q : mBroadcastQueues) {
14064 if (q.mParallelBroadcasts.size() != 0 || q.mOrderedBroadcasts.size() != 0) {
14065 processingBroadcasts = true;
14066 }
14067 }
14068 return !processingBroadcasts
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014069 && (mSleeping || (mMainStack.mResumedActivity != null &&
14070 mMainStack.mResumedActivity.idle));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014071 }
14072
14073 /**
14074 * Perform GCs on all processes that are waiting for it, but only
14075 * if things are idle.
14076 */
14077 final void performAppGcsLocked() {
14078 final int N = mProcessesToGc.size();
14079 if (N <= 0) {
14080 return;
14081 }
Josh Bartel7f208742010-02-25 11:01:44 -060014082 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014083 while (mProcessesToGc.size() > 0) {
14084 ProcessRecord proc = mProcessesToGc.remove(0);
Dianne Hackborn7d608422011-08-07 16:24:18 -070014085 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014086 if ((proc.lastRequestedGc+GC_MIN_INTERVAL)
14087 <= SystemClock.uptimeMillis()) {
14088 // To avoid spamming the system, we will GC processes one
14089 // at a time, waiting a few seconds between each.
14090 performAppGcLocked(proc);
14091 scheduleAppGcsLocked();
14092 return;
14093 } else {
14094 // It hasn't been long enough since we last GCed this
14095 // process... put it in the list to wait for its time.
14096 addProcessToGcListLocked(proc);
14097 break;
14098 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014099 }
14100 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014101
14102 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014103 }
14104 }
14105
14106 /**
14107 * If all looks good, perform GCs on all processes waiting for them.
14108 */
14109 final void performAppGcsIfAppropriateLocked() {
Josh Bartel7f208742010-02-25 11:01:44 -060014110 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014111 performAppGcsLocked();
14112 return;
14113 }
14114 // Still not idle, wait some more.
14115 scheduleAppGcsLocked();
14116 }
14117
14118 /**
14119 * Schedule the execution of all pending app GCs.
14120 */
14121 final void scheduleAppGcsLocked() {
14122 mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014123
14124 if (mProcessesToGc.size() > 0) {
14125 // Schedule a GC for the time to the next process.
14126 ProcessRecord proc = mProcessesToGc.get(0);
14127 Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG);
14128
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014129 long when = proc.lastRequestedGc + GC_MIN_INTERVAL;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014130 long now = SystemClock.uptimeMillis();
14131 if (when < (now+GC_TIMEOUT)) {
14132 when = now + GC_TIMEOUT;
14133 }
14134 mHandler.sendMessageAtTime(msg, when);
14135 }
14136 }
14137
14138 /**
14139 * Add a process to the array of processes waiting to be GCed. Keeps the
14140 * list in sorted order by the last GC time. The process can't already be
14141 * on the list.
14142 */
14143 final void addProcessToGcListLocked(ProcessRecord proc) {
14144 boolean added = false;
14145 for (int i=mProcessesToGc.size()-1; i>=0; i--) {
14146 if (mProcessesToGc.get(i).lastRequestedGc <
14147 proc.lastRequestedGc) {
14148 added = true;
14149 mProcessesToGc.add(i+1, proc);
14150 break;
14151 }
14152 }
14153 if (!added) {
14154 mProcessesToGc.add(0, proc);
14155 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014156 }
14157
14158 /**
14159 * Set up to ask a process to GC itself. This will either do it
14160 * immediately, or put it on the list of processes to gc the next
14161 * time things are idle.
14162 */
14163 final void scheduleAppGcLocked(ProcessRecord app) {
14164 long now = SystemClock.uptimeMillis();
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014165 if ((app.lastRequestedGc+GC_MIN_INTERVAL) > now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014166 return;
14167 }
14168 if (!mProcessesToGc.contains(app)) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014169 addProcessToGcListLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014170 scheduleAppGcsLocked();
14171 }
14172 }
14173
Dianne Hackborn287952c2010-09-22 22:34:31 -070014174 final void checkExcessivePowerUsageLocked(boolean doKills) {
14175 updateCpuStatsNow();
14176
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014177 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborn287952c2010-09-22 22:34:31 -070014178 boolean doWakeKills = doKills;
14179 boolean doCpuKills = doKills;
14180 if (mLastPowerCheckRealtime == 0) {
14181 doWakeKills = false;
14182 }
14183 if (mLastPowerCheckUptime == 0) {
14184 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014185 }
14186 if (stats.isScreenOn()) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070014187 doWakeKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014188 }
14189 final long curRealtime = SystemClock.elapsedRealtime();
Dianne Hackborn287952c2010-09-22 22:34:31 -070014190 final long realtimeSince = curRealtime - mLastPowerCheckRealtime;
14191 final long curUptime = SystemClock.uptimeMillis();
14192 final long uptimeSince = curUptime - mLastPowerCheckUptime;
14193 mLastPowerCheckRealtime = curRealtime;
14194 mLastPowerCheckUptime = curUptime;
14195 if (realtimeSince < WAKE_LOCK_MIN_CHECK_DURATION) {
14196 doWakeKills = false;
14197 }
14198 if (uptimeSince < CPU_MIN_CHECK_DURATION) {
14199 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014200 }
14201 int i = mLruProcesses.size();
14202 while (i > 0) {
14203 i--;
14204 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn287952c2010-09-22 22:34:31 -070014205 if (!app.keeping) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014206 long wtime;
14207 synchronized (stats) {
14208 wtime = stats.getProcessWakeTime(app.info.uid,
14209 app.pid, curRealtime);
14210 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070014211 long wtimeUsed = wtime - app.lastWakeTime;
14212 long cputimeUsed = app.curCpuTime - app.lastCpuTime;
14213 if (DEBUG_POWER) {
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014214 StringBuilder sb = new StringBuilder(128);
14215 sb.append("Wake for ");
14216 app.toShortString(sb);
14217 sb.append(": over ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070014218 TimeUtils.formatDuration(realtimeSince, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014219 sb.append(" used ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070014220 TimeUtils.formatDuration(wtimeUsed, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014221 sb.append(" (");
Dianne Hackborn287952c2010-09-22 22:34:31 -070014222 sb.append((wtimeUsed*100)/realtimeSince);
14223 sb.append("%)");
14224 Slog.i(TAG, sb.toString());
14225 sb.setLength(0);
14226 sb.append("CPU for ");
14227 app.toShortString(sb);
14228 sb.append(": over ");
14229 TimeUtils.formatDuration(uptimeSince, sb);
14230 sb.append(" used ");
14231 TimeUtils.formatDuration(cputimeUsed, sb);
14232 sb.append(" (");
14233 sb.append((cputimeUsed*100)/uptimeSince);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014234 sb.append("%)");
14235 Slog.i(TAG, sb.toString());
14236 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014237 // If a process has held a wake lock for more
14238 // than 50% of the time during this period,
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014239 // that sounds bad. Kill!
Dianne Hackborn287952c2010-09-22 22:34:31 -070014240 if (doWakeKills && realtimeSince > 0
14241 && ((wtimeUsed*100)/realtimeSince) >= 50) {
14242 synchronized (stats) {
14243 stats.reportExcessiveWakeLocked(app.info.uid, app.processName,
14244 realtimeSince, wtimeUsed);
14245 }
14246 Slog.w(TAG, "Excessive wake lock in " + app.processName
14247 + " (pid " + app.pid + "): held " + wtimeUsed
14248 + " during " + realtimeSince);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014249 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14250 app.processName, app.setAdj, "excessive wake lock");
14251 Process.killProcessQuiet(app.pid);
Dianne Hackborn287952c2010-09-22 22:34:31 -070014252 } else if (doCpuKills && uptimeSince > 0
14253 && ((cputimeUsed*100)/uptimeSince) >= 50) {
14254 synchronized (stats) {
14255 stats.reportExcessiveCpuLocked(app.info.uid, app.processName,
14256 uptimeSince, cputimeUsed);
14257 }
14258 Slog.w(TAG, "Excessive CPU in " + app.processName
14259 + " (pid " + app.pid + "): used " + cputimeUsed
14260 + " during " + uptimeSince);
14261 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14262 app.processName, app.setAdj, "excessive cpu");
14263 Process.killProcessQuiet(app.pid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014264 } else {
14265 app.lastWakeTime = wtime;
Dianne Hackborn287952c2010-09-22 22:34:31 -070014266 app.lastCpuTime = app.curCpuTime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014267 }
14268 }
14269 }
14270 }
14271
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014272 private final boolean updateOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014273 ProcessRecord app, int hiddenAdj, ProcessRecord TOP_APP, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014274 app.hiddenAdj = hiddenAdj;
14275
14276 if (app.thread == null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014277 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014278 }
14279
Dianne Hackborn287952c2010-09-22 22:34:31 -070014280 final boolean wasKeeping = app.keeping;
14281
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014282 boolean success = true;
14283
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014284 computeOomAdjLocked(app, hiddenAdj, TOP_APP, false, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014285
Jeff Brown10e89712011-07-08 18:52:57 -070014286 if (app.curRawAdj != app.setRawAdj) {
Jeff Brown10e89712011-07-08 18:52:57 -070014287 if (wasKeeping && !app.keeping) {
14288 // This app is no longer something we want to keep. Note
14289 // its current wake lock time to later know to kill it if
14290 // it is not behaving well.
14291 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
14292 synchronized (stats) {
14293 app.lastWakeTime = stats.getProcessWakeTime(app.info.uid,
14294 app.pid, SystemClock.elapsedRealtime());
14295 }
14296 app.lastCpuTime = app.curCpuTime;
14297 }
14298
14299 app.setRawAdj = app.curRawAdj;
14300 }
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014301
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014302 if (app.curAdj != app.setAdj) {
14303 if (Process.setOomAdj(app.pid, app.curAdj)) {
Dianne Hackbornbbb09ac2011-11-30 11:31:29 -080014304 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014305 TAG, "Set " + app.pid + " " + app.processName +
14306 " adj " + app.curAdj + ": " + app.adjType);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014307 app.setAdj = app.curAdj;
Jeff Brown10e89712011-07-08 18:52:57 -070014308 } else {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014309 success = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014310 Slog.w(TAG, "Failed setting oom adj of " + app + " to " + app.curAdj);
Jeff Brown10e89712011-07-08 18:52:57 -070014311 }
14312 }
14313 if (app.setSchedGroup != app.curSchedGroup) {
14314 app.setSchedGroup = app.curSchedGroup;
14315 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
14316 "Setting process group of " + app.processName
14317 + " to " + app.curSchedGroup);
14318 if (app.waitingToKill != null &&
14319 app.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
14320 Slog.i(TAG, "Killing " + app.toShortString() + ": " + app.waitingToKill);
14321 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14322 app.processName, app.setAdj, app.waitingToKill);
14323 Process.killProcessQuiet(app.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014324 success = false;
Jeff Brown10e89712011-07-08 18:52:57 -070014325 } else {
14326 if (true) {
14327 long oldId = Binder.clearCallingIdentity();
14328 try {
14329 Process.setProcessGroup(app.pid, app.curSchedGroup);
14330 } catch (Exception e) {
14331 Slog.w(TAG, "Failed setting process group of " + app.pid
14332 + " to " + app.curSchedGroup);
14333 e.printStackTrace();
14334 } finally {
14335 Binder.restoreCallingIdentity(oldId);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014336 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014337 } else {
Jeff Brown10e89712011-07-08 18:52:57 -070014338 if (app.thread != null) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070014339 try {
Jeff Brown10e89712011-07-08 18:52:57 -070014340 app.thread.setSchedulingGroup(app.curSchedGroup);
14341 } catch (RemoteException e) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070014342 }
14343 }
14344 }
14345 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014346 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014347 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014348 }
14349
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014350 private final ActivityRecord resumedAppLocked() {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014351 ActivityRecord resumedActivity = mMainStack.mResumedActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014352 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -080014353 resumedActivity = mMainStack.mPausingActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014354 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014355 resumedActivity = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014356 }
14357 }
14358 return resumedActivity;
14359 }
14360
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014361 private final boolean updateOomAdjLocked(ProcessRecord app) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014362 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014363 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
14364 int curAdj = app.curAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070014365 final boolean wasHidden = curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
14366 && curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014367
14368 mAdjSeq++;
14369
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014370 boolean success = updateOomAdjLocked(app, app.hiddenAdj, TOP_APP, false);
Dianne Hackborn7d608422011-08-07 16:24:18 -070014371 final boolean nowHidden = app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
14372 && app.curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014373 if (nowHidden != wasHidden) {
14374 // Changed to/from hidden state, so apps after it in the LRU
14375 // list may also be changed.
14376 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014377 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014378 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014379 }
14380
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014381 final void updateOomAdjLocked() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014382 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014383 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
14384
14385 if (false) {
14386 RuntimeException e = new RuntimeException();
14387 e.fillInStackTrace();
Joe Onorato8a9b2202010-02-26 18:56:32 -080014388 Slog.i(TAG, "updateOomAdj: top=" + TOP_ACT, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014389 }
14390
14391 mAdjSeq++;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014392 mNewNumServiceProcs = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014393
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014394 // Let's determine how many processes we have running vs.
14395 // how many slots we have for background processes; we may want
14396 // to put multiple processes in a slot of there are enough of
14397 // them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014398 int numSlots = ProcessList.HIDDEN_APP_MAX_ADJ - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014399 int factor = (mLruProcesses.size()-4)/numSlots;
14400 if (factor < 1) factor = 1;
14401 int step = 0;
Dianne Hackborn8633e682010-04-22 16:03:41 -070014402 int numHidden = 0;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014403 int numTrimming = 0;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014404
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014405 // First update the OOM adjustment for each of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014406 // application processes based on their current state.
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014407 int i = mLruProcesses.size();
Dianne Hackborn7d608422011-08-07 16:24:18 -070014408 int curHiddenAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014409 while (i > 0) {
14410 i--;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014411 ProcessRecord app = mLruProcesses.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080014412 //Slog.i(TAG, "OOM " + app + ": cur hidden=" + curHiddenAdj);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014413 updateOomAdjLocked(app, curHiddenAdj, TOP_APP, true);
14414 if (curHiddenAdj < ProcessList.HIDDEN_APP_MAX_ADJ
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014415 && app.curAdj == curHiddenAdj) {
14416 step++;
14417 if (step >= factor) {
14418 step = 0;
14419 curHiddenAdj++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014420 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014421 }
14422 if (!app.killedBackground) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070014423 if (app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014424 numHidden++;
14425 if (numHidden > mProcessLimit) {
14426 Slog.i(TAG, "No longer want " + app.processName
14427 + " (pid " + app.pid + "): hidden #" + numHidden);
14428 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14429 app.processName, app.setAdj, "too many background");
14430 app.killedBackground = true;
14431 Process.killProcessQuiet(app.pid);
Dianne Hackborn8633e682010-04-22 16:03:41 -070014432 }
14433 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -080014434 if (!app.killedBackground && app.isolated && app.services.size() <= 0) {
14435 // If this is an isolated process, and there are no
14436 // services running in it, then the process is no longer
14437 // needed. We agressively kill these because we can by
14438 // definition not re-use the same process again, and it is
14439 // good to avoid having whatever code was running in them
14440 // left sitting around after no longer needed.
14441 Slog.i(TAG, "Isolated process " + app.processName
14442 + " (pid " + app.pid + ") no longer needed");
14443 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14444 app.processName, app.setAdj, "isolated not needed");
14445 app.killedBackground = true;
14446 Process.killProcessQuiet(app.pid);
14447 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014448 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
14449 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
14450 && !app.killedBackground) {
14451 numTrimming++;
14452 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014453 }
14454 }
14455
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014456 mNumServiceProcs = mNewNumServiceProcs;
14457
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014458 // Now determine the memory trimming level of background processes.
14459 // Unfortunately we need to start at the back of the list to do this
14460 // properly. We only do this if the number of background apps we
14461 // are managing to keep around is less than half the maximum we desire;
14462 // if we are keeping a good number around, we'll let them use whatever
14463 // memory they want.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014464 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/2)) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014465 final int N = mLruProcesses.size();
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014466 factor = numTrimming/3;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080014467 int minFactor = 2;
14468 if (mHomeProcess != null) minFactor++;
14469 if (mPreviousProcess != null) minFactor++;
14470 if (factor < minFactor) factor = minFactor;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014471 step = 0;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014472 int fgTrimLevel;
14473 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/5)) {
14474 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL;
14475 } else if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/3)) {
14476 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW;
14477 } else {
14478 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE;
14479 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014480 int curLevel = ComponentCallbacks2.TRIM_MEMORY_COMPLETE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014481 for (i=0; i<N; i++) {
14482 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014483 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
14484 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080014485 && !app.killedBackground) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014486 if (app.trimMemoryLevel < curLevel && app.thread != null) {
14487 try {
14488 app.thread.scheduleTrimMemory(curLevel);
14489 } catch (RemoteException e) {
14490 }
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080014491 if (false) {
14492 // For now we won't do this; our memory trimming seems
14493 // to be good enough at this point that destroying
14494 // activities causes more harm than good.
14495 if (curLevel >= ComponentCallbacks2.TRIM_MEMORY_COMPLETE
14496 && app != mHomeProcess && app != mPreviousProcess) {
14497 // For these apps we will also finish their activities
14498 // to help them free memory.
14499 mMainStack.destroyActivitiesLocked(app, false, "trim");
14500 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014501 }
14502 }
14503 app.trimMemoryLevel = curLevel;
14504 step++;
14505 if (step >= factor) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014506 step = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014507 switch (curLevel) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014508 case ComponentCallbacks2.TRIM_MEMORY_COMPLETE:
14509 curLevel = ComponentCallbacks2.TRIM_MEMORY_MODERATE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014510 break;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014511 case ComponentCallbacks2.TRIM_MEMORY_MODERATE:
14512 curLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014513 break;
14514 }
14515 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014516 } else if (app.nonStoppingAdj == ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014517 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014518 && app.thread != null) {
14519 try {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014520 app.thread.scheduleTrimMemory(
14521 ComponentCallbacks2.TRIM_MEMORY_BACKGROUND);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014522 } catch (RemoteException e) {
14523 }
14524 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014525 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014526 } else {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014527 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014528 && app.pendingUiClean) {
14529 // If this application is now in the background and it
14530 // had done UI, then give it the special trim level to
14531 // have it free UI resources.
14532 final int level = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
14533 if (app.trimMemoryLevel < level && app.thread != null) {
14534 try {
14535 app.thread.scheduleTrimMemory(level);
14536 } catch (RemoteException e) {
14537 }
14538 }
14539 app.pendingUiClean = false;
14540 }
14541 if (app.trimMemoryLevel < fgTrimLevel && app.thread != null) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014542 try {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014543 app.thread.scheduleTrimMemory(fgTrimLevel);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014544 } catch (RemoteException e) {
14545 }
14546 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014547 app.trimMemoryLevel = fgTrimLevel;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014548 }
14549 }
14550 } else {
14551 final int N = mLruProcesses.size();
14552 for (i=0; i<N; i++) {
14553 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014554 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014555 && app.pendingUiClean) {
14556 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
14557 && app.thread != null) {
14558 try {
14559 app.thread.scheduleTrimMemory(
14560 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
14561 } catch (RemoteException e) {
14562 }
14563 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014564 app.pendingUiClean = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014565 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014566 app.trimMemoryLevel = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014567 }
14568 }
14569
14570 if (mAlwaysFinishActivities) {
Dianne Hackborn28695e02011-11-02 21:59:51 -070014571 mMainStack.destroyActivitiesLocked(null, false, "always-finish");
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014572 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014573 }
14574
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014575 final void trimApplications() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014576 synchronized (this) {
14577 int i;
14578
14579 // First remove any unused application processes whose package
14580 // has been removed.
14581 for (i=mRemovedProcesses.size()-1; i>=0; i--) {
14582 final ProcessRecord app = mRemovedProcesses.get(i);
14583 if (app.activities.size() == 0
14584 && app.curReceiver == null && app.services.size() == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080014585 Slog.i(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014586 TAG, "Exiting empty application process "
14587 + app.processName + " ("
14588 + (app.thread != null ? app.thread.asBinder() : null)
14589 + ")\n");
14590 if (app.pid > 0 && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070014591 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14592 app.processName, app.setAdj, "empty");
14593 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014594 } else {
14595 try {
14596 app.thread.scheduleExit();
14597 } catch (Exception e) {
14598 // Ignore exceptions.
14599 }
14600 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070014601 cleanUpApplicationRecordLocked(app, false, true, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014602 mRemovedProcesses.remove(i);
14603
14604 if (app.persistent) {
14605 if (app.persistent) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080014606 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014607 }
14608 }
14609 }
14610 }
14611
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014612 // Now update the oom adj for all processes.
14613 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014614 }
14615 }
14616
14617 /** This method sends the specified signal to each of the persistent apps */
14618 public void signalPersistentProcesses(int sig) throws RemoteException {
14619 if (sig != Process.SIGNAL_USR1) {
14620 throw new SecurityException("Only SIGNAL_USR1 is allowed");
14621 }
14622
14623 synchronized (this) {
14624 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
14625 != PackageManager.PERMISSION_GRANTED) {
14626 throw new SecurityException("Requires permission "
14627 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
14628 }
14629
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014630 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
14631 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014632 if (r.thread != null && r.persistent) {
14633 Process.sendSignal(r.pid, sig);
14634 }
14635 }
14636 }
14637 }
14638
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014639 private void stopProfilerLocked(ProcessRecord proc, String path, int profileType) {
14640 if (proc == null || proc == mProfileProc) {
14641 proc = mProfileProc;
14642 path = mProfileFile;
14643 profileType = mProfileType;
14644 clearProfilerLocked();
14645 }
14646 if (proc == null) {
14647 return;
14648 }
14649 try {
14650 proc.thread.profilerControl(false, path, null, profileType);
14651 } catch (RemoteException e) {
14652 throw new IllegalStateException("Process disappeared");
14653 }
14654 }
14655
14656 private void clearProfilerLocked() {
14657 if (mProfileFd != null) {
14658 try {
14659 mProfileFd.close();
14660 } catch (IOException e) {
14661 }
14662 }
14663 mProfileApp = null;
14664 mProfileProc = null;
14665 mProfileFile = null;
14666 mProfileType = 0;
14667 mAutoStopProfiler = false;
14668 }
14669
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014670 public boolean profileControl(String process, boolean start,
Romain Guy7eabe552011-07-21 14:56:34 -070014671 String path, ParcelFileDescriptor fd, int profileType) throws RemoteException {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014672
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014673 try {
14674 synchronized (this) {
14675 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14676 // its own permission.
14677 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14678 != PackageManager.PERMISSION_GRANTED) {
14679 throw new SecurityException("Requires permission "
14680 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014681 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014682
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014683 if (start && fd == null) {
14684 throw new IllegalArgumentException("null fd");
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014685 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014686
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014687 ProcessRecord proc = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014688 if (process != null) {
14689 try {
14690 int pid = Integer.parseInt(process);
14691 synchronized (mPidsSelfLocked) {
14692 proc = mPidsSelfLocked.get(pid);
14693 }
14694 } catch (NumberFormatException e) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014695 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014696
14697 if (proc == null) {
14698 HashMap<String, SparseArray<ProcessRecord>> all
14699 = mProcessNames.getMap();
14700 SparseArray<ProcessRecord> procs = all.get(process);
14701 if (procs != null && procs.size() > 0) {
14702 proc = procs.valueAt(0);
14703 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014704 }
14705 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014706
14707 if (start && (proc == null || proc.thread == null)) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014708 throw new IllegalArgumentException("Unknown process: " + process);
14709 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014710
14711 if (start) {
14712 stopProfilerLocked(null, null, 0);
14713 setProfileApp(proc.info, proc.processName, path, fd, false);
14714 mProfileProc = proc;
14715 mProfileType = profileType;
14716 try {
14717 fd = fd.dup();
14718 } catch (IOException e) {
14719 fd = null;
14720 }
14721 proc.thread.profilerControl(start, path, fd, profileType);
14722 fd = null;
14723 mProfileFd = null;
14724 } else {
14725 stopProfilerLocked(proc, path, profileType);
14726 if (fd != null) {
14727 try {
14728 fd.close();
14729 } catch (IOException e) {
14730 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014731 }
14732 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014733
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014734 return true;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014735 }
14736 } catch (RemoteException e) {
14737 throw new IllegalStateException("Process disappeared");
14738 } finally {
14739 if (fd != null) {
14740 try {
14741 fd.close();
14742 } catch (IOException e) {
14743 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014744 }
14745 }
14746 }
Andy McFadden824c5102010-07-09 16:26:57 -070014747
14748 public boolean dumpHeap(String process, boolean managed,
14749 String path, ParcelFileDescriptor fd) throws RemoteException {
14750
14751 try {
14752 synchronized (this) {
14753 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14754 // its own permission (same as profileControl).
14755 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14756 != PackageManager.PERMISSION_GRANTED) {
14757 throw new SecurityException("Requires permission "
14758 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
14759 }
14760
14761 if (fd == null) {
14762 throw new IllegalArgumentException("null fd");
14763 }
14764
14765 ProcessRecord proc = null;
14766 try {
14767 int pid = Integer.parseInt(process);
14768 synchronized (mPidsSelfLocked) {
14769 proc = mPidsSelfLocked.get(pid);
14770 }
14771 } catch (NumberFormatException e) {
14772 }
14773
14774 if (proc == null) {
14775 HashMap<String, SparseArray<ProcessRecord>> all
14776 = mProcessNames.getMap();
14777 SparseArray<ProcessRecord> procs = all.get(process);
14778 if (procs != null && procs.size() > 0) {
14779 proc = procs.valueAt(0);
14780 }
14781 }
14782
14783 if (proc == null || proc.thread == null) {
14784 throw new IllegalArgumentException("Unknown process: " + process);
14785 }
14786
Dianne Hackbornf02e57b2011-03-01 22:21:04 -080014787 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
14788 if (!isDebuggable) {
Andy McFadden824c5102010-07-09 16:26:57 -070014789 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
14790 throw new SecurityException("Process not debuggable: " + proc);
14791 }
14792 }
14793
14794 proc.thread.dumpHeap(managed, path, fd);
14795 fd = null;
14796 return true;
14797 }
14798 } catch (RemoteException e) {
14799 throw new IllegalStateException("Process disappeared");
14800 } finally {
14801 if (fd != null) {
14802 try {
14803 fd.close();
14804 } catch (IOException e) {
14805 }
14806 }
14807 }
14808 }
14809
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014810 /** In this method we try to acquire our lock to make sure that we have not deadlocked */
14811 public void monitor() {
14812 synchronized (this) { }
14813 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014814
Dianne Hackborna573f6a2012-02-09 16:12:18 -080014815 void onCoreSettingsChange(Bundle settings) {
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014816 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
14817 ProcessRecord processRecord = mLruProcesses.get(i);
14818 try {
14819 if (processRecord.thread != null) {
14820 processRecord.thread.setCoreSettings(settings);
14821 }
14822 } catch (RemoteException re) {
14823 /* ignore */
14824 }
14825 }
14826 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014827
14828 // Multi-user methods
14829
Amith Yamasani742a6712011-05-04 14:49:28 -070014830 private int mCurrentUserId;
14831 private SparseIntArray mLoggedInUsers = new SparseIntArray(5);
14832
14833 public boolean switchUser(int userId) {
14834 final int callingUid = Binder.getCallingUid();
14835 if (callingUid != 0 && callingUid != Process.myUid()) {
14836 Slog.e(TAG, "Trying to switch user from unauthorized app");
14837 return false;
14838 }
14839 if (mCurrentUserId == userId)
14840 return true;
14841
14842 synchronized (this) {
14843 // Check if user is already logged in, otherwise check if user exists first before
14844 // adding to the list of logged in users.
14845 if (mLoggedInUsers.indexOfKey(userId) < 0) {
14846 if (!userExists(userId)) {
14847 return false;
14848 }
14849 mLoggedInUsers.append(userId, userId);
14850 }
14851
14852 mCurrentUserId = userId;
14853 boolean haveActivities = mMainStack.switchUser(userId);
14854 if (!haveActivities) {
14855 startHomeActivityLocked(userId);
14856 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014857
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014858 }
Amith Yamasani13593602012-03-22 16:16:17 -070014859
14860 // Inform of user switch
14861 Intent addedIntent = new Intent(Intent.ACTION_USER_SWITCHED);
14862 addedIntent.putExtra(Intent.EXTRA_USERID, userId);
14863 mContext.sendBroadcast(addedIntent, android.Manifest.permission.MANAGE_ACCOUNTS);
14864
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014865 return true;
14866 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014867
Amith Yamasani52f1d752012-03-28 18:19:29 -070014868 @Override
14869 public UserInfo getCurrentUser() throws RemoteException {
14870 final int callingUid = Binder.getCallingUid();
14871 if (callingUid != 0 && callingUid != Process.myUid()) {
14872 Slog.e(TAG, "Trying to get user from unauthorized app");
14873 return null;
14874 }
14875 return AppGlobals.getPackageManager().getUser(mCurrentUserId);
14876 }
14877
Amith Yamasani13593602012-03-22 16:16:17 -070014878 private void onUserRemoved(Intent intent) {
14879 int extraUserId = intent.getIntExtra(Intent.EXTRA_USERID, -1);
14880 if (extraUserId < 1) return;
14881
14882 // Kill all the processes for the user
14883 ArrayList<Pair<String, Integer>> pkgAndUids = new ArrayList<Pair<String,Integer>>();
14884 synchronized (this) {
14885 HashMap<String,SparseArray<ProcessRecord>> map = mProcessNames.getMap();
14886 for (Entry<String, SparseArray<ProcessRecord>> uidMap : map.entrySet()) {
14887 SparseArray<ProcessRecord> uids = uidMap.getValue();
14888 for (int i = 0; i < uids.size(); i++) {
14889 if (UserId.getUserId(uids.keyAt(i)) == extraUserId) {
14890 pkgAndUids.add(new Pair<String,Integer>(uidMap.getKey(), uids.keyAt(i)));
14891 }
14892 }
14893 }
14894
14895 for (Pair<String,Integer> pkgAndUid : pkgAndUids) {
14896 forceStopPackageLocked(pkgAndUid.first, pkgAndUid.second,
14897 false, false, true, true, extraUserId);
14898 }
14899 }
14900 }
14901
Amith Yamasani742a6712011-05-04 14:49:28 -070014902 private boolean userExists(int userId) {
14903 try {
Amith Yamasani13593602012-03-22 16:16:17 -070014904 UserInfo user = AppGlobals.getPackageManager().getUser(userId);
14905 return user != null;
Amith Yamasani742a6712011-05-04 14:49:28 -070014906 } catch (RemoteException re) {
14907 // Won't happen, in same process
14908 }
14909
14910 return false;
14911 }
14912
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014913 private void checkValidCaller(int uid, int userId) {
14914 if (UserId.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) return;
14915
14916 throw new SecurityException("Caller uid=" + uid
14917 + " is not privileged to communicate with user=" + userId);
14918 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014919
14920 private int applyUserId(int uid, int userId) {
14921 return UserId.getUid(userId, uid);
14922 }
14923
14924 private ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080014925 if (info == null) return null;
Amith Yamasani742a6712011-05-04 14:49:28 -070014926 ApplicationInfo newInfo = new ApplicationInfo(info);
14927 newInfo.uid = applyUserId(info.uid, userId);
Amith Yamasania4a54e22012-04-16 15:44:19 -070014928 newInfo.dataDir = USER_DATA_DIR + userId + "/"
14929 + info.packageName;
Amith Yamasani742a6712011-05-04 14:49:28 -070014930 return newInfo;
14931 }
14932
14933 ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) {
Amith Yamasania4a54e22012-04-16 15:44:19 -070014934 if (aInfo == null
14935 || (userId < 1 && aInfo.applicationInfo.uid < UserId.PER_USER_RANGE)) {
Amith Yamasani742a6712011-05-04 14:49:28 -070014936 return aInfo;
14937 }
14938
14939 ActivityInfo info = new ActivityInfo(aInfo);
14940 info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId);
14941 return info;
14942 }
14943
14944 static class ServiceMap {
14945
14946 private final SparseArray<HashMap<ComponentName, ServiceRecord>> mServicesByNamePerUser
14947 = new SparseArray<HashMap<ComponentName, ServiceRecord>>();
14948 private final SparseArray<HashMap<Intent.FilterComparison, ServiceRecord>>
14949 mServicesByIntentPerUser = new SparseArray<
14950 HashMap<Intent.FilterComparison, ServiceRecord>>();
14951
14952 ServiceRecord getServiceByName(ComponentName name, int callingUser) {
14953 // TODO: Deal with global services
14954 if (DEBUG_MU)
14955 Slog.v(TAG_MU, "getServiceByName(" + name + "), callingUser = " + callingUser);
14956 return getServices(callingUser).get(name);
14957 }
14958
14959 ServiceRecord getServiceByName(ComponentName name) {
14960 return getServiceByName(name, -1);
14961 }
14962
14963 ServiceRecord getServiceByIntent(Intent.FilterComparison filter, int callingUser) {
14964 // TODO: Deal with global services
14965 if (DEBUG_MU)
14966 Slog.v(TAG_MU, "getServiceByIntent(" + filter + "), callingUser = " + callingUser);
14967 return getServicesByIntent(callingUser).get(filter);
14968 }
14969
14970 ServiceRecord getServiceByIntent(Intent.FilterComparison filter) {
14971 return getServiceByIntent(filter, -1);
14972 }
14973
14974 void putServiceByName(ComponentName name, int callingUser, ServiceRecord value) {
14975 // TODO: Deal with global services
14976 getServices(callingUser).put(name, value);
14977 }
14978
14979 void putServiceByIntent(Intent.FilterComparison filter, int callingUser,
14980 ServiceRecord value) {
14981 // TODO: Deal with global services
14982 getServicesByIntent(callingUser).put(filter, value);
14983 }
14984
14985 void removeServiceByName(ComponentName name, int callingUser) {
14986 // TODO: Deal with global services
14987 ServiceRecord removed = getServices(callingUser).remove(name);
14988 if (DEBUG_MU)
14989 Slog.v(TAG, "removeServiceByName user=" + callingUser + " name=" + name
14990 + " removed=" + removed);
14991 }
14992
14993 void removeServiceByIntent(Intent.FilterComparison filter, int callingUser) {
14994 // TODO: Deal with global services
14995 ServiceRecord removed = getServicesByIntent(callingUser).remove(filter);
14996 if (DEBUG_MU)
14997 Slog.v(TAG_MU, "removeServiceByIntent user=" + callingUser + " intent=" + filter
14998 + " removed=" + removed);
14999 }
15000
15001 Collection<ServiceRecord> getAllServices(int callingUser) {
15002 // TODO: Deal with global services
15003 return getServices(callingUser).values();
15004 }
15005
15006 private HashMap<ComponentName, ServiceRecord> getServices(int callingUser) {
15007 HashMap map = mServicesByNamePerUser.get(callingUser);
15008 if (map == null) {
15009 map = new HashMap<ComponentName, ServiceRecord>();
15010 mServicesByNamePerUser.put(callingUser, map);
15011 }
15012 return map;
15013 }
15014
15015 private HashMap<Intent.FilterComparison, ServiceRecord> getServicesByIntent(
15016 int callingUser) {
15017 HashMap map = mServicesByIntentPerUser.get(callingUser);
15018 if (map == null) {
15019 map = new HashMap<Intent.FilterComparison, ServiceRecord>();
15020 mServicesByIntentPerUser.put(callingUser, map);
15021 }
15022 return map;
15023 }
15024 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015025}