blob: bbaebd9b3fc687cddd920c410c1a02655e4ae96f [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;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065import android.content.Intent;
66import android.content.IntentFilter;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070067import android.content.IIntentReceiver;
68import android.content.IIntentSender;
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;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070078import android.content.pm.PathPermission;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080079import android.content.pm.ProviderInfo;
80import android.content.pm.ResolveInfo;
81import android.content.pm.ServiceInfo;
Amith Yamasani742a6712011-05-04 14:49:28 -070082import android.content.pm.UserInfo;
Dianne Hackborn860755f2010-06-03 18:47:52 -070083import android.content.pm.PackageManager.NameNotFoundException;
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;
Dianne Hackborn905577f2011-09-07 18:31:28 -0700116import android.util.Pair;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800117import android.util.Slog;
Joe Onorato5d3bea62010-03-01 13:44:29 -0800118import android.util.Log;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800119import android.util.PrintWriterPrinter;
120import 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.IllegalStateException;
144import java.lang.ref.WeakReference;
145import java.util.ArrayList;
Amith Yamasani742a6712011-05-04 14:49:28 -0700146import java.util.Collection;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700147import java.util.Collections;
148import java.util.Comparator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800149import java.util.HashMap;
150import java.util.HashSet;
151import java.util.Iterator;
152import java.util.List;
153import java.util.Locale;
154import java.util.Map;
Amith Yamasani13593602012-03-22 16:16:17 -0700155import java.util.Map.Entry;
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -0700156import java.util.Set;
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700157import java.util.concurrent.atomic.AtomicBoolean;
158import java.util.concurrent.atomic.AtomicLong;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800159
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700160public final class ActivityManagerService extends ActivityManagerNative
161 implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
Amith Yamasani742a6712011-05-04 14:49:28 -0700162 private static final String USER_DATA_DIR = "/data/user/";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800163 static final String TAG = "ActivityManager";
Amith Yamasani742a6712011-05-04 14:49:28 -0700164 static final String TAG_MU = "ActivityManagerServiceMU";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800165 static final boolean DEBUG = false;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400166 static final boolean localLOGV = DEBUG;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800167 static final boolean DEBUG_SWITCH = localLOGV || false;
168 static final boolean DEBUG_TASKS = localLOGV || false;
169 static final boolean DEBUG_PAUSE = localLOGV || false;
170 static final boolean DEBUG_OOM_ADJ = localLOGV || false;
171 static final boolean DEBUG_TRANSITION = localLOGV || false;
172 static final boolean DEBUG_BROADCAST = localLOGV || false;
Christopher Tatef46723b2012-01-26 14:19:24 -0800173 static final boolean DEBUG_BACKGROUND_BROADCAST = DEBUG_BROADCAST || false;
Dianne Hackborn82f3f002009-06-16 18:49:05 -0700174 static final boolean DEBUG_BROADCAST_LIGHT = DEBUG_BROADCAST || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800175 static final boolean DEBUG_SERVICE = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700176 static final boolean DEBUG_SERVICE_EXECUTING = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800177 static final boolean DEBUG_VISBILITY = localLOGV || false;
178 static final boolean DEBUG_PROCESSES = localLOGV || false;
Dianne Hackborna1e989b2009-09-01 19:54:29 -0700179 static final boolean DEBUG_PROVIDER = localLOGV || false;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800180 static final boolean DEBUG_URI_PERMISSION = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800181 static final boolean DEBUG_USER_LEAVING = localLOGV || false;
The Android Open Source Project10592532009-03-18 17:39:46 -0700182 static final boolean DEBUG_RESULTS = localLOGV || false;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -0700183 static final boolean DEBUG_BACKUP = localLOGV || false;
Dianne Hackborndc6b6352009-09-30 14:20:09 -0700184 static final boolean DEBUG_CONFIGURATION = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700185 static final boolean DEBUG_POWER = localLOGV || false;
186 static final boolean DEBUG_POWER_QUICK = DEBUG_POWER || false;
Amith Yamasani742a6712011-05-04 14:49:28 -0700187 static final boolean DEBUG_MU = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800188 static final boolean VALIDATE_TOKENS = false;
189 static final boolean SHOW_ACTIVITY_START_TIME = true;
190
191 // Control over CPU and battery monitoring.
192 static final long BATTERY_STATS_TIME = 30*60*1000; // write battery stats every 30 minutes.
193 static final boolean MONITOR_CPU_USAGE = true;
194 static final long MONITOR_CPU_MIN_TIME = 5*1000; // don't sample cpu less than every 5 seconds.
195 static final long MONITOR_CPU_MAX_TIME = 0x0fffffff; // wait possibly forever for next cpu sample.
196 static final boolean MONITOR_THREAD_CPU_USAGE = false;
197
Dianne Hackborn1655be42009-05-08 14:29:01 -0700198 // The flags that are set for all calls we make to the package manager.
Dianne Hackborn11b822d2009-07-21 20:03:02 -0700199 static final int STOCK_PM_FLAGS = PackageManager.GET_SHARED_LIBRARY_FILES;
Dianne Hackborn1655be42009-05-08 14:29:01 -0700200
Dianne Hackbornf02e57b2011-03-01 22:21:04 -0800201 private static final String SYSTEM_DEBUGGABLE = "ro.debuggable";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800202
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700203 static final boolean IS_USER_BUILD = "user".equals(Build.TYPE);
204
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800205 // Maximum number of recent tasks that we can remember.
206 static final int MAX_RECENT_TASKS = 20;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700207
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700208 // Amount of time after a call to stopAppSwitches() during which we will
209 // prevent further untrusted switches from happening.
210 static final long APP_SWITCH_DELAY_TIME = 5*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800211
212 // How long we wait for a launched process to attach to the activity manager
213 // before we decide it's never going to come up for real.
214 static final int PROC_START_TIMEOUT = 10*1000;
215
Jeff Brown3f9dd282011-07-08 20:02:19 -0700216 // How long we wait for a launched process to attach to the activity manager
217 // before we decide it's never going to come up for real, when the process was
218 // started with a wrapper for instrumentation (such as Valgrind) because it
219 // could take much longer than usual.
220 static final int PROC_START_TIMEOUT_WITH_WRAPPER = 300*1000;
221
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800222 // How long to wait after going idle before forcing apps to GC.
223 static final int GC_TIMEOUT = 5*1000;
224
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700225 // The minimum amount of time between successive GC requests for a process.
226 static final int GC_MIN_INTERVAL = 60*1000;
227
Dianne Hackborn287952c2010-09-22 22:34:31 -0700228 // The rate at which we check for apps using excessive power -- 15 mins.
229 static final int POWER_CHECK_DELAY = (DEBUG_POWER_QUICK ? 2 : 15) * 60*1000;
230
231 // The minimum sample duration we will allow before deciding we have
232 // enough data on wake locks to start killing things.
233 static final int WAKE_LOCK_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
234
235 // The minimum sample duration we will allow before deciding we have
236 // enough data on CPU usage to start killing things.
237 static final int CPU_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700238
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800239 // How long we allow a receiver to run before giving up on it.
Christopher Tatef46723b2012-01-26 14:19:24 -0800240 static final int BROADCAST_FG_TIMEOUT = 10*1000;
241 static final int BROADCAST_BG_TIMEOUT = 60*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800242
243 // How long we wait for a service to finish executing.
244 static final int SERVICE_TIMEOUT = 20*1000;
245
246 // How long a service needs to be running until restarting its process
247 // is no longer considered to be a relaunch of the service.
248 static final int SERVICE_RESTART_DURATION = 5*1000;
249
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700250 // How long a service needs to be running until it will start back at
251 // SERVICE_RESTART_DURATION after being killed.
252 static final int SERVICE_RESET_RUN_DURATION = 60*1000;
253
254 // Multiplying factor to increase restart duration time by, for each time
255 // a service is killed before it has run for SERVICE_RESET_RUN_DURATION.
256 static final int SERVICE_RESTART_DURATION_FACTOR = 4;
257
258 // The minimum amount of time between restarting services that we allow.
259 // That is, when multiple services are restarting, we won't allow each
260 // to restart less than this amount of time from the last one.
261 static final int SERVICE_MIN_RESTART_TIME_BETWEEN = 10*1000;
262
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800263 // Maximum amount of time for there to be no activity on a service before
264 // we consider it non-essential and allow its process to go on the
265 // LRU background list.
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700266 static final int MAX_SERVICE_INACTIVITY = 30*60*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800267
268 // How long we wait until we timeout on key dispatching.
269 static final int KEY_DISPATCHING_TIMEOUT = 5*1000;
270
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800271 // How long we wait until we timeout on key dispatching during instrumentation.
272 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT = 60*1000;
273
Dan Egnor42471dd2010-01-07 17:25:22 -0800274 static final int MY_PID = Process.myPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800275
276 static final String[] EMPTY_STRING_ARRAY = new String[0];
277
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700278 public ActivityStack mMainStack;
Mike Lockwood3a74bd32011-08-12 13:55:22 -0700279
280 private final boolean mHeadless;
281
Joe Onorato54a4a412011-11-02 20:50:08 -0700282 // Whether we should show our dialogs (ANR, crash, etc) or just perform their
283 // default actuion automatically. Important for devices without direct input
284 // devices.
285 private boolean mShowDialogs = true;
286
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800287 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700288 * Description of a request to start a new activity, which has been held
289 * due to app switches being disabled.
290 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700291 static class PendingActivityLaunch {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700292 ActivityRecord r;
293 ActivityRecord sourceRecord;
Dianne Hackborna4972e92012-03-14 10:38:05 -0700294 int startFlags;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700295 }
296
297 final ArrayList<PendingActivityLaunch> mPendingActivityLaunches
298 = new ArrayList<PendingActivityLaunch>();
299
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800300
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800301 BroadcastQueue mFgBroadcastQueue;
302 BroadcastQueue mBgBroadcastQueue;
Christopher Tatef46723b2012-01-26 14:19:24 -0800303 // Convenient for easy iteration over the queues. Foreground is first
304 // so that dispatch of foreground broadcasts gets precedence.
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800305 final BroadcastQueue[] mBroadcastQueues = new BroadcastQueue[2];
Christopher Tatef46723b2012-01-26 14:19:24 -0800306
307 BroadcastQueue broadcastQueueForIntent(Intent intent) {
308 final boolean isFg = (intent.getFlags() & Intent.FLAG_RECEIVER_FOREGROUND) != 0;
309 if (DEBUG_BACKGROUND_BROADCAST) {
310 Slog.i(TAG, "Broadcast intent " + intent + " on "
311 + (isFg ? "foreground" : "background")
312 + " queue");
313 }
314 return (isFg) ? mFgBroadcastQueue : mBgBroadcastQueue;
315 }
316
317 BroadcastRecord broadcastRecordForReceiverLocked(IBinder receiver) {
318 for (BroadcastQueue queue : mBroadcastQueues) {
319 BroadcastRecord r = queue.getMatchingOrderedReceiver(receiver);
320 if (r != null) {
321 return r;
322 }
323 }
324 return null;
325 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800326
327 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800328 * Activity we have told the window manager to have key focus.
329 */
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700330 ActivityRecord mFocusedActivity = null;
Dianne Hackbornbfe319e2009-09-21 00:34:05 -0700331 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800332 * List of intents that were used to start the most recent tasks.
333 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700334 final ArrayList<TaskRecord> mRecentTasks = new ArrayList<TaskRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800335
336 /**
Dianne Hackborn7d608422011-08-07 16:24:18 -0700337 * Process management.
338 */
339 final ProcessList mProcessList = new ProcessList();
340
341 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800342 * All of the applications we currently have running organized by name.
343 * The keys are strings of the application package name (as
344 * returned by the package manager), and the keys are ApplicationRecord
345 * objects.
346 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700347 final ProcessMap<ProcessRecord> mProcessNames = new ProcessMap<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800348
349 /**
Dianne Hackborna0c283e2012-02-09 10:47:01 -0800350 * The currently running isolated processes.
351 */
352 final SparseArray<ProcessRecord> mIsolatedProcesses = new SparseArray<ProcessRecord>();
353
354 /**
355 * Counter for assigning isolated process uids, to avoid frequently reusing the
356 * same ones.
357 */
358 int mNextIsolatedProcessUid = 0;
359
360 /**
Dianne Hackborn860755f2010-06-03 18:47:52 -0700361 * The currently running heavy-weight process, if any.
362 */
363 ProcessRecord mHeavyWeightProcess = null;
364
365 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800366 * The last time that various processes have crashed.
367 */
368 final ProcessMap<Long> mProcessCrashTimes = new ProcessMap<Long>();
369
370 /**
371 * Set of applications that we consider to be bad, and will reject
372 * incoming broadcasts from (which the user has no control over).
373 * Processes are added to this set when they have crashed twice within
374 * a minimum amount of time; they are removed from it when they are
375 * later restarted (hopefully due to some user action). The value is the
376 * time it was added to the list.
377 */
378 final ProcessMap<Long> mBadProcesses = new ProcessMap<Long>();
379
380 /**
381 * All of the processes we currently have running organized by pid.
382 * The keys are the pid running the application.
383 *
384 * <p>NOTE: This object is protected by its own lock, NOT the global
385 * activity manager lock!
386 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700387 final SparseArray<ProcessRecord> mPidsSelfLocked = new SparseArray<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800388
389 /**
390 * All of the processes that have been forced to be foreground. The key
391 * is the pid of the caller who requested it (we hold a death
392 * link on it).
393 */
394 abstract class ForegroundToken implements IBinder.DeathRecipient {
395 int pid;
396 IBinder token;
397 }
398 final SparseArray<ForegroundToken> mForegroundProcesses
399 = new SparseArray<ForegroundToken>();
400
401 /**
402 * List of records for processes that someone had tried to start before the
403 * system was ready. We don't start them at that point, but ensure they
404 * are started by the time booting is complete.
405 */
406 final ArrayList<ProcessRecord> mProcessesOnHold
407 = new ArrayList<ProcessRecord>();
408
409 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800410 * List of persistent applications that are in the process
411 * of being started.
412 */
413 final ArrayList<ProcessRecord> mPersistentStartingProcesses
414 = new ArrayList<ProcessRecord>();
415
416 /**
417 * Processes that are being forcibly torn down.
418 */
419 final ArrayList<ProcessRecord> mRemovedProcesses
420 = new ArrayList<ProcessRecord>();
421
422 /**
423 * List of running applications, sorted by recent usage.
424 * The first entry in the list is the least recently used.
425 * It contains ApplicationRecord objects. This list does NOT include
426 * any persistent application records (since we never want to exit them).
427 */
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800428 final ArrayList<ProcessRecord> mLruProcesses
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800429 = new ArrayList<ProcessRecord>();
430
431 /**
432 * List of processes that should gc as soon as things are idle.
433 */
434 final ArrayList<ProcessRecord> mProcessesToGc
435 = new ArrayList<ProcessRecord>();
436
437 /**
The Android Open Source Project4df24232009-03-05 14:34:35 -0800438 * This is the process holding what we currently consider to be
439 * the "home" activity.
440 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700441 ProcessRecord mHomeProcess;
The Android Open Source Project4df24232009-03-05 14:34:35 -0800442
443 /**
Dianne Hackbornf35fe232011-11-01 19:25:20 -0700444 * This is the process holding the activity the user last visited that
445 * is in a different process from the one they are currently in.
446 */
447 ProcessRecord mPreviousProcess;
Dianne Hackborn50685602011-12-01 12:23:37 -0800448
449 /**
450 * The time at which the previous process was last visible.
451 */
452 long mPreviousProcessVisibleTime;
453
Dianne Hackbornf35fe232011-11-01 19:25:20 -0700454 /**
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400455 * Packages that the user has asked to have run in screen size
456 * compatibility mode instead of filling the screen.
457 */
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -0700458 final CompatModePackages mCompatModePackages;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400459
460 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800461 * Set of PendingResultRecord objects that are currently active.
462 */
463 final HashSet mPendingResultRecords = new HashSet();
464
465 /**
466 * Set of IntentSenderRecord objects that are currently active.
467 */
468 final HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>> mIntentSenderRecords
469 = new HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>>();
470
471 /**
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -0800472 * Fingerprints (hashCode()) of stack traces that we've
Brad Fitzpatrick143666f2010-06-14 12:40:21 -0700473 * already logged DropBox entries for. Guarded by itself. If
474 * something (rogue user app) forces this over
475 * MAX_DUP_SUPPRESSED_STACKS entries, the contents are cleared.
476 */
477 private final HashSet<Integer> mAlreadyLoggedViolatedStacks = new HashSet<Integer>();
478 private static final int MAX_DUP_SUPPRESSED_STACKS = 5000;
479
480 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -0700481 * Strict Mode background batched logging state.
482 *
483 * The string buffer is guarded by itself, and its lock is also
484 * used to determine if another batched write is already
485 * in-flight.
486 */
487 private final StringBuilder mStrictModeBuffer = new StringBuilder();
488
489 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800490 * Keeps track of all IIntentReceivers that have been registered for
491 * broadcasts. Hash keys are the receiver IBinder, hash value is
492 * a ReceiverList.
493 */
494 final HashMap mRegisteredReceivers = new HashMap();
495
496 /**
497 * Resolver for broadcast intents to registered receivers.
498 * Holds BroadcastFilter (subclass of IntentFilter).
499 */
500 final IntentResolver<BroadcastFilter, BroadcastFilter> mReceiverResolver
501 = new IntentResolver<BroadcastFilter, BroadcastFilter>() {
502 @Override
503 protected boolean allowFilterResult(
504 BroadcastFilter filter, List<BroadcastFilter> dest) {
505 IBinder target = filter.receiverList.receiver.asBinder();
506 for (int i=dest.size()-1; i>=0; i--) {
507 if (dest.get(i).receiverList.receiver.asBinder() == target) {
508 return false;
509 }
510 }
511 return true;
512 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700513
514 @Override
515 protected String packageForFilter(BroadcastFilter filter) {
516 return filter.packageName;
517 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800518 };
519
520 /**
521 * State of all active sticky broadcasts. Keys are the action of the
522 * sticky Intent, values are an ArrayList of all broadcasted intents with
523 * that action (which should usually be one).
524 */
525 final HashMap<String, ArrayList<Intent>> mStickyBroadcasts =
526 new HashMap<String, ArrayList<Intent>>();
527
Amith Yamasani742a6712011-05-04 14:49:28 -0700528 final ServiceMap mServiceMap = new ServiceMap();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800529
530 /**
531 * All currently bound service connections. Keys are the IBinder of
532 * the client's IServiceConnection.
533 */
Dianne Hackborn43d9ac82010-08-25 15:06:25 -0700534 final HashMap<IBinder, ArrayList<ConnectionRecord>> mServiceConnections
535 = new HashMap<IBinder, ArrayList<ConnectionRecord>>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800536
537 /**
538 * List of services that we have been asked to start,
539 * but haven't yet been able to. It is used to hold start requests
540 * while waiting for their corresponding application thread to get
541 * going.
542 */
543 final ArrayList<ServiceRecord> mPendingServices
544 = new ArrayList<ServiceRecord>();
545
546 /**
547 * List of services that are scheduled to restart following a crash.
548 */
549 final ArrayList<ServiceRecord> mRestartingServices
550 = new ArrayList<ServiceRecord>();
551
552 /**
553 * List of services that are in the process of being stopped.
554 */
555 final ArrayList<ServiceRecord> mStoppingServices
556 = new ArrayList<ServiceRecord>();
557
558 /**
Christopher Tate181fafa2009-05-14 11:12:14 -0700559 * Backup/restore process management
560 */
561 String mBackupAppName = null;
562 BackupRecord mBackupTarget = null;
563
564 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800565 * List of PendingThumbnailsRecord objects of clients who are still
566 * waiting to receive all of the thumbnails for a task.
567 */
568 final ArrayList mPendingThumbnails = new ArrayList();
569
570 /**
571 * List of HistoryRecord objects that have been finished and must
572 * still report back to a pending thumbnail receiver.
573 */
574 final ArrayList mCancelledThumbnails = new ArrayList();
575
Amith Yamasani742a6712011-05-04 14:49:28 -0700576 final ProviderMap mProviderMap = new ProviderMap();
577
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800578 /**
579 * List of content providers who have clients waiting for them. The
580 * application is currently being launched and the provider will be
581 * removed from this list once it is published.
582 */
Dianne Hackborn860755f2010-06-03 18:47:52 -0700583 final ArrayList<ContentProviderRecord> mLaunchingProviders
584 = new ArrayList<ContentProviderRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800585
586 /**
587 * Global set of specific Uri permissions that have been granted.
588 */
589 final private SparseArray<HashMap<Uri, UriPermission>> mGrantedUriPermissions
590 = new SparseArray<HashMap<Uri, UriPermission>>();
591
Svetoslav Ganov54d068e2011-03-02 12:58:40 -0800592 CoreSettingsObserver mCoreSettingsObserver;
593
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800594 /**
595 * Thread-local storage used to carry caller permissions over through
596 * indirect content-provider access.
597 * @see #ActivityManagerService.openContentUri()
598 */
599 private class Identity {
600 public int pid;
601 public int uid;
602
603 Identity(int _pid, int _uid) {
604 pid = _pid;
605 uid = _uid;
606 }
607 }
Amith Yamasani742a6712011-05-04 14:49:28 -0700608
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800609 private static ThreadLocal<Identity> sCallerIdentity = new ThreadLocal<Identity>();
610
611 /**
612 * All information we have collected about the runtime performance of
613 * any user id that can impact battery performance.
614 */
615 final BatteryStatsService mBatteryStatsService;
616
617 /**
618 * information about component usage
619 */
620 final UsageStatsService mUsageStatsService;
621
622 /**
623 * Current configuration information. HistoryRecord objects are given
624 * a reference to this object to indicate which configuration they are
625 * currently running in, so this object must be kept immutable.
626 */
627 Configuration mConfiguration = new Configuration();
628
629 /**
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800630 * Current sequencing integer of the configuration, for skipping old
631 * configurations.
632 */
633 int mConfigurationSeq = 0;
634
635 /**
Jack Palevichb90d28c2009-07-22 15:35:24 -0700636 * Hardware-reported OpenGLES version.
637 */
638 final int GL_ES_VERSION;
639
640 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800641 * List of initialization arguments to pass to all processes when binding applications to them.
642 * For example, references to the commonly used services.
643 */
644 HashMap<String, IBinder> mAppBindArgs;
645
646 /**
Dianne Hackbornf210d6b2009-04-13 18:42:49 -0700647 * Temporary to avoid allocations. Protected by main lock.
648 */
649 final StringBuilder mStringBuilder = new StringBuilder(256);
650
651 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800652 * Used to control how we initialize the service.
653 */
654 boolean mStartRunning = false;
655 ComponentName mTopComponent;
656 String mTopAction;
657 String mTopData;
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700658 boolean mProcessesReady = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800659 boolean mSystemReady = false;
660 boolean mBooting = false;
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700661 boolean mWaitingUpdate = false;
662 boolean mDidUpdate = false;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700663 boolean mOnBattery = false;
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700664 boolean mLaunchWarningShown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800665
666 Context mContext;
667
668 int mFactoryTest;
669
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -0700670 boolean mCheckedForSetup;
671
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800672 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700673 * The time at which we will allow normal application switches again,
674 * after a call to {@link #stopAppSwitches()}.
675 */
676 long mAppSwitchesAllowedTime;
677
678 /**
679 * This is set to true after the first switch after mAppSwitchesAllowedTime
680 * is set; any switches after that will clear the time.
681 */
682 boolean mDidAppSwitch;
683
684 /**
Dianne Hackborn287952c2010-09-22 22:34:31 -0700685 * Last time (in realtime) at which we checked for power usage.
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700686 */
Dianne Hackborn287952c2010-09-22 22:34:31 -0700687 long mLastPowerCheckRealtime;
688
689 /**
690 * Last time (in uptime) at which we checked for power usage.
691 */
692 long mLastPowerCheckUptime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700693
694 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800695 * Set while we are wanting to sleep, to prevent any
696 * activities from being started/resumed.
697 */
698 boolean mSleeping = false;
699
700 /**
Dianne Hackborn55280a92009-05-07 15:53:46 -0700701 * Set if we are shutting down the system, similar to sleeping.
702 */
703 boolean mShuttingDown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800704
705 /**
706 * Task identifier that activities are currently being started
707 * in. Incremented each time a new task is created.
708 * todo: Replace this with a TokenSpace class that generates non-repeating
709 * integers that won't wrap.
710 */
711 int mCurTask = 1;
712
713 /**
714 * Current sequence id for oom_adj computation traversal.
715 */
716 int mAdjSeq = 0;
717
718 /**
Dianne Hackborn906497c2010-05-10 15:57:38 -0700719 * Current sequence id for process LRU updating.
720 */
721 int mLruSeq = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800722
723 /**
Dianne Hackborne02c88a2011-10-28 13:58:15 -0700724 * Keep track of the number of service processes we last found, to
725 * determine on the next iteration which should be B services.
726 */
727 int mNumServiceProcs = 0;
728 int mNewNumServiceProcs = 0;
729
730 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800731 * System monitoring: number of processes that died since the last
732 * N procs were started.
733 */
734 int[] mProcDeaths = new int[20];
735
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700736 /**
737 * This is set if we had to do a delayed dexopt of an app before launching
738 * it, to increasing the ANR timeouts in that case.
739 */
740 boolean mDidDexOpt;
741
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800742 String mDebugApp = null;
743 boolean mWaitForDebugger = false;
744 boolean mDebugTransient = false;
745 String mOrigDebugApp = null;
746 boolean mOrigWaitForDebugger = false;
747 boolean mAlwaysFinishActivities = false;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700748 IActivityController mController = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700749 String mProfileApp = null;
750 ProcessRecord mProfileProc = null;
751 String mProfileFile;
752 ParcelFileDescriptor mProfileFd;
753 int mProfileType = 0;
754 boolean mAutoStopProfiler = false;
Siva Velusamy92a8b222012-03-09 16:24:04 -0800755 String mOpenGlTraceApp = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800756
Jeff Sharkeya4620792011-05-20 15:29:23 -0700757 final RemoteCallbackList<IProcessObserver> mProcessObservers
758 = new RemoteCallbackList<IProcessObserver>();
759
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800760 /**
761 * Callback of last caller to {@link #requestPss}.
762 */
763 Runnable mRequestPssCallback;
764
765 /**
766 * Remaining processes for which we are waiting results from the last
767 * call to {@link #requestPss}.
768 */
769 final ArrayList<ProcessRecord> mRequestPssList
770 = new ArrayList<ProcessRecord>();
771
772 /**
773 * Runtime statistics collection thread. This object's lock is used to
774 * protect all related state.
775 */
776 final Thread mProcessStatsThread;
777
778 /**
779 * Used to collect process stats when showing not responding dialog.
780 * Protected by mProcessStatsThread.
781 */
782 final ProcessStats mProcessStats = new ProcessStats(
783 MONITOR_THREAD_CPU_USAGE);
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700784 final AtomicLong mLastCpuTime = new AtomicLong(0);
785 final AtomicBoolean mProcessStatsMutexFree = new AtomicBoolean(true);
786
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800787 long mLastWriteTime = 0;
788
789 /**
790 * Set to true after the system has finished booting.
791 */
792 boolean mBooted = false;
793
Dianne Hackborn7d608422011-08-07 16:24:18 -0700794 int mProcessLimit = ProcessList.MAX_HIDDEN_APPS;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700795 int mProcessLimitOverride = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800796
797 WindowManagerService mWindowManager;
798
799 static ActivityManagerService mSelf;
800 static ActivityThread mSystemThread;
801
802 private final class AppDeathRecipient implements IBinder.DeathRecipient {
803 final ProcessRecord mApp;
804 final int mPid;
805 final IApplicationThread mAppThread;
806
807 AppDeathRecipient(ProcessRecord app, int pid,
808 IApplicationThread thread) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800809 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800810 TAG, "New death recipient " + this
811 + " for thread " + thread.asBinder());
812 mApp = app;
813 mPid = pid;
814 mAppThread = thread;
815 }
816
817 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800818 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800819 TAG, "Death received in " + this
820 + " for thread " + mAppThread.asBinder());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800821 synchronized(ActivityManagerService.this) {
822 appDiedLocked(mApp, mPid, mAppThread);
823 }
824 }
825 }
826
827 static final int SHOW_ERROR_MSG = 1;
828 static final int SHOW_NOT_RESPONDING_MSG = 2;
829 static final int SHOW_FACTORY_ERROR_MSG = 3;
830 static final int UPDATE_CONFIGURATION_MSG = 4;
831 static final int GC_BACKGROUND_PROCESSES_MSG = 5;
832 static final int WAIT_FOR_DEBUGGER_MSG = 6;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800833 static final int SERVICE_TIMEOUT_MSG = 12;
834 static final int UPDATE_TIME_ZONE = 13;
835 static final int SHOW_UID_ERROR_MSG = 14;
836 static final int IM_FEELING_LUCKY_MSG = 15;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800837 static final int PROC_START_TIMEOUT_MSG = 20;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700838 static final int DO_PENDING_ACTIVITY_LAUNCHES_MSG = 21;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -0700839 static final int KILL_APPLICATION_MSG = 22;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800840 static final int FINALIZE_PENDING_INTENT_MSG = 23;
Dianne Hackborn860755f2010-06-03 18:47:52 -0700841 static final int POST_HEAVY_NOTIFICATION_MSG = 24;
842 static final int CANCEL_HEAVY_NOTIFICATION_MSG = 25;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700843 static final int SHOW_STRICT_MODE_VIOLATION_MSG = 26;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700844 static final int CHECK_EXCESSIVE_WAKE_LOCKS_MSG = 27;
Robert Greenwalt03595d02010-11-02 14:08:23 -0700845 static final int CLEAR_DNS_CACHE = 28;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700846 static final int UPDATE_HTTP_PROXY = 29;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700847 static final int SHOW_COMPAT_MODE_DIALOG_MSG = 30;
Dianne Hackborn36f80f32011-05-31 18:26:45 -0700848 static final int DISPATCH_FOREGROUND_ACTIVITIES_CHANGED = 31;
849 static final int DISPATCH_PROCESS_DIED = 32;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700850 static final int REPORT_MEM_USAGE = 33;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800851
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800852 static final int FIRST_ACTIVITY_STACK_MSG = 100;
853 static final int FIRST_BROADCAST_QUEUE_MSG = 200;
854 static final int FIRST_COMPAT_MODE_MSG = 300;
855
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800856 AlertDialog mUidAlert;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700857 CompatModeDialog mCompatModeDialog;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700858 long mLastMemUsageReportTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800859
860 final Handler mHandler = new Handler() {
861 //public Handler() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800862 // if (localLOGV) Slog.v(TAG, "Handler started!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800863 //}
864
865 public void handleMessage(Message msg) {
866 switch (msg.what) {
867 case SHOW_ERROR_MSG: {
868 HashMap data = (HashMap) msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800869 synchronized (ActivityManagerService.this) {
870 ProcessRecord proc = (ProcessRecord)data.get("app");
871 if (proc != null && proc.crashDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800872 Slog.e(TAG, "App already has crash dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800873 return;
874 }
875 AppErrorResult res = (AppErrorResult) data.get("result");
Joe Onorato54a4a412011-11-02 20:50:08 -0700876 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Dan Egnorb7f03672009-12-09 16:22:32 -0800877 Dialog d = new AppErrorDialog(mContext, res, proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800878 d.show();
879 proc.crashDialog = d;
880 } else {
881 // The device is asleep, so just pretend that the user
882 // saw a crash dialog and hit "force quit".
883 res.set(0);
884 }
885 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700886
887 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800888 } break;
889 case SHOW_NOT_RESPONDING_MSG: {
890 synchronized (ActivityManagerService.this) {
891 HashMap data = (HashMap) msg.obj;
892 ProcessRecord proc = (ProcessRecord)data.get("app");
893 if (proc != null && proc.anrDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800894 Slog.e(TAG, "App already has anr dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800895 return;
896 }
The Android Open Source Project4df24232009-03-05 14:34:35 -0800897
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700898 Intent intent = new Intent("android.intent.action.ANR");
899 if (!mProcessesReady) {
Christopher Tatef46723b2012-01-26 14:19:24 -0800900 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
901 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700902 }
903 broadcastIntentLocked(null, null, intent,
The Android Open Source Project4df24232009-03-05 14:34:35 -0800904 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -0700905 false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
The Android Open Source Project4df24232009-03-05 14:34:35 -0800906
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800907 Dialog d = new AppNotRespondingDialog(ActivityManagerService.this,
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700908 mContext, proc, (ActivityRecord)data.get("activity"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800909 d.show();
910 proc.anrDialog = d;
911 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700912
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700913 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800914 } break;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700915 case SHOW_STRICT_MODE_VIOLATION_MSG: {
916 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj;
917 synchronized (ActivityManagerService.this) {
918 ProcessRecord proc = (ProcessRecord) data.get("app");
919 if (proc == null) {
920 Slog.e(TAG, "App not found when showing strict mode dialog.");
921 break;
922 }
923 if (proc.crashDialog != null) {
924 Slog.e(TAG, "App already has strict mode dialog: " + proc);
925 return;
926 }
927 AppErrorResult res = (AppErrorResult) data.get("result");
Joe Onorato54a4a412011-11-02 20:50:08 -0700928 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700929 Dialog d = new StrictModeViolationDialog(mContext, res, proc);
930 d.show();
931 proc.crashDialog = d;
932 } else {
933 // The device is asleep, so just pretend that the user
934 // saw a crash dialog and hit "force quit".
935 res.set(0);
936 }
937 }
938 ensureBootCompleted();
939 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800940 case SHOW_FACTORY_ERROR_MSG: {
941 Dialog d = new FactoryErrorDialog(
942 mContext, msg.getData().getCharSequence("msg"));
943 d.show();
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700944 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800945 } break;
946 case UPDATE_CONFIGURATION_MSG: {
947 final ContentResolver resolver = mContext.getContentResolver();
948 Settings.System.putConfiguration(resolver, (Configuration)msg.obj);
949 } break;
950 case GC_BACKGROUND_PROCESSES_MSG: {
951 synchronized (ActivityManagerService.this) {
952 performAppGcsIfAppropriateLocked();
953 }
954 } break;
955 case WAIT_FOR_DEBUGGER_MSG: {
956 synchronized (ActivityManagerService.this) {
957 ProcessRecord app = (ProcessRecord)msg.obj;
958 if (msg.arg1 != 0) {
959 if (!app.waitedForDebugger) {
960 Dialog d = new AppWaitingForDebuggerDialog(
961 ActivityManagerService.this,
962 mContext, app);
963 app.waitDialog = d;
964 app.waitedForDebugger = true;
965 d.show();
966 }
967 } else {
968 if (app.waitDialog != null) {
969 app.waitDialog.dismiss();
970 app.waitDialog = null;
971 }
972 }
973 }
974 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800975 case SERVICE_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700976 if (mDidDexOpt) {
977 mDidDexOpt = false;
978 Message nmsg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
979 nmsg.obj = msg.obj;
980 mHandler.sendMessageDelayed(nmsg, SERVICE_TIMEOUT);
981 return;
982 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800983 serviceTimeout((ProcessRecord)msg.obj);
984 } break;
985 case UPDATE_TIME_ZONE: {
986 synchronized (ActivityManagerService.this) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800987 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
988 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800989 if (r.thread != null) {
990 try {
991 r.thread.updateTimeZone();
992 } catch (RemoteException ex) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800993 Slog.w(TAG, "Failed to update time zone for: " + r.info.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800994 }
995 }
996 }
997 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700998 } break;
Robert Greenwalt03595d02010-11-02 14:08:23 -0700999 case CLEAR_DNS_CACHE: {
1000 synchronized (ActivityManagerService.this) {
1001 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1002 ProcessRecord r = mLruProcesses.get(i);
1003 if (r.thread != null) {
1004 try {
1005 r.thread.clearDnsCache();
1006 } catch (RemoteException ex) {
1007 Slog.w(TAG, "Failed to clear dns cache for: " + r.info.processName);
1008 }
1009 }
1010 }
1011 }
1012 } break;
Robert Greenwalt434203a2010-10-11 16:00:27 -07001013 case UPDATE_HTTP_PROXY: {
1014 ProxyProperties proxy = (ProxyProperties)msg.obj;
1015 String host = "";
1016 String port = "";
1017 String exclList = "";
1018 if (proxy != null) {
1019 host = proxy.getHost();
1020 port = Integer.toString(proxy.getPort());
1021 exclList = proxy.getExclusionList();
1022 }
1023 synchronized (ActivityManagerService.this) {
1024 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1025 ProcessRecord r = mLruProcesses.get(i);
1026 if (r.thread != null) {
1027 try {
1028 r.thread.setHttpProxy(host, port, exclList);
1029 } catch (RemoteException ex) {
1030 Slog.w(TAG, "Failed to update http proxy for: " +
1031 r.info.processName);
1032 }
1033 }
1034 }
1035 }
1036 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001037 case SHOW_UID_ERROR_MSG: {
Joe Onorato54a4a412011-11-02 20:50:08 -07001038 String title = "System UIDs Inconsistent";
1039 String text = "UIDs on the system are inconsistent, you need to wipe your"
1040 + " data partition or your device will be unstable.";
1041 Log.e(TAG, title + ": " + text);
1042 if (mShowDialogs) {
1043 // XXX This is a temporary dialog, no need to localize.
1044 AlertDialog d = new BaseErrorDialog(mContext);
1045 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
1046 d.setCancelable(false);
1047 d.setTitle(title);
1048 d.setMessage(text);
1049 d.setButton(DialogInterface.BUTTON_POSITIVE, "I'm Feeling Lucky",
1050 mHandler.obtainMessage(IM_FEELING_LUCKY_MSG));
1051 mUidAlert = d;
1052 d.show();
1053 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001054 } break;
1055 case IM_FEELING_LUCKY_MSG: {
1056 if (mUidAlert != null) {
1057 mUidAlert.dismiss();
1058 mUidAlert = null;
1059 }
1060 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001061 case PROC_START_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001062 if (mDidDexOpt) {
1063 mDidDexOpt = false;
1064 Message nmsg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
1065 nmsg.obj = msg.obj;
1066 mHandler.sendMessageDelayed(nmsg, PROC_START_TIMEOUT);
1067 return;
1068 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001069 ProcessRecord app = (ProcessRecord)msg.obj;
1070 synchronized (ActivityManagerService.this) {
1071 processStartTimedOutLocked(app);
1072 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001073 } break;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07001074 case DO_PENDING_ACTIVITY_LAUNCHES_MSG: {
1075 synchronized (ActivityManagerService.this) {
1076 doPendingActivityLaunchesLocked(true);
1077 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001078 } break;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001079 case KILL_APPLICATION_MSG: {
1080 synchronized (ActivityManagerService.this) {
1081 int uid = msg.arg1;
1082 boolean restart = (msg.arg2 == 1);
1083 String pkg = (String) msg.obj;
Amith Yamasani483f3b02012-03-13 16:08:00 -07001084 forceStopPackageLocked(pkg, uid, restart, false, true, false,
1085 UserId.getUserId(uid));
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001086 }
1087 } break;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001088 case FINALIZE_PENDING_INTENT_MSG: {
1089 ((PendingIntentRecord)msg.obj).completeFinalize();
1090 } break;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001091 case POST_HEAVY_NOTIFICATION_MSG: {
1092 INotificationManager inm = NotificationManager.getService();
1093 if (inm == null) {
1094 return;
1095 }
1096
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001097 ActivityRecord root = (ActivityRecord)msg.obj;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001098 ProcessRecord process = root.app;
1099 if (process == null) {
1100 return;
1101 }
1102
1103 try {
1104 Context context = mContext.createPackageContext(process.info.packageName, 0);
1105 String text = mContext.getString(R.string.heavy_weight_notification,
1106 context.getApplicationInfo().loadLabel(context.getPackageManager()));
1107 Notification notification = new Notification();
1108 notification.icon = com.android.internal.R.drawable.stat_sys_adb; //context.getApplicationInfo().icon;
1109 notification.when = 0;
1110 notification.flags = Notification.FLAG_ONGOING_EVENT;
1111 notification.tickerText = text;
1112 notification.defaults = 0; // please be quiet
1113 notification.sound = null;
1114 notification.vibrate = null;
1115 notification.setLatestEventInfo(context, text,
1116 mContext.getText(R.string.heavy_weight_notification_detail),
1117 PendingIntent.getActivity(mContext, 0, root.intent,
1118 PendingIntent.FLAG_CANCEL_CURRENT));
1119
1120 try {
1121 int[] outId = new int[1];
1122 inm.enqueueNotification("android", R.string.heavy_weight_notification,
1123 notification, outId);
1124 } catch (RuntimeException e) {
1125 Slog.w(ActivityManagerService.TAG,
1126 "Error showing notification for heavy-weight app", e);
1127 } catch (RemoteException e) {
1128 }
1129 } catch (NameNotFoundException e) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07001130 Slog.w(TAG, "Unable to create context for heavy notification", e);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001131 }
1132 } break;
1133 case CANCEL_HEAVY_NOTIFICATION_MSG: {
1134 INotificationManager inm = NotificationManager.getService();
1135 if (inm == null) {
1136 return;
1137 }
1138 try {
1139 inm.cancelNotification("android",
1140 R.string.heavy_weight_notification);
1141 } catch (RuntimeException e) {
1142 Slog.w(ActivityManagerService.TAG,
1143 "Error canceling notification for service", e);
1144 } catch (RemoteException e) {
1145 }
1146 } break;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001147 case CHECK_EXCESSIVE_WAKE_LOCKS_MSG: {
1148 synchronized (ActivityManagerService.this) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001149 checkExcessivePowerUsageLocked(true);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07001150 removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001151 Message nmsg = obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
1152 sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001153 }
1154 } break;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001155 case SHOW_COMPAT_MODE_DIALOG_MSG: {
1156 synchronized (ActivityManagerService.this) {
1157 ActivityRecord ar = (ActivityRecord)msg.obj;
1158 if (mCompatModeDialog != null) {
1159 if (mCompatModeDialog.mAppInfo.packageName.equals(
1160 ar.info.applicationInfo.packageName)) {
1161 return;
1162 }
1163 mCompatModeDialog.dismiss();
1164 mCompatModeDialog = null;
1165 }
Dianne Hackborn29478262011-06-07 15:44:22 -07001166 if (ar != null && false) {
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001167 if (mCompatModePackages.getPackageAskCompatModeLocked(
1168 ar.packageName)) {
1169 int mode = mCompatModePackages.computeCompatModeLocked(
1170 ar.info.applicationInfo);
1171 if (mode == ActivityManager.COMPAT_MODE_DISABLED
1172 || mode == ActivityManager.COMPAT_MODE_ENABLED) {
1173 mCompatModeDialog = new CompatModeDialog(
1174 ActivityManagerService.this, mContext,
1175 ar.info.applicationInfo);
1176 mCompatModeDialog.show();
1177 }
1178 }
1179 }
1180 }
Dianne Hackborn36f80f32011-05-31 18:26:45 -07001181 break;
1182 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001183 case DISPATCH_FOREGROUND_ACTIVITIES_CHANGED: {
Jeff Sharkey287bd832011-05-28 19:36:26 -07001184 final int pid = msg.arg1;
1185 final int uid = msg.arg2;
1186 final boolean foregroundActivities = (Boolean) msg.obj;
1187 dispatchForegroundActivitiesChanged(pid, uid, foregroundActivities);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001188 break;
1189 }
1190 case DISPATCH_PROCESS_DIED: {
Jeff Sharkey287bd832011-05-28 19:36:26 -07001191 final int pid = msg.arg1;
1192 final int uid = msg.arg2;
1193 dispatchProcessDied(pid, uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001194 break;
1195 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001196 case REPORT_MEM_USAGE: {
1197 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
1198 if (!isDebuggable) {
1199 return;
1200 }
1201 synchronized (ActivityManagerService.this) {
1202 long now = SystemClock.uptimeMillis();
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001203 if (now < (mLastMemUsageReportTime+5*60*1000)) {
1204 // Don't report more than every 5 minutes to somewhat
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001205 // avoid spamming.
1206 return;
1207 }
1208 mLastMemUsageReportTime = now;
1209 }
1210 Thread thread = new Thread() {
1211 @Override public void run() {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001212 StringBuilder dropBuilder = new StringBuilder(1024);
1213 StringBuilder logBuilder = new StringBuilder(1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -08001214 StringWriter oomSw = new StringWriter();
1215 PrintWriter oomPw = new PrintWriter(oomSw);
1216 StringWriter catSw = new StringWriter();
1217 PrintWriter catPw = new PrintWriter(catSw);
1218 String[] emptyArgs = new String[] { };
1219 StringBuilder tag = new StringBuilder(128);
1220 StringBuilder stack = new StringBuilder(128);
1221 tag.append("Low on memory -- ");
1222 dumpApplicationMemoryUsage(null, oomPw, " ", emptyArgs, true, catPw,
1223 tag, stack);
1224 dropBuilder.append(stack);
1225 dropBuilder.append('\n');
1226 dropBuilder.append('\n');
1227 String oomString = oomSw.toString();
1228 dropBuilder.append(oomString);
1229 dropBuilder.append('\n');
1230 logBuilder.append(oomString);
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001231 try {
1232 java.lang.Process proc = Runtime.getRuntime().exec(new String[] {
1233 "procrank", });
1234 final InputStreamReader converter = new InputStreamReader(
1235 proc.getInputStream());
1236 BufferedReader in = new BufferedReader(converter);
1237 String line;
1238 while (true) {
1239 line = in.readLine();
1240 if (line == null) {
1241 break;
1242 }
1243 if (line.length() > 0) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001244 logBuilder.append(line);
1245 logBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001246 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001247 dropBuilder.append(line);
1248 dropBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001249 }
1250 converter.close();
1251 } catch (IOException e) {
1252 }
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001253 synchronized (ActivityManagerService.this) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08001254 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001255 dumpProcessesLocked(null, catPw, emptyArgs, 0, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001256 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001257 dumpServicesLocked(null, catPw, emptyArgs, 0, false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001258 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001259 dumpActivitiesLocked(null, catPw, emptyArgs, 0, false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001260 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001261 dropBuilder.append(catSw.toString());
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001262 addErrorToDropBox("lowmem", null, "system_server", null,
1263 null, tag.toString(), dropBuilder.toString(), null, null);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001264 Slog.i(TAG, logBuilder.toString());
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001265 synchronized (ActivityManagerService.this) {
1266 long now = SystemClock.uptimeMillis();
1267 if (mLastMemUsageReportTime < now) {
1268 mLastMemUsageReportTime = now;
1269 }
1270 }
1271 }
1272 };
1273 thread.start();
1274 break;
1275 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001276 }
1277 }
1278 };
1279
1280 public static void setSystemProcess() {
1281 try {
1282 ActivityManagerService m = mSelf;
1283
Dianne Hackborna573f6a2012-02-09 16:12:18 -08001284 ServiceManager.addService("activity", m, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001285 ServiceManager.addService("meminfo", new MemBinder(m));
Chet Haase9c1e23b2011-03-24 10:51:31 -07001286 ServiceManager.addService("gfxinfo", new GraphicsBinder(m));
Jeff Brown6754ba22011-12-14 20:20:01 -08001287 ServiceManager.addService("dbinfo", new DbBinder(m));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001288 if (MONITOR_CPU_USAGE) {
1289 ServiceManager.addService("cpuinfo", new CpuBinder(m));
1290 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001291 ServiceManager.addService("permission", new PermissionController(m));
1292
1293 ApplicationInfo info =
1294 mSelf.mContext.getPackageManager().getApplicationInfo(
Amith Yamasani483f3b02012-03-13 16:08:00 -07001295 "android", STOCK_PM_FLAGS);
Mike Cleron432b7132009-09-24 15:28:29 -07001296 mSystemThread.installSystemApplicationInfo(info);
1297
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001298 synchronized (mSelf) {
1299 ProcessRecord app = mSelf.newProcessRecordLocked(
1300 mSystemThread.getApplicationThread(), info,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001301 info.processName, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001302 app.persistent = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08001303 app.pid = MY_PID;
Dianne Hackborn7d608422011-08-07 16:24:18 -07001304 app.maxAdj = ProcessList.SYSTEM_ADJ;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001305 mSelf.mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001306 synchronized (mSelf.mPidsSelfLocked) {
1307 mSelf.mPidsSelfLocked.put(app.pid, app);
1308 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001309 mSelf.updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001310 }
1311 } catch (PackageManager.NameNotFoundException e) {
1312 throw new RuntimeException(
1313 "Unable to find android system package", e);
1314 }
1315 }
1316
1317 public void setWindowManager(WindowManagerService wm) {
1318 mWindowManager = wm;
1319 }
1320
1321 public static final Context main(int factoryTest) {
1322 AThread thr = new AThread();
1323 thr.start();
1324
1325 synchronized (thr) {
1326 while (thr.mService == null) {
1327 try {
1328 thr.wait();
1329 } catch (InterruptedException e) {
1330 }
1331 }
1332 }
1333
1334 ActivityManagerService m = thr.mService;
1335 mSelf = m;
1336 ActivityThread at = ActivityThread.systemMain();
1337 mSystemThread = at;
1338 Context context = at.getSystemContext();
Dianne Hackborn247fe742011-01-08 17:25:57 -08001339 context.setTheme(android.R.style.Theme_Holo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001340 m.mContext = context;
1341 m.mFactoryTest = factoryTest;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001342 m.mMainStack = new ActivityStack(m, context, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001343
1344 m.mBatteryStatsService.publish(context);
1345 m.mUsageStatsService.publish(context);
1346
1347 synchronized (thr) {
1348 thr.mReady = true;
1349 thr.notifyAll();
1350 }
1351
1352 m.startRunning(null, null, null, null);
1353
1354 return context;
1355 }
1356
1357 public static ActivityManagerService self() {
1358 return mSelf;
1359 }
1360
1361 static class AThread extends Thread {
1362 ActivityManagerService mService;
1363 boolean mReady = false;
1364
1365 public AThread() {
1366 super("ActivityManager");
1367 }
1368
1369 public void run() {
1370 Looper.prepare();
1371
1372 android.os.Process.setThreadPriority(
1373 android.os.Process.THREAD_PRIORITY_FOREGROUND);
Christopher Tate160edb32010-06-30 17:46:30 -07001374 android.os.Process.setCanSelfBackground(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001375
1376 ActivityManagerService m = new ActivityManagerService();
1377
1378 synchronized (this) {
1379 mService = m;
1380 notifyAll();
1381 }
1382
1383 synchronized (this) {
1384 while (!mReady) {
1385 try {
1386 wait();
1387 } catch (InterruptedException e) {
1388 }
1389 }
1390 }
1391
Brad Fitzpatrickec062f62010-11-03 09:56:54 -07001392 // For debug builds, log event loop stalls to dropbox for analysis.
1393 if (StrictMode.conditionallyEnableDebugLogging()) {
1394 Slog.i(TAG, "Enabled StrictMode logging for AThread's Looper");
1395 }
1396
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001397 Looper.loop();
1398 }
1399 }
1400
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001401 static class MemBinder extends Binder {
1402 ActivityManagerService mActivityManagerService;
1403 MemBinder(ActivityManagerService activityManagerService) {
1404 mActivityManagerService = activityManagerService;
1405 }
1406
1407 @Override
1408 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001409 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1410 != PackageManager.PERMISSION_GRANTED) {
1411 pw.println("Permission Denial: can't dump meminfo from from pid="
1412 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1413 + " without permission " + android.Manifest.permission.DUMP);
1414 return;
1415 }
1416
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001417 mActivityManagerService.dumpApplicationMemoryUsage(fd, pw, " ", args,
Dianne Hackborn672342c2011-11-29 11:29:02 -08001418 false, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001419 }
1420 }
1421
Chet Haase9c1e23b2011-03-24 10:51:31 -07001422 static class GraphicsBinder extends Binder {
1423 ActivityManagerService mActivityManagerService;
1424 GraphicsBinder(ActivityManagerService activityManagerService) {
1425 mActivityManagerService = activityManagerService;
1426 }
1427
1428 @Override
1429 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001430 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1431 != PackageManager.PERMISSION_GRANTED) {
1432 pw.println("Permission Denial: can't dump gfxinfo from from pid="
1433 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1434 + " without permission " + android.Manifest.permission.DUMP);
1435 return;
1436 }
1437
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001438 mActivityManagerService.dumpGraphicsHardwareUsage(fd, pw, args);
Chet Haase9c1e23b2011-03-24 10:51:31 -07001439 }
1440 }
1441
Jeff Brown6754ba22011-12-14 20:20:01 -08001442 static class DbBinder extends Binder {
1443 ActivityManagerService mActivityManagerService;
1444 DbBinder(ActivityManagerService activityManagerService) {
1445 mActivityManagerService = activityManagerService;
1446 }
1447
1448 @Override
1449 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1450 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1451 != PackageManager.PERMISSION_GRANTED) {
1452 pw.println("Permission Denial: can't dump dbinfo from from pid="
1453 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1454 + " without permission " + android.Manifest.permission.DUMP);
1455 return;
1456 }
1457
1458 mActivityManagerService.dumpDbInfo(fd, pw, args);
1459 }
1460 }
1461
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001462 static class CpuBinder extends Binder {
1463 ActivityManagerService mActivityManagerService;
1464 CpuBinder(ActivityManagerService activityManagerService) {
1465 mActivityManagerService = activityManagerService;
1466 }
1467
1468 @Override
1469 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001470 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1471 != PackageManager.PERMISSION_GRANTED) {
1472 pw.println("Permission Denial: can't dump cpuinfo from from pid="
1473 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1474 + " without permission " + android.Manifest.permission.DUMP);
1475 return;
1476 }
1477
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001478 synchronized (mActivityManagerService.mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07001479 pw.print(mActivityManagerService.mProcessStats.printCurrentLoad());
1480 pw.print(mActivityManagerService.mProcessStats.printCurrentState(
1481 SystemClock.uptimeMillis()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001482 }
1483 }
1484 }
1485
1486 private ActivityManagerService() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001487 Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
Dianne Hackborn2c6c5e62009-10-08 17:55:49 -07001488
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001489 mFgBroadcastQueue = new BroadcastQueue(this, "foreground", BROADCAST_FG_TIMEOUT);
1490 mBgBroadcastQueue = new BroadcastQueue(this, "background", BROADCAST_BG_TIMEOUT);
1491 mBroadcastQueues[0] = mFgBroadcastQueue;
1492 mBroadcastQueues[1] = mBgBroadcastQueue;
1493
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001494 File dataDir = Environment.getDataDirectory();
1495 File systemDir = new File(dataDir, "system");
1496 systemDir.mkdirs();
1497 mBatteryStatsService = new BatteryStatsService(new File(
1498 systemDir, "batterystats.bin").toString());
1499 mBatteryStatsService.getActiveStatistics().readLocked();
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001500 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
Dianne Hackborn287952c2010-09-22 22:34:31 -07001501 mOnBattery = DEBUG_POWER ? true
1502 : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001503 mBatteryStatsService.getActiveStatistics().setCallback(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001504
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001505 mUsageStatsService = new UsageStatsService(new File(
Dianne Hackborn6447ca32009-04-07 19:50:08 -07001506 systemDir, "usagestats").toString());
Mike Lockwood3a74bd32011-08-12 13:55:22 -07001507 mHeadless = "1".equals(SystemProperties.get("ro.config.headless", "0"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001508
Jack Palevichb90d28c2009-07-22 15:35:24 -07001509 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",
1510 ConfigurationInfo.GL_ES_VERSION_UNDEFINED);
1511
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001512 mConfiguration.setToDefaults();
1513 mConfiguration.locale = Locale.getDefault();
Dianne Hackborn813075a62011-11-14 17:45:19 -08001514 mConfigurationSeq = mConfiguration.seq = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001515 mProcessStats.init();
1516
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07001517 mCompatModePackages = new CompatModePackages(this, systemDir);
1518
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001519 // Add ourself to the Watchdog monitors.
1520 Watchdog.getInstance().addMonitor(this);
1521
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001522 mProcessStatsThread = new Thread("ProcessStats") {
1523 public void run() {
1524 while (true) {
1525 try {
1526 try {
1527 synchronized(this) {
1528 final long now = SystemClock.uptimeMillis();
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001529 long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001530 long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001531 //Slog.i(TAG, "Cpu delay=" + nextCpuDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001532 // + ", write delay=" + nextWriteDelay);
1533 if (nextWriteDelay < nextCpuDelay) {
1534 nextCpuDelay = nextWriteDelay;
1535 }
1536 if (nextCpuDelay > 0) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001537 mProcessStatsMutexFree.set(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001538 this.wait(nextCpuDelay);
1539 }
1540 }
1541 } catch (InterruptedException e) {
1542 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001543 updateCpuStatsNow();
1544 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001545 Slog.e(TAG, "Unexpected exception collecting process stats", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001546 }
1547 }
1548 }
1549 };
1550 mProcessStatsThread.start();
1551 }
1552
1553 @Override
1554 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1555 throws RemoteException {
1556 try {
1557 return super.onTransact(code, data, reply, flags);
1558 } catch (RuntimeException e) {
1559 // The activity manager only throws security exceptions, so let's
1560 // log all others.
1561 if (!(e instanceof SecurityException)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001562 Slog.e(TAG, "Activity Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001563 }
1564 throw e;
1565 }
1566 }
1567
1568 void updateCpuStats() {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001569 final long now = SystemClock.uptimeMillis();
1570 if (mLastCpuTime.get() >= now - MONITOR_CPU_MIN_TIME) {
1571 return;
1572 }
1573 if (mProcessStatsMutexFree.compareAndSet(true, false)) {
1574 synchronized (mProcessStatsThread) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001575 mProcessStatsThread.notify();
1576 }
1577 }
1578 }
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001579
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001580 void updateCpuStatsNow() {
1581 synchronized (mProcessStatsThread) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001582 mProcessStatsMutexFree.set(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001583 final long now = SystemClock.uptimeMillis();
1584 boolean haveNewCpuStats = false;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07001585
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001586 if (MONITOR_CPU_USAGE &&
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001587 mLastCpuTime.get() < (now-MONITOR_CPU_MIN_TIME)) {
1588 mLastCpuTime.set(now);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001589 haveNewCpuStats = true;
1590 mProcessStats.update();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001591 //Slog.i(TAG, mProcessStats.printCurrentState());
1592 //Slog.i(TAG, "Total CPU usage: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001593 // + mProcessStats.getTotalCpuPercent() + "%");
1594
Joe Onorato8a9b2202010-02-26 18:56:32 -08001595 // Slog the cpu usage if the property is set.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001596 if ("true".equals(SystemProperties.get("events.cpu"))) {
1597 int user = mProcessStats.getLastUserTime();
1598 int system = mProcessStats.getLastSystemTime();
1599 int iowait = mProcessStats.getLastIoWaitTime();
1600 int irq = mProcessStats.getLastIrqTime();
1601 int softIrq = mProcessStats.getLastSoftIrqTime();
1602 int idle = mProcessStats.getLastIdleTime();
1603
1604 int total = user + system + iowait + irq + softIrq + idle;
1605 if (total == 0) total = 1;
1606
Doug Zongker2bec3d42009-12-04 12:52:44 -08001607 EventLog.writeEvent(EventLogTags.CPU,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001608 ((user+system+iowait+irq+softIrq) * 100) / total,
1609 (user * 100) / total,
1610 (system * 100) / total,
1611 (iowait * 100) / total,
1612 (irq * 100) / total,
1613 (softIrq * 100) / total);
1614 }
1615 }
1616
Amith Yamasanie43530a2009-08-21 13:11:37 -07001617 long[] cpuSpeedTimes = mProcessStats.getLastCpuSpeedTimes();
Amith Yamasani819f9282009-06-24 23:18:15 -07001618 final BatteryStatsImpl bstats = mBatteryStatsService.getActiveStatistics();
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001619 synchronized(bstats) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001620 synchronized(mPidsSelfLocked) {
1621 if (haveNewCpuStats) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001622 if (mOnBattery) {
1623 int perc = bstats.startAddingCpuLocked();
1624 int totalUTime = 0;
1625 int totalSTime = 0;
Dianne Hackborn287952c2010-09-22 22:34:31 -07001626 final int N = mProcessStats.countStats();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001627 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001628 ProcessStats.Stats st = mProcessStats.getStats(i);
1629 if (!st.working) {
1630 continue;
1631 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001632 ProcessRecord pr = mPidsSelfLocked.get(st.pid);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001633 int otherUTime = (st.rel_utime*perc)/100;
1634 int otherSTime = (st.rel_stime*perc)/100;
1635 totalUTime += otherUTime;
1636 totalSTime += otherSTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001637 if (pr != null) {
1638 BatteryStatsImpl.Uid.Proc ps = pr.batteryStats;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001639 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1640 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001641 ps.addSpeedStepTimes(cpuSpeedTimes);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001642 pr.curCpuTime += (st.rel_utime+st.rel_stime) * 10;
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001643 } else {
1644 BatteryStatsImpl.Uid.Proc ps =
Amith Yamasani819f9282009-06-24 23:18:15 -07001645 bstats.getProcessStatsLocked(st.name, st.pid);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001646 if (ps != null) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001647 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1648 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001649 ps.addSpeedStepTimes(cpuSpeedTimes);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001650 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001651 }
1652 }
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001653 bstats.finishAddingCpuLocked(perc, totalUTime,
1654 totalSTime, cpuSpeedTimes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001655 }
1656 }
1657 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001658
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001659 if (mLastWriteTime < (now-BATTERY_STATS_TIME)) {
1660 mLastWriteTime = now;
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001661 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001662 }
1663 }
1664 }
1665 }
1666
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001667 @Override
1668 public void batteryNeedsCpuUpdate() {
1669 updateCpuStatsNow();
1670 }
1671
1672 @Override
1673 public void batteryPowerChanged(boolean onBattery) {
1674 // When plugging in, update the CPU stats first before changing
1675 // the plug state.
1676 updateCpuStatsNow();
1677 synchronized (this) {
1678 synchronized(mPidsSelfLocked) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001679 mOnBattery = DEBUG_POWER ? true : onBattery;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001680 }
1681 }
1682 }
1683
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001684 /**
1685 * Initialize the application bind args. These are passed to each
1686 * process when the bindApplication() IPC is sent to the process. They're
1687 * lazily setup to make sure the services are running when they're asked for.
1688 */
1689 private HashMap<String, IBinder> getCommonServicesLocked() {
1690 if (mAppBindArgs == null) {
1691 mAppBindArgs = new HashMap<String, IBinder>();
1692
1693 // Setup the application init args
1694 mAppBindArgs.put("package", ServiceManager.getService("package"));
1695 mAppBindArgs.put("window", ServiceManager.getService("window"));
1696 mAppBindArgs.put(Context.ALARM_SERVICE,
1697 ServiceManager.getService(Context.ALARM_SERVICE));
1698 }
1699 return mAppBindArgs;
1700 }
1701
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001702 final void setFocusedActivityLocked(ActivityRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001703 if (mFocusedActivity != r) {
1704 mFocusedActivity = r;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001705 if (r != null) {
1706 mWindowManager.setFocusedApp(r.appToken, true);
1707 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001708 }
1709 }
1710
Dianne Hackborn906497c2010-05-10 15:57:38 -07001711 private final void updateLruProcessInternalLocked(ProcessRecord app,
1712 boolean oomAdj, boolean updateActivityTime, int bestPos) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001713 // put it on the LRU to keep track of when it should be exited.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001714 int lrui = mLruProcesses.indexOf(app);
1715 if (lrui >= 0) mLruProcesses.remove(lrui);
1716
1717 int i = mLruProcesses.size()-1;
1718 int skipTop = 0;
1719
Dianne Hackborn906497c2010-05-10 15:57:38 -07001720 app.lruSeq = mLruSeq;
1721
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001722 // compute the new weight for this process.
1723 if (updateActivityTime) {
1724 app.lastActivityTime = SystemClock.uptimeMillis();
1725 }
1726 if (app.activities.size() > 0) {
1727 // If this process has activities, we more strongly want to keep
1728 // it around.
1729 app.lruWeight = app.lastActivityTime;
1730 } else if (app.pubProviders.size() > 0) {
1731 // If this process contains content providers, we want to keep
1732 // it a little more strongly.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001733 app.lruWeight = app.lastActivityTime - ProcessList.CONTENT_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001734 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001735 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001736 } else {
1737 // If this process doesn't have activities, we less strongly
1738 // want to keep it around, and generally want to avoid getting
1739 // in front of any very recently used activities.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001740 app.lruWeight = app.lastActivityTime - ProcessList.EMPTY_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001741 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001742 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001743 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001744
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001745 while (i >= 0) {
1746 ProcessRecord p = mLruProcesses.get(i);
1747 // If this app shouldn't be in front of the first N background
1748 // apps, then skip over that many that are currently hidden.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001749 if (skipTop > 0 && p.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001750 skipTop--;
1751 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001752 if (p.lruWeight <= app.lruWeight || i < bestPos) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001753 mLruProcesses.add(i+1, app);
1754 break;
1755 }
1756 i--;
1757 }
1758 if (i < 0) {
1759 mLruProcesses.add(0, app);
1760 }
1761
Dianne Hackborn906497c2010-05-10 15:57:38 -07001762 // If the app is currently using a content provider or service,
1763 // bump those processes as well.
1764 if (app.connections.size() > 0) {
1765 for (ConnectionRecord cr : app.connections) {
1766 if (cr.binding != null && cr.binding.service != null
1767 && cr.binding.service.app != null
1768 && cr.binding.service.app.lruSeq != mLruSeq) {
1769 updateLruProcessInternalLocked(cr.binding.service.app, oomAdj,
1770 updateActivityTime, i+1);
1771 }
1772 }
1773 }
1774 if (app.conProviders.size() > 0) {
1775 for (ContentProviderRecord cpr : app.conProviders.keySet()) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07001776 if (cpr.proc != null && cpr.proc.lruSeq != mLruSeq) {
1777 updateLruProcessInternalLocked(cpr.proc, oomAdj,
Dianne Hackborn906497c2010-05-10 15:57:38 -07001778 updateActivityTime, i+1);
1779 }
1780 }
1781 }
1782
Joe Onorato8a9b2202010-02-26 18:56:32 -08001783 //Slog.i(TAG, "Putting proc to front: " + app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001784 if (oomAdj) {
1785 updateOomAdjLocked();
1786 }
1787 }
1788
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001789 final void updateLruProcessLocked(ProcessRecord app,
Dianne Hackborn906497c2010-05-10 15:57:38 -07001790 boolean oomAdj, boolean updateActivityTime) {
1791 mLruSeq++;
1792 updateLruProcessInternalLocked(app, oomAdj, updateActivityTime, 0);
1793 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001794
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001795 final ProcessRecord getProcessRecordLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001796 String processName, int uid) {
Amith Yamasani0184ce92012-03-28 22:41:41 -07001797 // Temporary hack to make Settings run per user
1798 if (uid == Process.SYSTEM_UID && !processName.equals("com.android.settings")) {
1799 // The system gets to run in any process. If there are multiple
1800 // processes with the same uid, just pick the first (this
1801 // should never happen).
1802 SparseArray<ProcessRecord> procs = mProcessNames.getMap().get(
1803 processName);
1804 return procs != null ? procs.valueAt(0) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001805 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001806 // uid = applyUserId(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001807 ProcessRecord proc = mProcessNames.get(processName, uid);
1808 return proc;
1809 }
1810
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001811 void ensurePackageDexOpt(String packageName) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001812 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001813 try {
1814 if (pm.performDexOpt(packageName)) {
1815 mDidDexOpt = true;
1816 }
1817 } catch (RemoteException e) {
1818 }
1819 }
1820
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001821 boolean isNextTransitionForward() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001822 int transit = mWindowManager.getPendingAppTransition();
1823 return transit == WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
1824 || transit == WindowManagerPolicy.TRANSIT_TASK_OPEN
1825 || transit == WindowManagerPolicy.TRANSIT_TASK_TO_FRONT;
1826 }
1827
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001828 final ProcessRecord startProcessLocked(String processName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001829 ApplicationInfo info, boolean knownToBeDead, int intentFlags,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001830 String hostingType, ComponentName hostingName, boolean allowWhileBooting,
1831 boolean isolated) {
1832 ProcessRecord app;
1833 if (!isolated) {
1834 app = getProcessRecordLocked(processName, info.uid);
1835 } else {
1836 // If this is an isolated process, it can't re-use an existing process.
1837 app = null;
1838 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001839 // We don't have to do anything more if:
1840 // (1) There is an existing application record; and
1841 // (2) The caller doesn't think it is dead, OR there is no thread
1842 // object attached to it so we know it couldn't have crashed; and
1843 // (3) There is a pid assigned to it, so it is either starting or
1844 // already running.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001845 if (DEBUG_PROCESSES) Slog.v(TAG, "startProcess: name=" + processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001846 + " app=" + app + " knownToBeDead=" + knownToBeDead
1847 + " thread=" + (app != null ? app.thread : null)
1848 + " pid=" + (app != null ? app.pid : -1));
Magnus Edlund7bb25812010-02-24 15:45:06 +01001849 if (app != null && app.pid > 0) {
1850 if (!knownToBeDead || app.thread == null) {
Dianne Hackborn20cb56e2010-03-04 00:58:29 -08001851 // We already have the app running, or are waiting for it to
1852 // come up (we have a pid but not yet its thread), so keep it.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001853 if (DEBUG_PROCESSES) Slog.v(TAG, "App already running: " + app);
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001854 // If this is a new package in the process, add the package to the list
1855 app.addPackage(info.packageName);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001856 return app;
1857 } else {
1858 // An application record is attached to a previous process,
1859 // clean it up now.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001860 if (DEBUG_PROCESSES) Slog.v(TAG, "App died: " + app);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07001861 handleAppDiedLocked(app, true, true);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001862 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001863 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01001864
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001865 String hostingNameStr = hostingName != null
1866 ? hostingName.flattenToShortString() : null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001867
1868 if (!isolated) {
1869 if ((intentFlags&Intent.FLAG_FROM_BACKGROUND) != 0) {
1870 // If we are in the background, then check to see if this process
1871 // is bad. If so, we will just silently fail.
1872 if (mBadProcesses.get(info.processName, info.uid) != null) {
1873 if (DEBUG_PROCESSES) Slog.v(TAG, "Bad process: " + info.uid
1874 + "/" + info.processName);
1875 return null;
1876 }
1877 } else {
1878 // When the user is explicitly starting a process, then clear its
1879 // crash count so that we won't make it bad until they see at
1880 // least one crash dialog again, and make the process good again
1881 // if it had been bad.
1882 if (DEBUG_PROCESSES) Slog.v(TAG, "Clearing bad process: " + info.uid
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001883 + "/" + info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001884 mProcessCrashTimes.remove(info.processName, info.uid);
1885 if (mBadProcesses.get(info.processName, info.uid) != null) {
1886 EventLog.writeEvent(EventLogTags.AM_PROC_GOOD, info.uid,
1887 info.processName);
1888 mBadProcesses.remove(info.processName, info.uid);
1889 if (app != null) {
1890 app.bad = false;
1891 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001892 }
1893 }
1894 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001895
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001896 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001897 app = newProcessRecordLocked(null, info, processName, isolated);
1898 if (app == null) {
1899 Slog.w(TAG, "Failed making new process record for "
1900 + processName + "/" + info.uid + " isolated=" + isolated);
1901 return null;
1902 }
1903 mProcessNames.put(processName, app.uid, app);
1904 if (isolated) {
1905 mIsolatedProcesses.put(app.uid, app);
1906 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001907 } else {
1908 // If this is a new package in the process, add the package to the list
1909 app.addPackage(info.packageName);
1910 }
1911
1912 // If the system is not ready yet, then hold off on starting this
1913 // process until it is.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001914 if (!mProcessesReady
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001915 && !isAllowedWhileBooting(info)
1916 && !allowWhileBooting) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001917 if (!mProcessesOnHold.contains(app)) {
1918 mProcessesOnHold.add(app);
1919 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001920 if (DEBUG_PROCESSES) Slog.v(TAG, "System not ready, putting on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001921 return app;
1922 }
1923
1924 startProcessLocked(app, hostingType, hostingNameStr);
1925 return (app.pid != 0) ? app : null;
1926 }
1927
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001928 boolean isAllowedWhileBooting(ApplicationInfo ai) {
1929 return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0;
1930 }
1931
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001932 private final void startProcessLocked(ProcessRecord app,
1933 String hostingType, String hostingNameStr) {
1934 if (app.pid > 0 && app.pid != MY_PID) {
1935 synchronized (mPidsSelfLocked) {
1936 mPidsSelfLocked.remove(app.pid);
1937 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
1938 }
1939 app.pid = 0;
1940 }
1941
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001942 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
1943 "startProcessLocked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001944 mProcessesOnHold.remove(app);
1945
1946 updateCpuStats();
1947
1948 System.arraycopy(mProcDeaths, 0, mProcDeaths, 1, mProcDeaths.length-1);
1949 mProcDeaths[0] = 0;
1950
1951 try {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001952 int uid = app.uid;
Amith Yamasani742a6712011-05-04 14:49:28 -07001953
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001954 int[] gids = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001955 if (!app.isolated) {
1956 try {
1957 gids = mContext.getPackageManager().getPackageGids(
1958 app.info.packageName);
1959 } catch (PackageManager.NameNotFoundException e) {
1960 Slog.w(TAG, "Unable to retrieve gids", e);
1961 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001962 }
1963 if (mFactoryTest != SystemServer.FACTORY_TEST_OFF) {
1964 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
1965 && mTopComponent != null
1966 && app.processName.equals(mTopComponent.getPackageName())) {
1967 uid = 0;
1968 }
1969 if (mFactoryTest == SystemServer.FACTORY_TEST_HIGH_LEVEL
1970 && (app.info.flags&ApplicationInfo.FLAG_FACTORY_TEST) != 0) {
1971 uid = 0;
1972 }
1973 }
1974 int debugFlags = 0;
1975 if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
1976 debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;
Elliott Hughesfa36aee2011-06-17 14:39:41 -07001977 // Also turn on CheckJNI for debuggable apps. It's quite
1978 // awkward to turn on otherwise.
1979 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001980 }
Ben Cheng6c0afff2010-02-14 16:18:56 -08001981 // Run the app in safe mode if its manifest requests so or the
1982 // system is booted in safe mode.
1983 if ((app.info.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0 ||
1984 Zygote.systemInSafeMode == true) {
Ben Cheng23085b72010-02-08 16:06:32 -08001985 debugFlags |= Zygote.DEBUG_ENABLE_SAFEMODE;
1986 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001987 if ("1".equals(SystemProperties.get("debug.checkjni"))) {
1988 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
1989 }
Elliott Hughesae07ecf2011-07-06 17:33:27 -07001990 if ("1".equals(SystemProperties.get("debug.jni.logging"))) {
1991 debugFlags |= Zygote.DEBUG_ENABLE_JNI_LOGGING;
1992 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001993 if ("1".equals(SystemProperties.get("debug.assert"))) {
1994 debugFlags |= Zygote.DEBUG_ENABLE_ASSERT;
1995 }
Jeff Brown3f9dd282011-07-08 20:02:19 -07001996
1997 // Start the process. It will either succeed and return a result containing
1998 // the PID of the new process, or else throw a RuntimeException.
1999 Process.ProcessStartResult startResult = Process.start("android.app.ActivityThread",
Elliott Hughese1dfcb72011-07-08 11:08:07 -07002000 app.processName, uid, uid, gids, debugFlags,
2001 app.info.targetSdkVersion, null);
Jeff Brown3f9dd282011-07-08 20:02:19 -07002002
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002003 BatteryStatsImpl bs = app.batteryStats.getBatteryStats();
2004 synchronized (bs) {
2005 if (bs.isOnBattery()) {
2006 app.batteryStats.incStartsLocked();
2007 }
2008 }
2009
Jeff Brown3f9dd282011-07-08 20:02:19 -07002010 EventLog.writeEvent(EventLogTags.AM_PROC_START, startResult.pid, uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002011 app.processName, hostingType,
2012 hostingNameStr != null ? hostingNameStr : "");
2013
2014 if (app.persistent) {
Jeff Brown3f9dd282011-07-08 20:02:19 -07002015 Watchdog.getInstance().processStarted(app.processName, startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002016 }
2017
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07002018 StringBuilder buf = mStringBuilder;
2019 buf.setLength(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002020 buf.append("Start proc ");
2021 buf.append(app.processName);
2022 buf.append(" for ");
2023 buf.append(hostingType);
2024 if (hostingNameStr != null) {
2025 buf.append(" ");
2026 buf.append(hostingNameStr);
2027 }
2028 buf.append(": pid=");
Jeff Brown3f9dd282011-07-08 20:02:19 -07002029 buf.append(startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002030 buf.append(" uid=");
2031 buf.append(uid);
2032 buf.append(" gids={");
2033 if (gids != null) {
2034 for (int gi=0; gi<gids.length; gi++) {
2035 if (gi != 0) buf.append(", ");
2036 buf.append(gids[gi]);
2037
2038 }
2039 }
2040 buf.append("}");
Joe Onorato8a9b2202010-02-26 18:56:32 -08002041 Slog.i(TAG, buf.toString());
Jeff Brown3f9dd282011-07-08 20:02:19 -07002042 app.pid = startResult.pid;
2043 app.usingWrapper = startResult.usingWrapper;
2044 app.removed = false;
2045 synchronized (mPidsSelfLocked) {
2046 this.mPidsSelfLocked.put(startResult.pid, app);
2047 Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
2048 msg.obj = app;
2049 mHandler.sendMessageDelayed(msg, startResult.usingWrapper
2050 ? PROC_START_TIMEOUT_WITH_WRAPPER : PROC_START_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002051 }
2052 } catch (RuntimeException e) {
2053 // XXX do better error recovery.
2054 app.pid = 0;
Joe Onorato8a9b2202010-02-26 18:56:32 -08002055 Slog.e(TAG, "Failure starting process " + app.processName, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002056 }
2057 }
2058
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002059 void updateUsageStats(ActivityRecord resumedComponent, boolean resumed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002060 if (resumed) {
2061 mUsageStatsService.noteResumeComponent(resumedComponent.realActivity);
2062 } else {
2063 mUsageStatsService.notePauseComponent(resumedComponent.realActivity);
2064 }
2065 }
2066
Amith Yamasani742a6712011-05-04 14:49:28 -07002067 boolean startHomeActivityLocked(int userId) {
Mike Lockwooda8f767a2011-08-31 14:32:37 -04002068 if (mHeadless) {
2069 // Added because none of the other calls to ensureBootCompleted seem to fire
2070 // when running headless.
2071 ensureBootCompleted();
2072 return false;
2073 }
2074
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002075 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2076 && mTopAction == null) {
2077 // We are running in factory test mode, but unable to find
2078 // the factory test app, so just sit around displaying the
2079 // error message and don't try to start anything.
2080 return false;
2081 }
2082 Intent intent = new Intent(
2083 mTopAction,
2084 mTopData != null ? Uri.parse(mTopData) : null);
2085 intent.setComponent(mTopComponent);
2086 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
2087 intent.addCategory(Intent.CATEGORY_HOME);
2088 }
2089 ActivityInfo aInfo =
2090 intent.resolveActivityInfo(mContext.getPackageManager(),
2091 STOCK_PM_FLAGS);
2092 if (aInfo != null) {
2093 intent.setComponent(new ComponentName(
2094 aInfo.applicationInfo.packageName, aInfo.name));
2095 // Don't do this if the home app is currently being
2096 // instrumented.
Amith Yamasani742a6712011-05-04 14:49:28 -07002097 aInfo = new ActivityInfo(aInfo);
2098 aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002099 ProcessRecord app = getProcessRecordLocked(aInfo.processName,
2100 aInfo.applicationInfo.uid);
2101 if (app == null || app.instrumentationClass == null) {
2102 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002103 mMainStack.startActivityLocked(null, intent, null, aInfo,
2104 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002105 }
2106 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002107
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002108 return true;
2109 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002110
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002111 /**
2112 * Starts the "new version setup screen" if appropriate.
2113 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002114 void startSetupActivityLocked() {
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002115 // Only do this once per boot.
2116 if (mCheckedForSetup) {
2117 return;
2118 }
2119
2120 // We will show this screen if the current one is a different
2121 // version than the last one shown, and we are not running in
2122 // low-level factory test mode.
2123 final ContentResolver resolver = mContext.getContentResolver();
2124 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL &&
2125 Settings.Secure.getInt(resolver,
2126 Settings.Secure.DEVICE_PROVISIONED, 0) != 0) {
2127 mCheckedForSetup = true;
2128
2129 // See if we should be showing the platform update setup UI.
2130 Intent intent = new Intent(Intent.ACTION_UPGRADE_SETUP);
2131 List<ResolveInfo> ris = mSelf.mContext.getPackageManager()
2132 .queryIntentActivities(intent, PackageManager.GET_META_DATA);
2133
2134 // We don't allow third party apps to replace this.
2135 ResolveInfo ri = null;
2136 for (int i=0; ris != null && i<ris.size(); i++) {
2137 if ((ris.get(i).activityInfo.applicationInfo.flags
2138 & ApplicationInfo.FLAG_SYSTEM) != 0) {
2139 ri = ris.get(i);
2140 break;
2141 }
2142 }
2143
2144 if (ri != null) {
2145 String vers = ri.activityInfo.metaData != null
2146 ? ri.activityInfo.metaData.getString(Intent.METADATA_SETUP_VERSION)
2147 : null;
2148 if (vers == null && ri.activityInfo.applicationInfo.metaData != null) {
2149 vers = ri.activityInfo.applicationInfo.metaData.getString(
2150 Intent.METADATA_SETUP_VERSION);
2151 }
2152 String lastVers = Settings.Secure.getString(
2153 resolver, Settings.Secure.LAST_SETUP_SHOWN);
2154 if (vers != null && !vers.equals(lastVers)) {
2155 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2156 intent.setComponent(new ComponentName(
2157 ri.activityInfo.packageName, ri.activityInfo.name));
Dianne Hackborna4972e92012-03-14 10:38:05 -07002158 mMainStack.startActivityLocked(null, intent, null, ri.activityInfo,
2159 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002160 }
2161 }
2162 }
2163 }
2164
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002165 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002166 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002167 }
2168
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002169 void enforceNotIsolatedCaller(String caller) {
2170 if (UserId.isIsolated(Binder.getCallingUid())) {
2171 throw new SecurityException("Isolated process not allowed to call " + caller);
2172 }
2173 }
2174
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002175 public int getFrontActivityScreenCompatMode() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002176 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002177 synchronized (this) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002178 return mCompatModePackages.getFrontActivityScreenCompatModeLocked();
2179 }
2180 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002181
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002182 public void setFrontActivityScreenCompatMode(int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002183 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2184 "setFrontActivityScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002185 synchronized (this) {
2186 mCompatModePackages.setFrontActivityScreenCompatModeLocked(mode);
2187 }
2188 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002189
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002190 public int getPackageScreenCompatMode(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002191 enforceNotIsolatedCaller("getPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002192 synchronized (this) {
2193 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
2194 }
2195 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002196
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002197 public void setPackageScreenCompatMode(String packageName, int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002198 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2199 "setPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002200 synchronized (this) {
2201 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002202 }
2203 }
2204
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002205 public boolean getPackageAskScreenCompat(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002206 enforceNotIsolatedCaller("getPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002207 synchronized (this) {
2208 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
2209 }
2210 }
2211
2212 public void setPackageAskScreenCompat(String packageName, boolean ask) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002213 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2214 "setPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002215 synchronized (this) {
2216 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
2217 }
2218 }
2219
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002220 void reportResumedActivityLocked(ActivityRecord r) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002221 //Slog.i(TAG, "**** REPORT RESUME: " + r);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002222
2223 final int identHash = System.identityHashCode(r);
2224 updateUsageStats(r, true);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002225 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002226
Jeff Sharkeya4620792011-05-20 15:29:23 -07002227 private void dispatchForegroundActivitiesChanged(int pid, int uid, boolean foregroundActivities) {
2228 int i = mProcessObservers.beginBroadcast();
2229 while (i > 0) {
2230 i--;
2231 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2232 if (observer != null) {
2233 try {
2234 observer.onForegroundActivitiesChanged(pid, uid, foregroundActivities);
2235 } catch (RemoteException e) {
2236 }
2237 }
2238 }
2239 mProcessObservers.finishBroadcast();
2240 }
2241
2242 private void dispatchProcessDied(int pid, int uid) {
2243 int i = mProcessObservers.beginBroadcast();
2244 while (i > 0) {
2245 i--;
2246 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2247 if (observer != null) {
2248 try {
2249 observer.onProcessDied(pid, uid);
2250 } catch (RemoteException e) {
2251 }
2252 }
2253 }
2254 mProcessObservers.finishBroadcast();
2255 }
2256
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002257 final void doPendingActivityLaunchesLocked(boolean doResume) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002258 final int N = mPendingActivityLaunches.size();
2259 if (N <= 0) {
2260 return;
2261 }
2262 for (int i=0; i<N; i++) {
2263 PendingActivityLaunch pal = mPendingActivityLaunches.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002264 mMainStack.startActivityUncheckedLocked(pal.r, pal.sourceRecord,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002265 pal.startFlags, doResume && i == (N-1), null);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002266 }
2267 mPendingActivityLaunches.clear();
2268 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002269
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002270 public final int startActivity(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002271 Intent intent, String resolvedType, IBinder resultTo,
2272 String resultWho, int requestCode, int startFlags,
2273 String profileFile, ParcelFileDescriptor profileFd, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002274 enforceNotIsolatedCaller("startActivity");
Amith Yamasani742a6712011-05-04 14:49:28 -07002275 int userId = 0;
2276 if (intent.getCategories() != null && intent.getCategories().contains(Intent.CATEGORY_HOME)) {
2277 // Requesting home, set the identity to the current user
2278 // HACK!
2279 userId = mCurrentUserId;
2280 } else {
2281 // TODO: Fix this in a better way - calls coming from SystemUI should probably carry
2282 // the current user's userId
2283 if (Binder.getCallingUid() < Process.FIRST_APPLICATION_UID) {
2284 userId = 0;
2285 } else {
2286 userId = Binder.getOrigCallingUser();
2287 }
2288 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002289 return mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002290 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
2291 null, null, options, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002292 }
2293
2294 public final WaitResult startActivityAndWait(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002295 Intent intent, String resolvedType, IBinder resultTo,
2296 String resultWho, int requestCode, int startFlags, String profileFile,
2297 ParcelFileDescriptor profileFd, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002298 enforceNotIsolatedCaller("startActivityAndWait");
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002299 WaitResult res = new WaitResult();
Amith Yamasani742a6712011-05-04 14:49:28 -07002300 int userId = Binder.getOrigCallingUser();
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002301 mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002302 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
2303 res, null, options, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002304 return res;
2305 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08002306
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002307 public final int startActivityWithConfig(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002308 Intent intent, String resolvedType, IBinder resultTo,
2309 String resultWho, int requestCode, int startFlags, Configuration config,
2310 Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002311 enforceNotIsolatedCaller("startActivityWithConfig");
Amith Yamasani742a6712011-05-04 14:49:28 -07002312 int ret = mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002313 resultTo, resultWho, requestCode, startFlags,
2314 null, null, null, config, options, Binder.getOrigCallingUser());
Amith Yamasani742a6712011-05-04 14:49:28 -07002315 return ret;
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002316 }
2317
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002318 public int startActivityIntentSender(IApplicationThread caller,
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002319 IntentSender intent, Intent fillInIntent, String resolvedType,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002320 IBinder resultTo, String resultWho, int requestCode,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002321 int flagsMask, int flagsValues, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002322 enforceNotIsolatedCaller("startActivityIntentSender");
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002323 // Refuse possible leaked file descriptors
2324 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
2325 throw new IllegalArgumentException("File descriptors passed in Intent");
2326 }
2327
2328 IIntentSender sender = intent.getTarget();
2329 if (!(sender instanceof PendingIntentRecord)) {
2330 throw new IllegalArgumentException("Bad PendingIntent object");
2331 }
2332
2333 PendingIntentRecord pir = (PendingIntentRecord)sender;
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002334
2335 synchronized (this) {
2336 // If this is coming from the currently resumed activity, it is
2337 // effectively saying that app switches are allowed at this point.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002338 if (mMainStack.mResumedActivity != null
2339 && mMainStack.mResumedActivity.info.applicationInfo.uid ==
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002340 Binder.getCallingUid()) {
2341 mAppSwitchesAllowedTime = 0;
2342 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002343 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002344 int ret = pir.sendInner(0, fillInIntent, resolvedType, null, null,
2345 resultTo, resultWho, requestCode, flagsMask, flagsValues, options);
Amith Yamasani742a6712011-05-04 14:49:28 -07002346 return ret;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002347 }
2348
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002349 public boolean startNextMatchingActivity(IBinder callingActivity,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002350 Intent intent, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002351 // Refuse possible leaked file descriptors
2352 if (intent != null && intent.hasFileDescriptors() == true) {
2353 throw new IllegalArgumentException("File descriptors passed in Intent");
2354 }
2355
2356 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002357 ActivityRecord r = mMainStack.isInStackLocked(callingActivity);
2358 if (r == null) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002359 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002360 return false;
2361 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002362 if (r.app == null || r.app.thread == null) {
2363 // The caller is not running... d'oh!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002364 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002365 return false;
2366 }
2367 intent = new Intent(intent);
2368 // The caller is not allowed to change the data.
2369 intent.setDataAndType(r.intent.getData(), r.intent.getType());
2370 // And we are resetting to find the next component...
2371 intent.setComponent(null);
2372
2373 ActivityInfo aInfo = null;
2374 try {
2375 List<ResolveInfo> resolves =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002376 AppGlobals.getPackageManager().queryIntentActivities(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002377 intent, r.resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002378 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
2379 UserId.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002380
2381 // Look for the original activity in the list...
2382 final int N = resolves != null ? resolves.size() : 0;
2383 for (int i=0; i<N; i++) {
2384 ResolveInfo rInfo = resolves.get(i);
2385 if (rInfo.activityInfo.packageName.equals(r.packageName)
2386 && rInfo.activityInfo.name.equals(r.info.name)) {
2387 // We found the current one... the next matching is
2388 // after it.
2389 i++;
2390 if (i<N) {
2391 aInfo = resolves.get(i).activityInfo;
2392 }
2393 break;
2394 }
2395 }
2396 } catch (RemoteException e) {
2397 }
2398
2399 if (aInfo == null) {
2400 // Nobody who is next!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002401 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002402 return false;
2403 }
2404
2405 intent.setComponent(new ComponentName(
2406 aInfo.applicationInfo.packageName, aInfo.name));
2407 intent.setFlags(intent.getFlags()&~(
2408 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
2409 Intent.FLAG_ACTIVITY_CLEAR_TOP|
2410 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
2411 Intent.FLAG_ACTIVITY_NEW_TASK));
2412
2413 // Okay now we need to start the new activity, replacing the
2414 // currently running activity. This is a little tricky because
2415 // we want to start the new one as if the current one is finished,
2416 // but not finish the current one first so that there is no flicker.
2417 // And thus...
2418 final boolean wasFinishing = r.finishing;
2419 r.finishing = true;
2420
2421 // Propagate reply information over to the new activity.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002422 final ActivityRecord resultTo = r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002423 final String resultWho = r.resultWho;
2424 final int requestCode = r.requestCode;
2425 r.resultTo = null;
2426 if (resultTo != null) {
2427 resultTo.removeResultsLocked(r, resultWho, requestCode);
2428 }
2429
2430 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002431 int res = mMainStack.startActivityLocked(r.app.thread, intent,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002432 r.resolvedType, aInfo, resultTo != null ? resultTo.appToken : null,
2433 resultWho, requestCode, -1, r.launchedFromUid, 0,
2434 options, false, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002435 Binder.restoreCallingIdentity(origId);
2436
2437 r.finishing = wasFinishing;
Dianne Hackborna4972e92012-03-14 10:38:05 -07002438 if (res != ActivityManager.START_SUCCESS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002439 return false;
2440 }
2441 return true;
2442 }
2443 }
2444
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002445 public final int startActivityInPackage(int uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002446 Intent intent, String resolvedType, IBinder resultTo,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002447 String resultWho, int requestCode, int startFlags, Bundle options) {
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002448
2449 // This is so super not safe, that only the system (or okay root)
2450 // can do it.
Amith Yamasani742a6712011-05-04 14:49:28 -07002451 int userId = Binder.getOrigCallingUser();
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002452 final int callingUid = Binder.getCallingUid();
2453 if (callingUid != 0 && callingUid != Process.myUid()) {
2454 throw new SecurityException(
2455 "startActivityInPackage only available to the system");
2456 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002457
Amith Yamasani742a6712011-05-04 14:49:28 -07002458 int ret = mMainStack.startActivityMayWait(null, uid, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002459 resultTo, resultWho, requestCode, startFlags,
2460 null, null, null, null, options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002461 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002462 }
2463
2464 public final int startActivities(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002465 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002466 enforceNotIsolatedCaller("startActivities");
Amith Yamasani742a6712011-05-04 14:49:28 -07002467 int ret = mMainStack.startActivities(caller, -1, intents, resolvedTypes, resultTo,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002468 options, Binder.getOrigCallingUser());
Amith Yamasani742a6712011-05-04 14:49:28 -07002469 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002470 }
2471
2472 public final int startActivitiesInPackage(int uid,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002473 Intent[] intents, String[] resolvedTypes, IBinder resultTo,
2474 Bundle options) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002475
2476 // This is so super not safe, that only the system (or okay root)
2477 // can do it.
2478 final int callingUid = Binder.getCallingUid();
2479 if (callingUid != 0 && callingUid != Process.myUid()) {
2480 throw new SecurityException(
2481 "startActivityInPackage only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002482 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002483 int ret = mMainStack.startActivities(null, uid, intents, resolvedTypes, resultTo,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002484 options, UserId.getUserId(uid));
Amith Yamasani742a6712011-05-04 14:49:28 -07002485 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002486 }
2487
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002488 final void addRecentTaskLocked(TaskRecord task) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002489 int N = mRecentTasks.size();
Dianne Hackborn7c0e75e2010-12-21 19:15:40 -08002490 // Quick case: check if the top-most recent task is the same.
2491 if (N > 0 && mRecentTasks.get(0) == task) {
2492 return;
2493 }
2494 // Remove any existing entries that are the same kind of task.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002495 for (int i=0; i<N; i++) {
2496 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07002497 if (task.userId == tr.userId
2498 && ((task.affinity != null && task.affinity.equals(tr.affinity))
2499 || (task.intent != null && task.intent.filterEquals(tr.intent)))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002500 mRecentTasks.remove(i);
2501 i--;
2502 N--;
2503 if (task.intent == null) {
2504 // If the new recent task we are adding is not fully
2505 // specified, then replace it with the existing recent task.
2506 task = tr;
2507 }
2508 }
2509 }
2510 if (N >= MAX_RECENT_TASKS) {
2511 mRecentTasks.remove(N-1);
2512 }
2513 mRecentTasks.add(0, task);
2514 }
2515
2516 public void setRequestedOrientation(IBinder token,
2517 int requestedOrientation) {
2518 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002519 ActivityRecord r = mMainStack.isInStackLocked(token);
2520 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002521 return;
2522 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002523 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornbe707852011-11-11 14:32:10 -08002524 mWindowManager.setAppOrientation(r.appToken, requestedOrientation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002525 Configuration config = mWindowManager.updateOrientationFromAppTokens(
The Android Open Source Project10592532009-03-18 17:39:46 -07002526 mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -08002527 r.mayFreezeScreenLocked(r.app) ? r.appToken : null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002528 if (config != null) {
2529 r.frozenBeforeDestroy = true;
Dianne Hackborn813075a62011-11-14 17:45:19 -08002530 if (!updateConfigurationLocked(config, r, false, false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002531 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002532 }
2533 }
2534 Binder.restoreCallingIdentity(origId);
2535 }
2536 }
2537
2538 public int getRequestedOrientation(IBinder token) {
2539 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002540 ActivityRecord r = mMainStack.isInStackLocked(token);
2541 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002542 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
2543 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08002544 return mWindowManager.getAppOrientation(r.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002545 }
2546 }
2547
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002548 /**
2549 * This is the internal entry point for handling Activity.finish().
2550 *
2551 * @param token The Binder token referencing the Activity we want to finish.
2552 * @param resultCode Result code, if any, from this Activity.
2553 * @param resultData Result data (Intent), if any, from this Activity.
2554 *
Alexey Tarasov83bad3d2009-08-12 15:05:43 +11002555 * @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 -08002556 */
2557 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData) {
2558 // Refuse possible leaked file descriptors
2559 if (resultData != null && resultData.hasFileDescriptors() == true) {
2560 throw new IllegalArgumentException("File descriptors passed in Intent");
2561 }
2562
2563 synchronized(this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002564 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002565 // Find the first activity that is not finishing.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002566 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002567 if (next != null) {
2568 // ask watcher if this is allowed
2569 boolean resumeOK = true;
2570 try {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002571 resumeOK = mController.activityResuming(next.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002572 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002573 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002574 }
2575
2576 if (!resumeOK) {
2577 return false;
2578 }
2579 }
2580 }
2581 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002582 boolean res = mMainStack.requestFinishActivityLocked(token, resultCode,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002583 resultData, "app-request");
2584 Binder.restoreCallingIdentity(origId);
2585 return res;
2586 }
2587 }
2588
Dianne Hackborn860755f2010-06-03 18:47:52 -07002589 public final void finishHeavyWeightApp() {
2590 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2591 != PackageManager.PERMISSION_GRANTED) {
2592 String msg = "Permission Denial: finishHeavyWeightApp() from pid="
2593 + Binder.getCallingPid()
2594 + ", uid=" + Binder.getCallingUid()
2595 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2596 Slog.w(TAG, msg);
2597 throw new SecurityException(msg);
2598 }
2599
2600 synchronized(this) {
2601 if (mHeavyWeightProcess == null) {
2602 return;
2603 }
2604
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002605 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>(
Dianne Hackborn860755f2010-06-03 18:47:52 -07002606 mHeavyWeightProcess.activities);
2607 for (int i=0; i<activities.size(); i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002608 ActivityRecord r = activities.get(i);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002609 if (!r.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002610 int index = mMainStack.indexOfTokenLocked(r.appToken);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002611 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002612 mMainStack.finishActivityLocked(r, index, Activity.RESULT_CANCELED,
Dianne Hackborn860755f2010-06-03 18:47:52 -07002613 null, "finish-heavy");
2614 }
2615 }
2616 }
2617
2618 mHeavyWeightProcess = null;
2619 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
2620 }
2621 }
2622
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002623 public void crashApplication(int uid, int initialPid, String packageName,
2624 String message) {
2625 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2626 != PackageManager.PERMISSION_GRANTED) {
2627 String msg = "Permission Denial: crashApplication() from pid="
2628 + Binder.getCallingPid()
2629 + ", uid=" + Binder.getCallingUid()
2630 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2631 Slog.w(TAG, msg);
2632 throw new SecurityException(msg);
2633 }
2634
2635 synchronized(this) {
2636 ProcessRecord proc = null;
2637
2638 // Figure out which process to kill. We don't trust that initialPid
2639 // still has any relation to current pids, so must scan through the
2640 // list.
2641 synchronized (mPidsSelfLocked) {
2642 for (int i=0; i<mPidsSelfLocked.size(); i++) {
2643 ProcessRecord p = mPidsSelfLocked.valueAt(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002644 if (p.uid != uid) {
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002645 continue;
2646 }
2647 if (p.pid == initialPid) {
2648 proc = p;
2649 break;
2650 }
2651 for (String str : p.pkgList) {
2652 if (str.equals(packageName)) {
2653 proc = p;
2654 }
2655 }
2656 }
2657 }
2658
2659 if (proc == null) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07002660 Slog.w(TAG, "crashApplication: nothing for uid=" + uid
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002661 + " initialPid=" + initialPid
2662 + " packageName=" + packageName);
2663 return;
2664 }
2665
2666 if (proc.thread != null) {
Dianne Hackborn9f531192010-08-04 17:48:03 -07002667 if (proc.pid == Process.myPid()) {
2668 Log.w(TAG, "crashApplication: trying to crash self!");
2669 return;
2670 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002671 long ident = Binder.clearCallingIdentity();
2672 try {
2673 proc.thread.scheduleCrash(message);
2674 } catch (RemoteException e) {
2675 }
2676 Binder.restoreCallingIdentity(ident);
2677 }
2678 }
2679 }
2680
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002681 public final void finishSubActivity(IBinder token, String resultWho,
2682 int requestCode) {
2683 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002684 ActivityRecord self = mMainStack.isInStackLocked(token);
2685 if (self == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002686 return;
2687 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002688
2689 final long origId = Binder.clearCallingIdentity();
2690
2691 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002692 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2693 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002694 if (r.resultTo == self && r.requestCode == requestCode) {
2695 if ((r.resultWho == null && resultWho == null) ||
2696 (r.resultWho != null && r.resultWho.equals(resultWho))) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002697 mMainStack.finishActivityLocked(r, i,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002698 Activity.RESULT_CANCELED, null, "request-sub");
2699 }
2700 }
2701 }
2702
2703 Binder.restoreCallingIdentity(origId);
2704 }
2705 }
2706
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002707 public boolean willActivityBeVisible(IBinder token) {
2708 synchronized(this) {
2709 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002710 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2711 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08002712 if (r.appToken == token) {
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002713 return true;
2714 }
2715 if (r.fullscreen && !r.finishing) {
2716 return false;
2717 }
2718 }
2719 return true;
2720 }
2721 }
2722
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002723 public void overridePendingTransition(IBinder token, String packageName,
2724 int enterAnim, int exitAnim) {
2725 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002726 ActivityRecord self = mMainStack.isInStackLocked(token);
2727 if (self == null) {
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002728 return;
2729 }
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002730
2731 final long origId = Binder.clearCallingIdentity();
2732
2733 if (self.state == ActivityState.RESUMED
2734 || self.state == ActivityState.PAUSING) {
2735 mWindowManager.overridePendingAppTransition(packageName,
2736 enterAnim, exitAnim);
2737 }
2738
2739 Binder.restoreCallingIdentity(origId);
2740 }
2741 }
2742
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002743 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002744 * Main function for removing an existing process from the activity manager
2745 * as a result of that process going away. Clears out all connections
2746 * to the process.
2747 */
2748 private final void handleAppDiedLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002749 boolean restarting, boolean allowRestart) {
2750 cleanUpApplicationRecordLocked(app, restarting, allowRestart, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002751 if (!restarting) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002752 mLruProcesses.remove(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002753 }
2754
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002755 if (mProfileProc == app) {
2756 clearProfilerLocked();
2757 }
2758
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002759 // Just in case...
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002760 if (mMainStack.mPausingActivity != null && mMainStack.mPausingActivity.app == app) {
2761 if (DEBUG_PAUSE) Slog.v(TAG, "App died while pausing: " +mMainStack.mPausingActivity);
2762 mMainStack.mPausingActivity = null;
2763 }
2764 if (mMainStack.mLastPausedActivity != null && mMainStack.mLastPausedActivity.app == app) {
2765 mMainStack.mLastPausedActivity = null;
2766 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002767
2768 // Remove this application's activities from active lists.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002769 mMainStack.removeHistoryRecordsForAppLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002770
2771 boolean atTop = true;
2772 boolean hasVisibleActivities = false;
2773
2774 // Clean out the history list.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002775 int i = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08002776 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002777 TAG, "Removing app " + app + " from history with " + i + " entries");
2778 while (i > 0) {
2779 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002780 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002781 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002782 TAG, "Record #" + i + " " + r + ": app=" + r.app);
2783 if (r.app == app) {
2784 if ((!r.haveState && !r.stateNotNeeded) || r.finishing) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002785 if (ActivityStack.DEBUG_ADD_REMOVE) {
2786 RuntimeException here = new RuntimeException("here");
2787 here.fillInStackTrace();
2788 Slog.i(TAG, "Removing activity " + r + " from stack at " + i
2789 + ": haveState=" + r.haveState
2790 + " stateNotNeeded=" + r.stateNotNeeded
2791 + " finishing=" + r.finishing
2792 + " state=" + r.state, here);
2793 }
2794 if (!r.finishing) {
2795 Slog.w(TAG, "Force removing " + r + ": app died, no saved state");
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -08002796 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
2797 System.identityHashCode(r),
2798 r.task.taskId, r.shortComponentName,
2799 "proc died without state saved");
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002800 }
Dianne Hackborn5c607432012-02-28 14:44:19 -08002801 mMainStack.removeActivityFromHistoryLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002802
2803 } else {
2804 // We have the current state for this activity, so
2805 // it can be restarted later when needed.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002806 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002807 TAG, "Keeping entry, setting app to null");
2808 if (r.visible) {
2809 hasVisibleActivities = true;
2810 }
2811 r.app = null;
2812 r.nowVisible = false;
2813 if (!r.haveState) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002814 if (ActivityStack.DEBUG_SAVED_STATE) Slog.i(TAG,
2815 "App died, clearing saved state of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002816 r.icicle = null;
2817 }
2818 }
2819
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002820 r.stack.cleanUpActivityLocked(r, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002821 }
2822 atTop = false;
2823 }
2824
2825 app.activities.clear();
2826
2827 if (app.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002828 Slog.w(TAG, "Crash of app " + app.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002829 + " running instrumentation " + app.instrumentationClass);
2830 Bundle info = new Bundle();
2831 info.putString("shortMsg", "Process crashed.");
2832 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
2833 }
2834
2835 if (!restarting) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002836 if (!mMainStack.resumeTopActivityLocked(null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002837 // If there was nothing to resume, and we are not already
2838 // restarting this process, but there is a visible activity that
2839 // is hosted by the process... then make sure all visible
2840 // activities are running, taking care of restarting this
2841 // process.
2842 if (hasVisibleActivities) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002843 mMainStack.ensureActivitiesVisibleLocked(null, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002844 }
2845 }
2846 }
2847 }
2848
2849 private final int getLRURecordIndexForAppLocked(IApplicationThread thread) {
2850 IBinder threadBinder = thread.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002851 // Find the application record.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002852 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2853 ProcessRecord rec = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002854 if (rec.thread != null && rec.thread.asBinder() == threadBinder) {
2855 return i;
2856 }
2857 }
2858 return -1;
2859 }
2860
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002861 final ProcessRecord getRecordForAppLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002862 IApplicationThread thread) {
2863 if (thread == null) {
2864 return null;
2865 }
2866
2867 int appIndex = getLRURecordIndexForAppLocked(thread);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002868 return appIndex >= 0 ? mLruProcesses.get(appIndex) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002869 }
2870
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002871 final void appDiedLocked(ProcessRecord app, int pid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002872 IApplicationThread thread) {
2873
2874 mProcDeaths[0]++;
2875
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002876 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
2877 synchronized (stats) {
2878 stats.noteProcessDiedLocked(app.info.uid, pid);
2879 }
2880
Magnus Edlund7bb25812010-02-24 15:45:06 +01002881 // Clean up already done if the process has been re-started.
2882 if (app.pid == pid && app.thread != null &&
2883 app.thread.asBinder() == thread.asBinder()) {
Dianne Hackborn906497c2010-05-10 15:57:38 -07002884 if (!app.killedBackground) {
2885 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
2886 + ") has died.");
2887 }
Doug Zongker2bec3d42009-12-04 12:52:44 -08002888 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002889 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002890 TAG, "Dying app: " + app + ", pid: " + pid
2891 + ", thread: " + thread.asBinder());
2892 boolean doLowMem = app.instrumentationClass == null;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002893 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002894
2895 if (doLowMem) {
2896 // If there are no longer any background processes running,
2897 // and the app that died was not running instrumentation,
2898 // then tell everyone we are now low on memory.
2899 boolean haveBg = false;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002900 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2901 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -07002902 if (rec.thread != null && rec.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002903 haveBg = true;
2904 break;
2905 }
2906 }
2907
2908 if (!haveBg) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002909 EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mLruProcesses.size());
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002910 long now = SystemClock.uptimeMillis();
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002911 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2912 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn36124872009-10-08 16:22:03 -07002913 if (rec != app && rec.thread != null &&
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002914 (rec.lastLowMemory+GC_MIN_INTERVAL) <= now) {
2915 // The low memory report is overriding any current
2916 // state for a GC request. Make sure to do
Dianne Hackborn32907cf2010-06-10 17:50:20 -07002917 // heavy/important/visible/foreground processes first.
Dianne Hackborn7d608422011-08-07 16:24:18 -07002918 if (rec.setAdj <= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002919 rec.lastRequestedGc = 0;
2920 } else {
2921 rec.lastRequestedGc = rec.lastLowMemory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002922 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002923 rec.reportLowMemory = true;
2924 rec.lastLowMemory = now;
2925 mProcessesToGc.remove(rec);
2926 addProcessToGcListLocked(rec);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002927 }
2928 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07002929 mHandler.sendEmptyMessage(REPORT_MEM_USAGE);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002930 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002931 }
2932 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01002933 } else if (app.pid != pid) {
2934 // A new process has already been started.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002935 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
Magnus Edlund7bb25812010-02-24 15:45:06 +01002936 + ") has died and restarted (pid " + app.pid + ").");
Dianne Hackborn28a8c2b2010-03-01 11:30:02 -08002937 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08002938 } else if (DEBUG_PROCESSES) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002939 Slog.d(TAG, "Received spurious death notification for thread "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002940 + thread.asBinder());
2941 }
2942 }
2943
Dan Egnor42471dd2010-01-07 17:25:22 -08002944 /**
2945 * If a stack trace dump file is configured, dump process stack traces.
Christopher Tate6ee412d2010-05-28 12:01:56 -07002946 * @param clearTraces causes the dump file to be erased prior to the new
2947 * traces being written, if true; when false, the new traces will be
2948 * appended to any existing file content.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002949 * @param firstPids of dalvik VM processes to dump stack traces for first
2950 * @param lastPids of dalvik VM processes to dump stack traces for last
Dan Egnor42471dd2010-01-07 17:25:22 -08002951 * @return file containing stack traces, or null if no dump file is configured
2952 */
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002953 public static File dumpStackTraces(boolean clearTraces, ArrayList<Integer> firstPids,
2954 ProcessStats processStats, SparseArray<Boolean> lastPids) {
Dan Egnor42471dd2010-01-07 17:25:22 -08002955 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
2956 if (tracesPath == null || tracesPath.length() == 0) {
2957 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002958 }
Dan Egnor42471dd2010-01-07 17:25:22 -08002959
2960 File tracesFile = new File(tracesPath);
2961 try {
2962 File tracesDir = tracesFile.getParentFile();
2963 if (!tracesDir.exists()) tracesFile.mkdirs();
2964 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
2965
Christopher Tate6ee412d2010-05-28 12:01:56 -07002966 if (clearTraces && tracesFile.exists()) tracesFile.delete();
Dan Egnor42471dd2010-01-07 17:25:22 -08002967 tracesFile.createNewFile();
2968 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
2969 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002970 Slog.w(TAG, "Unable to prepare ANR traces file: " + tracesPath, e);
Dan Egnor42471dd2010-01-07 17:25:22 -08002971 return null;
2972 }
2973
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07002974 dumpStackTraces(tracesPath, firstPids, processStats, lastPids);
2975 return tracesFile;
2976 }
2977
2978 private static void dumpStackTraces(String tracesPath, ArrayList<Integer> firstPids,
2979 ProcessStats processStats, SparseArray<Boolean> lastPids) {
Dan Egnor42471dd2010-01-07 17:25:22 -08002980 // Use a FileObserver to detect when traces finish writing.
2981 // The order of traces is considered important to maintain for legibility.
2982 FileObserver observer = new FileObserver(tracesPath, FileObserver.CLOSE_WRITE) {
2983 public synchronized void onEvent(int event, String path) { notify(); }
2984 };
2985
2986 try {
2987 observer.startWatching();
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002988
2989 // First collect all of the stacks of the most important pids.
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07002990 if (firstPids != null) {
2991 try {
2992 int num = firstPids.size();
2993 for (int i = 0; i < num; i++) {
2994 synchronized (observer) {
2995 Process.sendSignal(firstPids.get(i), Process.SIGNAL_QUIT);
2996 observer.wait(200); // Wait for write-close, give up after 200msec
2997 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002998 }
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07002999 } catch (InterruptedException e) {
3000 Log.wtf(TAG, e);
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003001 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003002 }
3003
3004 // Next measure CPU usage.
3005 if (processStats != null) {
3006 processStats.init();
3007 System.gc();
3008 processStats.update();
3009 try {
3010 synchronized (processStats) {
3011 processStats.wait(500); // measure over 1/2 second.
3012 }
3013 } catch (InterruptedException e) {
3014 }
3015 processStats.update();
3016
3017 // We'll take the stack crawls of just the top apps using CPU.
3018 final int N = processStats.countWorkingStats();
3019 int numProcs = 0;
3020 for (int i=0; i<N && numProcs<5; i++) {
3021 ProcessStats.Stats stats = processStats.getWorkingStats(i);
3022 if (lastPids.indexOfKey(stats.pid) >= 0) {
3023 numProcs++;
3024 try {
3025 synchronized (observer) {
3026 Process.sendSignal(stats.pid, Process.SIGNAL_QUIT);
3027 observer.wait(200); // Wait for write-close, give up after 200msec
3028 }
3029 } catch (InterruptedException e) {
3030 Log.wtf(TAG, e);
3031 }
3032
3033 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003034 }
3035 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003036
Dan Egnor42471dd2010-01-07 17:25:22 -08003037 } finally {
3038 observer.stopWatching();
3039 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003040 }
3041
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003042 final void logAppTooSlow(ProcessRecord app, long startTime, String msg) {
Dianne Hackborn69dc66e2012-03-26 10:50:54 -07003043 if (true || IS_USER_BUILD) {
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003044 return;
3045 }
3046 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
3047 if (tracesPath == null || tracesPath.length() == 0) {
3048 return;
3049 }
3050
3051 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
3052 StrictMode.allowThreadDiskWrites();
3053 try {
3054 final File tracesFile = new File(tracesPath);
3055 final File tracesDir = tracesFile.getParentFile();
3056 final File tracesTmp = new File(tracesDir, "__tmp__");
3057 try {
3058 if (!tracesDir.exists()) tracesFile.mkdirs();
3059 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
3060
3061 if (tracesFile.exists()) {
3062 tracesTmp.delete();
3063 tracesFile.renameTo(tracesTmp);
3064 }
3065 StringBuilder sb = new StringBuilder();
3066 Time tobj = new Time();
3067 tobj.set(System.currentTimeMillis());
3068 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
3069 sb.append(": ");
3070 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
3071 sb.append(" since ");
3072 sb.append(msg);
3073 FileOutputStream fos = new FileOutputStream(tracesFile);
3074 fos.write(sb.toString().getBytes());
3075 if (app == null) {
3076 fos.write("\n*** No application process!".getBytes());
3077 }
3078 fos.close();
3079 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
3080 } catch (IOException e) {
3081 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesPath, e);
3082 return;
3083 }
3084
3085 if (app != null) {
3086 ArrayList<Integer> firstPids = new ArrayList<Integer>();
3087 firstPids.add(app.pid);
3088 dumpStackTraces(tracesPath, firstPids, null, null);
3089 }
3090
3091 File lastTracesFile = null;
3092 File curTracesFile = null;
3093 for (int i=9; i>=0; i--) {
3094 String name = String.format("slow%02d.txt", i);
3095 curTracesFile = new File(tracesDir, name);
3096 if (curTracesFile.exists()) {
3097 if (lastTracesFile != null) {
3098 curTracesFile.renameTo(lastTracesFile);
3099 } else {
3100 curTracesFile.delete();
3101 }
3102 }
3103 lastTracesFile = curTracesFile;
3104 }
3105 tracesFile.renameTo(curTracesFile);
3106 if (tracesTmp.exists()) {
3107 tracesTmp.renameTo(tracesFile);
3108 }
3109 } finally {
3110 StrictMode.setThreadPolicy(oldPolicy);
3111 }
3112 }
3113
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003114 final void appNotResponding(ProcessRecord app, ActivityRecord activity,
3115 ActivityRecord parent, final String annotation) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003116 ArrayList<Integer> firstPids = new ArrayList<Integer>(5);
3117 SparseArray<Boolean> lastPids = new SparseArray<Boolean>(20);
3118
Dianne Hackborn287952c2010-09-22 22:34:31 -07003119 if (mController != null) {
3120 try {
3121 // 0 == continue, -1 = kill process immediately
3122 int res = mController.appEarlyNotResponding(app.processName, app.pid, annotation);
3123 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3124 } catch (RemoteException e) {
3125 mController = null;
3126 }
3127 }
3128
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003129 long anrTime = SystemClock.uptimeMillis();
3130 if (MONITOR_CPU_USAGE) {
3131 updateCpuStatsNow();
3132 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003133
3134 synchronized (this) {
3135 // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down.
3136 if (mShuttingDown) {
3137 Slog.i(TAG, "During shutdown skipping ANR: " + app + " " + annotation);
3138 return;
3139 } else if (app.notResponding) {
3140 Slog.i(TAG, "Skipping duplicate ANR: " + app + " " + annotation);
3141 return;
3142 } else if (app.crashing) {
3143 Slog.i(TAG, "Crashing app skipping ANR: " + app + " " + annotation);
3144 return;
3145 }
3146
3147 // In case we come through here for the same app before completing
3148 // this one, mark as anring now so we will bail out.
3149 app.notResponding = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08003150
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003151 // Log the ANR to the event log.
3152 EventLog.writeEvent(EventLogTags.AM_ANR, app.pid, app.processName, app.info.flags,
3153 annotation);
Dan Egnor42471dd2010-01-07 17:25:22 -08003154
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003155 // Dump thread traces as quickly as we can, starting with "interesting" processes.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003156 firstPids.add(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003157
3158 int parentPid = app.pid;
3159 if (parent != null && parent.app != null && parent.app.pid > 0) parentPid = parent.app.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003160 if (parentPid != app.pid) firstPids.add(parentPid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003161
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003162 if (MY_PID != app.pid && MY_PID != parentPid) firstPids.add(MY_PID);
Dan Egnor42471dd2010-01-07 17:25:22 -08003163
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003164 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
3165 ProcessRecord r = mLruProcesses.get(i);
3166 if (r != null && r.thread != null) {
3167 int pid = r.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003168 if (pid > 0 && pid != app.pid && pid != parentPid && pid != MY_PID) {
3169 if (r.persistent) {
3170 firstPids.add(pid);
3171 } else {
3172 lastPids.put(pid, Boolean.TRUE);
3173 }
3174 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003175 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003176 }
3177 }
3178
Dan Egnor42471dd2010-01-07 17:25:22 -08003179 // Log the ANR to the main log.
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07003180 StringBuilder info = mStringBuilder;
3181 info.setLength(0);
Dan Egnor42471dd2010-01-07 17:25:22 -08003182 info.append("ANR in ").append(app.processName);
3183 if (activity != null && activity.shortComponentName != null) {
3184 info.append(" (").append(activity.shortComponentName).append(")");
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07003185 }
Eric Rowe6f4f6192010-02-17 18:29:04 -08003186 info.append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003187 if (annotation != null) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003188 info.append("Reason: ").append(annotation).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003189 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003190 if (parent != null && parent != activity) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003191 info.append("Parent: ").append(parent.shortComponentName).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003192 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003193
Dianne Hackborn287952c2010-09-22 22:34:31 -07003194 final ProcessStats processStats = new ProcessStats(true);
3195
3196 File tracesFile = dumpStackTraces(true, firstPids, processStats, lastPids);
3197
Dan Egnor42471dd2010-01-07 17:25:22 -08003198 String cpuInfo = null;
3199 if (MONITOR_CPU_USAGE) {
3200 updateCpuStatsNow();
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003201 synchronized (mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003202 cpuInfo = mProcessStats.printCurrentState(anrTime);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003203 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003204 info.append(processStats.printCurrentLoad());
Dan Egnor42471dd2010-01-07 17:25:22 -08003205 info.append(cpuInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003206 }
3207
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003208 info.append(processStats.printCurrentState(anrTime));
3209
Joe Onorato8a9b2202010-02-26 18:56:32 -08003210 Slog.e(TAG, info.toString());
Dan Egnor42471dd2010-01-07 17:25:22 -08003211 if (tracesFile == null) {
3212 // There is no trace file, so dump (only) the alleged culprit's threads to the log
3213 Process.sendSignal(app.pid, Process.SIGNAL_QUIT);
3214 }
3215
Jeff Sharkeya353d262011-10-28 11:12:06 -07003216 addErrorToDropBox("anr", app, app.processName, activity, parent, annotation,
3217 cpuInfo, tracesFile, null);
Dan Egnor42471dd2010-01-07 17:25:22 -08003218
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003219 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003220 try {
Dan Egnor42471dd2010-01-07 17:25:22 -08003221 // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately
3222 int res = mController.appNotResponding(app.processName, app.pid, info.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003223 if (res != 0) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003224 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3225 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003226 }
3227 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003228 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003229 }
3230 }
3231
Dan Egnor42471dd2010-01-07 17:25:22 -08003232 // Unless configured otherwise, swallow ANRs in background processes & kill the process.
3233 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
3234 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003235
3236 synchronized (this) {
3237 if (!showBackground && !app.isInterestingToUserLocked() && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003238 Slog.w(TAG, "Killing " + app + ": background ANR");
3239 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
3240 app.processName, app.setAdj, "background ANR");
3241 Process.killProcessQuiet(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003242 return;
3243 }
3244
3245 // Set the app's notResponding state, and look up the errorReportReceiver
3246 makeAppNotRespondingLocked(app,
3247 activity != null ? activity.shortComponentName : null,
3248 annotation != null ? "ANR " + annotation : "ANR",
3249 info.toString());
3250
3251 // Bring up the infamous App Not Responding dialog
3252 Message msg = Message.obtain();
3253 HashMap map = new HashMap();
3254 msg.what = SHOW_NOT_RESPONDING_MSG;
3255 msg.obj = map;
3256 map.put("app", app);
3257 if (activity != null) {
3258 map.put("activity", activity);
3259 }
3260
3261 mHandler.sendMessage(msg);
Dan Egnor42471dd2010-01-07 17:25:22 -08003262 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003263 }
3264
Dianne Hackborn0dad3642010-09-09 21:25:35 -07003265 final void showLaunchWarningLocked(final ActivityRecord cur, final ActivityRecord next) {
3266 if (!mLaunchWarningShown) {
3267 mLaunchWarningShown = true;
3268 mHandler.post(new Runnable() {
3269 @Override
3270 public void run() {
3271 synchronized (ActivityManagerService.this) {
3272 final Dialog d = new LaunchWarningWindow(mContext, cur, next);
3273 d.show();
3274 mHandler.postDelayed(new Runnable() {
3275 @Override
3276 public void run() {
3277 synchronized (ActivityManagerService.this) {
3278 d.dismiss();
3279 mLaunchWarningShown = false;
3280 }
3281 }
3282 }, 4000);
3283 }
3284 }
3285 });
3286 }
3287 }
3288
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003289 public boolean clearApplicationUserData(final String packageName,
Amith Yamasani742a6712011-05-04 14:49:28 -07003290 final IPackageDataObserver observer, final int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003291 enforceNotIsolatedCaller("clearApplicationUserData");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003292 int uid = Binder.getCallingUid();
3293 int pid = Binder.getCallingPid();
3294 long callingId = Binder.clearCallingIdentity();
3295 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003296 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003297 int pkgUid = -1;
3298 synchronized(this) {
3299 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003300 pkgUid = pm.getPackageUid(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003301 } catch (RemoteException e) {
3302 }
3303 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003304 Slog.w(TAG, "Invalid packageName:" + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003305 return false;
3306 }
3307 if (uid == pkgUid || checkComponentPermission(
3308 android.Manifest.permission.CLEAR_APP_USER_DATA,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08003309 pid, uid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003310 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003311 forceStopPackageLocked(packageName, pkgUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003312 } else {
3313 throw new SecurityException(pid+" does not have permission:"+
3314 android.Manifest.permission.CLEAR_APP_USER_DATA+" to clear data" +
3315 "for process:"+packageName);
3316 }
3317 }
3318
3319 try {
3320 //clear application user data
Amith Yamasani483f3b02012-03-13 16:08:00 -07003321 pm.clearApplicationUserData(packageName, observer, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003322 Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED,
3323 Uri.fromParts("package", packageName, null));
3324 intent.putExtra(Intent.EXTRA_UID, pkgUid);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003325 broadcastIntentInPackage("android", Process.SYSTEM_UID, intent,
Amith Yamasani742a6712011-05-04 14:49:28 -07003326 null, null, 0, null, null, null, false, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003327 } catch (RemoteException e) {
3328 }
3329 } finally {
3330 Binder.restoreCallingIdentity(callingId);
3331 }
3332 return true;
3333 }
3334
Dianne Hackborn03abb812010-01-04 18:43:19 -08003335 public void killBackgroundProcesses(final String packageName) {
3336 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3337 != PackageManager.PERMISSION_GRANTED &&
3338 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES)
3339 != PackageManager.PERMISSION_GRANTED) {
3340 String msg = "Permission Denial: killBackgroundProcesses() from pid="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003341 + Binder.getCallingPid()
3342 + ", uid=" + Binder.getCallingUid()
Dianne Hackborn03abb812010-01-04 18:43:19 -08003343 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003344 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003345 throw new SecurityException(msg);
3346 }
3347
Amith Yamasani483f3b02012-03-13 16:08:00 -07003348 int userId = UserId.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003349 long callingId = Binder.clearCallingIdentity();
3350 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003351 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003352 int pkgUid = -1;
3353 synchronized(this) {
3354 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003355 pkgUid = pm.getPackageUid(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003356 } catch (RemoteException e) {
3357 }
3358 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003359 Slog.w(TAG, "Invalid packageName: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003360 return;
3361 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003362 killPackageProcessesLocked(packageName, pkgUid,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003363 ProcessList.SERVICE_ADJ, false, true, true, false, "kill background");
3364 }
3365 } finally {
3366 Binder.restoreCallingIdentity(callingId);
3367 }
3368 }
3369
3370 public void killAllBackgroundProcesses() {
3371 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3372 != PackageManager.PERMISSION_GRANTED) {
3373 String msg = "Permission Denial: killAllBackgroundProcesses() from pid="
3374 + Binder.getCallingPid()
3375 + ", uid=" + Binder.getCallingUid()
3376 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
3377 Slog.w(TAG, msg);
3378 throw new SecurityException(msg);
3379 }
3380
3381 long callingId = Binder.clearCallingIdentity();
3382 try {
3383 synchronized(this) {
3384 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
3385 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3386 final int NA = apps.size();
3387 for (int ia=0; ia<NA; ia++) {
3388 ProcessRecord app = apps.valueAt(ia);
3389 if (app.persistent) {
3390 // we don't kill persistent processes
3391 continue;
3392 }
3393 if (app.removed) {
3394 procs.add(app);
3395 } else if (app.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
3396 app.removed = true;
3397 procs.add(app);
3398 }
3399 }
3400 }
3401
3402 int N = procs.size();
3403 for (int i=0; i<N; i++) {
3404 removeProcessLocked(procs.get(i), false, true, "kill all background");
3405 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003406 }
3407 } finally {
3408 Binder.restoreCallingIdentity(callingId);
3409 }
3410 }
3411
3412 public void forceStopPackage(final String packageName) {
3413 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3414 != PackageManager.PERMISSION_GRANTED) {
3415 String msg = "Permission Denial: forceStopPackage() from pid="
3416 + Binder.getCallingPid()
3417 + ", uid=" + Binder.getCallingUid()
3418 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003419 Slog.w(TAG, msg);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003420 throw new SecurityException(msg);
3421 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07003422 final int userId = UserId.getCallingUserId();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003423 long callingId = Binder.clearCallingIdentity();
3424 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003425 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003426 int pkgUid = -1;
3427 synchronized(this) {
3428 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003429 pkgUid = pm.getPackageUid(packageName, userId);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003430 } catch (RemoteException e) {
3431 }
3432 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003433 Slog.w(TAG, "Invalid packageName: " + packageName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003434 return;
3435 }
3436 forceStopPackageLocked(packageName, pkgUid);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003437 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003438 pm.setPackageStoppedState(packageName, true, userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003439 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08003440 } catch (IllegalArgumentException e) {
3441 Slog.w(TAG, "Failed trying to unstop package "
3442 + packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003443 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003444 }
3445 } finally {
3446 Binder.restoreCallingIdentity(callingId);
3447 }
3448 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003449
3450 /*
3451 * The pkg name and uid have to be specified.
3452 * @see android.app.IActivityManager#killApplicationWithUid(java.lang.String, int)
3453 */
3454 public void killApplicationWithUid(String pkg, int uid) {
3455 if (pkg == null) {
3456 return;
3457 }
3458 // Make sure the uid is valid.
3459 if (uid < 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003460 Slog.w(TAG, "Invalid uid specified for pkg : " + pkg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003461 return;
3462 }
3463 int callerUid = Binder.getCallingUid();
3464 // Only the system server can kill an application
3465 if (callerUid == Process.SYSTEM_UID) {
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07003466 // Post an aysnc message to kill the application
3467 Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG);
3468 msg.arg1 = uid;
3469 msg.arg2 = 0;
3470 msg.obj = pkg;
Suchi Amalapurapud50066f2009-08-18 16:57:41 -07003471 mHandler.sendMessage(msg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003472 } else {
3473 throw new SecurityException(callerUid + " cannot kill pkg: " +
3474 pkg);
3475 }
3476 }
3477
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003478 public void closeSystemDialogs(String reason) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003479 enforceNotIsolatedCaller("closeSystemDialogs");
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003480 Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003481 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003482 if (reason != null) {
3483 intent.putExtra("reason", reason);
3484 }
3485
3486 final int uid = Binder.getCallingUid();
3487 final long origId = Binder.clearCallingIdentity();
3488 synchronized (this) {
Dianne Hackbornffa42482009-09-23 22:20:11 -07003489 mWindowManager.closeSystemDialogs(reason);
3490
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08003491 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003492 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornffa42482009-09-23 22:20:11 -07003493 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003494 r.stack.finishActivityLocked(r, i,
Dianne Hackbornffa42482009-09-23 22:20:11 -07003495 Activity.RESULT_CANCELED, null, "close-sys");
3496 }
3497 }
3498
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003499 broadcastIntentLocked(null, null, intent, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07003500 null, 0, null, null, null, false, false, -1, uid, 0 /* TODO: Verify */);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003501 }
3502 Binder.restoreCallingIdentity(origId);
3503 }
3504
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003505 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids)
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003506 throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003507 enforceNotIsolatedCaller("getProcessMemoryInfo");
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003508 Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length];
3509 for (int i=pids.length-1; i>=0; i--) {
3510 infos[i] = new Debug.MemoryInfo();
3511 Debug.getMemoryInfo(pids[i], infos[i]);
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003512 }
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003513 return infos;
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003514 }
Christopher Tate5e1ab332009-09-01 20:32:49 -07003515
Dianne Hackbornb437e092011-08-05 17:50:29 -07003516 public long[] getProcessPss(int[] pids) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003517 enforceNotIsolatedCaller("getProcessPss");
Dianne Hackbornb437e092011-08-05 17:50:29 -07003518 long[] pss = new long[pids.length];
3519 for (int i=pids.length-1; i>=0; i--) {
3520 pss[i] = Debug.getPss(pids[i]);
3521 }
3522 return pss;
3523 }
3524
Christopher Tate5e1ab332009-09-01 20:32:49 -07003525 public void killApplicationProcess(String processName, int uid) {
3526 if (processName == null) {
3527 return;
3528 }
3529
3530 int callerUid = Binder.getCallingUid();
3531 // Only the system server can kill an application
3532 if (callerUid == Process.SYSTEM_UID) {
3533 synchronized (this) {
3534 ProcessRecord app = getProcessRecordLocked(processName, uid);
Christopher Tate4a627c72011-04-01 14:43:32 -07003535 if (app != null && app.thread != null) {
Christopher Tate5e1ab332009-09-01 20:32:49 -07003536 try {
3537 app.thread.scheduleSuicide();
3538 } catch (RemoteException e) {
3539 // If the other end already died, then our work here is done.
3540 }
3541 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003542 Slog.w(TAG, "Process/uid not found attempting kill of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07003543 + processName + " / " + uid);
3544 }
3545 }
3546 } else {
3547 throw new SecurityException(callerUid + " cannot kill app process: " +
3548 processName);
3549 }
3550 }
3551
Dianne Hackborn03abb812010-01-04 18:43:19 -08003552 private void forceStopPackageLocked(final String packageName, int uid) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003553 forceStopPackageLocked(packageName, uid, false, false, true, false, UserId.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003554 Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED,
3555 Uri.fromParts("package", packageName, null));
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003556 if (!mProcessesReady) {
3557 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3558 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003559 intent.putExtra(Intent.EXTRA_UID, uid);
3560 broadcastIntentLocked(null, null, intent,
3561 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07003562 false, false,
3563 MY_PID, Process.SYSTEM_UID, UserId.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003564 }
3565
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003566 private final boolean killPackageProcessesLocked(String packageName, int uid,
Christopher Tate3dacd842011-08-19 14:56:15 -07003567 int minOomAdj, boolean callerWillRestart, boolean allowRestart, boolean doit,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003568 boolean evenPersistent, String reason) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003569 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003570
Dianne Hackborn03abb812010-01-04 18:43:19 -08003571 // Remove all processes this package may have touched: all with the
3572 // same UID (except for the system or root user), and all whose name
3573 // matches the package name.
3574 final String procNamePrefix = packageName + ":";
3575 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3576 final int NA = apps.size();
3577 for (int ia=0; ia<NA; ia++) {
3578 ProcessRecord app = apps.valueAt(ia);
Christopher Tate3dacd842011-08-19 14:56:15 -07003579 if (app.persistent && !evenPersistent) {
Christopher Tate064d8422011-07-26 15:38:07 -07003580 // we don't kill persistent processes
3581 continue;
3582 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003583 if (app.removed) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003584 if (doit) {
3585 procs.add(app);
3586 }
Amith Yamasani13593602012-03-22 16:16:17 -07003587 // If uid is specified and the uid and process name match
3588 // Or, the uid is not specified and the process name matches
3589 } else if (((uid > 0 && uid != Process.SYSTEM_UID && app.info.uid == uid)
3590 && (app.processName.equals(packageName)
3591 || app.processName.startsWith(procNamePrefix)))
3592 || (uid < 0
3593 && (app.processName.equals(packageName)
3594 || app.processName.startsWith(procNamePrefix)))) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003595 if (app.setAdj >= minOomAdj) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003596 if (!doit) {
3597 return true;
3598 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003599 app.removed = true;
3600 procs.add(app);
3601 }
3602 }
3603 }
3604 }
3605
3606 int N = procs.size();
3607 for (int i=0; i<N; i++) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003608 removeProcessLocked(procs.get(i), callerWillRestart, allowRestart, reason);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003609 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003610 return N > 0;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003611 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003612
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003613 private final boolean forceStopPackageLocked(String name, int uid,
Christopher Tate3dacd842011-08-19 14:56:15 -07003614 boolean callerWillRestart, boolean purgeCache, boolean doit,
Amith Yamasani483f3b02012-03-13 16:08:00 -07003615 boolean evenPersistent, int userId) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003616 int i;
3617 int N;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003618
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003619 if (uid < 0) {
3620 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003621 uid = AppGlobals.getPackageManager().getPackageUid(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003622 } catch (RemoteException e) {
3623 }
3624 }
3625
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003626 if (doit) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003627 Slog.i(TAG, "Force stopping package " + name + " uid=" + uid);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003628
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003629 Iterator<SparseArray<Long>> badApps = mProcessCrashTimes.getMap().values().iterator();
3630 while (badApps.hasNext()) {
3631 SparseArray<Long> ba = badApps.next();
3632 if (ba.get(uid) != null) {
3633 badApps.remove();
3634 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003635 }
3636 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003637
3638 boolean didSomething = killPackageProcessesLocked(name, uid, -100,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003639 callerWillRestart, false, doit, evenPersistent, "force stop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003640
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003641 TaskRecord lastTask = null;
3642 for (i=0; i<mMainStack.mHistory.size(); i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003643 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003644 final boolean samePackage = r.packageName.equals(name);
Amith Yamasani13593602012-03-22 16:16:17 -07003645 if (r.userId == userId
3646 && (samePackage || r.task == lastTask)
Christopher Tate3dacd842011-08-19 14:56:15 -07003647 && (r.app == null || evenPersistent || !r.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003648 if (!doit) {
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003649 if (r.finishing) {
3650 // If this activity is just finishing, then it is not
3651 // interesting as far as something to stop.
3652 continue;
3653 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003654 return true;
3655 }
3656 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003657 Slog.i(TAG, " Force finishing activity " + r);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003658 if (samePackage) {
3659 if (r.app != null) {
3660 r.app.removed = true;
3661 }
3662 r.app = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003663 }
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003664 lastTask = r.task;
3665 if (r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003666 null, "force-stop", true)) {
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003667 i--;
3668 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003669 }
3670 }
3671
3672 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
Amith Yamasani742a6712011-05-04 14:49:28 -07003673 for (ServiceRecord service : mServiceMap.getAllServices(userId)) {
Christopher Tate064d8422011-07-26 15:38:07 -07003674 if (service.packageName.equals(name)
Christopher Tate3dacd842011-08-19 14:56:15 -07003675 && (service.app == null || evenPersistent || !service.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003676 if (!doit) {
3677 return true;
3678 }
3679 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003680 Slog.i(TAG, " Force stopping service " + service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003681 if (service.app != null) {
3682 service.app.removed = true;
3683 }
3684 service.app = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003685 service.isolatedProc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003686 services.add(service);
3687 }
3688 }
3689
3690 N = services.size();
3691 for (i=0; i<N; i++) {
3692 bringDownServiceLocked(services.get(i), true);
3693 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003694
3695 ArrayList<ContentProviderRecord> providers = new ArrayList<ContentProviderRecord>();
Amith Yamasani13593602012-03-22 16:16:17 -07003696 for (ContentProviderRecord provider : mProviderMap.getProvidersByClass(userId).values()) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003697 if (provider.info.packageName.equals(name)
3698 && (provider.proc == null || evenPersistent || !provider.proc.persistent)) {
3699 if (!doit) {
3700 return true;
3701 }
3702 didSomething = true;
3703 providers.add(provider);
3704 }
3705 }
3706
3707 N = providers.size();
3708 for (i=0; i<N; i++) {
3709 removeDyingProviderLocked(null, providers.get(i));
3710 }
3711
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003712 if (doit) {
3713 if (purgeCache) {
3714 AttributeCache ac = AttributeCache.instance();
3715 if (ac != null) {
3716 ac.removePackage(name);
3717 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003718 }
Dianne Hackborn38cc8962011-10-13 11:33:55 -07003719 if (mBooted) {
3720 mMainStack.resumeTopActivityLocked(null);
3721 mMainStack.scheduleIdleLocked();
3722 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003723 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003724
3725 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003726 }
3727
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003728 private final boolean removeProcessLocked(ProcessRecord app,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003729 boolean callerWillRestart, boolean allowRestart, String reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003730 final String name = app.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003731 final int uid = app.uid;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003732 if (DEBUG_PROCESSES) Slog.d(
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003733 TAG, "Force removing proc " + app.toShortString() + " (" + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003734 + "/" + uid + ")");
3735
3736 mProcessNames.remove(name, uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003737 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003738 if (mHeavyWeightProcess == app) {
3739 mHeavyWeightProcess = null;
3740 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3741 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003742 boolean needRestart = false;
3743 if (app.pid > 0 && app.pid != MY_PID) {
3744 int pid = app.pid;
3745 synchronized (mPidsSelfLocked) {
3746 mPidsSelfLocked.remove(pid);
3747 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3748 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003749 Slog.i(TAG, "Killing proc " + app.toShortString() + ": " + reason);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003750 handleAppDiedLocked(app, true, allowRestart);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003751 mLruProcesses.remove(app);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003752 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003753
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003754 if (app.persistent && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003755 if (!callerWillRestart) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003756 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003757 } else {
3758 needRestart = true;
3759 }
3760 }
3761 } else {
3762 mRemovedProcesses.add(app);
3763 }
3764
3765 return needRestart;
3766 }
3767
3768 private final void processStartTimedOutLocked(ProcessRecord app) {
3769 final int pid = app.pid;
3770 boolean gone = false;
3771 synchronized (mPidsSelfLocked) {
3772 ProcessRecord knownApp = mPidsSelfLocked.get(pid);
3773 if (knownApp != null && knownApp.thread == null) {
3774 mPidsSelfLocked.remove(pid);
3775 gone = true;
3776 }
3777 }
3778
3779 if (gone) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003780 Slog.w(TAG, "Process " + app + " failed to attach");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003781 EventLog.writeEvent(EventLogTags.AM_PROCESS_START_TIMEOUT, pid, app.uid,
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003782 app.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003783 mProcessNames.remove(app.processName, app.uid);
3784 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003785 if (mHeavyWeightProcess == app) {
3786 mHeavyWeightProcess = null;
3787 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3788 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003789 // Take care of any launching providers waiting for this process.
3790 checkAppInLaunchingProvidersLocked(app, true);
3791 // Take care of any services that are waiting for the process.
3792 for (int i=0; i<mPendingServices.size(); i++) {
3793 ServiceRecord sr = mPendingServices.get(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003794 if ((app.uid == sr.appInfo.uid
3795 && app.processName.equals(sr.processName))
3796 || sr.isolatedProc == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003797 Slog.w(TAG, "Forcing bringing down service: " + sr);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003798 sr.isolatedProc = null;
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003799 mPendingServices.remove(i);
3800 i--;
3801 bringDownServiceLocked(sr, true);
3802 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003803 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003804 EventLog.writeEvent(EventLogTags.AM_KILL, pid,
3805 app.processName, app.setAdj, "start timeout");
3806 Process.killProcessQuiet(pid);
Christopher Tate181fafa2009-05-14 11:12:14 -07003807 if (mBackupTarget != null && mBackupTarget.app.pid == pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003808 Slog.w(TAG, "Unattached app died before backup, skipping");
Christopher Tate181fafa2009-05-14 11:12:14 -07003809 try {
3810 IBackupManager bm = IBackupManager.Stub.asInterface(
3811 ServiceManager.getService(Context.BACKUP_SERVICE));
3812 bm.agentDisconnected(app.info.packageName);
3813 } catch (RemoteException e) {
3814 // Can't happen; the backup manager is local
3815 }
3816 }
Christopher Tatef46723b2012-01-26 14:19:24 -08003817 if (isPendingBroadcastProcessLocked(pid)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003818 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
Christopher Tatef46723b2012-01-26 14:19:24 -08003819 skipPendingBroadcastLocked(pid);
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003820 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003821 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003822 Slog.w(TAG, "Spurious process start timeout - pid not known for " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003823 }
3824 }
3825
3826 private final boolean attachApplicationLocked(IApplicationThread thread,
3827 int pid) {
3828
3829 // Find the application record that is being attached... either via
3830 // the pid if we are running in multiple processes, or just pull the
3831 // next app record if we are emulating process with anonymous threads.
3832 ProcessRecord app;
3833 if (pid != MY_PID && pid >= 0) {
3834 synchronized (mPidsSelfLocked) {
3835 app = mPidsSelfLocked.get(pid);
3836 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003837 } else {
3838 app = null;
3839 }
3840
3841 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003842 Slog.w(TAG, "No pending application record for pid " + pid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003843 + " (IApplicationThread " + thread + "); dropping process");
Doug Zongker2bec3d42009-12-04 12:52:44 -08003844 EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003845 if (pid > 0 && pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003846 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003847 } else {
3848 try {
3849 thread.scheduleExit();
3850 } catch (Exception e) {
3851 // Ignore exceptions.
3852 }
3853 }
3854 return false;
3855 }
3856
3857 // If this application record is still attached to a previous
3858 // process, clean it up now.
3859 if (app.thread != null) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003860 handleAppDiedLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003861 }
3862
3863 // Tell the process all about itself.
3864
Joe Onorato8a9b2202010-02-26 18:56:32 -08003865 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003866 TAG, "Binding process pid " + pid + " to record " + app);
3867
3868 String processName = app.processName;
3869 try {
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07003870 AppDeathRecipient adr = new AppDeathRecipient(
3871 app, pid, thread);
3872 thread.asBinder().linkToDeath(adr, 0);
3873 app.deathRecipient = adr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003874 } catch (RemoteException e) {
3875 app.resetPackageList();
3876 startProcessLocked(app, "link fail", processName);
3877 return false;
3878 }
3879
Doug Zongker2bec3d42009-12-04 12:52:44 -08003880 EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.pid, app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003881
3882 app.thread = thread;
3883 app.curAdj = app.setAdj = -100;
Dianne Hackborn09c916b2009-12-08 14:50:51 -08003884 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
3885 app.setSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003886 app.forcingToForeground = null;
3887 app.foregroundServices = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07003888 app.hasShownUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003889 app.debugging = false;
3890
3891 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3892
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003893 boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003894 List providers = normalMode ? generateApplicationProvidersLocked(app) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003895
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003896 if (!normalMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003897 Slog.i(TAG, "Launching preboot mode app: " + app);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003898 }
3899
Joe Onorato8a9b2202010-02-26 18:56:32 -08003900 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003901 TAG, "New app record " + app
3902 + " thread=" + thread.asBinder() + " pid=" + pid);
3903 try {
3904 int testMode = IApplicationThread.DEBUG_OFF;
3905 if (mDebugApp != null && mDebugApp.equals(processName)) {
3906 testMode = mWaitForDebugger
3907 ? IApplicationThread.DEBUG_WAIT
3908 : IApplicationThread.DEBUG_ON;
3909 app.debugging = true;
3910 if (mDebugTransient) {
3911 mDebugApp = mOrigDebugApp;
3912 mWaitForDebugger = mOrigWaitForDebugger;
3913 }
3914 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003915 String profileFile = app.instrumentationProfileFile;
3916 ParcelFileDescriptor profileFd = null;
3917 boolean profileAutoStop = false;
3918 if (mProfileApp != null && mProfileApp.equals(processName)) {
3919 mProfileProc = app;
3920 profileFile = mProfileFile;
3921 profileFd = mProfileFd;
3922 profileAutoStop = mAutoStopProfiler;
3923 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08003924 boolean enableOpenGlTrace = false;
3925 if (mOpenGlTraceApp != null && mOpenGlTraceApp.equals(processName)) {
3926 enableOpenGlTrace = true;
3927 mOpenGlTraceApp = null;
3928 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003929
Christopher Tate181fafa2009-05-14 11:12:14 -07003930 // If the app is being launched for restore or full backup, set it up specially
3931 boolean isRestrictedBackupMode = false;
3932 if (mBackupTarget != null && mBackupAppName.equals(processName)) {
3933 isRestrictedBackupMode = (mBackupTarget.backupMode == BackupRecord.RESTORE)
Christopher Tate75a99702011-05-18 16:28:19 -07003934 || (mBackupTarget.backupMode == BackupRecord.RESTORE_FULL)
Christopher Tate181fafa2009-05-14 11:12:14 -07003935 || (mBackupTarget.backupMode == BackupRecord.BACKUP_FULL);
3936 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003937
Dianne Hackbornd7f6daa2009-06-22 17:06:35 -07003938 ensurePackageDexOpt(app.instrumentationInfo != null
3939 ? app.instrumentationInfo.packageName
3940 : app.info.packageName);
3941 if (app.instrumentationClass != null) {
3942 ensurePackageDexOpt(app.instrumentationClass.getPackageName());
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003943 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08003944 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Binding proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003945 + processName + " with config " + mConfiguration);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003946 ApplicationInfo appInfo = app.instrumentationInfo != null
3947 ? app.instrumentationInfo : app.info;
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -07003948 app.compat = compatibilityInfoForPackageLocked(appInfo);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003949 if (profileFd != null) {
3950 profileFd = profileFd.dup();
3951 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003952 thread.bindApplication(processName, appInfo, providers,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003953 app.instrumentationClass, profileFile, profileFd, profileAutoStop,
Siva Velusamy92a8b222012-03-09 16:24:04 -08003954 app.instrumentationArguments, app.instrumentationWatcher, testMode,
3955 enableOpenGlTrace, isRestrictedBackupMode || !normalMode, app.persistent,
Dianne Hackborn813075a62011-11-14 17:45:19 -08003956 new Configuration(mConfiguration), app.compat, getCommonServicesLocked(),
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08003957 mCoreSettingsObserver.getCoreSettingsLocked());
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003958 updateLruProcessLocked(app, false, true);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003959 app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003960 } catch (Exception e) {
3961 // todo: Yikes! What should we do? For now we will try to
3962 // start another process, but that could easily get us in
3963 // an infinite loop of restarting processes...
Joe Onorato8a9b2202010-02-26 18:56:32 -08003964 Slog.w(TAG, "Exception thrown during bind!", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003965
3966 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07003967 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003968 startProcessLocked(app, "bind fail", processName);
3969 return false;
3970 }
3971
3972 // Remove this record from the list of starting applications.
3973 mPersistentStartingProcesses.remove(app);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003974 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
3975 "Attach application locked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003976 mProcessesOnHold.remove(app);
3977
3978 boolean badApp = false;
3979 boolean didSomething = false;
3980
3981 // See if the top visible activity is waiting to run in this process...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003982 ActivityRecord hr = mMainStack.topRunningActivityLocked(null);
Christopher Tate04c0af82010-06-07 18:35:20 -07003983 if (hr != null && normalMode) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003984 if (hr.app == null && app.uid == hr.info.applicationInfo.uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003985 && processName.equals(hr.processName)) {
3986 try {
Mike Lockwood3a74bd32011-08-12 13:55:22 -07003987 if (mHeadless) {
3988 Slog.e(TAG, "Starting activities not supported on headless device: " + hr);
3989 } else if (mMainStack.realStartActivityLocked(hr, app, true, true)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003990 didSomething = true;
3991 }
3992 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003993 Slog.w(TAG, "Exception in new application when starting activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003994 + hr.intent.getComponent().flattenToShortString(), e);
3995 badApp = true;
3996 }
3997 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003998 mMainStack.ensureActivitiesVisibleLocked(hr, null, processName, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003999 }
4000 }
4001
4002 // Find any services that should be running in this process...
4003 if (!badApp && mPendingServices.size() > 0) {
4004 ServiceRecord sr = null;
4005 try {
4006 for (int i=0; i<mPendingServices.size(); i++) {
4007 sr = mPendingServices.get(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004008 if (app != sr.isolatedProc && (app.uid != sr.appInfo.uid
4009 || !processName.equals(sr.processName))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004010 continue;
4011 }
4012
4013 mPendingServices.remove(i);
4014 i--;
4015 realStartServiceLocked(sr, app);
4016 didSomething = true;
4017 }
4018 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004019 Slog.w(TAG, "Exception in new application when starting service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004020 + sr.shortName, e);
4021 badApp = true;
4022 }
4023 }
4024
Christopher Tatef46723b2012-01-26 14:19:24 -08004025 // Check if a next-broadcast receiver is in this process...
4026 if (!badApp && isPendingBroadcastProcessLocked(pid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004027 try {
Christopher Tatef46723b2012-01-26 14:19:24 -08004028 didSomething = sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004029 } catch (Exception e) {
Christopher Tatef46723b2012-01-26 14:19:24 -08004030 // If the app died trying to launch the receiver we declare it 'bad'
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004031 badApp = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004032 }
4033 }
4034
Christopher Tate181fafa2009-05-14 11:12:14 -07004035 // Check whether the next backup agent is in this process...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004036 if (!badApp && mBackupTarget != null && mBackupTarget.appInfo.uid == app.uid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004037 if (DEBUG_BACKUP) Slog.v(TAG, "New app is backup target, launching agent for " + app);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004038 ensurePackageDexOpt(mBackupTarget.appInfo.packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07004039 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004040 thread.scheduleCreateBackupAgent(mBackupTarget.appInfo,
4041 compatibilityInfoForPackageLocked(mBackupTarget.appInfo),
4042 mBackupTarget.backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -07004043 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004044 Slog.w(TAG, "Exception scheduling backup agent creation: ");
Christopher Tate181fafa2009-05-14 11:12:14 -07004045 e.printStackTrace();
4046 }
4047 }
4048
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004049 if (badApp) {
4050 // todo: Also need to kill application to deal with all
4051 // kinds of exceptions.
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004052 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004053 return false;
4054 }
4055
4056 if (!didSomething) {
4057 updateOomAdjLocked();
4058 }
4059
4060 return true;
4061 }
4062
4063 public final void attachApplication(IApplicationThread thread) {
4064 synchronized (this) {
4065 int callingPid = Binder.getCallingPid();
4066 final long origId = Binder.clearCallingIdentity();
4067 attachApplicationLocked(thread, callingPid);
4068 Binder.restoreCallingIdentity(origId);
4069 }
4070 }
4071
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004072 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004073 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004074 ActivityRecord r = mMainStack.activityIdleInternal(token, false, config);
4075 if (stopProfiling) {
4076 synchronized (this) {
4077 if (mProfileProc == r.app) {
4078 if (mProfileFd != null) {
4079 try {
4080 mProfileFd.close();
4081 } catch (IOException e) {
4082 }
4083 clearProfilerLocked();
4084 }
4085 }
4086 }
4087 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004088 Binder.restoreCallingIdentity(origId);
4089 }
4090
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004091 void enableScreenAfterBoot() {
Doug Zongker2bec3d42009-12-04 12:52:44 -08004092 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004093 SystemClock.uptimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004094 mWindowManager.enableScreenAfterBoot();
4095 }
4096
Dianne Hackborn661cd522011-08-22 00:26:20 -07004097 public void showBootMessage(final CharSequence msg, final boolean always) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004098 enforceNotIsolatedCaller("showBootMessage");
Dianne Hackborn661cd522011-08-22 00:26:20 -07004099 mWindowManager.showBootMessage(msg, always);
4100 }
4101
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004102 public void dismissKeyguardOnNextActivity() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004103 enforceNotIsolatedCaller("dismissKeyguardOnNextActivity");
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004104 synchronized (this) {
4105 mMainStack.dismissKeyguardOnNextActivityLocked();
4106 }
4107 }
4108
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004109 final void finishBooting() {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004110 IntentFilter pkgFilter = new IntentFilter();
4111 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
4112 pkgFilter.addDataScheme("package");
4113 mContext.registerReceiver(new BroadcastReceiver() {
4114 @Override
4115 public void onReceive(Context context, Intent intent) {
4116 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
4117 if (pkgs != null) {
4118 for (String pkg : pkgs) {
Vairavan Srinivasan61f07652010-07-22 13:36:40 -07004119 synchronized (ActivityManagerService.this) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07004120 if (forceStopPackageLocked(pkg, -1, false, false, false, false, 0)) {
4121 setResultCode(Activity.RESULT_OK);
4122 return;
4123 }
4124 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004125 }
4126 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004127 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004128 }, pkgFilter);
Amith Yamasani13593602012-03-22 16:16:17 -07004129
4130 IntentFilter userFilter = new IntentFilter();
4131 userFilter.addAction(Intent.ACTION_USER_REMOVED);
4132 mContext.registerReceiver(new BroadcastReceiver() {
4133 @Override
4134 public void onReceive(Context context, Intent intent) {
4135 onUserRemoved(intent);
4136 }
4137 }, userFilter);
4138
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004139 synchronized (this) {
4140 // Ensure that any processes we had put on hold are now started
4141 // up.
4142 final int NP = mProcessesOnHold.size();
4143 if (NP > 0) {
4144 ArrayList<ProcessRecord> procs =
4145 new ArrayList<ProcessRecord>(mProcessesOnHold);
4146 for (int ip=0; ip<NP; ip++) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004147 if (DEBUG_PROCESSES) Slog.v(TAG, "Starting process on hold: "
4148 + procs.get(ip));
4149 startProcessLocked(procs.get(ip), "on-hold", null);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004150 }
4151 }
4152
4153 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004154 // Start looking for apps that are abusing wake locks.
4155 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07004156 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004157 // Tell anyone interested that we are done booting!
Dianne Hackbornf4c454b2010-08-11 12:47:41 -07004158 SystemProperties.set("sys.boot_completed", "1");
Guang Zhu191713a2012-01-12 12:02:22 -08004159 SystemProperties.set("dev.bootcomplete", "1");
Amith Yamasani742a6712011-05-04 14:49:28 -07004160 /* TODO: Send this to all users that are to be logged in on startup */
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004161 broadcastIntentLocked(null, null,
4162 new Intent(Intent.ACTION_BOOT_COMPLETED, null),
4163 null, null, 0, null, null,
4164 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
Amith Yamasani742a6712011-05-04 14:49:28 -07004165 false, false, MY_PID, Process.SYSTEM_UID, Binder.getOrigCallingUser());
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004166 }
4167 }
4168 }
4169
4170 final void ensureBootCompleted() {
4171 boolean booting;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004172 boolean enableScreen;
4173 synchronized (this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004174 booting = mBooting;
4175 mBooting = false;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004176 enableScreen = !mBooted;
4177 mBooted = true;
4178 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004179
4180 if (booting) {
4181 finishBooting();
4182 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004183
4184 if (enableScreen) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004185 enableScreenAfterBoot();
4186 }
4187 }
4188
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004189 public final void activityPaused(IBinder token) {
4190 final long origId = Binder.clearCallingIdentity();
4191 mMainStack.activityPaused(token, false);
4192 Binder.restoreCallingIdentity(origId);
4193 }
4194
4195 public final void activityStopped(IBinder token, Bundle icicle, Bitmap thumbnail,
4196 CharSequence description) {
4197 if (localLOGV) Slog.v(
4198 TAG, "Activity stopped: token=" + token);
4199
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004200 // Refuse possible leaked file descriptors
4201 if (icicle != null && icicle.hasFileDescriptors()) {
4202 throw new IllegalArgumentException("File descriptors passed in Bundle");
4203 }
4204
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004205 ActivityRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004206
4207 final long origId = Binder.clearCallingIdentity();
4208
4209 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004210 r = mMainStack.isInStackLocked(token);
4211 if (r != null) {
4212 r.stack.activityStoppedLocked(r, icicle, thumbnail, description);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004213 }
4214 }
4215
4216 if (r != null) {
4217 sendPendingThumbnail(r, null, null, null, false);
4218 }
4219
4220 trimApplications();
4221
4222 Binder.restoreCallingIdentity(origId);
4223 }
4224
4225 public final void activityDestroyed(IBinder token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004226 if (DEBUG_SWITCH) Slog.v(TAG, "ACTIVITY DESTROYED: " + token);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004227 mMainStack.activityDestroyed(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004228 }
4229
4230 public String getCallingPackage(IBinder token) {
4231 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004232 ActivityRecord r = getCallingRecordLocked(token);
Dianne Hackborn9bbcb912009-10-20 15:42:38 -07004233 return r != null && r.app != null ? r.info.packageName : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004234 }
4235 }
4236
4237 public ComponentName getCallingActivity(IBinder token) {
4238 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004239 ActivityRecord r = getCallingRecordLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004240 return r != null ? r.intent.getComponent() : null;
4241 }
4242 }
4243
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004244 private ActivityRecord getCallingRecordLocked(IBinder token) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004245 ActivityRecord r = mMainStack.isInStackLocked(token);
4246 if (r == null) {
4247 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004248 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004249 return r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004250 }
4251
4252 public ComponentName getActivityClassForToken(IBinder token) {
4253 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004254 ActivityRecord r = mMainStack.isInStackLocked(token);
4255 if (r == null) {
4256 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004257 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004258 return r.intent.getComponent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004259 }
4260 }
4261
4262 public String getPackageForToken(IBinder token) {
4263 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004264 ActivityRecord r = mMainStack.isInStackLocked(token);
4265 if (r == null) {
4266 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004267 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004268 return r.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004269 }
4270 }
4271
4272 public IIntentSender getIntentSender(int type,
4273 String packageName, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004274 int requestCode, Intent[] intents, String[] resolvedTypes,
4275 int flags, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004276 enforceNotIsolatedCaller("getIntentSender");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004277 // Refuse possible leaked file descriptors
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004278 if (intents != null) {
4279 if (intents.length < 1) {
4280 throw new IllegalArgumentException("Intents array length must be >= 1");
4281 }
4282 for (int i=0; i<intents.length; i++) {
4283 Intent intent = intents[i];
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004284 if (intent != null) {
4285 if (intent.hasFileDescriptors()) {
4286 throw new IllegalArgumentException("File descriptors passed in Intent");
4287 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07004288 if (type == ActivityManager.INTENT_SENDER_BROADCAST &&
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004289 (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
4290 throw new IllegalArgumentException(
4291 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
4292 }
4293 intents[i] = new Intent(intent);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004294 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004295 }
4296 if (resolvedTypes != null && resolvedTypes.length != intents.length) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004297 throw new IllegalArgumentException(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004298 "Intent array length does not match resolvedTypes length");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004299 }
4300 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004301 if (options != null) {
4302 if (options.hasFileDescriptors()) {
4303 throw new IllegalArgumentException("File descriptors passed in options");
4304 }
4305 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004306
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004307 synchronized(this) {
4308 int callingUid = Binder.getCallingUid();
4309 try {
Jeff Brown10e89712011-07-08 18:52:57 -07004310 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004311 int uid = AppGlobals.getPackageManager()
Amith Yamasani483f3b02012-03-13 16:08:00 -07004312 .getPackageUid(packageName, UserId.getUserId(callingUid));
4313 if (!UserId.isSameApp(callingUid, uid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004314 String msg = "Permission Denial: getIntentSender() from pid="
4315 + Binder.getCallingPid()
4316 + ", uid=" + Binder.getCallingUid()
4317 + ", (need uid=" + uid + ")"
4318 + " is not allowed to send as package " + packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004319 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004320 throw new SecurityException(msg);
4321 }
4322 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004323
Amith Yamasani742a6712011-05-04 14:49:28 -07004324 if (DEBUG_MU)
4325 Slog.i(TAG_MU, "Getting intent sender for origCallingUid="
4326 + Binder.getOrigCallingUid());
4327 return getIntentSenderLocked(type, packageName, Binder.getOrigCallingUid(),
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004328 token, resultWho, requestCode, intents, resolvedTypes, flags, options);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004329
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004330 } catch (RemoteException e) {
4331 throw new SecurityException(e);
4332 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004333 }
4334 }
4335
4336 IIntentSender getIntentSenderLocked(int type,
4337 String packageName, int callingUid, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004338 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
4339 Bundle options) {
Amith Yamasani742a6712011-05-04 14:49:28 -07004340 if (DEBUG_MU)
4341 Slog.v(TAG_MU, "getIntentSenderLocked(): uid=" + callingUid);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004342 ActivityRecord activity = null;
Dianne Hackborna4972e92012-03-14 10:38:05 -07004343 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004344 activity = mMainStack.isInStackLocked(token);
4345 if (activity == null) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004346 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004347 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004348 if (activity.finishing) {
4349 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004350 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004351 }
4352
4353 final boolean noCreate = (flags&PendingIntent.FLAG_NO_CREATE) != 0;
4354 final boolean cancelCurrent = (flags&PendingIntent.FLAG_CANCEL_CURRENT) != 0;
4355 final boolean updateCurrent = (flags&PendingIntent.FLAG_UPDATE_CURRENT) != 0;
4356 flags &= ~(PendingIntent.FLAG_NO_CREATE|PendingIntent.FLAG_CANCEL_CURRENT
4357 |PendingIntent.FLAG_UPDATE_CURRENT);
4358
4359 PendingIntentRecord.Key key = new PendingIntentRecord.Key(
4360 type, packageName, activity, resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004361 requestCode, intents, resolvedTypes, flags, options);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004362 WeakReference<PendingIntentRecord> ref;
4363 ref = mIntentSenderRecords.get(key);
4364 PendingIntentRecord rec = ref != null ? ref.get() : null;
4365 if (rec != null) {
4366 if (!cancelCurrent) {
4367 if (updateCurrent) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004368 if (rec.key.requestIntent != null) {
4369 rec.key.requestIntent.replaceExtras(intents != null ? intents[0] : null);
4370 }
4371 if (intents != null) {
4372 intents[intents.length-1] = rec.key.requestIntent;
4373 rec.key.allIntents = intents;
4374 rec.key.allResolvedTypes = resolvedTypes;
4375 } else {
4376 rec.key.allIntents = null;
4377 rec.key.allResolvedTypes = null;
4378 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004379 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004380 return rec;
4381 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004382 rec.canceled = true;
4383 mIntentSenderRecords.remove(key);
4384 }
4385 if (noCreate) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004386 return rec;
4387 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004388 rec = new PendingIntentRecord(this, key, callingUid);
4389 mIntentSenderRecords.put(key, rec.ref);
Dianne Hackborna4972e92012-03-14 10:38:05 -07004390 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004391 if (activity.pendingResults == null) {
4392 activity.pendingResults
4393 = new HashSet<WeakReference<PendingIntentRecord>>();
4394 }
4395 activity.pendingResults.add(rec.ref);
4396 }
4397 return rec;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004398 }
4399
4400 public void cancelIntentSender(IIntentSender sender) {
4401 if (!(sender instanceof PendingIntentRecord)) {
4402 return;
4403 }
4404 synchronized(this) {
4405 PendingIntentRecord rec = (PendingIntentRecord)sender;
4406 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004407 int uid = AppGlobals.getPackageManager()
Amith Yamasani483f3b02012-03-13 16:08:00 -07004408 .getPackageUid(rec.key.packageName, UserId.getCallingUserId());
Amith Yamasani04e0d262012-02-14 11:50:53 -08004409 if (!UserId.isSameApp(uid, Binder.getCallingUid())) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004410 String msg = "Permission Denial: cancelIntentSender() from pid="
4411 + Binder.getCallingPid()
4412 + ", uid=" + Binder.getCallingUid()
4413 + " is not allowed to cancel packges "
4414 + rec.key.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004415 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004416 throw new SecurityException(msg);
4417 }
4418 } catch (RemoteException e) {
4419 throw new SecurityException(e);
4420 }
4421 cancelIntentSenderLocked(rec, true);
4422 }
4423 }
4424
4425 void cancelIntentSenderLocked(PendingIntentRecord rec, boolean cleanActivity) {
4426 rec.canceled = true;
4427 mIntentSenderRecords.remove(rec.key);
4428 if (cleanActivity && rec.key.activity != null) {
4429 rec.key.activity.pendingResults.remove(rec.ref);
4430 }
4431 }
4432
4433 public String getPackageForIntentSender(IIntentSender pendingResult) {
4434 if (!(pendingResult instanceof PendingIntentRecord)) {
4435 return null;
4436 }
Brad Fitzpatrickb213d102010-04-19 11:58:52 -07004437 try {
4438 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4439 return res.key.packageName;
4440 } catch (ClassCastException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004441 }
4442 return null;
4443 }
4444
Dianne Hackborn6c418d52011-06-29 14:05:33 -07004445 public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) {
4446 if (!(pendingResult instanceof PendingIntentRecord)) {
4447 return false;
4448 }
4449 try {
4450 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4451 if (res.key.allIntents == null) {
4452 return false;
4453 }
4454 for (int i=0; i<res.key.allIntents.length; i++) {
4455 Intent intent = res.key.allIntents[i];
4456 if (intent.getPackage() != null && intent.getComponent() != null) {
4457 return false;
4458 }
4459 }
4460 return true;
4461 } catch (ClassCastException e) {
4462 }
4463 return false;
4464 }
4465
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004466 public void setProcessLimit(int max) {
4467 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4468 "setProcessLimit()");
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004469 synchronized (this) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07004470 mProcessLimit = max < 0 ? ProcessList.MAX_HIDDEN_APPS : max;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004471 mProcessLimitOverride = max;
4472 }
4473 trimApplications();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004474 }
4475
4476 public int getProcessLimit() {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004477 synchronized (this) {
4478 return mProcessLimitOverride;
4479 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004480 }
4481
4482 void foregroundTokenDied(ForegroundToken token) {
4483 synchronized (ActivityManagerService.this) {
4484 synchronized (mPidsSelfLocked) {
4485 ForegroundToken cur
4486 = mForegroundProcesses.get(token.pid);
4487 if (cur != token) {
4488 return;
4489 }
4490 mForegroundProcesses.remove(token.pid);
4491 ProcessRecord pr = mPidsSelfLocked.get(token.pid);
4492 if (pr == null) {
4493 return;
4494 }
4495 pr.forcingToForeground = null;
4496 pr.foregroundServices = false;
4497 }
4498 updateOomAdjLocked();
4499 }
4500 }
4501
4502 public void setProcessForeground(IBinder token, int pid, boolean isForeground) {
4503 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4504 "setProcessForeground()");
4505 synchronized(this) {
4506 boolean changed = false;
4507
4508 synchronized (mPidsSelfLocked) {
4509 ProcessRecord pr = mPidsSelfLocked.get(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004510 if (pr == null && isForeground) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004511 Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004512 return;
4513 }
4514 ForegroundToken oldToken = mForegroundProcesses.get(pid);
4515 if (oldToken != null) {
4516 oldToken.token.unlinkToDeath(oldToken, 0);
4517 mForegroundProcesses.remove(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004518 if (pr != null) {
4519 pr.forcingToForeground = null;
4520 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004521 changed = true;
4522 }
4523 if (isForeground && token != null) {
4524 ForegroundToken newToken = new ForegroundToken() {
4525 public void binderDied() {
4526 foregroundTokenDied(this);
4527 }
4528 };
4529 newToken.pid = pid;
4530 newToken.token = token;
4531 try {
4532 token.linkToDeath(newToken, 0);
4533 mForegroundProcesses.put(pid, newToken);
4534 pr.forcingToForeground = token;
4535 changed = true;
4536 } catch (RemoteException e) {
4537 // If the process died while doing this, we will later
4538 // do the cleanup with the process death link.
4539 }
4540 }
4541 }
4542
4543 if (changed) {
4544 updateOomAdjLocked();
4545 }
4546 }
4547 }
4548
4549 // =========================================================
4550 // PERMISSIONS
4551 // =========================================================
4552
4553 static class PermissionController extends IPermissionController.Stub {
4554 ActivityManagerService mActivityManagerService;
4555 PermissionController(ActivityManagerService activityManagerService) {
4556 mActivityManagerService = activityManagerService;
4557 }
4558
4559 public boolean checkPermission(String permission, int pid, int uid) {
4560 return mActivityManagerService.checkPermission(permission, pid,
4561 uid) == PackageManager.PERMISSION_GRANTED;
4562 }
4563 }
4564
4565 /**
4566 * This can be called with or without the global lock held.
4567 */
4568 int checkComponentPermission(String permission, int pid, int uid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004569 int owningUid, boolean exported) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004570 // We might be performing an operation on behalf of an indirect binder
4571 // invocation, e.g. via {@link #openContentUri}. Check and adjust the
4572 // client identity accordingly before proceeding.
4573 Identity tlsIdentity = sCallerIdentity.get();
4574 if (tlsIdentity != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004575 Slog.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004576 + tlsIdentity.pid + "," + tlsIdentity.uid + "}");
4577 uid = tlsIdentity.uid;
4578 pid = tlsIdentity.pid;
4579 }
4580
4581 // Root, system server and our own process get to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07004582 if (uid == 0 || uid == Process.SYSTEM_UID || pid == MY_PID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004583 return PackageManager.PERMISSION_GRANTED;
4584 }
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004585 // Isolated processes don't get any permissions.
4586 if (UserId.isIsolated(uid)) {
4587 return PackageManager.PERMISSION_DENIED;
4588 }
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004589 // If there is a uid that owns whatever is being accessed, it has
4590 // blanket access to it regardless of the permissions it requires.
Amith Yamasani742a6712011-05-04 14:49:28 -07004591 if (owningUid >= 0 && UserId.isSameApp(uid, owningUid)) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004592 return PackageManager.PERMISSION_GRANTED;
4593 }
4594 // If the target is not exported, then nobody else can get to it.
4595 if (!exported) {
4596 Slog.w(TAG, "Permission denied: checkComponentPermission() owningUid=" + owningUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004597 return PackageManager.PERMISSION_DENIED;
4598 }
4599 if (permission == null) {
4600 return PackageManager.PERMISSION_GRANTED;
4601 }
4602 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004603 return AppGlobals.getPackageManager()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004604 .checkUidPermission(permission, uid);
4605 } catch (RemoteException e) {
4606 // Should never happen, but if it does... deny!
Joe Onorato8a9b2202010-02-26 18:56:32 -08004607 Slog.e(TAG, "PackageManager is dead?!?", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004608 }
4609 return PackageManager.PERMISSION_DENIED;
4610 }
4611
4612 /**
4613 * As the only public entry point for permissions checking, this method
4614 * can enforce the semantic that requesting a check on a null global
4615 * permission is automatically denied. (Internally a null permission
4616 * string is used when calling {@link #checkComponentPermission} in cases
4617 * when only uid-based security is needed.)
4618 *
4619 * This can be called with or without the global lock held.
4620 */
4621 public int checkPermission(String permission, int pid, int uid) {
4622 if (permission == null) {
4623 return PackageManager.PERMISSION_DENIED;
4624 }
Amith Yamasani742a6712011-05-04 14:49:28 -07004625 return checkComponentPermission(permission, pid, UserId.getAppId(uid), -1, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004626 }
4627
4628 /**
4629 * Binder IPC calls go through the public entry point.
4630 * This can be called with or without the global lock held.
4631 */
4632 int checkCallingPermission(String permission) {
4633 return checkPermission(permission,
4634 Binder.getCallingPid(),
Amith Yamasani742a6712011-05-04 14:49:28 -07004635 UserId.getAppId(Binder.getCallingUid()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004636 }
4637
4638 /**
4639 * This can be called with or without the global lock held.
4640 */
4641 void enforceCallingPermission(String permission, String func) {
4642 if (checkCallingPermission(permission)
4643 == PackageManager.PERMISSION_GRANTED) {
4644 return;
4645 }
4646
4647 String msg = "Permission Denial: " + func + " from pid="
4648 + Binder.getCallingPid()
4649 + ", uid=" + Binder.getCallingUid()
4650 + " requires " + permission;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004651 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004652 throw new SecurityException(msg);
4653 }
4654
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004655 /**
4656 * Determine if UID is holding permissions required to access {@link Uri} in
4657 * the given {@link ProviderInfo}. Final permission checking is always done
4658 * in {@link ContentProvider}.
4659 */
4660 private final boolean checkHoldingPermissionsLocked(
4661 IPackageManager pm, ProviderInfo pi, Uri uri, int uid, int modeFlags) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004662 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4663 "checkHoldingPermissionsLocked: uri=" + uri + " uid=" + uid);
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004664
4665 if (pi.applicationInfo.uid == uid) {
4666 return true;
4667 } else if (!pi.exported) {
4668 return false;
4669 }
4670
4671 boolean readMet = (modeFlags & Intent.FLAG_GRANT_READ_URI_PERMISSION) == 0;
4672 boolean writeMet = (modeFlags & Intent.FLAG_GRANT_WRITE_URI_PERMISSION) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004673 try {
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004674 // check if target holds top-level <provider> permissions
4675 if (!readMet && pi.readPermission != null
4676 && (pm.checkUidPermission(pi.readPermission, uid) == PERMISSION_GRANTED)) {
4677 readMet = true;
4678 }
4679 if (!writeMet && pi.writePermission != null
4680 && (pm.checkUidPermission(pi.writePermission, uid) == PERMISSION_GRANTED)) {
4681 writeMet = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004682 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004683
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004684 // track if unprotected read/write is allowed; any denied
4685 // <path-permission> below removes this ability
4686 boolean allowDefaultRead = pi.readPermission == null;
4687 boolean allowDefaultWrite = pi.writePermission == null;
Dianne Hackborn48058e82010-09-27 16:53:23 -07004688
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004689 // check if target holds any <path-permission> that match uri
4690 final PathPermission[] pps = pi.pathPermissions;
4691 if (pps != null) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004692 final String path = uri.getPath();
4693 int i = pps.length;
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004694 while (i > 0 && (!readMet || !writeMet)) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004695 i--;
4696 PathPermission pp = pps[i];
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004697 if (pp.match(path)) {
4698 if (!readMet) {
4699 final String pprperm = pp.getReadPermission();
4700 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking read perm for "
4701 + pprperm + " for " + pp.getPath()
4702 + ": match=" + pp.match(path)
4703 + " check=" + pm.checkUidPermission(pprperm, uid));
4704 if (pprperm != null) {
4705 if (pm.checkUidPermission(pprperm, uid) == PERMISSION_GRANTED) {
4706 readMet = true;
4707 } else {
4708 allowDefaultRead = false;
4709 }
4710 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004711 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004712 if (!writeMet) {
4713 final String ppwperm = pp.getWritePermission();
4714 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking write perm "
4715 + ppwperm + " for " + pp.getPath()
4716 + ": match=" + pp.match(path)
4717 + " check=" + pm.checkUidPermission(ppwperm, uid));
4718 if (ppwperm != null) {
4719 if (pm.checkUidPermission(ppwperm, uid) == PERMISSION_GRANTED) {
4720 writeMet = true;
4721 } else {
4722 allowDefaultWrite = false;
4723 }
4724 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004725 }
4726 }
4727 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07004728 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004729
4730 // grant unprotected <provider> read/write, if not blocked by
4731 // <path-permission> above
4732 if (allowDefaultRead) readMet = true;
4733 if (allowDefaultWrite) writeMet = true;
4734
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004735 } catch (RemoteException e) {
4736 return false;
4737 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004738
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004739 return readMet && writeMet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004740 }
4741
4742 private final boolean checkUriPermissionLocked(Uri uri, int uid,
4743 int modeFlags) {
4744 // Root gets to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07004745 if (uid == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004746 return true;
4747 }
4748 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(uid);
4749 if (perms == null) return false;
4750 UriPermission perm = perms.get(uri);
4751 if (perm == null) return false;
4752 return (modeFlags&perm.modeFlags) == modeFlags;
4753 }
4754
4755 public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004756 enforceNotIsolatedCaller("checkUriPermission");
4757
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004758 // Another redirected-binder-call permissions check as in
4759 // {@link checkComponentPermission}.
4760 Identity tlsIdentity = sCallerIdentity.get();
4761 if (tlsIdentity != null) {
4762 uid = tlsIdentity.uid;
4763 pid = tlsIdentity.pid;
4764 }
4765
Amith Yamasani742a6712011-05-04 14:49:28 -07004766 uid = UserId.getAppId(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004767 // Our own process gets to do everything.
4768 if (pid == MY_PID) {
4769 return PackageManager.PERMISSION_GRANTED;
4770 }
4771 synchronized(this) {
4772 return checkUriPermissionLocked(uri, uid, modeFlags)
4773 ? PackageManager.PERMISSION_GRANTED
4774 : PackageManager.PERMISSION_DENIED;
4775 }
4776 }
4777
Dianne Hackborn39792d22010-08-19 18:01:52 -07004778 /**
4779 * Check if the targetPkg can be granted permission to access uri by
4780 * the callingUid using the given modeFlags. Throws a security exception
4781 * if callingUid is not allowed to do this. Returns the uid of the target
4782 * if the URI permission grant should be performed; returns -1 if it is not
4783 * needed (for example targetPkg already has permission to access the URI).
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004784 * If you already know the uid of the target, you can supply it in
4785 * lastTargetUid else set that to -1.
Dianne Hackborn39792d22010-08-19 18:01:52 -07004786 */
4787 int checkGrantUriPermissionLocked(int callingUid, String targetPkg,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004788 Uri uri, int modeFlags, int lastTargetUid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004789 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4790 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4791 if (modeFlags == 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004792 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004793 }
4794
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004795 if (targetPkg != null) {
4796 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4797 "Checking grant " + targetPkg + " permission to " + uri);
4798 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004799
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004800 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004801
4802 // If this is not a content: uri, we can't do anything with it.
4803 if (!ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004804 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004805 "Can't grant URI permission for non-content URI: " + uri);
Dianne Hackborn39792d22010-08-19 18:01:52 -07004806 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004807 }
4808
4809 String name = uri.getAuthority();
4810 ProviderInfo pi = null;
Amith Yamasani742a6712011-05-04 14:49:28 -07004811 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
4812 UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004813 if (cpr != null) {
4814 pi = cpr.info;
4815 } else {
4816 try {
4817 pi = pm.resolveContentProvider(name,
Amith Yamasani483f3b02012-03-13 16:08:00 -07004818 PackageManager.GET_URI_PERMISSION_PATTERNS, UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004819 } catch (RemoteException ex) {
4820 }
4821 }
4822 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07004823 Slog.w(TAG, "No content provider found for permission check: " + uri.toSafeString());
Dianne Hackborn39792d22010-08-19 18:01:52 -07004824 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004825 }
4826
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004827 int targetUid = lastTargetUid;
4828 if (targetUid < 0 && targetPkg != null) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004829 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07004830 targetUid = pm.getPackageUid(targetPkg, UserId.getUserId(callingUid));
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004831 if (targetUid < 0) {
4832 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4833 "Can't grant URI permission no uid for: " + targetPkg);
4834 return -1;
4835 }
4836 } catch (RemoteException ex) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004837 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004838 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004839 }
4840
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004841 if (targetUid >= 0) {
4842 // First... does the target actually need this permission?
4843 if (checkHoldingPermissionsLocked(pm, pi, uri, targetUid, modeFlags)) {
4844 // No need to grant the target this permission.
4845 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4846 "Target " + targetPkg + " already has full permission to " + uri);
4847 return -1;
4848 }
4849 } else {
4850 // First... there is no target package, so can anyone access it?
4851 boolean allowed = pi.exported;
4852 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
4853 if (pi.readPermission != null) {
4854 allowed = false;
4855 }
4856 }
4857 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
4858 if (pi.writePermission != null) {
4859 allowed = false;
4860 }
4861 }
4862 if (allowed) {
4863 return -1;
4864 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004865 }
4866
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004867 // Second... is the provider allowing granting of URI permissions?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004868 if (!pi.grantUriPermissions) {
4869 throw new SecurityException("Provider " + pi.packageName
4870 + "/" + pi.name
4871 + " does not allow granting of Uri permissions (uri "
4872 + uri + ")");
4873 }
4874 if (pi.uriPermissionPatterns != null) {
4875 final int N = pi.uriPermissionPatterns.length;
4876 boolean allowed = false;
4877 for (int i=0; i<N; i++) {
4878 if (pi.uriPermissionPatterns[i] != null
4879 && pi.uriPermissionPatterns[i].match(uri.getPath())) {
4880 allowed = true;
4881 break;
4882 }
4883 }
4884 if (!allowed) {
4885 throw new SecurityException("Provider " + pi.packageName
4886 + "/" + pi.name
4887 + " does not allow granting of permission to path of Uri "
4888 + uri);
4889 }
4890 }
4891
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004892 // Third... does the caller itself have permission to access
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004893 // this uri?
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004894 if (callingUid != Process.myUid()) {
4895 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
4896 if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
4897 throw new SecurityException("Uid " + callingUid
4898 + " does not have permission to uri " + uri);
4899 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004900 }
4901 }
4902
Dianne Hackborn39792d22010-08-19 18:01:52 -07004903 return targetUid;
4904 }
4905
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004906 public int checkGrantUriPermission(int callingUid, String targetPkg,
4907 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004908 enforceNotIsolatedCaller("checkGrantUriPermission");
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004909 synchronized(this) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004910 return checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004911 }
4912 }
4913
Dianne Hackborn39792d22010-08-19 18:01:52 -07004914 void grantUriPermissionUncheckedLocked(int targetUid, String targetPkg,
4915 Uri uri, int modeFlags, UriPermissionOwner owner) {
4916 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4917 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4918 if (modeFlags == 0) {
4919 return;
4920 }
4921
4922 // So here we are: the caller has the assumed permission
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004923 // to the uri, and the target doesn't. Let's now give this to
4924 // the target.
4925
Joe Onorato8a9b2202010-02-26 18:56:32 -08004926 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn39792d22010-08-19 18:01:52 -07004927 "Granting " + targetPkg + "/" + targetUid + " permission to " + uri);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004928
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004929 HashMap<Uri, UriPermission> targetUris
4930 = mGrantedUriPermissions.get(targetUid);
4931 if (targetUris == null) {
4932 targetUris = new HashMap<Uri, UriPermission>();
4933 mGrantedUriPermissions.put(targetUid, targetUris);
4934 }
4935
4936 UriPermission perm = targetUris.get(uri);
4937 if (perm == null) {
4938 perm = new UriPermission(targetUid, uri);
4939 targetUris.put(uri, perm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004940 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07004941
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004942 perm.modeFlags |= modeFlags;
Dianne Hackborn39792d22010-08-19 18:01:52 -07004943 if (owner == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004944 perm.globalModeFlags |= modeFlags;
Vairavan Srinivasan91c12c22011-01-21 18:26:06 -08004945 } else {
4946 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
4947 perm.readOwners.add(owner);
4948 owner.addReadPermission(perm);
4949 }
4950 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
4951 perm.writeOwners.add(owner);
4952 owner.addWritePermission(perm);
4953 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004954 }
4955 }
4956
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004957 void grantUriPermissionLocked(int callingUid, String targetPkg, Uri uri,
4958 int modeFlags, UriPermissionOwner owner) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004959 if (targetPkg == null) {
4960 throw new NullPointerException("targetPkg");
4961 }
4962
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004963 int targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn39792d22010-08-19 18:01:52 -07004964 if (targetUid < 0) {
4965 return;
4966 }
4967
4968 grantUriPermissionUncheckedLocked(targetUid, targetPkg, uri, modeFlags, owner);
4969 }
4970
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004971 static class NeededUriGrants extends ArrayList<Uri> {
4972 final String targetPkg;
4973 final int targetUid;
4974 final int flags;
4975
4976 NeededUriGrants(String _targetPkg, int _targetUid, int _flags) {
4977 targetPkg = _targetPkg;
4978 targetUid = _targetUid;
4979 flags = _flags;
4980 }
4981 }
4982
Dianne Hackborn39792d22010-08-19 18:01:52 -07004983 /**
4984 * Like checkGrantUriPermissionLocked, but takes an Intent.
4985 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004986 NeededUriGrants checkGrantUriPermissionFromIntentLocked(int callingUid,
4987 String targetPkg, Intent intent, int mode, NeededUriGrants needed) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07004988 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004989 "Checking URI perm to data=" + (intent != null ? intent.getData() : null)
4990 + " clip=" + (intent != null ? intent.getClipData() : null)
Dianne Hackbornb424b632010-08-18 15:59:05 -07004991 + " from " + intent + "; flags=0x"
4992 + Integer.toHexString(intent != null ? intent.getFlags() : 0));
4993
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004994 if (targetPkg == null) {
4995 throw new NullPointerException("targetPkg");
4996 }
4997
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004998 if (intent == null) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004999 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005000 }
5001 Uri data = intent.getData();
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005002 ClipData clip = intent.getClipData();
5003 if (data == null && clip == null) {
5004 return null;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005005 }
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005006 if (data != null) {
5007 int target = checkGrantUriPermissionLocked(callingUid, targetPkg, data,
5008 mode, needed != null ? needed.targetUid : -1);
5009 if (target > 0) {
5010 if (needed == null) {
5011 needed = new NeededUriGrants(targetPkg, target, mode);
5012 }
5013 needed.add(data);
5014 }
5015 }
5016 if (clip != null) {
5017 for (int i=0; i<clip.getItemCount(); i++) {
5018 Uri uri = clip.getItemAt(i).getUri();
5019 if (uri != null) {
5020 int target = -1;
5021 target = checkGrantUriPermissionLocked(callingUid, targetPkg, uri,
5022 mode, needed != null ? needed.targetUid : -1);
5023 if (target > 0) {
5024 if (needed == null) {
5025 needed = new NeededUriGrants(targetPkg, target, mode);
5026 }
5027 needed.add(uri);
5028 }
5029 } else {
5030 Intent clipIntent = clip.getItemAt(i).getIntent();
5031 if (clipIntent != null) {
5032 NeededUriGrants newNeeded = checkGrantUriPermissionFromIntentLocked(
5033 callingUid, targetPkg, clipIntent, mode, needed);
5034 if (newNeeded != null) {
5035 needed = newNeeded;
5036 }
5037 }
5038 }
5039 }
5040 }
5041
5042 return needed;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005043 }
5044
5045 /**
5046 * Like grantUriPermissionUncheckedLocked, but takes an Intent.
5047 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005048 void grantUriPermissionUncheckedFromIntentLocked(NeededUriGrants needed,
5049 UriPermissionOwner owner) {
5050 if (needed != null) {
5051 for (int i=0; i<needed.size(); i++) {
5052 grantUriPermissionUncheckedLocked(needed.targetUid, needed.targetPkg,
5053 needed.get(i), needed.flags, owner);
5054 }
5055 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005056 }
5057
5058 void grantUriPermissionFromIntentLocked(int callingUid,
5059 String targetPkg, Intent intent, UriPermissionOwner owner) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005060 NeededUriGrants needed = checkGrantUriPermissionFromIntentLocked(callingUid, targetPkg,
Dianne Hackbornd9781fe2012-03-08 18:04:18 -08005061 intent, intent != null ? intent.getFlags() : 0, null);
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005062 if (needed == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005063 return;
5064 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005065
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005066 grantUriPermissionUncheckedFromIntentLocked(needed, owner);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005067 }
5068
5069 public void grantUriPermission(IApplicationThread caller, String targetPkg,
5070 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005071 enforceNotIsolatedCaller("grantUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005072 synchronized(this) {
5073 final ProcessRecord r = getRecordForAppLocked(caller);
5074 if (r == null) {
5075 throw new SecurityException("Unable to find app for caller "
5076 + caller
5077 + " when granting permission to uri " + uri);
5078 }
5079 if (targetPkg == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005080 throw new IllegalArgumentException("null target");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005081 }
5082 if (uri == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005083 throw new IllegalArgumentException("null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005084 }
5085
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005086 grantUriPermissionLocked(r.uid, targetPkg, uri, modeFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005087 null);
5088 }
5089 }
5090
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005091 void removeUriPermissionIfNeededLocked(UriPermission perm) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005092 if ((perm.modeFlags&(Intent.FLAG_GRANT_READ_URI_PERMISSION
5093 |Intent.FLAG_GRANT_WRITE_URI_PERMISSION)) == 0) {
5094 HashMap<Uri, UriPermission> perms
5095 = mGrantedUriPermissions.get(perm.uid);
5096 if (perms != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005097 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005098 "Removing " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005099 perms.remove(perm.uri);
5100 if (perms.size() == 0) {
5101 mGrantedUriPermissions.remove(perm.uid);
5102 }
5103 }
5104 }
5105 }
5106
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005107 private void revokeUriPermissionLocked(int callingUid, Uri uri,
5108 int modeFlags) {
5109 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5110 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5111 if (modeFlags == 0) {
5112 return;
5113 }
5114
Joe Onorato8a9b2202010-02-26 18:56:32 -08005115 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005116 "Revoking all granted permissions to " + uri);
5117
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005118 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005119
5120 final String authority = uri.getAuthority();
5121 ProviderInfo pi = null;
Amith Yamasani483f3b02012-03-13 16:08:00 -07005122 int userId = UserId.getUserId(callingUid);
5123 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005124 if (cpr != null) {
5125 pi = cpr.info;
5126 } else {
5127 try {
5128 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005129 PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005130 } catch (RemoteException ex) {
5131 }
5132 }
5133 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005134 Slog.w(TAG, "No content provider found for permission revoke: " + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005135 return;
5136 }
5137
5138 // Does the caller have this permission on the URI?
Dianne Hackborn48058e82010-09-27 16:53:23 -07005139 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005140 // Right now, if you are not the original owner of the permission,
5141 // you are not allowed to revoke it.
5142 //if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5143 throw new SecurityException("Uid " + callingUid
5144 + " does not have permission to uri " + uri);
5145 //}
5146 }
5147
5148 // Go through all of the permissions and remove any that match.
5149 final List<String> SEGMENTS = uri.getPathSegments();
5150 if (SEGMENTS != null) {
5151 final int NS = SEGMENTS.size();
5152 int N = mGrantedUriPermissions.size();
5153 for (int i=0; i<N; i++) {
5154 HashMap<Uri, UriPermission> perms
5155 = mGrantedUriPermissions.valueAt(i);
5156 Iterator<UriPermission> it = perms.values().iterator();
5157 toploop:
5158 while (it.hasNext()) {
5159 UriPermission perm = it.next();
5160 Uri targetUri = perm.uri;
5161 if (!authority.equals(targetUri.getAuthority())) {
5162 continue;
5163 }
5164 List<String> targetSegments = targetUri.getPathSegments();
5165 if (targetSegments == null) {
5166 continue;
5167 }
5168 if (targetSegments.size() < NS) {
5169 continue;
5170 }
5171 for (int j=0; j<NS; j++) {
5172 if (!SEGMENTS.get(j).equals(targetSegments.get(j))) {
5173 continue toploop;
5174 }
5175 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08005176 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005177 "Revoking " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005178 perm.clearModes(modeFlags);
5179 if (perm.modeFlags == 0) {
5180 it.remove();
5181 }
5182 }
5183 if (perms.size() == 0) {
5184 mGrantedUriPermissions.remove(
5185 mGrantedUriPermissions.keyAt(i));
5186 N--;
5187 i--;
5188 }
5189 }
5190 }
5191 }
5192
5193 public void revokeUriPermission(IApplicationThread caller, Uri uri,
5194 int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005195 enforceNotIsolatedCaller("revokeUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005196 synchronized(this) {
5197 final ProcessRecord r = getRecordForAppLocked(caller);
5198 if (r == null) {
5199 throw new SecurityException("Unable to find app for caller "
5200 + caller
5201 + " when revoking permission to uri " + uri);
5202 }
5203 if (uri == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005204 Slog.w(TAG, "revokeUriPermission: null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005205 return;
5206 }
5207
5208 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5209 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5210 if (modeFlags == 0) {
5211 return;
5212 }
5213
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005214 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005215
5216 final String authority = uri.getAuthority();
5217 ProviderInfo pi = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005218 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005219 if (cpr != null) {
5220 pi = cpr.info;
5221 } else {
5222 try {
5223 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005224 PackageManager.GET_URI_PERMISSION_PATTERNS, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005225 } catch (RemoteException ex) {
5226 }
5227 }
5228 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005229 Slog.w(TAG, "No content provider found for permission revoke: "
5230 + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005231 return;
5232 }
5233
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005234 revokeUriPermissionLocked(r.uid, uri, modeFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005235 }
5236 }
5237
Dianne Hackborn7e269642010-08-25 19:50:20 -07005238 @Override
5239 public IBinder newUriPermissionOwner(String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005240 enforceNotIsolatedCaller("newUriPermissionOwner");
Dianne Hackborn7e269642010-08-25 19:50:20 -07005241 synchronized(this) {
5242 UriPermissionOwner owner = new UriPermissionOwner(this, name);
5243 return owner.getExternalTokenLocked();
5244 }
5245 }
5246
5247 @Override
5248 public void grantUriPermissionFromOwner(IBinder token, int fromUid, String targetPkg,
5249 Uri uri, int modeFlags) {
5250 synchronized(this) {
5251 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5252 if (owner == null) {
5253 throw new IllegalArgumentException("Unknown owner: " + token);
5254 }
5255 if (fromUid != Binder.getCallingUid()) {
5256 if (Binder.getCallingUid() != Process.myUid()) {
5257 // Only system code can grant URI permissions on behalf
5258 // of other users.
5259 throw new SecurityException("nice try");
5260 }
5261 }
5262 if (targetPkg == null) {
5263 throw new IllegalArgumentException("null target");
5264 }
5265 if (uri == null) {
5266 throw new IllegalArgumentException("null uri");
5267 }
5268
5269 grantUriPermissionLocked(fromUid, targetPkg, uri, modeFlags, owner);
5270 }
5271 }
5272
5273 @Override
5274 public void revokeUriPermissionFromOwner(IBinder token, Uri uri, int mode) {
5275 synchronized(this) {
5276 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5277 if (owner == null) {
5278 throw new IllegalArgumentException("Unknown owner: " + token);
5279 }
5280
5281 if (uri == null) {
5282 owner.removeUriPermissionsLocked(mode);
5283 } else {
5284 owner.removeUriPermissionLocked(uri, mode);
5285 }
5286 }
5287 }
5288
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005289 public void showWaitingForDebugger(IApplicationThread who, boolean waiting) {
5290 synchronized (this) {
5291 ProcessRecord app =
5292 who != null ? getRecordForAppLocked(who) : null;
5293 if (app == null) return;
5294
5295 Message msg = Message.obtain();
5296 msg.what = WAIT_FOR_DEBUGGER_MSG;
5297 msg.obj = app;
5298 msg.arg1 = waiting ? 1 : 0;
5299 mHandler.sendMessage(msg);
5300 }
5301 }
5302
5303 public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07005304 final long homeAppMem = mProcessList.getMemLevel(ProcessList.HOME_APP_ADJ);
5305 final long hiddenAppMem = mProcessList.getMemLevel(ProcessList.HIDDEN_APP_MIN_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005306 outInfo.availMem = Process.getFreeMemory();
Dianne Hackborn7d608422011-08-07 16:24:18 -07005307 outInfo.threshold = homeAppMem;
5308 outInfo.lowMemory = outInfo.availMem < (homeAppMem + ((hiddenAppMem-homeAppMem)/2));
5309 outInfo.hiddenAppThreshold = hiddenAppMem;
5310 outInfo.secondaryServerThreshold = mProcessList.getMemLevel(
Dianne Hackborne02c88a2011-10-28 13:58:15 -07005311 ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07005312 outInfo.visibleAppThreshold = mProcessList.getMemLevel(
5313 ProcessList.VISIBLE_APP_ADJ);
5314 outInfo.foregroundAppThreshold = mProcessList.getMemLevel(
5315 ProcessList.FOREGROUND_APP_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005316 }
5317
5318 // =========================================================
5319 // TASK MANAGEMENT
5320 // =========================================================
5321
5322 public List getTasks(int maxNum, int flags,
5323 IThumbnailReceiver receiver) {
5324 ArrayList list = new ArrayList();
5325
5326 PendingThumbnailsRecord pending = null;
5327 IApplicationThread topThumbnail = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005328 ActivityRecord topRecord = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005329
5330 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005331 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005332 TAG, "getTasks: max=" + maxNum + ", flags=" + flags
5333 + ", receiver=" + receiver);
5334
5335 if (checkCallingPermission(android.Manifest.permission.GET_TASKS)
5336 != PackageManager.PERMISSION_GRANTED) {
5337 if (receiver != null) {
5338 // If the caller wants to wait for pending thumbnails,
5339 // it ain't gonna get them.
5340 try {
5341 receiver.finished();
5342 } catch (RemoteException ex) {
5343 }
5344 }
5345 String msg = "Permission Denial: getTasks() from pid="
5346 + Binder.getCallingPid()
5347 + ", uid=" + Binder.getCallingUid()
5348 + " requires " + android.Manifest.permission.GET_TASKS;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005349 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005350 throw new SecurityException(msg);
5351 }
5352
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005353 int pos = mMainStack.mHistory.size()-1;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005354 ActivityRecord next =
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005355 pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005356 ActivityRecord top = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005357 TaskRecord curTask = null;
5358 int numActivities = 0;
5359 int numRunning = 0;
5360 while (pos >= 0 && maxNum > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005361 final ActivityRecord r = next;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005362 pos--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005363 next = pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005364
5365 // Initialize state for next task if needed.
5366 if (top == null ||
5367 (top.state == ActivityState.INITIALIZING
5368 && top.task == r.task)) {
5369 top = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005370 curTask = r.task;
5371 numActivities = numRunning = 0;
5372 }
5373
5374 // Add 'r' into the current task.
5375 numActivities++;
5376 if (r.app != null && r.app.thread != null) {
5377 numRunning++;
5378 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005379
Joe Onorato8a9b2202010-02-26 18:56:32 -08005380 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005381 TAG, r.intent.getComponent().flattenToShortString()
5382 + ": task=" + r.task);
5383
5384 // If the next one is a different task, generate a new
5385 // TaskInfo entry for what we have.
5386 if (next == null || next.task != curTask) {
5387 ActivityManager.RunningTaskInfo ci
5388 = new ActivityManager.RunningTaskInfo();
5389 ci.id = curTask.taskId;
5390 ci.baseActivity = r.intent.getComponent();
5391 ci.topActivity = top.intent.getComponent();
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005392 if (top.thumbHolder != null) {
5393 ci.description = top.thumbHolder.lastDescription;
5394 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005395 ci.numActivities = numActivities;
5396 ci.numRunning = numRunning;
5397 //System.out.println(
5398 // "#" + maxNum + ": " + " descr=" + ci.description);
5399 if (ci.thumbnail == null && receiver != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005400 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005401 TAG, "State=" + top.state + "Idle=" + top.idle
5402 + " app=" + top.app
5403 + " thr=" + (top.app != null ? top.app.thread : null));
5404 if (top.state == ActivityState.RESUMED
5405 || top.state == ActivityState.PAUSING) {
5406 if (top.idle && top.app != null
5407 && top.app.thread != null) {
5408 topRecord = top;
5409 topThumbnail = top.app.thread;
5410 } else {
5411 top.thumbnailNeeded = true;
5412 }
5413 }
5414 if (pending == null) {
5415 pending = new PendingThumbnailsRecord(receiver);
5416 }
5417 pending.pendingRecords.add(top);
5418 }
5419 list.add(ci);
5420 maxNum--;
5421 top = null;
5422 }
5423 }
5424
5425 if (pending != null) {
5426 mPendingThumbnails.add(pending);
5427 }
5428 }
5429
Joe Onorato8a9b2202010-02-26 18:56:32 -08005430 if (localLOGV) Slog.v(TAG, "We have pending thumbnails: " + pending);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005431
5432 if (topThumbnail != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005433 if (localLOGV) Slog.v(TAG, "Requesting top thumbnail");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005434 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08005435 topThumbnail.requestThumbnail(topRecord.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005436 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005437 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005438 sendPendingThumbnail(null, topRecord.appToken, null, null, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005439 }
5440 }
5441
5442 if (pending == null && receiver != null) {
5443 // In this case all thumbnails were available and the client
5444 // is being asked to be told when the remaining ones come in...
5445 // which is unusually, since the top-most currently running
5446 // activity should never have a canned thumbnail! Oh well.
5447 try {
5448 receiver.finished();
5449 } catch (RemoteException ex) {
5450 }
5451 }
5452
5453 return list;
5454 }
5455
5456 public List<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum,
5457 int flags) {
Amith Yamasani742a6712011-05-04 14:49:28 -07005458 final int callingUid = Binder.getCallingUid();
5459 // If it's the system uid asking, then use the current user id.
5460 // TODO: Make sure that there aren't any other legitimate calls from the system uid that
5461 // require the entire list.
5462 final int callingUserId = callingUid == Process.SYSTEM_UID
5463 ? mCurrentUserId : UserId.getUserId(callingUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005464 synchronized (this) {
5465 enforceCallingPermission(android.Manifest.permission.GET_TASKS,
5466 "getRecentTasks()");
5467
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005468 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005469
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005470 final int N = mRecentTasks.size();
5471 ArrayList<ActivityManager.RecentTaskInfo> res
5472 = new ArrayList<ActivityManager.RecentTaskInfo>(
5473 maxNum < N ? maxNum : N);
5474 for (int i=0; i<N && maxNum > 0; i++) {
5475 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005476 // Only add calling user's recent tasks
5477 if (tr.userId != callingUserId) continue;
Dianne Hackborn905577f2011-09-07 18:31:28 -07005478 // Return the entry if desired by the caller. We always return
5479 // the first entry, because callers always expect this to be the
Amith Yamasani742a6712011-05-04 14:49:28 -07005480 // foreground app. We may filter others if the caller has
Dianne Hackborn905577f2011-09-07 18:31:28 -07005481 // not supplied RECENT_WITH_EXCLUDED and there is some reason
5482 // we should exclude the entry.
Amith Yamasani742a6712011-05-04 14:49:28 -07005483
Dianne Hackborn905577f2011-09-07 18:31:28 -07005484 if (i == 0
5485 || ((flags&ActivityManager.RECENT_WITH_EXCLUDED) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005486 || (tr.intent == null)
5487 || ((tr.intent.getFlags()
5488 &Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) == 0)) {
5489 ActivityManager.RecentTaskInfo rti
5490 = new ActivityManager.RecentTaskInfo();
5491 rti.id = tr.numActivities > 0 ? tr.taskId : -1;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005492 rti.persistentId = tr.taskId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005493 rti.baseIntent = new Intent(
5494 tr.intent != null ? tr.intent : tr.affinityIntent);
5495 rti.origActivity = tr.origActivity;
Dianne Hackbornd2835932010-12-13 16:28:46 -08005496 rti.description = tr.lastDescription;
5497
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005498 if ((flags&ActivityManager.RECENT_IGNORE_UNAVAILABLE) != 0) {
5499 // Check whether this activity is currently available.
5500 try {
5501 if (rti.origActivity != null) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07005502 if (pm.getActivityInfo(rti.origActivity, 0, callingUserId)
5503 == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005504 continue;
5505 }
5506 } else if (rti.baseIntent != null) {
5507 if (pm.queryIntentActivities(rti.baseIntent,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005508 null, 0, callingUserId) == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005509 continue;
5510 }
5511 }
5512 } catch (RemoteException e) {
5513 // Will never happen.
5514 }
5515 }
5516
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005517 res.add(rti);
5518 maxNum--;
5519 }
5520 }
5521 return res;
5522 }
5523 }
5524
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005525 private TaskRecord taskForIdLocked(int id) {
5526 final int N = mRecentTasks.size();
5527 for (int i=0; i<N; i++) {
5528 TaskRecord tr = mRecentTasks.get(i);
5529 if (tr.taskId == id) {
5530 return tr;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005531 }
5532 }
5533 return null;
5534 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005535
5536 public ActivityManager.TaskThumbnails getTaskThumbnails(int id) {
5537 synchronized (this) {
5538 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
5539 "getTaskThumbnails()");
5540 TaskRecord tr = taskForIdLocked(id);
5541 if (tr != null) {
5542 return mMainStack.getTaskThumbnailsLocked(tr);
5543 }
5544 }
5545 return null;
5546 }
5547
5548 public boolean removeSubTask(int taskId, int subTaskIndex) {
5549 synchronized (this) {
5550 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5551 "removeSubTask()");
5552 long ident = Binder.clearCallingIdentity();
5553 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005554 return mMainStack.removeTaskActivitiesLocked(taskId, subTaskIndex,
5555 true) != null;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005556 } finally {
5557 Binder.restoreCallingIdentity(ident);
5558 }
5559 }
5560 }
5561
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005562 private void cleanUpRemovedTaskLocked(TaskRecord tr, int flags) {
5563 final boolean killProcesses = (flags&ActivityManager.REMOVE_TASK_KILL_PROCESS) != 0;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005564 Intent baseIntent = new Intent(
5565 tr.intent != null ? tr.intent : tr.affinityIntent);
5566 ComponentName component = baseIntent.getComponent();
5567 if (component == null) {
5568 Slog.w(TAG, "Now component for base intent of task: " + tr);
5569 return;
5570 }
5571
5572 // Find any running services associated with this app.
5573 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005574 for (ServiceRecord sr : mServiceMap.getAllServices(tr.userId)) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005575 if (sr.packageName.equals(component.getPackageName())) {
5576 services.add(sr);
5577 }
5578 }
5579
5580 // Take care of any running services associated with the app.
5581 for (int i=0; i<services.size(); i++) {
5582 ServiceRecord sr = services.get(i);
5583 if (sr.startRequested) {
5584 if ((sr.serviceInfo.flags&ServiceInfo.FLAG_STOP_WITH_TASK) != 0) {
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005585 Slog.i(TAG, "Stopping service " + sr.shortName + ": remove task");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005586 stopServiceLocked(sr);
5587 } else {
5588 sr.pendingStarts.add(new ServiceRecord.StartItem(sr, true,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005589 sr.makeNextStartId(), baseIntent, null));
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005590 if (sr.app != null && sr.app.thread != null) {
5591 sendServiceArgsLocked(sr, false);
5592 }
5593 }
5594 }
5595 }
5596
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005597 if (killProcesses) {
5598 // Find any running processes associated with this app.
5599 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
5600 SparseArray<ProcessRecord> appProcs
5601 = mProcessNames.getMap().get(component.getPackageName());
5602 if (appProcs != null) {
5603 for (int i=0; i<appProcs.size(); i++) {
5604 procs.add(appProcs.valueAt(i));
5605 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005606 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005607
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005608 // Kill the running processes.
5609 for (int i=0; i<procs.size(); i++) {
5610 ProcessRecord pr = procs.get(i);
5611 if (pr.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
5612 Slog.i(TAG, "Killing " + pr.toShortString() + ": remove task");
5613 EventLog.writeEvent(EventLogTags.AM_KILL, pr.pid,
5614 pr.processName, pr.setAdj, "remove task");
5615 Process.killProcessQuiet(pr.pid);
5616 } else {
5617 pr.waitingToKill = "remove task";
5618 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005619 }
5620 }
5621 }
5622
5623 public boolean removeTask(int taskId, int flags) {
5624 synchronized (this) {
5625 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5626 "removeTask()");
5627 long ident = Binder.clearCallingIdentity();
5628 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005629 ActivityRecord r = mMainStack.removeTaskActivitiesLocked(taskId, -1,
5630 false);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005631 if (r != null) {
5632 mRecentTasks.remove(r.task);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005633 cleanUpRemovedTaskLocked(r.task, flags);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005634 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005635 } else {
5636 TaskRecord tr = null;
5637 int i=0;
5638 while (i < mRecentTasks.size()) {
5639 TaskRecord t = mRecentTasks.get(i);
5640 if (t.taskId == taskId) {
5641 tr = t;
5642 break;
5643 }
5644 i++;
5645 }
5646 if (tr != null) {
5647 if (tr.numActivities <= 0) {
5648 // Caller is just removing a recent task that is
5649 // not actively running. That is easy!
5650 mRecentTasks.remove(i);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005651 cleanUpRemovedTaskLocked(tr, flags);
5652 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005653 } else {
5654 Slog.w(TAG, "removeTask: task " + taskId
5655 + " does not have activities to remove, "
5656 + " but numActivities=" + tr.numActivities
5657 + ": " + tr);
5658 }
5659 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005660 }
5661 } finally {
5662 Binder.restoreCallingIdentity(ident);
5663 }
5664 }
5665 return false;
5666 }
Dianne Hackbornd94df452011-02-16 18:53:31 -08005667
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005668 private final int findAffinityTaskTopLocked(int startIndex, String affinity) {
5669 int j;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005670 TaskRecord startTask = ((ActivityRecord)mMainStack.mHistory.get(startIndex)).task;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005671 TaskRecord jt = startTask;
5672
5673 // First look backwards
5674 for (j=startIndex-1; j>=0; j--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005675 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005676 if (r.task != jt) {
5677 jt = r.task;
5678 if (affinity.equals(jt.affinity)) {
5679 return j;
5680 }
5681 }
5682 }
5683
5684 // Now look forwards
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005685 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005686 jt = startTask;
5687 for (j=startIndex+1; j<N; j++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005688 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005689 if (r.task != jt) {
5690 if (affinity.equals(jt.affinity)) {
5691 return j;
5692 }
5693 jt = r.task;
5694 }
5695 }
5696
5697 // Might it be at the top?
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005698 if (affinity.equals(((ActivityRecord)mMainStack.mHistory.get(N-1)).task.affinity)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005699 return N-1;
5700 }
5701
5702 return -1;
5703 }
5704
5705 /**
Dianne Hackbornb06ea702009-07-13 13:07:51 -07005706 * TODO: Add mController hook
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005707 */
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005708 public void moveTaskToFront(int task, int flags, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005709 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5710 "moveTaskToFront()");
5711
5712 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005713 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5714 Binder.getCallingUid(), "Task to front")) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005715 ActivityOptions.abort(options);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005716 return;
5717 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005718 final long origId = Binder.clearCallingIdentity();
5719 try {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005720 TaskRecord tr = taskForIdLocked(task);
5721 if (tr != null) {
5722 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5723 mMainStack.mUserLeaving = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005724 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005725 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5726 // Caller wants the home activity moved with it. To accomplish this,
5727 // we'll just move the home task to the top first.
5728 mMainStack.moveHomeToFrontLocked();
5729 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005730 mMainStack.moveTaskToFrontLocked(tr, null, options);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005731 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005732 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005733 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
5734 ActivityRecord hr = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005735 if (hr.task.taskId == task) {
Dianne Hackbornd94df452011-02-16 18:53:31 -08005736 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5737 mMainStack.mUserLeaving = true;
5738 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005739 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5740 // Caller wants the home activity moved with it. To accomplish this,
5741 // we'll just move the home task to the top first.
5742 mMainStack.moveHomeToFrontLocked();
5743 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005744 mMainStack.moveTaskToFrontLocked(hr.task, null, options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005745 return;
5746 }
5747 }
5748 } finally {
5749 Binder.restoreCallingIdentity(origId);
5750 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005751 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005752 }
5753 }
5754
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005755 public void moveTaskToBack(int task) {
5756 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5757 "moveTaskToBack()");
5758
5759 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005760 if (mMainStack.mResumedActivity != null
5761 && mMainStack.mResumedActivity.task.taskId == task) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005762 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5763 Binder.getCallingUid(), "Task to back")) {
5764 return;
5765 }
5766 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005767 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005768 mMainStack.moveTaskToBackLocked(task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005769 Binder.restoreCallingIdentity(origId);
5770 }
5771 }
5772
5773 /**
5774 * Moves an activity, and all of the other activities within the same task, to the bottom
5775 * of the history stack. The activity's order within the task is unchanged.
5776 *
5777 * @param token A reference to the activity we wish to move
5778 * @param nonRoot If false then this only works if the activity is the root
5779 * of a task; if true it will work for any activity in a task.
5780 * @return Returns true if the move completed, false if not.
5781 */
5782 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005783 enforceNotIsolatedCaller("moveActivityTaskToBack");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005784 synchronized(this) {
5785 final long origId = Binder.clearCallingIdentity();
5786 int taskId = getTaskForActivityLocked(token, !nonRoot);
5787 if (taskId >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005788 return mMainStack.moveTaskToBackLocked(taskId, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005789 }
5790 Binder.restoreCallingIdentity(origId);
5791 }
5792 return false;
5793 }
5794
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005795 public void moveTaskBackwards(int task) {
5796 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5797 "moveTaskBackwards()");
5798
5799 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005800 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5801 Binder.getCallingUid(), "Task backwards")) {
5802 return;
5803 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005804 final long origId = Binder.clearCallingIdentity();
5805 moveTaskBackwardsLocked(task);
5806 Binder.restoreCallingIdentity(origId);
5807 }
5808 }
5809
5810 private final void moveTaskBackwardsLocked(int task) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005811 Slog.e(TAG, "moveTaskBackwards not yet implemented!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005812 }
5813
5814 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
5815 synchronized(this) {
5816 return getTaskForActivityLocked(token, onlyRoot);
5817 }
5818 }
5819
5820 int getTaskForActivityLocked(IBinder token, boolean onlyRoot) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005821 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005822 TaskRecord lastTask = null;
5823 for (int i=0; i<N; i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005824 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005825 if (r.appToken == token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005826 if (!onlyRoot || lastTask != r.task) {
5827 return r.task.taskId;
5828 }
5829 return -1;
5830 }
5831 lastTask = r.task;
5832 }
5833
5834 return -1;
5835 }
5836
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005837 // =========================================================
5838 // THUMBNAILS
5839 // =========================================================
5840
5841 public void reportThumbnail(IBinder token,
5842 Bitmap thumbnail, CharSequence description) {
5843 //System.out.println("Report thumbnail for " + token + ": " + thumbnail);
5844 final long origId = Binder.clearCallingIdentity();
5845 sendPendingThumbnail(null, token, thumbnail, description, true);
5846 Binder.restoreCallingIdentity(origId);
5847 }
5848
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005849 final void sendPendingThumbnail(ActivityRecord r, IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005850 Bitmap thumbnail, CharSequence description, boolean always) {
5851 TaskRecord task = null;
5852 ArrayList receivers = null;
5853
5854 //System.out.println("Send pending thumbnail: " + r);
5855
5856 synchronized(this) {
5857 if (r == null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07005858 r = mMainStack.isInStackLocked(token);
5859 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005860 return;
5861 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005862 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005863 if (thumbnail == null && r.thumbHolder != null) {
5864 thumbnail = r.thumbHolder.lastThumbnail;
5865 description = r.thumbHolder.lastDescription;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005866 }
5867 if (thumbnail == null && !always) {
5868 // If there is no thumbnail, and this entry is not actually
5869 // going away, then abort for now and pick up the next
5870 // thumbnail we get.
5871 return;
5872 }
5873 task = r.task;
5874
5875 int N = mPendingThumbnails.size();
5876 int i=0;
5877 while (i<N) {
5878 PendingThumbnailsRecord pr =
5879 (PendingThumbnailsRecord)mPendingThumbnails.get(i);
5880 //System.out.println("Looking in " + pr.pendingRecords);
5881 if (pr.pendingRecords.remove(r)) {
5882 if (receivers == null) {
5883 receivers = new ArrayList();
5884 }
5885 receivers.add(pr);
5886 if (pr.pendingRecords.size() == 0) {
5887 pr.finished = true;
5888 mPendingThumbnails.remove(i);
5889 N--;
5890 continue;
5891 }
5892 }
5893 i++;
5894 }
5895 }
5896
5897 if (receivers != null) {
5898 final int N = receivers.size();
5899 for (int i=0; i<N; i++) {
5900 try {
5901 PendingThumbnailsRecord pr =
5902 (PendingThumbnailsRecord)receivers.get(i);
5903 pr.receiver.newThumbnail(
5904 task != null ? task.taskId : -1, thumbnail, description);
5905 if (pr.finished) {
5906 pr.receiver.finished();
5907 }
5908 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005909 Slog.w(TAG, "Exception thrown when sending thumbnail", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005910 }
5911 }
5912 }
5913 }
5914
5915 // =========================================================
5916 // CONTENT PROVIDERS
5917 // =========================================================
5918
Jeff Brown10e89712011-07-08 18:52:57 -07005919 private final List<ProviderInfo> generateApplicationProvidersLocked(ProcessRecord app) {
5920 List<ProviderInfo> providers = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005921 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005922 providers = AppGlobals.getPackageManager().
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005923 queryContentProviders(app.processName, app.uid,
Dianne Hackborn1655be42009-05-08 14:29:01 -07005924 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005925 } catch (RemoteException ex) {
5926 }
Amith Yamasani742a6712011-05-04 14:49:28 -07005927 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005928 Slog.v(TAG_MU, "generateApplicationProvidersLocked, app.info.uid = " + app.uid);
5929 int userId = app.userId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005930 if (providers != null) {
5931 final int N = providers.size();
5932 for (int i=0; i<N; i++) {
5933 ProviderInfo cpi =
5934 (ProviderInfo)providers.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005935
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07005936 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07005937 ContentProviderRecord cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005938 if (cpr == null) {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08005939 cpr = new ContentProviderRecord(this, cpi, app.info, comp);
Amith Yamasani742a6712011-05-04 14:49:28 -07005940 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005941 }
Amith Yamasani742a6712011-05-04 14:49:28 -07005942 if (DEBUG_MU)
5943 Slog.v(TAG_MU, "generateApplicationProvidersLocked, cpi.uid = " + cpr.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005944 app.pubProviders.put(cpi.name, cpr);
5945 app.addPackage(cpi.applicationInfo.packageName);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07005946 ensurePackageDexOpt(cpi.applicationInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005947 }
5948 }
5949 return providers;
5950 }
5951
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005952 /**
5953 * Check if {@link ProcessRecord} has a possible chance at accessing the
5954 * given {@link ProviderInfo}. Final permission checking is always done
5955 * in {@link ContentProvider}.
5956 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005957 private final String checkContentProviderPermissionLocked(
Dianne Hackbornb424b632010-08-18 15:59:05 -07005958 ProviderInfo cpi, ProcessRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005959 final int callingPid = (r != null) ? r.pid : Binder.getCallingPid();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005960 final int callingUid = (r != null) ? r.uid : Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005961 if (checkComponentPermission(cpi.readPermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005962 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005963 == PackageManager.PERMISSION_GRANTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005964 return null;
5965 }
5966 if (checkComponentPermission(cpi.writePermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005967 cpi.applicationInfo.uid, cpi.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005968 == PackageManager.PERMISSION_GRANTED) {
5969 return null;
5970 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07005971
5972 PathPermission[] pps = cpi.pathPermissions;
5973 if (pps != null) {
5974 int i = pps.length;
5975 while (i > 0) {
5976 i--;
5977 PathPermission pp = pps[i];
5978 if (checkComponentPermission(pp.getReadPermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005979 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005980 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07005981 return null;
5982 }
5983 if (checkComponentPermission(pp.getWritePermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005984 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackborn2af632f2009-07-08 14:56:37 -07005985 == PackageManager.PERMISSION_GRANTED) {
5986 return null;
5987 }
5988 }
5989 }
5990
Dianne Hackbornb424b632010-08-18 15:59:05 -07005991 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(callingUid);
5992 if (perms != null) {
5993 for (Map.Entry<Uri, UriPermission> uri : perms.entrySet()) {
5994 if (uri.getKey().getAuthority().equals(cpi.authority)) {
5995 return null;
5996 }
5997 }
5998 }
5999
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006000 String msg;
6001 if (!cpi.exported) {
6002 msg = "Permission Denial: opening provider " + cpi.name
6003 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6004 + ", uid=" + callingUid + ") that is not exported from uid "
6005 + cpi.applicationInfo.uid;
6006 } else {
6007 msg = "Permission Denial: opening provider " + cpi.name
6008 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6009 + ", uid=" + callingUid + ") requires "
6010 + cpi.readPermission + " or " + cpi.writePermission;
6011 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08006012 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006013 return msg;
6014 }
6015
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006016 boolean incProviderCount(ProcessRecord r, final ContentProviderRecord cpr,
6017 IBinder externalProcessToken) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006018 if (r != null) {
6019 Integer cnt = r.conProviders.get(cpr);
6020 if (DEBUG_PROVIDER) Slog.v(TAG,
6021 "Adding provider requested by "
6022 + r.processName + " from process "
6023 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
6024 + " cnt=" + (cnt == null ? 1 : cnt));
6025 if (cnt == null) {
6026 cpr.clients.add(r);
6027 r.conProviders.put(cpr, new Integer(1));
6028 return true;
6029 } else {
6030 r.conProviders.put(cpr, new Integer(cnt.intValue()+1));
6031 }
6032 } else {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006033 cpr.addExternalProcessHandleLocked(externalProcessToken);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006034 }
6035 return false;
6036 }
6037
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006038 boolean decProviderCount(ProcessRecord r, final ContentProviderRecord cpr,
6039 IBinder externalProcessToken) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006040 if (r != null) {
6041 Integer cnt = r.conProviders.get(cpr);
6042 if (DEBUG_PROVIDER) Slog.v(TAG,
6043 "Removing provider requested by "
6044 + r.processName + " from process "
6045 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
6046 + " cnt=" + cnt);
6047 if (cnt == null || cnt.intValue() <= 1) {
6048 cpr.clients.remove(r);
6049 r.conProviders.remove(cpr);
6050 return true;
6051 } else {
6052 r.conProviders.put(cpr, new Integer(cnt.intValue()-1));
6053 }
6054 } else {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006055 cpr.removeExternalProcessHandleLocked(externalProcessToken);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006056 }
6057 return false;
6058 }
6059
Amith Yamasani742a6712011-05-04 14:49:28 -07006060 private final ContentProviderHolder getContentProviderImpl(IApplicationThread caller,
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006061 String name, IBinder token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006062 ContentProviderRecord cpr;
6063 ProviderInfo cpi = null;
6064
6065 synchronized(this) {
6066 ProcessRecord r = null;
6067 if (caller != null) {
6068 r = getRecordForAppLocked(caller);
6069 if (r == null) {
6070 throw new SecurityException(
6071 "Unable to find app for caller " + caller
6072 + " (pid=" + Binder.getCallingPid()
6073 + ") when getting content provider " + name);
6074 }
6075 }
6076
6077 // First check if this content provider has been published...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006078 int userId = UserId.getUserId(r != null ? r.uid : Binder.getCallingUid());
Amith Yamasani742a6712011-05-04 14:49:28 -07006079 cpr = mProviderMap.getProviderByName(name, userId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006080 boolean providerRunning = cpr != null;
6081 if (providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006082 cpi = cpr.info;
Dianne Hackbornb424b632010-08-18 15:59:05 -07006083 String msg;
6084 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6085 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006086 }
6087
6088 if (r != null && cpr.canRunHere(r)) {
6089 // This provider has been published or is in the process
6090 // of being published... but it is also allowed to run
6091 // in the caller's process, so don't make a connection
6092 // and just let the caller instantiate its own instance.
6093 if (cpr.provider != null) {
6094 // don't give caller the provider object, it needs
6095 // to make its own.
6096 cpr = new ContentProviderRecord(cpr);
6097 }
6098 return cpr;
6099 }
6100
6101 final long origId = Binder.clearCallingIdentity();
6102
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006103 // In this case the provider instance already exists, so we can
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006104 // return it right away.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006105 final boolean countChanged = incProviderCount(r, cpr, token);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006106 if (countChanged) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006107 if (cpr.proc != null && r.setAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006108 // If this is a perceptible app accessing the provider,
Dianne Hackborn906497c2010-05-10 15:57:38 -07006109 // make sure to count it as being accessed and thus
6110 // back up on the LRU list. This is good because
6111 // content providers are often expensive to start.
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006112 updateLruProcessLocked(cpr.proc, false, true);
Dianne Hackborn906497c2010-05-10 15:57:38 -07006113 }
Dianne Hackborn6f86c0e2010-05-11 14:20:52 -07006114 }
6115
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006116 if (cpr.proc != null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006117 if (false) {
6118 if (cpr.name.flattenToShortString().equals(
6119 "com.android.providers.calendar/.CalendarProvider2")) {
6120 Slog.v(TAG, "****************** KILLING "
6121 + cpr.name.flattenToShortString());
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006122 Process.killProcess(cpr.proc.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006123 }
6124 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006125 boolean success = updateOomAdjLocked(cpr.proc);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006126 if (DEBUG_PROVIDER) Slog.i(TAG, "Adjust success: " + success);
6127 // NOTE: there is still a race here where a signal could be
6128 // pending on the process even though we managed to update its
6129 // adj level. Not sure what to do about this, but at least
6130 // the race is now smaller.
6131 if (!success) {
6132 // Uh oh... it looks like the provider's process
6133 // has been killed on us. We need to wait for a new
6134 // process to be started, and make sure its death
6135 // doesn't kill our process.
6136 Slog.i(TAG,
6137 "Existing provider " + cpr.name.flattenToShortString()
6138 + " is crashing; detaching " + r);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006139 boolean lastRef = decProviderCount(r, cpr, token);
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006140 appDiedLocked(cpr.proc, cpr.proc.pid, cpr.proc.thread);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006141 if (!lastRef) {
6142 // This wasn't the last ref our process had on
6143 // the provider... we have now been killed, bail.
6144 return null;
6145 }
6146 providerRunning = false;
6147 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006148 }
6149
6150 Binder.restoreCallingIdentity(origId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006151 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006152
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006153 if (!providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006154 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006155 cpi = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07006156 resolveContentProvider(name,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006157 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006158 } catch (RemoteException ex) {
6159 }
6160 if (cpi == null) {
6161 return null;
6162 }
6163
Amith Yamasani483f3b02012-03-13 16:08:00 -07006164 cpi.applicationInfo = getAppInfoForUser(cpi.applicationInfo, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07006165
Dianne Hackbornb424b632010-08-18 15:59:05 -07006166 String msg;
6167 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6168 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006169 }
6170
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07006171 if (!mProcessesReady && !mDidUpdate && !mWaitingUpdate
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006172 && !cpi.processName.equals("system")) {
6173 // If this content provider does not run in the system
6174 // process, and the system is not yet ready to run other
6175 // processes, then fail fast instead of hanging.
6176 throw new IllegalArgumentException(
6177 "Attempt to launch content provider before system ready");
6178 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006179
6180 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani483f3b02012-03-13 16:08:00 -07006181 cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006182 final boolean firstClass = cpr == null;
6183 if (firstClass) {
6184 try {
6185 ApplicationInfo ai =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006186 AppGlobals.getPackageManager().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006187 getApplicationInfo(
6188 cpi.applicationInfo.packageName,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006189 STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006190 if (ai == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006191 Slog.w(TAG, "No package info for content provider "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006192 + cpi.name);
6193 return null;
6194 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006195 ai = getAppInfoForUser(ai, userId);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006196 cpr = new ContentProviderRecord(this, cpi, ai, comp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006197 } catch (RemoteException ex) {
6198 // pm is in same process, this will never happen.
6199 }
6200 }
6201
6202 if (r != null && cpr.canRunHere(r)) {
6203 // If this is a multiprocess provider, then just return its
6204 // info and allow the caller to instantiate it. Only do
6205 // this if the provider is the same user as the caller's
6206 // process, or can run as root (so can be in any process).
6207 return cpr;
6208 }
6209
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006210 if (DEBUG_PROVIDER) {
6211 RuntimeException e = new RuntimeException("here");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006212 Slog.w(TAG, "LAUNCHING REMOTE PROVIDER (myuid " + r.uid
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006213 + " pruid " + cpr.appInfo.uid + "): " + cpr.info.name, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006214 }
6215
6216 // This is single process, and our app is now connecting to it.
6217 // See if we are already in the process of launching this
6218 // provider.
6219 final int N = mLaunchingProviders.size();
6220 int i;
6221 for (i=0; i<N; i++) {
6222 if (mLaunchingProviders.get(i) == cpr) {
6223 break;
6224 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006225 }
6226
6227 // If the provider is not already being launched, then get it
6228 // started.
6229 if (i >= N) {
6230 final long origId = Binder.clearCallingIdentity();
Dianne Hackborne7f97212011-02-24 14:40:20 -08006231
6232 try {
6233 // Content provider is now in use, its package can't be stopped.
6234 try {
6235 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07006236 cpr.appInfo.packageName, false, userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006237 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006238 } catch (IllegalArgumentException e) {
6239 Slog.w(TAG, "Failed trying to unstop package "
6240 + cpr.appInfo.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006241 }
6242
6243 ProcessRecord proc = startProcessLocked(cpi.processName,
6244 cpr.appInfo, false, 0, "content provider",
6245 new ComponentName(cpi.applicationInfo.packageName,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006246 cpi.name), false, false);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006247 if (proc == null) {
6248 Slog.w(TAG, "Unable to launch app "
6249 + cpi.applicationInfo.packageName + "/"
6250 + cpi.applicationInfo.uid + " for provider "
6251 + name + ": process is bad");
6252 return null;
6253 }
6254 cpr.launchingApp = proc;
6255 mLaunchingProviders.add(cpr);
6256 } finally {
6257 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006258 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006259 }
6260
6261 // Make sure the provider is published (the same provider class
6262 // may be published under multiple names).
6263 if (firstClass) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006264 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006265 }
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006266
Amith Yamasani742a6712011-05-04 14:49:28 -07006267 mProviderMap.putProviderByName(name, cpr);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006268 incProviderCount(r, cpr, token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006269 }
6270 }
6271
6272 // Wait for the provider to be published...
6273 synchronized (cpr) {
6274 while (cpr.provider == null) {
6275 if (cpr.launchingApp == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006276 Slog.w(TAG, "Unable to launch app "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006277 + cpi.applicationInfo.packageName + "/"
6278 + cpi.applicationInfo.uid + " for provider "
6279 + name + ": launching app became null");
Doug Zongker2bec3d42009-12-04 12:52:44 -08006280 EventLog.writeEvent(EventLogTags.AM_PROVIDER_LOST_PROCESS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006281 cpi.applicationInfo.packageName,
6282 cpi.applicationInfo.uid, name);
6283 return null;
6284 }
6285 try {
Amith Yamasani742a6712011-05-04 14:49:28 -07006286 if (DEBUG_MU) {
6287 Slog.v(TAG_MU, "Waiting to start provider " + cpr + " launchingApp="
6288 + cpr.launchingApp);
6289 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006290 cpr.wait();
6291 } catch (InterruptedException ex) {
6292 }
6293 }
6294 }
6295 return cpr;
6296 }
6297
6298 public final ContentProviderHolder getContentProvider(
6299 IApplicationThread caller, String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006300 enforceNotIsolatedCaller("getContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006301 if (caller == null) {
6302 String msg = "null IApplicationThread when getting content provider "
6303 + name;
Joe Onorato8a9b2202010-02-26 18:56:32 -08006304 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006305 throw new SecurityException(msg);
6306 }
6307
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006308 return getContentProviderImpl(caller, name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006309 }
6310
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006311 public ContentProviderHolder getContentProviderExternal(String name, IBinder token) {
6312 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6313 "Do not have permission in call getContentProviderExternal()");
6314 return getContentProviderExternalUnchecked(name, token);
6315 }
6316
6317 private ContentProviderHolder getContentProviderExternalUnchecked(String name,IBinder token) {
6318 return getContentProviderImpl(null, name, token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006319 }
6320
6321 /**
6322 * Drop a content provider from a ProcessRecord's bookkeeping
6323 * @param cpr
6324 */
6325 public void removeContentProvider(IApplicationThread caller, String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006326 enforceNotIsolatedCaller("removeContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006327 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006328 int userId = UserId.getUserId(Binder.getCallingUid());
6329 ContentProviderRecord cpr = mProviderMap.getProviderByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006330 if(cpr == null) {
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006331 // remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006332 if (DEBUG_PROVIDER) Slog.v(TAG, name +
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006333 " provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006334 return;
6335 }
6336 final ProcessRecord r = getRecordForAppLocked(caller);
6337 if (r == null) {
6338 throw new SecurityException(
6339 "Unable to find app for caller " + caller +
6340 " when removing content provider " + name);
6341 }
6342 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006343 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006344 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp, userId);
6345 if (DEBUG_PROVIDER) Slog.v(TAG, "Removing provider requested by "
6346 + r.info.processName + " from process "
6347 + localCpr.appInfo.processName);
6348 if (localCpr.launchingApp == r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006349 //should not happen. taken care of as a local provider
Joe Onorato8a9b2202010-02-26 18:56:32 -08006350 Slog.w(TAG, "removeContentProvider called on local provider: "
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006351 + cpr.info.name + " in process " + r.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006352 return;
6353 } else {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006354 if (decProviderCount(r, localCpr, null)) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006355 updateOomAdjLocked();
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07006356 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006357 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006358 }
6359 }
6360
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006361 public void removeContentProviderExternal(String name, IBinder token) {
6362 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6363 "Do not have permission in call removeContentProviderExternal()");
6364 removeContentProviderExternalUnchecked(name, token);
6365 }
6366
6367 private void removeContentProviderExternalUnchecked(String name, IBinder token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006368 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006369 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
6370 Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006371 if(cpr == null) {
6372 //remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006373 if(localLOGV) Slog.v(TAG, name+" content provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006374 return;
6375 }
6376
6377 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006378 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006379 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp,
6380 Binder.getOrigCallingUser());
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006381 if (localCpr.hasExternalProcessHandles()) {
6382 if (localCpr.removeExternalProcessHandleLocked(token)) {
6383 updateOomAdjLocked();
6384 } else {
6385 Slog.e(TAG, "Attmpt to remove content provider " + localCpr
6386 + " with no external reference for token: "
6387 + token + ".");
6388 }
6389 } else {
6390 Slog.e(TAG, "Attmpt to remove content provider: " + localCpr
6391 + " with no external references.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006392 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006393 }
6394 }
6395
6396 public final void publishContentProviders(IApplicationThread caller,
6397 List<ContentProviderHolder> providers) {
6398 if (providers == null) {
6399 return;
6400 }
6401
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006402 enforceNotIsolatedCaller("publishContentProviders");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006403 synchronized(this) {
6404 final ProcessRecord r = getRecordForAppLocked(caller);
Amith Yamasani742a6712011-05-04 14:49:28 -07006405 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006406 Slog.v(TAG_MU, "ProcessRecord uid = " + r.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006407 if (r == null) {
6408 throw new SecurityException(
6409 "Unable to find app for caller " + caller
6410 + " (pid=" + Binder.getCallingPid()
6411 + ") when publishing content providers");
6412 }
6413
6414 final long origId = Binder.clearCallingIdentity();
6415
6416 final int N = providers.size();
6417 for (int i=0; i<N; i++) {
6418 ContentProviderHolder src = providers.get(i);
6419 if (src == null || src.info == null || src.provider == null) {
6420 continue;
6421 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07006422 ContentProviderRecord dst = r.pubProviders.get(src.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006423 if (DEBUG_MU)
6424 Slog.v(TAG_MU, "ContentProviderRecord uid = " + dst.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006425 if (dst != null) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006426 ComponentName comp = new ComponentName(dst.info.packageName, dst.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006427 mProviderMap.putProviderByClass(comp, dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006428 String names[] = dst.info.authority.split(";");
6429 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006430 mProviderMap.putProviderByName(names[j], dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006431 }
6432
6433 int NL = mLaunchingProviders.size();
6434 int j;
6435 for (j=0; j<NL; j++) {
6436 if (mLaunchingProviders.get(j) == dst) {
6437 mLaunchingProviders.remove(j);
6438 j--;
6439 NL--;
6440 }
6441 }
6442 synchronized (dst) {
6443 dst.provider = src.provider;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006444 dst.proc = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006445 dst.notifyAll();
6446 }
6447 updateOomAdjLocked(r);
6448 }
6449 }
6450
6451 Binder.restoreCallingIdentity(origId);
6452 }
6453 }
6454
6455 public static final void installSystemProviders() {
Jeff Brown10e89712011-07-08 18:52:57 -07006456 List<ProviderInfo> providers;
Josh Bartel2ecce342010-02-25 10:55:48 -06006457 synchronized (mSelf) {
6458 ProcessRecord app = mSelf.mProcessNames.get("system", Process.SYSTEM_UID);
6459 providers = mSelf.generateApplicationProvidersLocked(app);
Dianne Hackborn5c83a5f2010-03-12 16:46:46 -08006460 if (providers != null) {
6461 for (int i=providers.size()-1; i>=0; i--) {
6462 ProviderInfo pi = (ProviderInfo)providers.get(i);
6463 if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6464 Slog.w(TAG, "Not installing system proc provider " + pi.name
6465 + ": not system .apk");
6466 providers.remove(i);
6467 }
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006468 }
6469 }
6470 }
Josh Bartel2ecce342010-02-25 10:55:48 -06006471 if (providers != null) {
6472 mSystemThread.installSystemProviders(providers);
6473 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08006474
6475 mSelf.mCoreSettingsObserver = new CoreSettingsObserver(mSelf);
Mark Brophyc6350272011-08-05 16:16:39 +01006476
6477 mSelf.mUsageStatsService.monitorPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006478 }
6479
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006480 /**
6481 * Allows app to retrieve the MIME type of a URI without having permission
6482 * to access its content provider.
6483 *
6484 * CTS tests for this functionality can be run with "runtest cts-appsecurity".
6485 *
6486 * Test cases are at cts/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/
6487 * src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java
6488 */
6489 public String getProviderMimeType(Uri uri) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006490 enforceNotIsolatedCaller("getProviderMimeType");
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006491 final String name = uri.getAuthority();
6492 final long ident = Binder.clearCallingIdentity();
6493 ContentProviderHolder holder = null;
6494
6495 try {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006496 holder = getContentProviderExternalUnchecked(name, null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006497 if (holder != null) {
6498 return holder.provider.getType(uri);
6499 }
6500 } catch (RemoteException e) {
6501 Log.w(TAG, "Content provider dead retrieving " + uri, e);
6502 return null;
6503 } finally {
6504 if (holder != null) {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006505 removeContentProviderExternalUnchecked(name, null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006506 }
6507 Binder.restoreCallingIdentity(ident);
6508 }
6509
6510 return null;
6511 }
6512
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006513 // =========================================================
6514 // GLOBAL MANAGEMENT
6515 // =========================================================
6516
6517 final ProcessRecord newProcessRecordLocked(IApplicationThread thread,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006518 ApplicationInfo info, String customProcess, boolean isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006519 String proc = customProcess != null ? customProcess : info.processName;
6520 BatteryStatsImpl.Uid.Proc ps = null;
6521 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006522 int uid = info.uid;
6523 if (isolated) {
6524 int userId = UserId.getUserId(uid);
6525 int stepsLeft = Process.LAST_ISOLATED_UID - Process.FIRST_ISOLATED_UID + 1;
6526 uid = 0;
6527 while (true) {
6528 if (mNextIsolatedProcessUid < Process.FIRST_ISOLATED_UID
6529 || mNextIsolatedProcessUid > Process.LAST_ISOLATED_UID) {
6530 mNextIsolatedProcessUid = Process.FIRST_ISOLATED_UID;
6531 }
6532 uid = UserId.getUid(userId, mNextIsolatedProcessUid);
6533 mNextIsolatedProcessUid++;
6534 if (mIsolatedProcesses.indexOfKey(uid) < 0) {
6535 // No process for this uid, use it.
6536 break;
6537 }
6538 stepsLeft--;
6539 if (stepsLeft <= 0) {
6540 return null;
6541 }
6542 }
6543 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006544 synchronized (stats) {
6545 ps = stats.getProcessStatsLocked(info.uid, proc);
6546 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006547 return new ProcessRecord(ps, thread, info, proc, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006548 }
6549
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006550 final ProcessRecord addAppLocked(ApplicationInfo info, boolean isolated) {
6551 ProcessRecord app;
6552 if (!isolated) {
6553 app = getProcessRecordLocked(info.processName, info.uid);
6554 } else {
6555 app = null;
6556 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006557
6558 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006559 app = newProcessRecordLocked(null, info, null, isolated);
6560 mProcessNames.put(info.processName, app.uid, app);
6561 if (isolated) {
6562 mIsolatedProcesses.put(app.uid, app);
6563 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08006564 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006565 }
6566
Dianne Hackborne7f97212011-02-24 14:40:20 -08006567 // This package really, really can not be stopped.
6568 try {
6569 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07006570 info.packageName, false, UserId.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -08006571 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006572 } catch (IllegalArgumentException e) {
6573 Slog.w(TAG, "Failed trying to unstop package "
6574 + info.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006575 }
6576
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006577 if ((info.flags&(ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT))
6578 == (ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT)) {
6579 app.persistent = true;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07006580 app.maxAdj = ProcessList.PERSISTENT_PROC_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006581 }
6582 if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) {
6583 mPersistentStartingProcesses.add(app);
6584 startProcessLocked(app, "added application", app.processName);
6585 }
6586
6587 return app;
6588 }
6589
6590 public void unhandledBack() {
6591 enforceCallingPermission(android.Manifest.permission.FORCE_BACK,
6592 "unhandledBack()");
6593
6594 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006595 int count = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08006596 if (DEBUG_SWITCH) Slog.d(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006597 TAG, "Performing unhandledBack(): stack size = " + count);
6598 if (count > 1) {
6599 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006600 mMainStack.finishActivityLocked((ActivityRecord)mMainStack.mHistory.get(count-1),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006601 count-1, Activity.RESULT_CANCELED, null, "unhandled-back");
6602 Binder.restoreCallingIdentity(origId);
6603 }
6604 }
6605 }
6606
6607 public ParcelFileDescriptor openContentUri(Uri uri) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006608 enforceNotIsolatedCaller("openContentUri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006609 String name = uri.getAuthority();
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006610 ContentProviderHolder cph = getContentProviderExternalUnchecked(name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006611 ParcelFileDescriptor pfd = null;
6612 if (cph != null) {
6613 // We record the binder invoker's uid in thread-local storage before
6614 // going to the content provider to open the file. Later, in the code
6615 // that handles all permissions checks, we look for this uid and use
6616 // that rather than the Activity Manager's own uid. The effect is that
6617 // we do the check against the caller's permissions even though it looks
6618 // to the content provider like the Activity Manager itself is making
6619 // the request.
6620 sCallerIdentity.set(new Identity(
6621 Binder.getCallingPid(), Binder.getCallingUid()));
6622 try {
6623 pfd = cph.provider.openFile(uri, "r");
6624 } catch (FileNotFoundException e) {
6625 // do nothing; pfd will be returned null
6626 } finally {
6627 // Ensure that whatever happens, we clean up the identity state
6628 sCallerIdentity.remove();
6629 }
6630
6631 // We've got the fd now, so we're done with the provider.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006632 removeContentProviderExternalUnchecked(name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006633 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006634 Slog.d(TAG, "Failed to get provider for authority '" + name + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006635 }
6636 return pfd;
6637 }
6638
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006639 // Actually is sleeping or shutting down or whatever else in the future
6640 // is an inactive state.
6641 public boolean isSleeping() {
6642 return mSleeping || mShuttingDown;
6643 }
6644
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006645 public void goingToSleep() {
6646 synchronized(this) {
6647 mSleeping = true;
6648 mWindowManager.setEventDispatching(false);
6649
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006650 mMainStack.stopIfSleepingLocked();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006651
6652 // Initialize the wake times of all processes.
Dianne Hackborn287952c2010-09-22 22:34:31 -07006653 checkExcessivePowerUsageLocked(false);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006654 mHandler.removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
6655 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07006656 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006657 }
6658 }
6659
Dianne Hackborn55280a92009-05-07 15:53:46 -07006660 public boolean shutdown(int timeout) {
6661 if (checkCallingPermission(android.Manifest.permission.SHUTDOWN)
6662 != PackageManager.PERMISSION_GRANTED) {
6663 throw new SecurityException("Requires permission "
6664 + android.Manifest.permission.SHUTDOWN);
6665 }
6666
6667 boolean timedout = false;
6668
6669 synchronized(this) {
6670 mShuttingDown = true;
6671 mWindowManager.setEventDispatching(false);
6672
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006673 if (mMainStack.mResumedActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006674 mMainStack.stopIfSleepingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07006675 final long endTime = System.currentTimeMillis() + timeout;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006676 while (mMainStack.mResumedActivity != null
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08006677 || mMainStack.mPausingActivity != null) {
Dianne Hackborn55280a92009-05-07 15:53:46 -07006678 long delay = endTime - System.currentTimeMillis();
6679 if (delay <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006680 Slog.w(TAG, "Activity manager shutdown timed out");
Dianne Hackborn55280a92009-05-07 15:53:46 -07006681 timedout = true;
6682 break;
6683 }
6684 try {
6685 this.wait();
6686 } catch (InterruptedException e) {
6687 }
6688 }
6689 }
6690 }
6691
6692 mUsageStatsService.shutdown();
6693 mBatteryStatsService.shutdown();
6694
6695 return timedout;
6696 }
6697
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006698 public final void activitySlept(IBinder token) {
6699 if (localLOGV) Slog.v(
6700 TAG, "Activity slept: token=" + token);
6701
6702 ActivityRecord r = null;
6703
6704 final long origId = Binder.clearCallingIdentity();
6705
6706 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006707 r = mMainStack.isInStackLocked(token);
6708 if (r != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006709 mMainStack.activitySleptLocked(r);
6710 }
6711 }
6712
6713 Binder.restoreCallingIdentity(origId);
6714 }
6715
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006716 public void wakingUp() {
6717 synchronized(this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006718 mWindowManager.setEventDispatching(true);
6719 mSleeping = false;
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006720 mMainStack.awakeFromSleepingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006721 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006722 }
6723 }
6724
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006725 public void stopAppSwitches() {
6726 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
6727 != PackageManager.PERMISSION_GRANTED) {
6728 throw new SecurityException("Requires permission "
6729 + android.Manifest.permission.STOP_APP_SWITCHES);
6730 }
6731
6732 synchronized(this) {
6733 mAppSwitchesAllowedTime = SystemClock.uptimeMillis()
6734 + APP_SWITCH_DELAY_TIME;
6735 mDidAppSwitch = false;
6736 mHandler.removeMessages(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
6737 Message msg = mHandler.obtainMessage(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
6738 mHandler.sendMessageDelayed(msg, APP_SWITCH_DELAY_TIME);
6739 }
6740 }
6741
6742 public void resumeAppSwitches() {
6743 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
6744 != PackageManager.PERMISSION_GRANTED) {
6745 throw new SecurityException("Requires permission "
6746 + android.Manifest.permission.STOP_APP_SWITCHES);
6747 }
6748
6749 synchronized(this) {
6750 // Note that we don't execute any pending app switches... we will
6751 // let those wait until either the timeout, or the next start
6752 // activity request.
6753 mAppSwitchesAllowedTime = 0;
6754 }
6755 }
6756
6757 boolean checkAppSwitchAllowedLocked(int callingPid, int callingUid,
6758 String name) {
6759 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
6760 return true;
6761 }
6762
6763 final int perm = checkComponentPermission(
6764 android.Manifest.permission.STOP_APP_SWITCHES, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006765 callingUid, -1, true);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006766 if (perm == PackageManager.PERMISSION_GRANTED) {
6767 return true;
6768 }
6769
Joe Onorato8a9b2202010-02-26 18:56:32 -08006770 Slog.w(TAG, name + " request from " + callingUid + " stopped");
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006771 return false;
6772 }
6773
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006774 public void setDebugApp(String packageName, boolean waitForDebugger,
6775 boolean persistent) {
6776 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
6777 "setDebugApp()");
6778
6779 // Note that this is not really thread safe if there are multiple
6780 // callers into it at the same time, but that's not a situation we
6781 // care about.
6782 if (persistent) {
6783 final ContentResolver resolver = mContext.getContentResolver();
6784 Settings.System.putString(
6785 resolver, Settings.System.DEBUG_APP,
6786 packageName);
6787 Settings.System.putInt(
6788 resolver, Settings.System.WAIT_FOR_DEBUGGER,
6789 waitForDebugger ? 1 : 0);
6790 }
6791
6792 synchronized (this) {
6793 if (!persistent) {
6794 mOrigDebugApp = mDebugApp;
6795 mOrigWaitForDebugger = mWaitForDebugger;
6796 }
6797 mDebugApp = packageName;
6798 mWaitForDebugger = waitForDebugger;
6799 mDebugTransient = !persistent;
6800 if (packageName != null) {
6801 final long origId = Binder.clearCallingIdentity();
Amith Yamasani483f3b02012-03-13 16:08:00 -07006802 forceStopPackageLocked(packageName, -1, false, false, true, true, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006803 Binder.restoreCallingIdentity(origId);
6804 }
6805 }
6806 }
6807
Siva Velusamy92a8b222012-03-09 16:24:04 -08006808 void setOpenGlTraceApp(ApplicationInfo app, String processName) {
6809 synchronized (this) {
6810 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
6811 if (!isDebuggable) {
6812 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
6813 throw new SecurityException("Process not debuggable: " + app.packageName);
6814 }
6815 }
6816
6817 mOpenGlTraceApp = processName;
6818 }
6819 }
6820
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07006821 void setProfileApp(ApplicationInfo app, String processName, String profileFile,
6822 ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
6823 synchronized (this) {
6824 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
6825 if (!isDebuggable) {
6826 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
6827 throw new SecurityException("Process not debuggable: " + app.packageName);
6828 }
6829 }
6830 mProfileApp = processName;
6831 mProfileFile = profileFile;
6832 if (mProfileFd != null) {
6833 try {
6834 mProfileFd.close();
6835 } catch (IOException e) {
6836 }
6837 mProfileFd = null;
6838 }
6839 mProfileFd = profileFd;
6840 mProfileType = 0;
6841 mAutoStopProfiler = autoStopProfiler;
6842 }
6843 }
6844
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006845 public void setAlwaysFinish(boolean enabled) {
6846 enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH,
6847 "setAlwaysFinish()");
6848
6849 Settings.System.putInt(
6850 mContext.getContentResolver(),
6851 Settings.System.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0);
6852
6853 synchronized (this) {
6854 mAlwaysFinishActivities = enabled;
6855 }
6856 }
6857
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006858 public void setActivityController(IActivityController controller) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006859 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006860 "setActivityController()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006861 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006862 mController = controller;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006863 }
6864 }
6865
Dianne Hackborn9327f4f2010-01-29 10:38:29 -08006866 public boolean isUserAMonkey() {
6867 // For now the fact that there is a controller implies
6868 // we have a monkey.
6869 synchronized (this) {
6870 return mController != null;
6871 }
6872 }
6873
Jeff Sharkeya4620792011-05-20 15:29:23 -07006874 public void registerProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08006875 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
6876 "registerProcessObserver()");
6877 synchronized (this) {
6878 mProcessObservers.register(observer);
6879 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07006880 }
6881
6882 public void unregisterProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08006883 synchronized (this) {
6884 mProcessObservers.unregister(observer);
6885 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07006886 }
6887
Daniel Sandler69a48172010-06-23 16:29:36 -04006888 public void setImmersive(IBinder token, boolean immersive) {
6889 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006890 ActivityRecord r = mMainStack.isInStackLocked(token);
6891 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04006892 throw new IllegalArgumentException();
6893 }
Daniel Sandler69a48172010-06-23 16:29:36 -04006894 r.immersive = immersive;
6895 }
6896 }
6897
6898 public boolean isImmersive(IBinder token) {
6899 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006900 ActivityRecord r = mMainStack.isInStackLocked(token);
6901 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04006902 throw new IllegalArgumentException();
6903 }
Daniel Sandler69a48172010-06-23 16:29:36 -04006904 return r.immersive;
6905 }
6906 }
6907
6908 public boolean isTopActivityImmersive() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006909 enforceNotIsolatedCaller("startActivity");
Daniel Sandler69a48172010-06-23 16:29:36 -04006910 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006911 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Daniel Sandler69a48172010-06-23 16:29:36 -04006912 return (r != null) ? r.immersive : false;
6913 }
6914 }
6915
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006916 public final void enterSafeMode() {
6917 synchronized(this) {
6918 // It only makes sense to do this before the system is ready
6919 // and started launching other packages.
6920 if (!mSystemReady) {
6921 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006922 AppGlobals.getPackageManager().enterSafeMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006923 } catch (RemoteException e) {
6924 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006925 }
6926 }
6927 }
6928
Jeff Brownb09abc12011-01-13 21:08:27 -08006929 public final void showSafeModeOverlay() {
6930 View v = LayoutInflater.from(mContext).inflate(
6931 com.android.internal.R.layout.safe_mode, null);
6932 WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
6933 lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
6934 lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
6935 lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
6936 lp.gravity = Gravity.BOTTOM | Gravity.LEFT;
6937 lp.format = v.getBackground().getOpacity();
6938 lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
6939 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
6940 ((WindowManager)mContext.getSystemService(
6941 Context.WINDOW_SERVICE)).addView(v, lp);
6942 }
6943
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006944 public void noteWakeupAlarm(IIntentSender sender) {
6945 if (!(sender instanceof PendingIntentRecord)) {
6946 return;
6947 }
6948 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
6949 synchronized (stats) {
6950 if (mBatteryStatsService.isOnBattery()) {
6951 mBatteryStatsService.enforceCallingPermission();
6952 PendingIntentRecord rec = (PendingIntentRecord)sender;
6953 int MY_UID = Binder.getCallingUid();
6954 int uid = rec.uid == MY_UID ? Process.SYSTEM_UID : rec.uid;
6955 BatteryStatsImpl.Uid.Pkg pkg =
6956 stats.getPackageStatsLocked(uid, rec.key.packageName);
6957 pkg.incWakeupsLocked();
6958 }
6959 }
6960 }
6961
Dianne Hackborn64825172011-03-02 21:32:58 -08006962 public boolean killPids(int[] pids, String pReason, boolean secure) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006963 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006964 throw new SecurityException("killPids only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006965 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006966 String reason = (pReason == null) ? "Unknown" : pReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006967 // XXX Note: don't acquire main activity lock here, because the window
6968 // manager calls in with its locks held.
6969
6970 boolean killed = false;
6971 synchronized (mPidsSelfLocked) {
6972 int[] types = new int[pids.length];
6973 int worstType = 0;
6974 for (int i=0; i<pids.length; i++) {
6975 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
6976 if (proc != null) {
6977 int type = proc.setAdj;
6978 types[i] = type;
6979 if (type > worstType) {
6980 worstType = type;
6981 }
6982 }
6983 }
6984
Dianne Hackborn64825172011-03-02 21:32:58 -08006985 // If the worst oom_adj is somewhere in the hidden proc LRU range,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006986 // then constrain it so we will kill all hidden procs.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07006987 if (worstType < ProcessList.HIDDEN_APP_MAX_ADJ
6988 && worstType > ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07006989 worstType = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006990 }
Dianne Hackborn64825172011-03-02 21:32:58 -08006991
6992 // If this is not a secure call, don't let it kill processes that
6993 // are important.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07006994 if (!secure && worstType < ProcessList.SERVICE_ADJ) {
6995 worstType = ProcessList.SERVICE_ADJ;
Dianne Hackborn64825172011-03-02 21:32:58 -08006996 }
6997
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006998 Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006999 for (int i=0; i<pids.length; i++) {
7000 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7001 if (proc == null) {
7002 continue;
7003 }
7004 int adj = proc.setAdj;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007005 if (adj >= worstType && !proc.killedBackground) {
Dianne Hackborn8633e682010-04-22 16:03:41 -07007006 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007007 EventLog.writeEvent(EventLogTags.AM_KILL, proc.pid,
7008 proc.processName, adj, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007009 killed = true;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007010 proc.killedBackground = true;
7011 Process.killProcessQuiet(pids[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007012 }
7013 }
7014 }
7015 return killed;
7016 }
Jeff Sharkeyb9a07012012-03-22 17:00:04 -07007017
7018 @Override
7019 public boolean killProcessesBelowForeground(String reason) {
7020 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7021 throw new SecurityException("killProcessesBelowForeground() only available to system");
7022 }
7023
7024 return killProcessesBelowAdj(ProcessList.FOREGROUND_APP_ADJ, reason);
7025 }
7026
7027 private boolean killProcessesBelowAdj(int belowAdj, String reason) {
7028 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7029 throw new SecurityException("killProcessesBelowAdj() only available to system");
7030 }
7031
7032 boolean killed = false;
7033 synchronized (mPidsSelfLocked) {
7034 final int size = mPidsSelfLocked.size();
7035 for (int i = 0; i < size; i++) {
7036 final int pid = mPidsSelfLocked.keyAt(i);
7037 final ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7038 if (proc == null) continue;
7039
7040 final int adj = proc.setAdj;
7041 if (adj > belowAdj && !proc.killedBackground) {
7042 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
7043 EventLog.writeEvent(
7044 EventLogTags.AM_KILL, proc.pid, proc.processName, adj, reason);
7045 killed = true;
7046 proc.killedBackground = true;
7047 Process.killProcessQuiet(pid);
7048 }
7049 }
7050 }
7051 return killed;
7052 }
7053
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007054 public final void startRunning(String pkg, String cls, String action,
7055 String data) {
7056 synchronized(this) {
7057 if (mStartRunning) {
7058 return;
7059 }
7060 mStartRunning = true;
7061 mTopComponent = pkg != null && cls != null
7062 ? new ComponentName(pkg, cls) : null;
7063 mTopAction = action != null ? action : Intent.ACTION_MAIN;
7064 mTopData = data;
7065 if (!mSystemReady) {
7066 return;
7067 }
7068 }
7069
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007070 systemReady(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007071 }
7072
7073 private void retrieveSettings() {
7074 final ContentResolver resolver = mContext.getContentResolver();
7075 String debugApp = Settings.System.getString(
7076 resolver, Settings.System.DEBUG_APP);
7077 boolean waitForDebugger = Settings.System.getInt(
7078 resolver, Settings.System.WAIT_FOR_DEBUGGER, 0) != 0;
7079 boolean alwaysFinishActivities = Settings.System.getInt(
7080 resolver, Settings.System.ALWAYS_FINISH_ACTIVITIES, 0) != 0;
7081
7082 Configuration configuration = new Configuration();
7083 Settings.System.getConfiguration(resolver, configuration);
7084
7085 synchronized (this) {
7086 mDebugApp = mOrigDebugApp = debugApp;
7087 mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger;
7088 mAlwaysFinishActivities = alwaysFinishActivities;
7089 // This happens before any activities are started, so we can
7090 // change mConfiguration in-place.
Dianne Hackborn813075a62011-11-14 17:45:19 -08007091 updateConfigurationLocked(configuration, null, false, true);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007092 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Initial config: " + mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007093 }
7094 }
7095
7096 public boolean testIsSystemReady() {
7097 // no need to synchronize(this) just to read & return the value
7098 return mSystemReady;
7099 }
7100
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007101 private static File getCalledPreBootReceiversFile() {
7102 File dataDir = Environment.getDataDirectory();
7103 File systemDir = new File(dataDir, "system");
7104 File fname = new File(systemDir, "called_pre_boots.dat");
7105 return fname;
7106 }
Dianne Hackborn661cd522011-08-22 00:26:20 -07007107
7108 static final int LAST_DONE_VERSION = 10000;
7109
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007110 private static ArrayList<ComponentName> readLastDonePreBootReceivers() {
7111 ArrayList<ComponentName> lastDoneReceivers = new ArrayList<ComponentName>();
7112 File file = getCalledPreBootReceiversFile();
7113 FileInputStream fis = null;
7114 try {
7115 fis = new FileInputStream(file);
7116 DataInputStream dis = new DataInputStream(new BufferedInputStream(fis, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007117 int fvers = dis.readInt();
7118 if (fvers == LAST_DONE_VERSION) {
7119 String vers = dis.readUTF();
7120 String codename = dis.readUTF();
7121 String build = dis.readUTF();
7122 if (android.os.Build.VERSION.RELEASE.equals(vers)
7123 && android.os.Build.VERSION.CODENAME.equals(codename)
7124 && android.os.Build.VERSION.INCREMENTAL.equals(build)) {
7125 int num = dis.readInt();
7126 while (num > 0) {
7127 num--;
7128 String pkg = dis.readUTF();
7129 String cls = dis.readUTF();
7130 lastDoneReceivers.add(new ComponentName(pkg, cls));
7131 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007132 }
7133 }
7134 } catch (FileNotFoundException e) {
7135 } catch (IOException e) {
7136 Slog.w(TAG, "Failure reading last done pre-boot receivers", e);
7137 } finally {
7138 if (fis != null) {
7139 try {
7140 fis.close();
7141 } catch (IOException e) {
7142 }
7143 }
7144 }
7145 return lastDoneReceivers;
7146 }
7147
7148 private static void writeLastDonePreBootReceivers(ArrayList<ComponentName> list) {
7149 File file = getCalledPreBootReceiversFile();
7150 FileOutputStream fos = null;
7151 DataOutputStream dos = null;
7152 try {
7153 Slog.i(TAG, "Writing new set of last done pre-boot receivers...");
7154 fos = new FileOutputStream(file);
7155 dos = new DataOutputStream(new BufferedOutputStream(fos, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007156 dos.writeInt(LAST_DONE_VERSION);
7157 dos.writeUTF(android.os.Build.VERSION.RELEASE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007158 dos.writeUTF(android.os.Build.VERSION.CODENAME);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007159 dos.writeUTF(android.os.Build.VERSION.INCREMENTAL);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007160 dos.writeInt(list.size());
7161 for (int i=0; i<list.size(); i++) {
7162 dos.writeUTF(list.get(i).getPackageName());
7163 dos.writeUTF(list.get(i).getClassName());
7164 }
7165 } catch (IOException e) {
7166 Slog.w(TAG, "Failure writing last done pre-boot receivers", e);
7167 file.delete();
7168 } finally {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07007169 FileUtils.sync(fos);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007170 if (dos != null) {
7171 try {
7172 dos.close();
7173 } catch (IOException e) {
7174 // TODO Auto-generated catch block
7175 e.printStackTrace();
7176 }
7177 }
7178 }
7179 }
7180
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007181 public void systemReady(final Runnable goingCallback) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007182 synchronized(this) {
7183 if (mSystemReady) {
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007184 if (goingCallback != null) goingCallback.run();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007185 return;
7186 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007187
7188 // Check to see if there are any update receivers to run.
7189 if (!mDidUpdate) {
7190 if (mWaitingUpdate) {
7191 return;
7192 }
7193 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
7194 List<ResolveInfo> ris = null;
7195 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007196 ris = AppGlobals.getPackageManager().queryIntentReceivers(
Amith Yamasani483f3b02012-03-13 16:08:00 -07007197 intent, null, 0, 0);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007198 } catch (RemoteException e) {
7199 }
7200 if (ris != null) {
7201 for (int i=ris.size()-1; i>=0; i--) {
7202 if ((ris.get(i).activityInfo.applicationInfo.flags
7203 &ApplicationInfo.FLAG_SYSTEM) == 0) {
7204 ris.remove(i);
7205 }
7206 }
7207 intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007208
7209 ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers();
7210
7211 final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007212 for (int i=0; i<ris.size(); i++) {
7213 ActivityInfo ai = ris.get(i).activityInfo;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007214 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7215 if (lastDoneReceivers.contains(comp)) {
7216 ris.remove(i);
7217 i--;
7218 }
7219 }
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07007220
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007221 for (int i=0; i<ris.size(); i++) {
7222 ActivityInfo ai = ris.get(i).activityInfo;
7223 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7224 doneReceivers.add(comp);
7225 intent.setComponent(comp);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007226 IIntentReceiver finisher = null;
Dianne Hackbornd6847842010-01-12 18:14:19 -08007227 if (i == ris.size()-1) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007228 finisher = new IIntentReceiver.Stub() {
7229 public void performReceive(Intent intent, int resultCode,
Dianne Hackborn68d881c2009-10-05 13:58:17 -07007230 String data, Bundle extras, boolean ordered,
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007231 boolean sticky) {
7232 // The raw IIntentReceiver interface is called
7233 // with the AM lock held, so redispatch to
7234 // execute our code without the lock.
7235 mHandler.post(new Runnable() {
7236 public void run() {
7237 synchronized (ActivityManagerService.this) {
7238 mDidUpdate = true;
7239 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007240 writeLastDonePreBootReceivers(doneReceivers);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007241 showBootMessage(mContext.getText(
7242 R.string.android_upgrading_complete),
7243 false);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007244 systemReady(goingCallback);
7245 }
7246 });
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007247 }
7248 };
7249 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08007250 Slog.i(TAG, "Sending system update to: " + intent.getComponent());
Amith Yamasani742a6712011-05-04 14:49:28 -07007251 /* TODO: Send this to all users */
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007252 broadcastIntentLocked(null, null, intent, null, finisher,
Amith Yamasani742a6712011-05-04 14:49:28 -07007253 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID,
Amith Yamasanic600e21f2012-02-14 16:08:07 -08007254 0 /* UserId zero */);
Dianne Hackbornd6847842010-01-12 18:14:19 -08007255 if (finisher != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007256 mWaitingUpdate = true;
7257 }
7258 }
7259 }
7260 if (mWaitingUpdate) {
7261 return;
7262 }
7263 mDidUpdate = true;
7264 }
7265
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007266 mSystemReady = true;
7267 if (!mStartRunning) {
7268 return;
7269 }
7270 }
7271
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007272 ArrayList<ProcessRecord> procsToKill = null;
7273 synchronized(mPidsSelfLocked) {
7274 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
7275 ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7276 if (!isAllowedWhileBooting(proc.info)){
7277 if (procsToKill == null) {
7278 procsToKill = new ArrayList<ProcessRecord>();
7279 }
7280 procsToKill.add(proc);
7281 }
7282 }
7283 }
7284
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007285 synchronized(this) {
7286 if (procsToKill != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007287 for (int i=procsToKill.size()-1; i>=0; i--) {
7288 ProcessRecord proc = procsToKill.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007289 Slog.i(TAG, "Removing system update proc: " + proc);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007290 removeProcessLocked(proc, true, false, "system update done");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007291 }
7292 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007293
7294 // Now that we have cleaned up any update processes, we
7295 // are ready to start launching real processes and know that
7296 // we won't trample on them any more.
7297 mProcessesReady = true;
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007298 }
7299
Joe Onorato8a9b2202010-02-26 18:56:32 -08007300 Slog.i(TAG, "System now ready");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007301 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007302 SystemClock.uptimeMillis());
7303
7304 synchronized(this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007305 // Make sure we have no pre-ready processes sitting around.
7306
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007307 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
7308 ResolveInfo ri = mContext.getPackageManager()
7309 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST),
Dianne Hackborn1655be42009-05-08 14:29:01 -07007310 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007311 CharSequence errorMsg = null;
7312 if (ri != null) {
7313 ActivityInfo ai = ri.activityInfo;
7314 ApplicationInfo app = ai.applicationInfo;
7315 if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7316 mTopAction = Intent.ACTION_FACTORY_TEST;
7317 mTopData = null;
7318 mTopComponent = new ComponentName(app.packageName,
7319 ai.name);
7320 } else {
7321 errorMsg = mContext.getResources().getText(
7322 com.android.internal.R.string.factorytest_not_system);
7323 }
7324 } else {
7325 errorMsg = mContext.getResources().getText(
7326 com.android.internal.R.string.factorytest_no_action);
7327 }
7328 if (errorMsg != null) {
7329 mTopAction = null;
7330 mTopData = null;
7331 mTopComponent = null;
7332 Message msg = Message.obtain();
7333 msg.what = SHOW_FACTORY_ERROR_MSG;
7334 msg.getData().putCharSequence("msg", errorMsg);
7335 mHandler.sendMessage(msg);
7336 }
7337 }
7338 }
7339
7340 retrieveSettings();
7341
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007342 if (goingCallback != null) goingCallback.run();
7343
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007344 synchronized (this) {
7345 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
7346 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007347 List apps = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07007348 getPersistentApplications(STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007349 if (apps != null) {
7350 int N = apps.size();
7351 int i;
7352 for (i=0; i<N; i++) {
7353 ApplicationInfo info
7354 = (ApplicationInfo)apps.get(i);
7355 if (info != null &&
7356 !info.packageName.equals("android")) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007357 addAppLocked(info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007358 }
7359 }
7360 }
7361 } catch (RemoteException ex) {
7362 // pm is in same process, this will never happen.
7363 }
7364 }
7365
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007366 // Start up initial activity.
7367 mBooting = true;
7368
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007369 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007370 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007371 Message msg = Message.obtain();
7372 msg.what = SHOW_UID_ERROR_MSG;
7373 mHandler.sendMessage(msg);
7374 }
7375 } catch (RemoteException e) {
7376 }
7377
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007378 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007379 }
7380 }
7381
Dan Egnorb7f03672009-12-09 16:22:32 -08007382 private boolean makeAppCrashingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007383 String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007384 app.crashing = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007385 app.crashingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007386 ActivityManager.ProcessErrorStateInfo.CRASHED, null, shortMsg, longMsg, stackTrace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007387 startAppProblemLocked(app);
7388 app.stopFreezingAllLocked();
7389 return handleAppCrashLocked(app);
7390 }
7391
Dan Egnorb7f03672009-12-09 16:22:32 -08007392 private void makeAppNotRespondingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007393 String activity, String shortMsg, String longMsg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007394 app.notResponding = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007395 app.notRespondingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007396 ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING,
7397 activity, shortMsg, longMsg, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007398 startAppProblemLocked(app);
7399 app.stopFreezingAllLocked();
7400 }
7401
7402 /**
7403 * Generate a process error record, suitable for attachment to a ProcessRecord.
7404 *
7405 * @param app The ProcessRecord in which the error occurred.
7406 * @param condition Crashing, Application Not Responding, etc. Values are defined in
7407 * ActivityManager.AppErrorStateInfo
Dan Egnor60d87622009-12-16 16:32:58 -08007408 * @param activity The activity associated with the crash, if known.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007409 * @param shortMsg Short message describing the crash.
7410 * @param longMsg Long message describing the crash.
Dan Egnorb7f03672009-12-09 16:22:32 -08007411 * @param stackTrace Full crash stack trace, may be null.
7412 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007413 * @return Returns a fully-formed AppErrorStateInfo record.
7414 */
7415 private ActivityManager.ProcessErrorStateInfo generateProcessError(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007416 int condition, String activity, String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007417 ActivityManager.ProcessErrorStateInfo report = new ActivityManager.ProcessErrorStateInfo();
Dan Egnorb7f03672009-12-09 16:22:32 -08007418
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007419 report.condition = condition;
7420 report.processName = app.processName;
7421 report.pid = app.pid;
7422 report.uid = app.info.uid;
Dan Egnor60d87622009-12-16 16:32:58 -08007423 report.tag = activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007424 report.shortMsg = shortMsg;
7425 report.longMsg = longMsg;
Dan Egnorb7f03672009-12-09 16:22:32 -08007426 report.stackTrace = stackTrace;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007427
7428 return report;
7429 }
7430
Dan Egnor42471dd2010-01-07 17:25:22 -08007431 void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007432 synchronized (this) {
7433 app.crashing = false;
7434 app.crashingReport = null;
7435 app.notResponding = false;
7436 app.notRespondingReport = null;
7437 if (app.anrDialog == fromDialog) {
7438 app.anrDialog = null;
7439 }
7440 if (app.waitDialog == fromDialog) {
7441 app.waitDialog = null;
7442 }
7443 if (app.pid > 0 && app.pid != MY_PID) {
Dan Egnor42471dd2010-01-07 17:25:22 -08007444 handleAppCrashLocked(app);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007445 Slog.i(ActivityManagerService.TAG, "Killing " + app + ": user's request");
Dianne Hackborn8633e682010-04-22 16:03:41 -07007446 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
7447 app.processName, app.setAdj, "user's request after error");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007448 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007449 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007450 }
7451 }
Dan Egnor42471dd2010-01-07 17:25:22 -08007452
Dan Egnorb7f03672009-12-09 16:22:32 -08007453 private boolean handleAppCrashLocked(ProcessRecord app) {
Mike Lockwood86548c42011-09-13 17:21:46 -04007454 if (mHeadless) {
7455 Log.e(TAG, "handleAppCrashLocked: " + app.processName);
7456 return false;
7457 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007458 long now = SystemClock.uptimeMillis();
7459
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007460 Long crashTime;
7461 if (!app.isolated) {
7462 crashTime = mProcessCrashTimes.get(app.info.processName, app.uid);
7463 } else {
7464 crashTime = null;
7465 }
Dianne Hackborn7d608422011-08-07 16:24:18 -07007466 if (crashTime != null && now < crashTime+ProcessList.MIN_CRASH_INTERVAL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007467 // This process loses!
Joe Onorato8a9b2202010-02-26 18:56:32 -08007468 Slog.w(TAG, "Process " + app.info.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007469 + " has crashed too many times: killing!");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007470 EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007471 app.info.processName, app.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007472 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
7473 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007474 if (r.app == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007475 Slog.w(TAG, " Force finishing activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007476 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007477 r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED, null, "crashed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007478 }
7479 }
7480 if (!app.persistent) {
7481 // We don't want to start this process again until the user
7482 // explicitly does so... but for persistent process, we really
7483 // need to keep it running. If a persistent process is actually
7484 // repeatedly crashing, then badness for everyone.
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007485 EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007486 app.info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007487 if (!app.isolated) {
7488 // XXX We don't have a way to mark isolated processes
7489 // as bad, since they don't have a peristent identity.
7490 mBadProcesses.put(app.info.processName, app.uid, now);
7491 mProcessCrashTimes.remove(app.info.processName, app.uid);
7492 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007493 app.bad = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007494 app.removed = true;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07007495 // Don't let services in this process be restarted and potentially
7496 // annoy the user repeatedly. Unless it is persistent, since those
7497 // processes run critical code.
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007498 removeProcessLocked(app, false, false, "crash");
Dianne Hackborncb44d962011-03-10 17:02:27 -08007499 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007500 return false;
7501 }
Dianne Hackborncb44d962011-03-10 17:02:27 -08007502 mMainStack.resumeTopActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007503 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007504 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Kevin Hester-Chowd87a9be2012-03-05 08:01:00 -08007505 if (r != null && r.app == app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007506 // If the top running activity is from this crashing
7507 // process, then terminate it to avoid getting in a loop.
7508 Slog.w(TAG, " Force finishing activity "
7509 + r.intent.getComponent().flattenToShortString());
Dianne Hackbornbe707852011-11-11 14:32:10 -08007510 int index = mMainStack.indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007511 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007512 Activity.RESULT_CANCELED, null, "crashed");
Dianne Hackborn070783f2010-12-29 16:46:28 -08007513 // Also terminate any activities below it that aren't yet
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007514 // stopped, to avoid a situation where one will get
7515 // re-start our crashing activity once it gets resumed again.
7516 index--;
7517 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007518 r = (ActivityRecord)mMainStack.mHistory.get(index);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007519 if (r.state == ActivityState.RESUMED
7520 || r.state == ActivityState.PAUSING
7521 || r.state == ActivityState.PAUSED) {
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08007522 if (!r.isHomeActivity || mHomeProcess != r.app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007523 Slog.w(TAG, " Force finishing activity "
7524 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007525 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007526 Activity.RESULT_CANCELED, null, "crashed");
7527 }
7528 }
7529 }
7530 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007531 }
7532
7533 // Bump up the crash count of any services currently running in the proc.
7534 if (app.services.size() != 0) {
7535 // Any services running in the application need to be placed
7536 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -07007537 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007538 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07007539 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007540 sr.crashCount++;
7541 }
7542 }
Mattias Larssona4fd0072010-06-22 22:37:03 +02007543
7544 // If the crashing process is what we consider to be the "home process" and it has been
7545 // replaced by a third-party app, clear the package preferred activities from packages
7546 // with a home activity running in the process to prevent a repeatedly crashing app
7547 // from blocking the user to manually clear the list.
7548 if (app == mHomeProcess && mHomeProcess.activities.size() > 0
7549 && (mHomeProcess.info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
7550 Iterator it = mHomeProcess.activities.iterator();
7551 while (it.hasNext()) {
Jean-Baptiste Queru5ea89f72010-07-30 09:30:31 -07007552 ActivityRecord r = (ActivityRecord)it.next();
Mattias Larssona4fd0072010-06-22 22:37:03 +02007553 if (r.isHomeActivity) {
7554 Log.i(TAG, "Clearing package preferred activities from " + r.packageName);
7555 try {
7556 ActivityThread.getPackageManager()
7557 .clearPackagePreferredActivities(r.packageName);
7558 } catch (RemoteException c) {
7559 // pm is in same process, this will never happen.
7560 }
7561 }
7562 }
7563 }
7564
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007565 if (!app.isolated) {
7566 // XXX Can't keep track of crash times for isolated processes,
7567 // because they don't have a perisistent identity.
7568 mProcessCrashTimes.put(app.info.processName, app.uid, now);
7569 }
7570
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007571 return true;
7572 }
7573
7574 void startAppProblemLocked(ProcessRecord app) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08007575 app.errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver(
7576 mContext, app.info.packageName, app.info.flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007577 skipCurrentReceiverLocked(app);
7578 }
7579
7580 void skipCurrentReceiverLocked(ProcessRecord app) {
Christopher Tatef46723b2012-01-26 14:19:24 -08007581 for (BroadcastQueue queue : mBroadcastQueues) {
7582 queue.skipCurrentReceiverLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007583 }
7584 }
7585
Dan Egnor60d87622009-12-16 16:32:58 -08007586 /**
7587 * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes.
7588 * The application process will exit immediately after this call returns.
7589 * @param app object of the crashing app, null for the system server
7590 * @param crashInfo describing the exception
7591 */
7592 public void handleApplicationCrash(IBinder app, ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007593 ProcessRecord r = findAppProcess(app, "Crash");
Jeff Sharkeya353d262011-10-28 11:12:06 -07007594 final String processName = app == null ? "system_server"
7595 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08007596
7597 EventLog.writeEvent(EventLogTags.AM_CRASH, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07007598 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08007599 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08007600 crashInfo.exceptionClassName,
7601 crashInfo.exceptionMessage,
7602 crashInfo.throwFileName,
7603 crashInfo.throwLineNumber);
7604
Jeff Sharkeya353d262011-10-28 11:12:06 -07007605 addErrorToDropBox("crash", r, processName, null, null, null, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08007606
7607 crashApplication(r, crashInfo);
7608 }
7609
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007610 public void handleApplicationStrictModeViolation(
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007611 IBinder app,
7612 int violationMask,
7613 StrictMode.ViolationInfo info) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007614 ProcessRecord r = findAppProcess(app, "StrictMode");
7615 if (r == null) {
7616 return;
7617 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007618
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007619 if ((violationMask & StrictMode.PENALTY_DROPBOX) != 0) {
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08007620 Integer stackFingerprint = info.hashCode();
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007621 boolean logIt = true;
7622 synchronized (mAlreadyLoggedViolatedStacks) {
7623 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) {
7624 logIt = false;
7625 // TODO: sub-sample into EventLog for these, with
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007626 // the info.durationMillis? Then we'd get
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007627 // the relative pain numbers, without logging all
7628 // the stack traces repeatedly. We'd want to do
7629 // likewise in the client code, which also does
7630 // dup suppression, before the Binder call.
7631 } else {
7632 if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) {
7633 mAlreadyLoggedViolatedStacks.clear();
7634 }
7635 mAlreadyLoggedViolatedStacks.add(stackFingerprint);
7636 }
7637 }
7638 if (logIt) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007639 logStrictModeViolationToDropBox(r, info);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007640 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007641 }
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007642
7643 if ((violationMask & StrictMode.PENALTY_DIALOG) != 0) {
7644 AppErrorResult result = new AppErrorResult();
7645 synchronized (this) {
7646 final long origId = Binder.clearCallingIdentity();
7647
7648 Message msg = Message.obtain();
7649 msg.what = SHOW_STRICT_MODE_VIOLATION_MSG;
7650 HashMap<String, Object> data = new HashMap<String, Object>();
7651 data.put("result", result);
7652 data.put("app", r);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007653 data.put("violationMask", violationMask);
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007654 data.put("info", info);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007655 msg.obj = data;
7656 mHandler.sendMessage(msg);
7657
7658 Binder.restoreCallingIdentity(origId);
7659 }
7660 int res = result.get();
Dianne Hackbornb424b632010-08-18 15:59:05 -07007661 Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007662 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007663 }
7664
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007665 // Depending on the policy in effect, there could be a bunch of
7666 // these in quick succession so we try to batch these together to
7667 // minimize disk writes, number of dropbox entries, and maximize
7668 // compression, by having more fewer, larger records.
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007669 private void logStrictModeViolationToDropBox(
7670 ProcessRecord process,
7671 StrictMode.ViolationInfo info) {
7672 if (info == null) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007673 return;
7674 }
7675 final boolean isSystemApp = process == null ||
7676 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM |
7677 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07007678 final String processName = process == null ? "unknown" : process.processName;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007679 final String dropboxTag = isSystemApp ? "system_app_strictmode" : "data_app_strictmode";
7680 final DropBoxManager dbox = (DropBoxManager)
7681 mContext.getSystemService(Context.DROPBOX_SERVICE);
7682
7683 // Exit early if the dropbox isn't configured to accept this report type.
7684 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
7685
7686 boolean bufferWasEmpty;
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007687 boolean needsFlush;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007688 final StringBuilder sb = isSystemApp ? mStrictModeBuffer : new StringBuilder(1024);
7689 synchronized (sb) {
7690 bufferWasEmpty = sb.length() == 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07007691 appendDropBoxProcessHeaders(process, processName, sb);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007692 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
7693 sb.append("System-App: ").append(isSystemApp).append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007694 sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n");
7695 if (info.violationNumThisLoop != 0) {
7696 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n");
7697 }
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07007698 if (info.numAnimationsRunning != 0) {
7699 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n");
7700 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07007701 if (info.broadcastIntentAction != null) {
7702 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n");
7703 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08007704 if (info.durationMillis != -1) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007705 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n");
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007706 }
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08007707 if (info.numInstances != -1) {
7708 sb.append("Instance-Count: ").append(info.numInstances).append("\n");
7709 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08007710 if (info.tags != null) {
7711 for (String tag : info.tags) {
7712 sb.append("Span-Tag: ").append(tag).append("\n");
7713 }
7714 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007715 sb.append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007716 if (info.crashInfo != null && info.crashInfo.stackTrace != null) {
7717 sb.append(info.crashInfo.stackTrace);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007718 }
7719 sb.append("\n");
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007720
7721 // Only buffer up to ~64k. Various logging bits truncate
7722 // things at 128k.
7723 needsFlush = (sb.length() > 64 * 1024);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007724 }
7725
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007726 // Flush immediately if the buffer's grown too large, or this
7727 // is a non-system app. Non-system apps are isolated with a
7728 // different tag & policy and not batched.
7729 //
7730 // Batching is useful during internal testing with
7731 // StrictMode settings turned up high. Without batching,
7732 // thousands of separate files could be created on boot.
7733 if (!isSystemApp || needsFlush) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007734 new Thread("Error dump: " + dropboxTag) {
7735 @Override
7736 public void run() {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007737 String report;
7738 synchronized (sb) {
7739 report = sb.toString();
7740 sb.delete(0, sb.length());
7741 sb.trimToSize();
7742 }
7743 if (report.length() != 0) {
7744 dbox.addText(dropboxTag, report);
7745 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007746 }
7747 }.start();
7748 return;
7749 }
7750
7751 // System app batching:
7752 if (!bufferWasEmpty) {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007753 // An existing dropbox-writing thread is outstanding, so
7754 // we don't need to start it up. The existing thread will
7755 // catch the buffer appends we just did.
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007756 return;
7757 }
7758
7759 // Worker thread to both batch writes and to avoid blocking the caller on I/O.
7760 // (After this point, we shouldn't access AMS internal data structures.)
7761 new Thread("Error dump: " + dropboxTag) {
7762 @Override
7763 public void run() {
7764 // 5 second sleep to let stacks arrive and be batched together
7765 try {
7766 Thread.sleep(5000); // 5 seconds
7767 } catch (InterruptedException e) {}
7768
7769 String errorReport;
7770 synchronized (mStrictModeBuffer) {
7771 errorReport = mStrictModeBuffer.toString();
7772 if (errorReport.length() == 0) {
7773 return;
7774 }
7775 mStrictModeBuffer.delete(0, mStrictModeBuffer.length());
7776 mStrictModeBuffer.trimToSize();
7777 }
7778 dbox.addText(dropboxTag, errorReport);
7779 }
7780 }.start();
7781 }
7782
Dan Egnor60d87622009-12-16 16:32:58 -08007783 /**
7784 * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors.
7785 * @param app object of the crashing app, null for the system server
7786 * @param tag reported by the caller
7787 * @param crashInfo describing the context of the error
7788 * @return true if the process should exit immediately (WTF is fatal)
7789 */
7790 public boolean handleApplicationWtf(IBinder app, String tag,
Dan Egnorb7f03672009-12-09 16:22:32 -08007791 ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007792 ProcessRecord r = findAppProcess(app, "WTF");
Jeff Sharkeya353d262011-10-28 11:12:06 -07007793 final String processName = app == null ? "system_server"
7794 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08007795
7796 EventLog.writeEvent(EventLogTags.AM_WTF, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07007797 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08007798 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08007799 tag, crashInfo.exceptionMessage);
7800
Jeff Sharkeya353d262011-10-28 11:12:06 -07007801 addErrorToDropBox("wtf", r, processName, null, null, tag, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08007802
Dianne Hackborn1ab43772011-03-15 14:38:02 -07007803 if (r != null && r.pid != Process.myPid() &&
7804 Settings.Secure.getInt(mContext.getContentResolver(),
7805 Settings.Secure.WTF_IS_FATAL, 0) != 0) {
Dan Egnor60d87622009-12-16 16:32:58 -08007806 crashApplication(r, crashInfo);
7807 return true;
7808 } else {
7809 return false;
7810 }
7811 }
7812
7813 /**
7814 * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit})
7815 * @return the corresponding {@link ProcessRecord} object, or null if none could be found
7816 */
Dianne Hackborncb44d962011-03-10 17:02:27 -08007817 private ProcessRecord findAppProcess(IBinder app, String reason) {
Dan Egnor60d87622009-12-16 16:32:58 -08007818 if (app == null) {
7819 return null;
7820 }
7821
7822 synchronized (this) {
7823 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
7824 final int NA = apps.size();
7825 for (int ia=0; ia<NA; ia++) {
7826 ProcessRecord p = apps.valueAt(ia);
7827 if (p.thread != null && p.thread.asBinder() == app) {
7828 return p;
7829 }
7830 }
7831 }
7832
Dianne Hackborncb44d962011-03-10 17:02:27 -08007833 Slog.w(TAG, "Can't find mystery application for " + reason
7834 + " from pid=" + Binder.getCallingPid()
7835 + " uid=" + Binder.getCallingUid() + ": " + app);
Dan Egnor60d87622009-12-16 16:32:58 -08007836 return null;
7837 }
7838 }
7839
7840 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007841 * Utility function for addErrorToDropBox and handleStrictModeViolation's logging
7842 * to append various headers to the dropbox log text.
Dan Egnor60d87622009-12-16 16:32:58 -08007843 */
Jeff Sharkeya353d262011-10-28 11:12:06 -07007844 private void appendDropBoxProcessHeaders(ProcessRecord process, String processName,
7845 StringBuilder sb) {
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08007846 // Watchdog thread ends up invoking this function (with
7847 // a null ProcessRecord) to add the stack file to dropbox.
7848 // Do not acquire a lock on this (am) in such cases, as it
7849 // could cause a potential deadlock, if and when watchdog
7850 // is invoked due to unavailability of lock on am and it
7851 // would prevent watchdog from killing system_server.
7852 if (process == null) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07007853 sb.append("Process: ").append(processName).append("\n");
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08007854 return;
7855 }
Brad Fitzpatrick1e02d362010-09-10 09:19:50 -07007856 // Note: ProcessRecord 'process' is guarded by the service
7857 // instance. (notably process.pkgList, which could otherwise change
7858 // concurrently during execution of this method)
7859 synchronized (this) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07007860 sb.append("Process: ").append(processName).append("\n");
Dan Egnora455d192010-03-12 08:52:28 -08007861 int flags = process.info.flags;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007862 IPackageManager pm = AppGlobals.getPackageManager();
Dan Egnora455d192010-03-12 08:52:28 -08007863 sb.append("Flags: 0x").append(Integer.toString(flags, 16)).append("\n");
7864 for (String pkg : process.pkgList) {
7865 sb.append("Package: ").append(pkg);
Dan Egnor42471dd2010-01-07 17:25:22 -08007866 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07007867 PackageInfo pi = pm.getPackageInfo(pkg, 0, 0);
Dan Egnora455d192010-03-12 08:52:28 -08007868 if (pi != null) {
7869 sb.append(" v").append(pi.versionCode);
7870 if (pi.versionName != null) {
7871 sb.append(" (").append(pi.versionName).append(")");
7872 }
7873 }
7874 } catch (RemoteException e) {
7875 Slog.e(TAG, "Error getting package info: " + pkg, e);
Dan Egnor60d87622009-12-16 16:32:58 -08007876 }
Dan Egnora455d192010-03-12 08:52:28 -08007877 sb.append("\n");
Dan Egnor60d87622009-12-16 16:32:58 -08007878 }
Dan Egnora455d192010-03-12 08:52:28 -08007879 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007880 }
7881
7882 private static String processClass(ProcessRecord process) {
7883 if (process == null || process.pid == MY_PID) {
7884 return "system_server";
7885 } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
7886 return "system_app";
7887 } else {
7888 return "data_app";
7889 }
7890 }
7891
7892 /**
7893 * Write a description of an error (crash, WTF, ANR) to the drop box.
7894 * @param eventType to include in the drop box tag ("crash", "wtf", etc.)
7895 * @param process which caused the error, null means the system server
7896 * @param activity which triggered the error, null if unknown
7897 * @param parent activity related to the error, null if unknown
7898 * @param subject line related to the error, null if absent
7899 * @param report in long form describing the error, null if absent
7900 * @param logFile to include in the report, null if none
7901 * @param crashInfo giving an application stack trace, null if absent
7902 */
7903 public void addErrorToDropBox(String eventType,
Jeff Sharkeya353d262011-10-28 11:12:06 -07007904 ProcessRecord process, String processName, ActivityRecord activity,
7905 ActivityRecord parent, String subject,
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007906 final String report, final File logFile,
7907 final ApplicationErrorReport.CrashInfo crashInfo) {
7908 // NOTE -- this must never acquire the ActivityManagerService lock,
7909 // otherwise the watchdog may be prevented from resetting the system.
7910
7911 final String dropboxTag = processClass(process) + "_" + eventType;
7912 final DropBoxManager dbox = (DropBoxManager)
7913 mContext.getSystemService(Context.DROPBOX_SERVICE);
7914
7915 // Exit early if the dropbox isn't configured to accept this report type.
7916 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
7917
7918 final StringBuilder sb = new StringBuilder(1024);
Jeff Sharkeya353d262011-10-28 11:12:06 -07007919 appendDropBoxProcessHeaders(process, processName, sb);
Dan Egnora455d192010-03-12 08:52:28 -08007920 if (activity != null) {
7921 sb.append("Activity: ").append(activity.shortComponentName).append("\n");
7922 }
7923 if (parent != null && parent.app != null && parent.app.pid != process.pid) {
7924 sb.append("Parent-Process: ").append(parent.app.processName).append("\n");
7925 }
7926 if (parent != null && parent != activity) {
7927 sb.append("Parent-Activity: ").append(parent.shortComponentName).append("\n");
7928 }
7929 if (subject != null) {
7930 sb.append("Subject: ").append(subject).append("\n");
7931 }
7932 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
Christian Lindeberg03d2ca62010-09-28 14:52:20 +02007933 if (Debug.isDebuggerConnected()) {
7934 sb.append("Debugger: Connected\n");
7935 }
Dan Egnora455d192010-03-12 08:52:28 -08007936 sb.append("\n");
7937
7938 // Do the rest in a worker thread to avoid blocking the caller on I/O
7939 // (After this point, we shouldn't access AMS internal data structures.)
7940 Thread worker = new Thread("Error dump: " + dropboxTag) {
7941 @Override
7942 public void run() {
7943 if (report != null) {
7944 sb.append(report);
7945 }
7946 if (logFile != null) {
7947 try {
7948 sb.append(FileUtils.readTextFile(logFile, 128 * 1024, "\n\n[[TRUNCATED]]"));
7949 } catch (IOException e) {
7950 Slog.e(TAG, "Error reading " + logFile, e);
7951 }
7952 }
7953 if (crashInfo != null && crashInfo.stackTrace != null) {
7954 sb.append(crashInfo.stackTrace);
7955 }
7956
7957 String setting = Settings.Secure.ERROR_LOGCAT_PREFIX + dropboxTag;
7958 int lines = Settings.Secure.getInt(mContext.getContentResolver(), setting, 0);
7959 if (lines > 0) {
7960 sb.append("\n");
7961
7962 // Merge several logcat streams, and take the last N lines
7963 InputStreamReader input = null;
7964 try {
7965 java.lang.Process logcat = new ProcessBuilder("/system/bin/logcat",
7966 "-v", "time", "-b", "events", "-b", "system", "-b", "main",
7967 "-t", String.valueOf(lines)).redirectErrorStream(true).start();
7968
7969 try { logcat.getOutputStream().close(); } catch (IOException e) {}
7970 try { logcat.getErrorStream().close(); } catch (IOException e) {}
7971 input = new InputStreamReader(logcat.getInputStream());
7972
7973 int num;
7974 char[] buf = new char[8192];
7975 while ((num = input.read(buf)) > 0) sb.append(buf, 0, num);
7976 } catch (IOException e) {
7977 Slog.e(TAG, "Error running logcat", e);
7978 } finally {
7979 if (input != null) try { input.close(); } catch (IOException e) {}
7980 }
7981 }
7982
7983 dbox.addText(dropboxTag, sb.toString());
Dan Egnor60d87622009-12-16 16:32:58 -08007984 }
Dan Egnora455d192010-03-12 08:52:28 -08007985 };
7986
7987 if (process == null || process.pid == MY_PID) {
7988 worker.run(); // We may be about to die -- need to run this synchronously
7989 } else {
7990 worker.start();
Dan Egnor60d87622009-12-16 16:32:58 -08007991 }
7992 }
7993
7994 /**
7995 * Bring up the "unexpected error" dialog box for a crashing app.
7996 * Deal with edge cases (intercepts from instrumented applications,
7997 * ActivityController, error intent receivers, that sort of thing).
7998 * @param r the application crashing
7999 * @param crashInfo describing the failure
8000 */
8001 private void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008002 long timeMillis = System.currentTimeMillis();
8003 String shortMsg = crashInfo.exceptionClassName;
8004 String longMsg = crashInfo.exceptionMessage;
8005 String stackTrace = crashInfo.stackTrace;
8006 if (shortMsg != null && longMsg != null) {
8007 longMsg = shortMsg + ": " + longMsg;
8008 } else if (shortMsg != null) {
8009 longMsg = shortMsg;
8010 }
8011
Dan Egnor60d87622009-12-16 16:32:58 -08008012 AppErrorResult result = new AppErrorResult();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008013 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008014 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008015 try {
8016 String name = r != null ? r.processName : null;
8017 int pid = r != null ? r.pid : Binder.getCallingPid();
Dan Egnor60d87622009-12-16 16:32:58 -08008018 if (!mController.appCrashed(name, pid,
Dan Egnorb7f03672009-12-09 16:22:32 -08008019 shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008020 Slog.w(TAG, "Force-killing crashed app " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008021 + " at watcher's request");
8022 Process.killProcess(pid);
Dan Egnorb7f03672009-12-09 16:22:32 -08008023 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008024 }
8025 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008026 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008027 }
8028 }
8029
8030 final long origId = Binder.clearCallingIdentity();
8031
8032 // If this process is running instrumentation, finish it.
8033 if (r != null && r.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008034 Slog.w(TAG, "Error in app " + r.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008035 + " running instrumentation " + r.instrumentationClass + ":");
Joe Onorato8a9b2202010-02-26 18:56:32 -08008036 if (shortMsg != null) Slog.w(TAG, " " + shortMsg);
8037 if (longMsg != null) Slog.w(TAG, " " + longMsg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008038 Bundle info = new Bundle();
8039 info.putString("shortMsg", shortMsg);
8040 info.putString("longMsg", longMsg);
8041 finishInstrumentationLocked(r, Activity.RESULT_CANCELED, info);
8042 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008043 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008044 }
8045
Dan Egnor60d87622009-12-16 16:32:58 -08008046 // If we can't identify the process or it's already exceeded its crash quota,
8047 // quit right away without showing a crash dialog.
8048 if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008049 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008050 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008051 }
8052
8053 Message msg = Message.obtain();
8054 msg.what = SHOW_ERROR_MSG;
8055 HashMap data = new HashMap();
8056 data.put("result", result);
8057 data.put("app", r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008058 msg.obj = data;
8059 mHandler.sendMessage(msg);
8060
8061 Binder.restoreCallingIdentity(origId);
8062 }
8063
8064 int res = result.get();
8065
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008066 Intent appErrorIntent = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008067 synchronized (this) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008068 if (r != null && !r.isolated) {
8069 // XXX Can't keep track of crash time for isolated processes,
8070 // since they don't have a persistent identity.
8071 mProcessCrashTimes.put(r.info.processName, r.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008072 SystemClock.uptimeMillis());
8073 }
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008074 if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008075 appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008076 }
8077 }
8078
8079 if (appErrorIntent != null) {
8080 try {
8081 mContext.startActivity(appErrorIntent);
8082 } catch (ActivityNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008083 Slog.w(TAG, "bug report receiver dissappeared", e);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008084 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008085 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008086 }
Dan Egnorb7f03672009-12-09 16:22:32 -08008087
8088 Intent createAppErrorIntentLocked(ProcessRecord r,
8089 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
8090 ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008091 if (report == null) {
8092 return null;
8093 }
8094 Intent result = new Intent(Intent.ACTION_APP_ERROR);
8095 result.setComponent(r.errorReportReceiver);
8096 result.putExtra(Intent.EXTRA_BUG_REPORT, report);
8097 result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
8098 return result;
8099 }
8100
Dan Egnorb7f03672009-12-09 16:22:32 -08008101 private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r,
8102 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008103 if (r.errorReportReceiver == null) {
8104 return null;
8105 }
8106
8107 if (!r.crashing && !r.notResponding) {
8108 return null;
8109 }
8110
Dan Egnorb7f03672009-12-09 16:22:32 -08008111 ApplicationErrorReport report = new ApplicationErrorReport();
8112 report.packageName = r.info.packageName;
8113 report.installerPackageName = r.errorReportReceiver.getPackageName();
8114 report.processName = r.processName;
8115 report.time = timeMillis;
Jacek Surazskie0ee6ef2010-01-07 16:23:03 +01008116 report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008117
Dan Egnorb7f03672009-12-09 16:22:32 -08008118 if (r.crashing) {
8119 report.type = ApplicationErrorReport.TYPE_CRASH;
8120 report.crashInfo = crashInfo;
8121 } else if (r.notResponding) {
8122 report.type = ApplicationErrorReport.TYPE_ANR;
8123 report.anrInfo = new ApplicationErrorReport.AnrInfo();
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008124
Dan Egnorb7f03672009-12-09 16:22:32 -08008125 report.anrInfo.activity = r.notRespondingReport.tag;
8126 report.anrInfo.cause = r.notRespondingReport.shortMsg;
8127 report.anrInfo.info = r.notRespondingReport.longMsg;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008128 }
8129
Dan Egnorb7f03672009-12-09 16:22:32 -08008130 return report;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008131 }
8132
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008133 public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008134 enforceNotIsolatedCaller("getProcessesInErrorState");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008135 // assume our apps are happy - lazy create the list
8136 List<ActivityManager.ProcessErrorStateInfo> errList = null;
8137
8138 synchronized (this) {
8139
8140 // iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008141 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8142 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008143 if ((app.thread != null) && (app.crashing || app.notResponding)) {
8144 // This one's in trouble, so we'll generate a report for it
8145 // crashes are higher priority (in case there's a crash *and* an anr)
8146 ActivityManager.ProcessErrorStateInfo report = null;
8147 if (app.crashing) {
8148 report = app.crashingReport;
8149 } else if (app.notResponding) {
8150 report = app.notRespondingReport;
8151 }
8152
8153 if (report != null) {
8154 if (errList == null) {
8155 errList = new ArrayList<ActivityManager.ProcessErrorStateInfo>(1);
8156 }
8157 errList.add(report);
8158 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008159 Slog.w(TAG, "Missing app error report, app = " + app.processName +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008160 " crashing = " + app.crashing +
8161 " notResponding = " + app.notResponding);
8162 }
8163 }
8164 }
8165 }
8166
8167 return errList;
8168 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07008169
8170 static int oomAdjToImportance(int adj, ActivityManager.RunningAppProcessInfo currApp) {
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008171 if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008172 if (currApp != null) {
8173 currApp.lru = adj - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
8174 }
8175 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008176 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
8177 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008178 } else if (adj >= ProcessList.HOME_APP_ADJ) {
8179 if (currApp != null) {
8180 currApp.lru = 0;
8181 }
8182 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008183 } else if (adj >= ProcessList.SERVICE_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008184 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
8185 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
8186 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
8187 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
8188 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
8189 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
8190 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
8191 } else {
8192 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
8193 }
8194 }
8195
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008196 private void fillInProcMemInfo(ProcessRecord app,
8197 ActivityManager.RunningAppProcessInfo outInfo) {
8198 outInfo.pid = app.pid;
8199 outInfo.uid = app.info.uid;
8200 if (mHeavyWeightProcess == app) {
8201 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_CANT_SAVE_STATE;
8202 }
8203 if (app.persistent) {
8204 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_PERSISTENT;
8205 }
8206 outInfo.lastTrimLevel = app.trimMemoryLevel;
8207 int adj = app.curAdj;
8208 outInfo.importance = oomAdjToImportance(adj, outInfo);
8209 outInfo.importanceReasonCode = app.adjTypeCode;
8210 }
8211
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008212 public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008213 enforceNotIsolatedCaller("getRunningAppProcesses");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008214 // Lazy instantiation of list
8215 List<ActivityManager.RunningAppProcessInfo> runList = null;
8216 synchronized (this) {
8217 // Iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008218 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8219 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008220 if ((app.thread != null) && (!app.crashing && !app.notResponding)) {
8221 // Generate process state info for running application
8222 ActivityManager.RunningAppProcessInfo currApp =
8223 new ActivityManager.RunningAppProcessInfo(app.processName,
8224 app.pid, app.getPackageList());
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008225 fillInProcMemInfo(app, currApp);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008226 if (app.adjSource instanceof ProcessRecord) {
8227 currApp.importanceReasonPid = ((ProcessRecord)app.adjSource).pid;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008228 currApp.importanceReasonImportance = oomAdjToImportance(
8229 app.adjSourceOom, null);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008230 } else if (app.adjSource instanceof ActivityRecord) {
8231 ActivityRecord r = (ActivityRecord)app.adjSource;
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008232 if (r.app != null) currApp.importanceReasonPid = r.app.pid;
8233 }
8234 if (app.adjTarget instanceof ComponentName) {
8235 currApp.importanceReasonComponent = (ComponentName)app.adjTarget;
8236 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08008237 //Slog.v(TAG, "Proc " + app.processName + ": imp=" + currApp.importance
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008238 // + " lru=" + currApp.lru);
8239 if (runList == null) {
8240 runList = new ArrayList<ActivityManager.RunningAppProcessInfo>();
8241 }
8242 runList.add(currApp);
8243 }
8244 }
8245 }
8246 return runList;
8247 }
8248
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008249 public List<ApplicationInfo> getRunningExternalApplications() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008250 enforceNotIsolatedCaller("getRunningExternalApplications");
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008251 List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses();
8252 List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>();
8253 if (runningApps != null && runningApps.size() > 0) {
8254 Set<String> extList = new HashSet<String>();
8255 for (ActivityManager.RunningAppProcessInfo app : runningApps) {
8256 if (app.pkgList != null) {
8257 for (String pkg : app.pkgList) {
8258 extList.add(pkg);
8259 }
8260 }
8261 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008262 IPackageManager pm = AppGlobals.getPackageManager();
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008263 for (String pkg : extList) {
8264 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07008265 ApplicationInfo info = pm.getApplicationInfo(pkg, 0, UserId.getCallingUserId());
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008266 if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
8267 retList.add(info);
8268 }
8269 } catch (RemoteException e) {
8270 }
8271 }
8272 }
8273 return retList;
8274 }
8275
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008276 @Override
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008277 public void getMyMemoryState(ActivityManager.RunningAppProcessInfo outInfo) {
8278 enforceNotIsolatedCaller("getMyMemoryState");
8279 synchronized (this) {
8280 ProcessRecord proc;
8281 synchronized (mPidsSelfLocked) {
8282 proc = mPidsSelfLocked.get(Binder.getCallingPid());
8283 }
8284 fillInProcMemInfo(proc, outInfo);
8285 }
8286 }
8287
8288 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008289 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008290 if (checkCallingPermission(android.Manifest.permission.DUMP)
8291 != PackageManager.PERMISSION_GRANTED) {
8292 pw.println("Permission Denial: can't dump ActivityManager from from pid="
8293 + Binder.getCallingPid()
8294 + ", uid=" + Binder.getCallingUid()
8295 + " without permission "
8296 + android.Manifest.permission.DUMP);
8297 return;
8298 }
8299
8300 boolean dumpAll = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008301 boolean dumpClient = false;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008302 String dumpPackage = null;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008303
8304 int opti = 0;
8305 while (opti < args.length) {
8306 String opt = args[opti];
8307 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
8308 break;
8309 }
8310 opti++;
8311 if ("-a".equals(opt)) {
8312 dumpAll = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008313 } else if ("-c".equals(opt)) {
8314 dumpClient = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008315 } else if ("-h".equals(opt)) {
8316 pw.println("Activity manager dump options:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008317 pw.println(" [-a] [-c] [-h] [cmd] ...");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008318 pw.println(" cmd may be one of:");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008319 pw.println(" a[ctivities]: activity stack state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008320 pw.println(" b[roadcasts] [PACKAGE_NAME]: broadcast state");
8321 pw.println(" i[ntents] [PACKAGE_NAME]: pending intent state");
8322 pw.println(" p[rocesses] [PACKAGE_NAME]: process state");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008323 pw.println(" o[om]: out of memory management");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008324 pw.println(" prov[iders] [COMP_SPEC ...]: content provider state");
Marco Nelissen18cb2872011-11-15 11:19:53 -08008325 pw.println(" provider [COMP_SPEC]: provider client-side state");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008326 pw.println(" s[ervices] [COMP_SPEC ...]: service state");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008327 pw.println(" service [COMP_SPEC]: service client-side state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008328 pw.println(" package [PACKAGE_NAME]: all state related to given package");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008329 pw.println(" all: dump all activities");
8330 pw.println(" top: dump the top activity");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008331 pw.println(" cmd may also be a COMP_SPEC to dump activities.");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008332 pw.println(" COMP_SPEC may be a component name (com.foo/.myApp),");
8333 pw.println(" a partial substring in a component name, a");
8334 pw.println(" hex object identifier.");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008335 pw.println(" -a: include all available server state.");
8336 pw.println(" -c: include client state.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008337 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008338 } else {
8339 pw.println("Unknown argument: " + opt + "; use -h for help");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008340 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008341 }
8342
8343 // Is the caller requesting to dump a particular piece of data?
8344 if (opti < args.length) {
8345 String cmd = args[opti];
8346 opti++;
8347 if ("activities".equals(cmd) || "a".equals(cmd)) {
8348 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008349 dumpActivitiesLocked(fd, pw, args, opti, true, dumpClient, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008350 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008351 return;
8352 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008353 String[] newArgs;
8354 String name;
8355 if (opti >= args.length) {
8356 name = null;
8357 newArgs = EMPTY_STRING_ARRAY;
8358 } else {
8359 name = args[opti];
8360 opti++;
8361 newArgs = new String[args.length - opti];
8362 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8363 args.length - opti);
8364 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008365 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008366 dumpBroadcastsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008367 }
8368 return;
8369 } else if ("intents".equals(cmd) || "i".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008370 String[] newArgs;
8371 String name;
8372 if (opti >= args.length) {
8373 name = null;
8374 newArgs = EMPTY_STRING_ARRAY;
8375 } else {
8376 name = args[opti];
8377 opti++;
8378 newArgs = new String[args.length - opti];
8379 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8380 args.length - opti);
8381 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008382 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008383 dumpPendingIntentsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008384 }
8385 return;
8386 } else if ("processes".equals(cmd) || "p".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008387 String[] newArgs;
8388 String name;
8389 if (opti >= args.length) {
8390 name = null;
8391 newArgs = EMPTY_STRING_ARRAY;
8392 } else {
8393 name = args[opti];
8394 opti++;
8395 newArgs = new String[args.length - opti];
8396 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8397 args.length - opti);
8398 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008399 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008400 dumpProcessesLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008401 }
8402 return;
Dianne Hackborn287952c2010-09-22 22:34:31 -07008403 } else if ("oom".equals(cmd) || "o".equals(cmd)) {
8404 synchronized (this) {
8405 dumpOomLocked(fd, pw, args, opti, true);
8406 }
8407 return;
Marco Nelissen18cb2872011-11-15 11:19:53 -08008408 } else if ("provider".equals(cmd)) {
8409 String[] newArgs;
8410 String name;
8411 if (opti >= args.length) {
8412 name = null;
8413 newArgs = EMPTY_STRING_ARRAY;
8414 } else {
8415 name = args[opti];
8416 opti++;
8417 newArgs = new String[args.length - opti];
8418 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
8419 }
8420 if (!dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) {
8421 pw.println("No providers match: " + name);
8422 pw.println("Use -h for help.");
8423 }
8424 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008425 } else if ("providers".equals(cmd) || "prov".equals(cmd)) {
8426 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008427 dumpProvidersLocked(fd, pw, args, opti, true, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008428 }
8429 return;
8430 } else if ("service".equals(cmd)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008431 String[] newArgs;
8432 String name;
8433 if (opti >= args.length) {
8434 name = null;
8435 newArgs = EMPTY_STRING_ARRAY;
8436 } else {
8437 name = args[opti];
8438 opti++;
8439 newArgs = new String[args.length - opti];
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008440 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8441 args.length - opti);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008442 }
8443 if (!dumpService(fd, pw, name, newArgs, 0, dumpAll)) {
8444 pw.println("No services match: " + name);
8445 pw.println("Use -h for help.");
8446 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008447 return;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008448 } else if ("package".equals(cmd)) {
8449 String[] newArgs;
8450 if (opti >= args.length) {
8451 pw.println("package: no package name specified");
8452 pw.println("Use -h for help.");
8453 return;
8454 } else {
8455 dumpPackage = args[opti];
8456 opti++;
8457 newArgs = new String[args.length - opti];
8458 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8459 args.length - opti);
8460 args = newArgs;
8461 opti = 0;
8462 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008463 } else if ("services".equals(cmd) || "s".equals(cmd)) {
8464 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008465 dumpServicesLocked(fd, pw, args, opti, true, dumpClient, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008466 }
8467 return;
Dianne Hackborn625ac272010-09-17 18:29:22 -07008468 } else {
8469 // Dumping a single activity?
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008470 if (!dumpActivity(fd, pw, cmd, args, opti, dumpAll)) {
8471 pw.println("Bad activity command, or no activities match: " + cmd);
8472 pw.println("Use -h for help.");
Dianne Hackborn625ac272010-09-17 18:29:22 -07008473 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08008474 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008475 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008476 }
8477
8478 // No piece of data specified, dump everything.
8479 synchronized (this) {
8480 boolean needSep;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008481 needSep = dumpPendingIntentsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008482 if (needSep) {
8483 pw.println(" ");
8484 }
8485 if (dumpAll) {
8486 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008487 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008488 needSep = dumpBroadcastsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008489 if (needSep) {
8490 pw.println(" ");
8491 }
8492 if (dumpAll) {
8493 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008494 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008495 needSep = dumpProvidersLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008496 if (needSep) {
8497 pw.println(" ");
8498 }
8499 if (dumpAll) {
8500 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008501 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008502 needSep = dumpServicesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008503 if (needSep) {
8504 pw.println(" ");
8505 }
8506 if (dumpAll) {
8507 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008508 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008509 needSep = dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008510 if (needSep) {
8511 pw.println(" ");
8512 }
8513 if (dumpAll) {
8514 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008515 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008516 dumpProcessesLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008517 }
8518 }
8519
8520 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008521 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008522 pw.println("ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
8523 pw.println(" Main stack:");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008524 dumpHistoryList(fd, pw, mMainStack.mHistory, " ", "Hist", true, !dumpAll, dumpClient,
8525 dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008526 pw.println(" ");
8527 pw.println(" Running activities (most recent first):");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008528 dumpHistoryList(fd, pw, mMainStack.mLRUActivities, " ", "Run", false, !dumpAll, false,
8529 dumpPackage);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008530 if (mMainStack.mWaitingVisibleActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008531 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008532 pw.println(" Activities waiting for another to become visible:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008533 dumpHistoryList(fd, pw, mMainStack.mWaitingVisibleActivities, " ", "Wait", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008534 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008535 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008536 if (mMainStack.mStoppingActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008537 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008538 pw.println(" Activities waiting to stop:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008539 dumpHistoryList(fd, pw, mMainStack.mStoppingActivities, " ", "Stop", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008540 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008541 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008542 if (mMainStack.mGoingToSleepActivities.size() > 0) {
8543 pw.println(" ");
8544 pw.println(" Activities waiting to sleep:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008545 dumpHistoryList(fd, pw, mMainStack.mGoingToSleepActivities, " ", "Sleep", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008546 !dumpAll, false, dumpPackage);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008547 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008548 if (mMainStack.mFinishingActivities.size() > 0) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008549 pw.println(" ");
8550 pw.println(" Activities waiting to finish:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008551 dumpHistoryList(fd, pw, mMainStack.mFinishingActivities, " ", "Fin", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008552 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008553 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008554
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008555 pw.println(" ");
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08008556 if (mMainStack.mPausingActivity != null) {
8557 pw.println(" mPausingActivity: " + mMainStack.mPausingActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008558 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008559 pw.println(" mResumedActivity: " + mMainStack.mResumedActivity);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008560 pw.println(" mFocusedActivity: " + mFocusedActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008561 if (dumpAll) {
8562 pw.println(" mLastPausedActivity: " + mMainStack.mLastPausedActivity);
8563 pw.println(" mSleepTimeout: " + mMainStack.mSleepTimeout);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07008564 pw.println(" mDismissKeyguardOnNextActivity: "
8565 + mMainStack.mDismissKeyguardOnNextActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008566 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008567
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008568 if (mRecentTasks.size() > 0) {
8569 pw.println();
8570 pw.println(" Recent tasks:");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008571
8572 final int N = mRecentTasks.size();
8573 for (int i=0; i<N; i++) {
8574 TaskRecord tr = mRecentTasks.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008575 if (dumpPackage != null) {
8576 if (tr.realActivity == null ||
8577 !dumpPackage.equals(tr.realActivity)) {
8578 continue;
8579 }
8580 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008581 pw.print(" * Recent #"); pw.print(i); pw.print(": ");
8582 pw.println(tr);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008583 if (dumpAll) {
8584 mRecentTasks.get(i).dump(pw, " ");
8585 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008586 }
8587 }
8588
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008589 if (dumpAll) {
8590 pw.println(" ");
8591 pw.println(" mCurTask: " + mCurTask);
8592 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008593
8594 return true;
8595 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008596
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008597 boolean dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008598 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008599 boolean needSep = false;
8600 int numPers = 0;
8601
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008602 pw.println("ACTIVITY MANAGER RUNNING PROCESSES (dumpsys activity processes)");
8603
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008604 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008605 for (SparseArray<ProcessRecord> procs : mProcessNames.getMap().values()) {
8606 final int NA = procs.size();
8607 for (int ia=0; ia<NA; ia++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008608 ProcessRecord r = procs.valueAt(ia);
8609 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8610 continue;
8611 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008612 if (!needSep) {
8613 pw.println(" All known processes:");
8614 needSep = true;
8615 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008616 pw.print(r.persistent ? " *PERS*" : " *APP*");
8617 pw.print(" UID "); pw.print(procs.keyAt(ia));
8618 pw.print(" "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008619 r.dump(pw, " ");
8620 if (r.persistent) {
8621 numPers++;
8622 }
8623 }
8624 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008625 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008626
8627 if (mIsolatedProcesses.size() > 0) {
8628 if (needSep) pw.println(" ");
8629 needSep = true;
8630 pw.println(" Isolated process list (sorted by uid):");
8631 for (int i=0; i<mIsolatedProcesses.size(); i++) {
8632 ProcessRecord r = mIsolatedProcesses.valueAt(i);
8633 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8634 continue;
8635 }
8636 pw.println(String.format("%sIsolated #%2d: %s",
8637 " ", i, r.toString()));
8638 }
8639 }
8640
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008641 if (mLruProcesses.size() > 0) {
8642 if (needSep) pw.println(" ");
8643 needSep = true;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008644 pw.println(" Process LRU list (sorted by oom_adj):");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008645 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008646 "Proc", "PERS", false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008647 needSep = true;
8648 }
8649
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008650 if (dumpAll) {
8651 synchronized (mPidsSelfLocked) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008652 boolean printed = false;
8653 for (int i=0; i<mPidsSelfLocked.size(); i++) {
8654 ProcessRecord r = mPidsSelfLocked.valueAt(i);
8655 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8656 continue;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008657 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008658 if (!printed) {
8659 if (needSep) pw.println(" ");
8660 needSep = true;
8661 pw.println(" PID mappings:");
8662 printed = true;
8663 }
8664 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i));
8665 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008666 }
8667 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008668 }
8669
8670 if (mForegroundProcesses.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008671 synchronized (mPidsSelfLocked) {
8672 boolean printed = false;
8673 for (int i=0; i<mForegroundProcesses.size(); i++) {
8674 ProcessRecord r = mPidsSelfLocked.get(
8675 mForegroundProcesses.valueAt(i).pid);
8676 if (dumpPackage != null && (r == null
8677 || !dumpPackage.equals(r.info.packageName))) {
8678 continue;
8679 }
8680 if (!printed) {
8681 if (needSep) pw.println(" ");
8682 needSep = true;
8683 pw.println(" Foreground Processes:");
8684 printed = true;
8685 }
8686 pw.print(" PID #"); pw.print(mForegroundProcesses.keyAt(i));
8687 pw.print(": "); pw.println(mForegroundProcesses.valueAt(i));
8688 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008689 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008690 }
8691
8692 if (mPersistentStartingProcesses.size() > 0) {
8693 if (needSep) pw.println(" ");
8694 needSep = true;
8695 pw.println(" Persisent processes that are starting:");
8696 dumpProcessList(pw, this, mPersistentStartingProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008697 "Starting Norm", "Restarting PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008698 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008699
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008700 if (mRemovedProcesses.size() > 0) {
8701 if (needSep) pw.println(" ");
8702 needSep = true;
8703 pw.println(" Processes that are being removed:");
8704 dumpProcessList(pw, this, mRemovedProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008705 "Removed Norm", "Removed PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008706 }
8707
8708 if (mProcessesOnHold.size() > 0) {
8709 if (needSep) pw.println(" ");
8710 needSep = true;
8711 pw.println(" Processes that are on old until the system is ready:");
8712 dumpProcessList(pw, this, mProcessesOnHold, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008713 "OnHold Norm", "OnHold PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008714 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008715
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008716 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008717
8718 if (mProcessCrashTimes.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008719 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008720 long now = SystemClock.uptimeMillis();
8721 for (Map.Entry<String, SparseArray<Long>> procs
8722 : mProcessCrashTimes.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008723 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008724 SparseArray<Long> uids = procs.getValue();
8725 final int N = uids.size();
8726 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008727 int puid = uids.keyAt(i);
8728 ProcessRecord r = mProcessNames.get(pname, puid);
8729 if (dumpPackage != null && (r == null
8730 || !dumpPackage.equals(r.info.packageName))) {
8731 continue;
8732 }
8733 if (!printed) {
8734 if (needSep) pw.println(" ");
8735 needSep = true;
8736 pw.println(" Time since processes crashed:");
8737 printed = true;
8738 }
8739 pw.print(" Process "); pw.print(pname);
8740 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008741 pw.print(": last crashed ");
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008742 TimeUtils.formatDuration(now-uids.valueAt(i), pw);
8743 pw.println(" ago");
Dianne Hackbornfd12af42009-08-27 00:44:33 -07008744 }
8745 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008746 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008747
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008748 if (mBadProcesses.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008749 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008750 for (Map.Entry<String, SparseArray<Long>> procs
8751 : mBadProcesses.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008752 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008753 SparseArray<Long> uids = procs.getValue();
8754 final int N = uids.size();
8755 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008756 int puid = uids.keyAt(i);
8757 ProcessRecord r = mProcessNames.get(pname, puid);
8758 if (dumpPackage != null && (r == null
8759 || !dumpPackage.equals(r.info.packageName))) {
8760 continue;
8761 }
8762 if (!printed) {
8763 if (needSep) pw.println(" ");
8764 needSep = true;
8765 pw.println(" Bad processes:");
8766 }
8767 pw.print(" Bad process "); pw.print(pname);
8768 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008769 pw.print(": crashed at time ");
8770 pw.println(uids.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008771 }
8772 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008773 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008774
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008775 pw.println();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008776 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07008777 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn50685602011-12-01 12:23:37 -08008778 if (dumpAll) {
8779 StringBuilder sb = new StringBuilder(128);
8780 sb.append(" mPreviousProcessVisibleTime: ");
8781 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
8782 pw.println(sb);
8783 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07008784 if (mHeavyWeightProcess != null) {
8785 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
8786 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008787 pw.println(" mConfiguration: " + mConfiguration);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008788 if (dumpAll) {
8789 pw.println(" mConfigWillChange: " + mMainStack.mConfigWillChange);
Dianne Hackborn3d0724d2011-05-12 15:39:41 -07008790 if (mCompatModePackages.getPackages().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008791 boolean printed = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07008792 for (Map.Entry<String, Integer> entry
8793 : mCompatModePackages.getPackages().entrySet()) {
8794 String pkg = entry.getKey();
8795 int mode = entry.getValue();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008796 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
8797 continue;
8798 }
8799 if (!printed) {
8800 pw.println(" mScreenCompatPackages:");
8801 printed = true;
8802 }
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07008803 pw.print(" "); pw.print(pkg); pw.print(": ");
8804 pw.print(mode); pw.println();
8805 }
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07008806 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008807 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008808 pw.println(" mSleeping=" + mSleeping + " mShuttingDown=" + mShuttingDown);
8809 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
8810 || mOrigWaitForDebugger) {
8811 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp
8812 + " mDebugTransient=" + mDebugTransient
8813 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger);
8814 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08008815 if (mOpenGlTraceApp != null) {
8816 pw.println(" mOpenGlTraceApp=" + mOpenGlTraceApp);
8817 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07008818 if (mProfileApp != null || mProfileProc != null || mProfileFile != null
8819 || mProfileFd != null) {
8820 pw.println(" mProfileApp=" + mProfileApp + " mProfileProc=" + mProfileProc);
8821 pw.println(" mProfileFile=" + mProfileFile + " mProfileFd=" + mProfileFd);
8822 pw.println(" mProfileType=" + mProfileType + " mAutoStopProfiler="
8823 + mAutoStopProfiler);
8824 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008825 if (mAlwaysFinishActivities || mController != null) {
8826 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities
8827 + " mController=" + mController);
8828 }
8829 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008830 pw.println(" Total persistent processes: " + numPers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008831 pw.println(" mStartRunning=" + mStartRunning
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07008832 + " mProcessesReady=" + mProcessesReady
8833 + " mSystemReady=" + mSystemReady);
8834 pw.println(" mBooting=" + mBooting
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008835 + " mBooted=" + mBooted
8836 + " mFactoryTest=" + mFactoryTest);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008837 pw.print(" mLastPowerCheckRealtime=");
8838 TimeUtils.formatDuration(mLastPowerCheckRealtime, pw);
8839 pw.println("");
8840 pw.print(" mLastPowerCheckUptime=");
8841 TimeUtils.formatDuration(mLastPowerCheckUptime, pw);
8842 pw.println("");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008843 pw.println(" mGoingToSleep=" + mMainStack.mGoingToSleep);
8844 pw.println(" mLaunchingActivity=" + mMainStack.mLaunchingActivity);
Dianne Hackborn906497c2010-05-10 15:57:38 -07008845 pw.println(" mAdjSeq=" + mAdjSeq + " mLruSeq=" + mLruSeq);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008846 pw.println(" mNumServiceProcs=" + mNumServiceProcs
8847 + " mNewNumServiceProcs=" + mNewNumServiceProcs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008848 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008849
8850 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008851 }
8852
Dianne Hackborn287952c2010-09-22 22:34:31 -07008853 boolean dumpProcessesToGc(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008854 int opti, boolean needSep, boolean dumpAll, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07008855 if (mProcessesToGc.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008856 boolean printed = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -07008857 long now = SystemClock.uptimeMillis();
8858 for (int i=0; i<mProcessesToGc.size(); i++) {
8859 ProcessRecord proc = mProcessesToGc.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008860 if (dumpPackage != null && !dumpPackage.equals(proc.info.packageName)) {
8861 continue;
8862 }
8863 if (!printed) {
8864 if (needSep) pw.println(" ");
8865 needSep = true;
8866 pw.println(" Processes that are waiting to GC:");
8867 printed = true;
8868 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008869 pw.print(" Process "); pw.println(proc);
8870 pw.print(" lowMem="); pw.print(proc.reportLowMemory);
8871 pw.print(", last gced=");
8872 pw.print(now-proc.lastRequestedGc);
8873 pw.print(" ms ago, last lowMem=");
8874 pw.print(now-proc.lastLowMemory);
8875 pw.println(" ms ago");
8876
8877 }
8878 }
8879 return needSep;
8880 }
8881
8882 boolean dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args,
8883 int opti, boolean dumpAll) {
8884 boolean needSep = false;
8885
8886 if (mLruProcesses.size() > 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07008887 if (needSep) pw.println(" ");
8888 needSep = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -07008889 pw.println(" OOM levels:");
Dianne Hackborn7d608422011-08-07 16:24:18 -07008890 pw.print(" SYSTEM_ADJ: "); pw.println(ProcessList.SYSTEM_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008891 pw.print(" PERSISTENT_PROC_ADJ: "); pw.println(ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07008892 pw.print(" FOREGROUND_APP_ADJ: "); pw.println(ProcessList.FOREGROUND_APP_ADJ);
8893 pw.print(" VISIBLE_APP_ADJ: "); pw.println(ProcessList.VISIBLE_APP_ADJ);
8894 pw.print(" PERCEPTIBLE_APP_ADJ: "); pw.println(ProcessList.PERCEPTIBLE_APP_ADJ);
8895 pw.print(" HEAVY_WEIGHT_APP_ADJ: "); pw.println(ProcessList.HEAVY_WEIGHT_APP_ADJ);
8896 pw.print(" BACKUP_APP_ADJ: "); pw.println(ProcessList.BACKUP_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008897 pw.print(" SERVICE_ADJ: "); pw.println(ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07008898 pw.print(" HOME_APP_ADJ: "); pw.println(ProcessList.HOME_APP_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07008899 pw.print(" PREVIOUS_APP_ADJ: "); pw.println(ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008900 pw.print(" SERVICE_B_ADJ: "); pw.println(ProcessList.SERVICE_B_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07008901 pw.print(" HIDDEN_APP_MIN_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008902 pw.print(" HIDDEN_APP_MAX_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MAX_ADJ);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07008903
8904 if (needSep) pw.println(" ");
8905 needSep = true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07008906 pw.println(" Process OOM control:");
Dianne Hackborn905577f2011-09-07 18:31:28 -07008907 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008908 "Proc", "PERS", true, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008909 needSep = true;
8910 }
8911
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008912 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008913
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008914 pw.println();
Dianne Hackborn287952c2010-09-22 22:34:31 -07008915 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07008916 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008917 if (mHeavyWeightProcess != null) {
8918 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
8919 }
8920
8921 return true;
8922 }
8923
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008924 /**
8925 * There are three ways to call this:
8926 * - no service specified: dump all the services
8927 * - a flattened component name that matched an existing service was specified as the
8928 * first arg: dump that one service
8929 * - the first arg isn't the flattened component name of an existing service:
8930 * dump all services whose component contains the first arg as a substring
8931 */
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008932 protected boolean dumpService(FileDescriptor fd, PrintWriter pw, String name, String[] args,
8933 int opti, boolean dumpAll) {
8934 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008935
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008936 if ("all".equals(name)) {
Dianne Hackborn14bfa392010-07-24 19:58:06 -07008937 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07008938 try {
8939 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
8940 for (UserInfo user : users) {
8941 for (ServiceRecord r1 : mServiceMap.getAllServices(user.id)) {
8942 services.add(r1);
8943 }
8944 }
8945 } catch (RemoteException re) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008946 }
8947 }
8948 } else {
8949 ComponentName componentName = name != null
8950 ? ComponentName.unflattenFromString(name) : null;
8951 int objectId = 0;
8952 if (componentName == null) {
8953 // Not a '/' separated full component name; maybe an object ID?
8954 try {
8955 objectId = Integer.parseInt(name, 16);
8956 name = null;
8957 componentName = null;
8958 } catch (RuntimeException e) {
8959 }
8960 }
8961
8962 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07008963 try {
8964 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
8965 for (UserInfo user : users) {
8966 for (ServiceRecord r1 : mServiceMap.getAllServices(user.id)) {
8967 if (componentName != null) {
8968 if (r1.name.equals(componentName)) {
8969 services.add(r1);
8970 }
8971 } else if (name != null) {
8972 if (r1.name.flattenToString().contains(name)) {
8973 services.add(r1);
8974 }
8975 } else if (System.identityHashCode(r1) == objectId) {
8976 services.add(r1);
8977 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008978 }
Dianne Hackborn14bfa392010-07-24 19:58:06 -07008979 }
Amith Yamasani742a6712011-05-04 14:49:28 -07008980 } catch (RemoteException re) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008981 }
8982 }
8983 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008984
8985 if (services.size() <= 0) {
8986 return false;
8987 }
8988
8989 boolean needSep = false;
8990 for (int i=0; i<services.size(); i++) {
8991 if (needSep) {
8992 pw.println();
8993 }
8994 needSep = true;
8995 dumpService("", fd, pw, services.get(i), args, dumpAll);
8996 }
8997 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008998 }
8999
9000 /**
9001 * Invokes IApplicationThread.dumpService() on the thread of the specified service if
9002 * there is a thread associated with the service.
9003 */
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009004 private void dumpService(String prefix, FileDescriptor fd, PrintWriter pw,
9005 final ServiceRecord r, String[] args, boolean dumpAll) {
9006 String innerPrefix = prefix + " ";
9007 synchronized (this) {
9008 pw.print(prefix); pw.print("SERVICE ");
9009 pw.print(r.shortName); pw.print(" ");
9010 pw.print(Integer.toHexString(System.identityHashCode(r)));
9011 pw.print(" pid=");
9012 if (r.app != null) pw.println(r.app.pid);
9013 else pw.println("(not running)");
9014 if (dumpAll) {
9015 r.dump(pw, innerPrefix);
9016 }
9017 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009018 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009019 pw.print(prefix); pw.println(" Client:");
9020 pw.flush();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009021 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009022 TransferPipe tp = new TransferPipe();
9023 try {
9024 r.app.thread.dumpService(tp.getWriteFd().getFileDescriptor(), r, args);
9025 tp.setBufferPrefix(prefix + " ");
9026 tp.go(fd);
9027 } finally {
9028 tp.kill();
9029 }
9030 } catch (IOException e) {
9031 pw.println(prefix + " Failure while dumping the service: " + e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009032 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009033 pw.println(prefix + " Got a RemoteException while dumping the service");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009034 }
9035 }
9036 }
9037
Marco Nelissen18cb2872011-11-15 11:19:53 -08009038 /**
9039 * There are three ways to call this:
9040 * - no provider specified: dump all the providers
9041 * - a flattened component name that matched an existing provider was specified as the
9042 * first arg: dump that one provider
9043 * - the first arg isn't the flattened component name of an existing provider:
9044 * dump all providers whose component contains the first arg as a substring
9045 */
9046 protected boolean dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9047 int opti, boolean dumpAll) {
Marco Nelissende7408c2012-02-08 14:57:38 -08009048 return mProviderMap.dumpProvider(fd, pw, name, args, opti, dumpAll);
Marco Nelissen18cb2872011-11-15 11:19:53 -08009049 }
9050
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009051 static class ItemMatcher {
9052 ArrayList<ComponentName> components;
9053 ArrayList<String> strings;
9054 ArrayList<Integer> objects;
9055 boolean all;
9056
9057 ItemMatcher() {
9058 all = true;
9059 }
9060
9061 void build(String name) {
9062 ComponentName componentName = ComponentName.unflattenFromString(name);
9063 if (componentName != null) {
9064 if (components == null) {
9065 components = new ArrayList<ComponentName>();
9066 }
9067 components.add(componentName);
9068 all = false;
9069 } else {
9070 int objectId = 0;
9071 // Not a '/' separated full component name; maybe an object ID?
9072 try {
9073 objectId = Integer.parseInt(name, 16);
9074 if (objects == null) {
9075 objects = new ArrayList<Integer>();
9076 }
9077 objects.add(objectId);
9078 all = false;
9079 } catch (RuntimeException e) {
9080 // Not an integer; just do string match.
9081 if (strings == null) {
9082 strings = new ArrayList<String>();
9083 }
9084 strings.add(name);
9085 all = false;
9086 }
9087 }
9088 }
9089
9090 int build(String[] args, int opti) {
9091 for (; opti<args.length; opti++) {
9092 String name = args[opti];
9093 if ("--".equals(name)) {
9094 return opti+1;
9095 }
9096 build(name);
9097 }
9098 return opti;
9099 }
9100
9101 boolean match(Object object, ComponentName comp) {
9102 if (all) {
9103 return true;
9104 }
9105 if (components != null) {
9106 for (int i=0; i<components.size(); i++) {
9107 if (components.get(i).equals(comp)) {
9108 return true;
9109 }
9110 }
9111 }
9112 if (objects != null) {
9113 for (int i=0; i<objects.size(); i++) {
9114 if (System.identityHashCode(object) == objects.get(i)) {
9115 return true;
9116 }
9117 }
9118 }
9119 if (strings != null) {
9120 String flat = comp.flattenToString();
9121 for (int i=0; i<strings.size(); i++) {
9122 if (flat.contains(strings.get(i))) {
9123 return true;
9124 }
9125 }
9126 }
9127 return false;
9128 }
9129 }
9130
Dianne Hackborn625ac272010-09-17 18:29:22 -07009131 /**
9132 * There are three things that cmd can be:
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009133 * - a flattened component name that matches an existing activity
Dianne Hackborn625ac272010-09-17 18:29:22 -07009134 * - the cmd arg isn't the flattened component name of an existing activity:
9135 * dump all activity whose component contains the cmd as a substring
9136 * - A hex number of the ActivityRecord object instance.
9137 */
9138 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9139 int opti, boolean dumpAll) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009140 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009141
9142 if ("all".equals(name)) {
9143 synchronized (this) {
9144 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009145 activities.add(r1);
9146 }
9147 }
Dianne Hackbornf9302322011-06-14 18:36:14 -07009148 } else if ("top".equals(name)) {
9149 synchronized (this) {
9150 final int N = mMainStack.mHistory.size();
9151 if (N > 0) {
9152 activities.add((ActivityRecord)mMainStack.mHistory.get(N-1));
9153 }
9154 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009155 } else {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009156 ItemMatcher matcher = new ItemMatcher();
9157 matcher.build(name);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009158
9159 synchronized (this) {
9160 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009161 if (matcher.match(r1, r1.intent.getComponent())) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009162 activities.add(r1);
9163 }
9164 }
9165 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009166 }
9167
9168 if (activities.size() <= 0) {
9169 return false;
9170 }
9171
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009172 String[] newArgs = new String[args.length - opti];
9173 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
9174
Dianne Hackborn30d71892010-12-11 10:37:55 -08009175 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009176 boolean needSep = false;
Dianne Hackborn30d71892010-12-11 10:37:55 -08009177 for (int i=activities.size()-1; i>=0; i--) {
9178 ActivityRecord r = (ActivityRecord)activities.get(i);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009179 if (needSep) {
9180 pw.println();
9181 }
9182 needSep = true;
9183 synchronized (this) {
9184 if (lastTask != r.task) {
9185 lastTask = r.task;
9186 pw.print("TASK "); pw.print(lastTask.affinity);
9187 pw.print(" id="); pw.println(lastTask.taskId);
9188 if (dumpAll) {
9189 lastTask.dump(pw, " ");
9190 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08009191 }
9192 }
9193 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009194 }
9195 return true;
9196 }
9197
9198 /**
9199 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
9200 * there is a thread associated with the activity.
9201 */
Dianne Hackborn30d71892010-12-11 10:37:55 -08009202 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009203 final ActivityRecord r, String[] args, boolean dumpAll) {
9204 String innerPrefix = prefix + " ";
Dianne Hackborn30d71892010-12-11 10:37:55 -08009205 synchronized (this) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009206 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
9207 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
9208 pw.print(" pid=");
Dianne Hackborn30d71892010-12-11 10:37:55 -08009209 if (r.app != null) pw.println(r.app.pid);
9210 else pw.println("(not running)");
9211 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009212 r.dump(pw, innerPrefix);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009213 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009214 }
9215 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009216 // flush anything that is already in the PrintWriter since the thread is going
9217 // to write to the file descriptor directly
9218 pw.flush();
Dianne Hackborn625ac272010-09-17 18:29:22 -07009219 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009220 TransferPipe tp = new TransferPipe();
9221 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009222 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9223 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009224 tp.go(fd);
9225 } finally {
9226 tp.kill();
9227 }
9228 } catch (IOException e) {
9229 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009230 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009231 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
Dianne Hackborn625ac272010-09-17 18:29:22 -07009232 }
9233 }
9234 }
9235
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009236 boolean dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009237 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009238 boolean needSep = false;
9239
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009240 pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009241 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009242 if (mRegisteredReceivers.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009243 boolean printed = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009244 Iterator it = mRegisteredReceivers.values().iterator();
9245 while (it.hasNext()) {
9246 ReceiverList r = (ReceiverList)it.next();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009247 if (dumpPackage != null && (r.app == null ||
9248 !dumpPackage.equals(r.app.info.packageName))) {
9249 continue;
9250 }
9251 if (!printed) {
9252 pw.println(" Registered Receivers:");
9253 needSep = true;
9254 printed = true;
9255 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009256 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009257 r.dump(pw, " ");
9258 }
9259 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009260
9261 if (mReceiverResolver.dump(pw, needSep ?
9262 "\n Receiver Resolver Table:" : " Receiver Resolver Table:",
9263 " ", dumpPackage, false)) {
9264 needSep = true;
9265 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009266 }
Christopher Tatef46723b2012-01-26 14:19:24 -08009267
9268 for (BroadcastQueue q : mBroadcastQueues) {
9269 needSep = q.dumpLocked(fd, pw, args, opti, dumpAll, dumpPackage, needSep);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009270 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009271
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009272 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009273
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009274 if (mStickyBroadcasts != null && dumpPackage == null) {
9275 if (needSep) {
9276 pw.println();
9277 }
9278 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009279 pw.println(" Sticky broadcasts:");
9280 StringBuilder sb = new StringBuilder(128);
9281 for (Map.Entry<String, ArrayList<Intent>> ent
9282 : mStickyBroadcasts.entrySet()) {
9283 pw.print(" * Sticky action "); pw.print(ent.getKey());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009284 if (dumpAll) {
9285 pw.println(":");
9286 ArrayList<Intent> intents = ent.getValue();
9287 final int N = intents.size();
9288 for (int i=0; i<N; i++) {
9289 sb.setLength(0);
9290 sb.append(" Intent: ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009291 intents.get(i).toShortString(sb, false, true, false, false);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009292 pw.println(sb.toString());
9293 Bundle bundle = intents.get(i).getExtras();
9294 if (bundle != null) {
9295 pw.print(" ");
9296 pw.println(bundle.toString());
9297 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009298 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009299 } else {
9300 pw.println("");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009301 }
9302 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009303 needSep = true;
9304 }
9305
9306 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009307 pw.println();
Christopher Tatef46723b2012-01-26 14:19:24 -08009308 for (BroadcastQueue queue : mBroadcastQueues) {
9309 pw.println(" mBroadcastsScheduled [" + queue.mQueueName + "]="
9310 + queue.mBroadcastsScheduled);
9311 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009312 pw.println(" mHandler:");
9313 mHandler.dump(new PrintWriterPrinter(pw), " ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009314 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009315 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009316
9317 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009318 }
9319
Marco Nelissen18cb2872011-11-15 11:19:53 -08009320 /**
9321 * Prints a list of ServiceRecords (dumpsys activity services)
9322 */
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009323 boolean dumpServicesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009324 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009325 boolean needSep = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009326
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009327 ItemMatcher matcher = new ItemMatcher();
9328 matcher.build(args, opti);
9329
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009330 pw.println("ACTIVITY MANAGER SERVICES (dumpsys activity services)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009331 try {
9332 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
9333 for (UserInfo user : users) {
9334 if (mServiceMap.getAllServices(user.id).size() > 0) {
9335 boolean printed = false;
9336 long nowReal = SystemClock.elapsedRealtime();
9337 Iterator<ServiceRecord> it = mServiceMap.getAllServices(
9338 user.id).iterator();
9339 needSep = false;
9340 while (it.hasNext()) {
9341 ServiceRecord r = it.next();
9342 if (!matcher.match(r, r.name)) {
9343 continue;
9344 }
9345 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9346 continue;
9347 }
9348 if (!printed) {
9349 pw.println(" Active services:");
9350 printed = true;
9351 }
9352 if (needSep) {
9353 pw.println();
9354 }
9355 pw.print(" * ");
9356 pw.println(r);
9357 if (dumpAll) {
9358 r.dump(pw, " ");
9359 needSep = true;
9360 } else {
9361 pw.print(" app=");
9362 pw.println(r.app);
9363 pw.print(" created=");
9364 TimeUtils.formatDuration(r.createTime, nowReal, pw);
9365 pw.print(" started=");
9366 pw.print(r.startRequested);
9367 pw.print(" connections=");
9368 pw.println(r.connections.size());
9369 if (r.connections.size() > 0) {
9370 pw.println(" Connections:");
9371 for (ArrayList<ConnectionRecord> clist : r.connections.values()) {
9372 for (int i = 0; i < clist.size(); i++) {
9373 ConnectionRecord conn = clist.get(i);
9374 pw.print(" ");
9375 pw.print(conn.binding.intent.intent.getIntent()
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009376 .toShortString(false, false, false, false));
Amith Yamasani742a6712011-05-04 14:49:28 -07009377 pw.print(" -> ");
9378 ProcessRecord proc = conn.binding.client;
9379 pw.println(proc != null ? proc.toShortString() : "null");
9380 }
9381 }
Dianne Hackborn8ec8d412011-11-14 18:27:24 -08009382 }
9383 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009384 if (dumpClient && r.app != null && r.app.thread != null) {
9385 pw.println(" Client:");
9386 pw.flush();
9387 try {
9388 TransferPipe tp = new TransferPipe();
9389 try {
9390 r.app.thread.dumpService(tp.getWriteFd().getFileDescriptor(),
9391 r, args);
9392 tp.setBufferPrefix(" ");
9393 // Short timeout, since blocking here can
9394 // deadlock with the application.
9395 tp.go(fd, 2000);
9396 } finally {
9397 tp.kill();
9398 }
9399 } catch (IOException e) {
9400 pw.println(" Failure while dumping the service: " + e);
9401 } catch (RemoteException e) {
9402 pw.println(" Got a RemoteException while dumping the service");
9403 }
9404 needSep = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009405 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009406 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009407 needSep = printed;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009408 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009409 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009410 } catch (RemoteException re) {
9411
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009412 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009413
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009414 if (mPendingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009415 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009416 for (int i=0; i<mPendingServices.size(); i++) {
9417 ServiceRecord r = mPendingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009418 if (!matcher.match(r, r.name)) {
9419 continue;
9420 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009421 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9422 continue;
9423 }
9424 if (!printed) {
9425 if (needSep) pw.println(" ");
9426 needSep = true;
9427 pw.println(" Pending services:");
9428 printed = true;
9429 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009430 pw.print(" * Pending "); pw.println(r);
9431 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009432 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009433 needSep = true;
9434 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009435
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009436 if (mRestartingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009437 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009438 for (int i=0; i<mRestartingServices.size(); i++) {
9439 ServiceRecord r = mRestartingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009440 if (!matcher.match(r, r.name)) {
9441 continue;
9442 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009443 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9444 continue;
9445 }
9446 if (!printed) {
9447 if (needSep) pw.println(" ");
9448 needSep = true;
9449 pw.println(" Restarting services:");
9450 printed = true;
9451 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009452 pw.print(" * Restarting "); pw.println(r);
9453 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009454 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009455 needSep = true;
9456 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009457
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009458 if (mStoppingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009459 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009460 for (int i=0; i<mStoppingServices.size(); i++) {
9461 ServiceRecord r = mStoppingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009462 if (!matcher.match(r, r.name)) {
9463 continue;
9464 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009465 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9466 continue;
9467 }
9468 if (!printed) {
9469 if (needSep) pw.println(" ");
9470 needSep = true;
9471 pw.println(" Stopping services:");
9472 printed = true;
9473 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009474 pw.print(" * Stopping "); pw.println(r);
9475 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009476 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009477 needSep = true;
9478 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009479
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009480 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009481 if (mServiceConnections.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009482 boolean printed = false;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009483 Iterator<ArrayList<ConnectionRecord>> it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009484 = mServiceConnections.values().iterator();
9485 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009486 ArrayList<ConnectionRecord> r = it.next();
9487 for (int i=0; i<r.size(); i++) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009488 ConnectionRecord cr = r.get(i);
9489 if (!matcher.match(cr.binding.service, cr.binding.service.name)) {
9490 continue;
9491 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009492 if (dumpPackage != null && (cr.binding.client == null
9493 || !dumpPackage.equals(cr.binding.client.info.packageName))) {
9494 continue;
9495 }
9496 if (!printed) {
9497 if (needSep) pw.println(" ");
9498 needSep = true;
9499 pw.println(" Connection bindings to services:");
9500 printed = true;
9501 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009502 pw.print(" * "); pw.println(cr);
9503 cr.dump(pw, " ");
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009504 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009505 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009506 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009507 }
9508 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009509
9510 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009511 }
9512
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009513 boolean dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009514 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07009515 boolean needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009516
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009517 ItemMatcher matcher = new ItemMatcher();
9518 matcher.build(args, opti);
9519
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009520 pw.println("ACTIVITY MANAGER CONTENT PROVIDERS (dumpsys activity providers)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009521
9522 mProviderMap.dumpProvidersLocked(pw, dumpAll);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009523
9524 if (mLaunchingProviders.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009525 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009526 for (int i=mLaunchingProviders.size()-1; i>=0; i--) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009527 ContentProviderRecord r = mLaunchingProviders.get(i);
9528 if (dumpPackage != null && !dumpPackage.equals(r.name.getPackageName())) {
9529 continue;
9530 }
9531 if (!printed) {
9532 if (needSep) pw.println(" ");
9533 needSep = true;
9534 pw.println(" Launching content providers:");
9535 printed = true;
9536 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009537 pw.print(" Launching #"); pw.print(i); pw.print(": ");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009538 pw.println(r);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009539 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009540 }
9541
9542 if (mGrantedUriPermissions.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009543 if (needSep) pw.println();
9544 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009545 pw.println("Granted Uri Permissions:");
9546 for (int i=0; i<mGrantedUriPermissions.size(); i++) {
9547 int uid = mGrantedUriPermissions.keyAt(i);
9548 HashMap<Uri, UriPermission> perms
9549 = mGrantedUriPermissions.valueAt(i);
9550 pw.print(" * UID "); pw.print(uid);
9551 pw.println(" holds:");
9552 for (UriPermission perm : perms.values()) {
9553 pw.print(" "); pw.println(perm);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009554 if (dumpAll) {
9555 perm.dump(pw, " ");
9556 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009557 }
9558 }
9559 needSep = true;
9560 }
9561
9562 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009563 }
9564
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009565 boolean dumpPendingIntentsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009566 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009567 boolean needSep = false;
9568
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009569 if (mIntentSenderRecords.size() > 0) {
9570 boolean printed = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009571 Iterator<WeakReference<PendingIntentRecord>> it
9572 = mIntentSenderRecords.values().iterator();
9573 while (it.hasNext()) {
9574 WeakReference<PendingIntentRecord> ref = it.next();
9575 PendingIntentRecord rec = ref != null ? ref.get(): null;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009576 if (dumpPackage != null && (rec == null
9577 || !dumpPackage.equals(rec.key.packageName))) {
9578 continue;
9579 }
9580 if (!printed) {
9581 pw.println("ACTIVITY MANAGER PENDING INTENTS (dumpsys activity intents)");
9582 printed = true;
9583 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009584 needSep = true;
9585 if (rec != null) {
9586 pw.print(" * "); pw.println(rec);
9587 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009588 rec.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009589 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009590 } else {
9591 pw.print(" * "); pw.println(ref);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009592 }
9593 }
9594 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009595
9596 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009597 }
9598
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009599 private static final void dumpHistoryList(FileDescriptor fd, PrintWriter pw, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009600 String prefix, String label, boolean complete, boolean brief, boolean client,
9601 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009602 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009603 boolean needNL = false;
9604 final String innerPrefix = prefix + " ";
9605 final String[] args = new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009606 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009607 final ActivityRecord r = (ActivityRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009608 if (dumpPackage != null && !dumpPackage.equals(r.packageName)) {
9609 continue;
9610 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07009611 final boolean full = !brief && (complete || !r.isInHistory());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009612 if (needNL) {
9613 pw.println(" ");
9614 needNL = false;
9615 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009616 if (lastTask != r.task) {
9617 lastTask = r.task;
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009618 pw.print(prefix);
9619 pw.print(full ? "* " : " ");
9620 pw.println(lastTask);
9621 if (full) {
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009622 lastTask.dump(pw, prefix + " ");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009623 } else if (complete) {
9624 // Complete + brief == give a summary. Isn't that obvious?!?
9625 if (lastTask.intent != null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009626 pw.print(prefix); pw.print(" ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009627 pw.println(lastTask.intent.toInsecureStringWithClip());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009628 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009629 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009630 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009631 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label);
9632 pw.print(" #"); pw.print(i); pw.print(": ");
9633 pw.println(r);
9634 if (full) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009635 r.dump(pw, innerPrefix);
9636 } else if (complete) {
9637 // Complete + brief == give a summary. Isn't that obvious?!?
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009638 pw.print(innerPrefix); pw.println(r.intent.toInsecureString());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009639 if (r.app != null) {
9640 pw.print(innerPrefix); pw.println(r.app);
9641 }
9642 }
9643 if (client && r.app != null && r.app.thread != null) {
9644 // flush anything that is already in the PrintWriter since the thread is going
9645 // to write to the file descriptor directly
9646 pw.flush();
9647 try {
9648 TransferPipe tp = new TransferPipe();
9649 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009650 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9651 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009652 // Short timeout, since blocking here can
9653 // deadlock with the application.
9654 tp.go(fd, 2000);
9655 } finally {
9656 tp.kill();
9657 }
9658 } catch (IOException e) {
9659 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
9660 } catch (RemoteException e) {
9661 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
9662 }
9663 needNL = true;
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009664 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009665 }
9666 }
9667
Dianne Hackborn09c916b2009-12-08 14:50:51 -08009668 private static String buildOomTag(String prefix, String space, int val, int base) {
9669 if (val == base) {
9670 if (space == null) return prefix;
9671 return prefix + " ";
9672 }
9673 return prefix + "+" + Integer.toString(val-base);
9674 }
9675
9676 private static final int dumpProcessList(PrintWriter pw,
9677 ActivityManagerService service, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009678 String prefix, String normalLabel, String persistentLabel,
9679 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009680 int numPers = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07009681 final int N = list.size()-1;
9682 for (int i=N; i>=0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009683 ProcessRecord r = (ProcessRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009684 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9685 continue;
9686 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009687 pw.println(String.format("%s%s #%2d: %s",
9688 prefix, (r.persistent ? persistentLabel : normalLabel),
9689 i, r.toString()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009690 if (r.persistent) {
9691 numPers++;
9692 }
9693 }
9694 return numPers;
9695 }
9696
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009697 private static final boolean dumpProcessOomList(PrintWriter pw,
Dianne Hackborn905577f2011-09-07 18:31:28 -07009698 ActivityManagerService service, List<ProcessRecord> origList,
Dianne Hackborn287952c2010-09-22 22:34:31 -07009699 String prefix, String normalLabel, String persistentLabel,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009700 boolean inclDetails, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009701
Dianne Hackborn905577f2011-09-07 18:31:28 -07009702 ArrayList<Pair<ProcessRecord, Integer>> list
9703 = new ArrayList<Pair<ProcessRecord, Integer>>(origList.size());
9704 for (int i=0; i<origList.size(); i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009705 ProcessRecord r = origList.get(i);
9706 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9707 continue;
9708 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07009709 list.add(new Pair<ProcessRecord, Integer>(origList.get(i), i));
9710 }
9711
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009712 if (list.size() <= 0) {
9713 return false;
9714 }
9715
Dianne Hackborn905577f2011-09-07 18:31:28 -07009716 Comparator<Pair<ProcessRecord, Integer>> comparator
9717 = new Comparator<Pair<ProcessRecord, Integer>>() {
9718 @Override
9719 public int compare(Pair<ProcessRecord, Integer> object1,
9720 Pair<ProcessRecord, Integer> object2) {
9721 if (object1.first.setAdj != object2.first.setAdj) {
9722 return object1.first.setAdj > object2.first.setAdj ? -1 : 1;
9723 }
9724 if (object1.second.intValue() != object2.second.intValue()) {
9725 return object1.second.intValue() > object2.second.intValue() ? -1 : 1;
9726 }
9727 return 0;
9728 }
9729 };
9730
9731 Collections.sort(list, comparator);
9732
Dianne Hackborn287952c2010-09-22 22:34:31 -07009733 final long curRealtime = SystemClock.elapsedRealtime();
9734 final long realtimeSince = curRealtime - service.mLastPowerCheckRealtime;
9735 final long curUptime = SystemClock.uptimeMillis();
9736 final long uptimeSince = curUptime - service.mLastPowerCheckUptime;
9737
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009738 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07009739 ProcessRecord r = list.get(i).first;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009740 String oomAdj;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009741 if (r.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07009742 oomAdj = buildOomTag("bak", " ", r.setAdj, ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009743 } else if (r.setAdj >= ProcessList.SERVICE_B_ADJ) {
9744 oomAdj = buildOomTag("svcb ", null, r.setAdj, ProcessList.SERVICE_B_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009745 } else if (r.setAdj >= ProcessList.PREVIOUS_APP_ADJ) {
9746 oomAdj = buildOomTag("prev ", null, r.setAdj, ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009747 } else if (r.setAdj >= ProcessList.HOME_APP_ADJ) {
9748 oomAdj = buildOomTag("home ", null, r.setAdj, ProcessList.HOME_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009749 } else if (r.setAdj >= ProcessList.SERVICE_ADJ) {
9750 oomAdj = buildOomTag("svc ", null, r.setAdj, ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009751 } else if (r.setAdj >= ProcessList.BACKUP_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08009752 oomAdj = buildOomTag("bkup ", null, r.setAdj, ProcessList.BACKUP_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009753 } else if (r.setAdj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
9754 oomAdj = buildOomTag("hvy ", null, r.setAdj, ProcessList.HEAVY_WEIGHT_APP_ADJ);
9755 } else if (r.setAdj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
9756 oomAdj = buildOomTag("prcp ", null, r.setAdj, ProcessList.PERCEPTIBLE_APP_ADJ);
9757 } else if (r.setAdj >= ProcessList.VISIBLE_APP_ADJ) {
9758 oomAdj = buildOomTag("vis ", null, r.setAdj, ProcessList.VISIBLE_APP_ADJ);
9759 } else if (r.setAdj >= ProcessList.FOREGROUND_APP_ADJ) {
9760 oomAdj = buildOomTag("fore ", null, r.setAdj, ProcessList.FOREGROUND_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009761 } else if (r.setAdj >= ProcessList.PERSISTENT_PROC_ADJ) {
9762 oomAdj = buildOomTag("pers ", null, r.setAdj, ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009763 } else if (r.setAdj >= ProcessList.SYSTEM_ADJ) {
9764 oomAdj = buildOomTag("sys ", null, r.setAdj, ProcessList.SYSTEM_ADJ);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009765 } else {
9766 oomAdj = Integer.toString(r.setAdj);
9767 }
9768 String schedGroup;
9769 switch (r.setSchedGroup) {
9770 case Process.THREAD_GROUP_BG_NONINTERACTIVE:
9771 schedGroup = "B";
9772 break;
9773 case Process.THREAD_GROUP_DEFAULT:
9774 schedGroup = "F";
9775 break;
9776 default:
9777 schedGroup = Integer.toString(r.setSchedGroup);
9778 break;
9779 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07009780 String foreground;
9781 if (r.foregroundActivities) {
9782 foreground = "A";
9783 } else if (r.foregroundServices) {
9784 foreground = "S";
9785 } else {
9786 foreground = " ";
9787 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07009788 pw.println(String.format("%s%s #%2d: adj=%s/%s%s trm=%2d %s (%s)",
Dianne Hackborn287952c2010-09-22 22:34:31 -07009789 prefix, (r.persistent ? persistentLabel : normalLabel),
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009790 (origList.size()-1)-list.get(i).second, oomAdj, schedGroup,
9791 foreground, r.trimMemoryLevel, r.toShortString(), r.adjType));
Dianne Hackborn287952c2010-09-22 22:34:31 -07009792 if (r.adjSource != null || r.adjTarget != null) {
9793 pw.print(prefix);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009794 pw.print(" ");
Dianne Hackborn287952c2010-09-22 22:34:31 -07009795 if (r.adjTarget instanceof ComponentName) {
9796 pw.print(((ComponentName)r.adjTarget).flattenToShortString());
9797 } else if (r.adjTarget != null) {
9798 pw.print(r.adjTarget.toString());
9799 } else {
9800 pw.print("{null}");
9801 }
9802 pw.print("<=");
9803 if (r.adjSource instanceof ProcessRecord) {
9804 pw.print("Proc{");
9805 pw.print(((ProcessRecord)r.adjSource).toShortString());
9806 pw.println("}");
9807 } else if (r.adjSource != null) {
9808 pw.println(r.adjSource.toString());
9809 } else {
9810 pw.println("{null}");
9811 }
9812 }
9813 if (inclDetails) {
9814 pw.print(prefix);
9815 pw.print(" ");
9816 pw.print("oom: max="); pw.print(r.maxAdj);
9817 pw.print(" hidden="); pw.print(r.hiddenAdj);
9818 pw.print(" curRaw="); pw.print(r.curRawAdj);
9819 pw.print(" setRaw="); pw.print(r.setRawAdj);
9820 pw.print(" cur="); pw.print(r.curAdj);
9821 pw.print(" set="); pw.println(r.setAdj);
9822 pw.print(prefix);
9823 pw.print(" ");
9824 pw.print("keeping="); pw.print(r.keeping);
9825 pw.print(" hidden="); pw.print(r.hidden);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009826 pw.print(" empty="); pw.print(r.empty);
9827 pw.print(" hasAboveClient="); pw.println(r.hasAboveClient);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009828
9829 if (!r.keeping) {
9830 if (r.lastWakeTime != 0) {
9831 long wtime;
9832 BatteryStatsImpl stats = service.mBatteryStatsService.getActiveStatistics();
9833 synchronized (stats) {
9834 wtime = stats.getProcessWakeTime(r.info.uid,
9835 r.pid, curRealtime);
9836 }
9837 long timeUsed = wtime - r.lastWakeTime;
9838 pw.print(prefix);
9839 pw.print(" ");
9840 pw.print("keep awake over ");
9841 TimeUtils.formatDuration(realtimeSince, pw);
9842 pw.print(" used ");
9843 TimeUtils.formatDuration(timeUsed, pw);
9844 pw.print(" (");
9845 pw.print((timeUsed*100)/realtimeSince);
9846 pw.println("%)");
9847 }
9848 if (r.lastCpuTime != 0) {
9849 long timeUsed = r.curCpuTime - r.lastCpuTime;
9850 pw.print(prefix);
9851 pw.print(" ");
9852 pw.print("run cpu over ");
9853 TimeUtils.formatDuration(uptimeSince, pw);
9854 pw.print(" used ");
9855 TimeUtils.formatDuration(timeUsed, pw);
9856 pw.print(" (");
9857 pw.print((timeUsed*100)/uptimeSince);
9858 pw.println("%)");
9859 }
9860 }
9861 }
9862 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009863 return true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009864 }
9865
Dianne Hackbornb437e092011-08-05 17:50:29 -07009866 ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, String[] args) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009867 ArrayList<ProcessRecord> procs;
9868 synchronized (this) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009869 if (args != null && args.length > start
9870 && args[start].charAt(0) != '-') {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009871 procs = new ArrayList<ProcessRecord>();
9872 int pid = -1;
9873 try {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009874 pid = Integer.parseInt(args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009875 } catch (NumberFormatException e) {
9876
9877 }
9878 for (int i=mLruProcesses.size()-1; i>=0; i--) {
9879 ProcessRecord proc = mLruProcesses.get(i);
9880 if (proc.pid == pid) {
9881 procs.add(proc);
Dianne Hackbornb437e092011-08-05 17:50:29 -07009882 } else if (proc.processName.equals(args[start])) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009883 procs.add(proc);
9884 }
9885 }
9886 if (procs.size() <= 0) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009887 pw.println("No process found for: " + args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009888 return null;
9889 }
9890 } else {
9891 procs = new ArrayList<ProcessRecord>(mLruProcesses);
9892 }
9893 }
9894 return procs;
9895 }
9896
9897 final void dumpGraphicsHardwareUsage(FileDescriptor fd,
9898 PrintWriter pw, String[] args) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009899 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009900 if (procs == null) {
9901 return;
9902 }
9903
9904 long uptime = SystemClock.uptimeMillis();
9905 long realtime = SystemClock.elapsedRealtime();
9906 pw.println("Applications Graphics Acceleration Info:");
9907 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
9908
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009909 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
9910 ProcessRecord r = procs.get(i);
Chet Haase9c1e23b2011-03-24 10:51:31 -07009911 if (r.thread != null) {
9912 pw.println("\n** Graphics info for pid " + r.pid + " [" + r.processName + "] **");
9913 pw.flush();
9914 try {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009915 TransferPipe tp = new TransferPipe();
9916 try {
9917 r.thread.dumpGfxInfo(tp.getWriteFd().getFileDescriptor(), args);
9918 tp.go(fd);
9919 } finally {
9920 tp.kill();
9921 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009922 } catch (IOException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009923 pw.println("Failure while dumping the app: " + r);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009924 pw.flush();
Chet Haase9c1e23b2011-03-24 10:51:31 -07009925 } catch (RemoteException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009926 pw.println("Got a RemoteException while dumping the app " + r);
Chet Haase9c1e23b2011-03-24 10:51:31 -07009927 pw.flush();
9928 }
9929 }
9930 }
Chet Haase9c1e23b2011-03-24 10:51:31 -07009931 }
9932
Jeff Brown6754ba22011-12-14 20:20:01 -08009933 final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) {
9934 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
9935 if (procs == null) {
9936 return;
9937 }
9938
9939 pw.println("Applications Database Info:");
9940
9941 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
9942 ProcessRecord r = procs.get(i);
9943 if (r.thread != null) {
9944 pw.println("\n** Database info for pid " + r.pid + " [" + r.processName + "] **");
9945 pw.flush();
9946 try {
9947 TransferPipe tp = new TransferPipe();
9948 try {
9949 r.thread.dumpDbInfo(tp.getWriteFd().getFileDescriptor(), args);
9950 tp.go(fd);
9951 } finally {
9952 tp.kill();
9953 }
9954 } catch (IOException e) {
9955 pw.println("Failure while dumping the app: " + r);
9956 pw.flush();
9957 } catch (RemoteException e) {
9958 pw.println("Got a RemoteException while dumping the app " + r);
9959 pw.flush();
9960 }
9961 }
9962 }
9963 }
9964
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009965 final static class MemItem {
9966 final String label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009967 final String shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009968 final long pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009969 final int id;
Dianne Hackborna4bacb82011-08-24 15:12:38 -07009970 ArrayList<MemItem> subitems;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009971
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009972 public MemItem(String _label, String _shortLabel, long _pss, int _id) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009973 label = _label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009974 shortLabel = _shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009975 pss = _pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009976 id = _id;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009977 }
9978 }
9979
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009980 static final void dumpMemItems(PrintWriter pw, String prefix, ArrayList<MemItem> items,
Dianne Hackbornb437e092011-08-05 17:50:29 -07009981 boolean sort) {
9982 if (sort) {
9983 Collections.sort(items, new Comparator<MemItem>() {
9984 @Override
9985 public int compare(MemItem lhs, MemItem rhs) {
9986 if (lhs.pss < rhs.pss) {
9987 return 1;
9988 } else if (lhs.pss > rhs.pss) {
9989 return -1;
9990 }
9991 return 0;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009992 }
Dianne Hackbornb437e092011-08-05 17:50:29 -07009993 });
9994 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009995
9996 for (int i=0; i<items.size(); i++) {
9997 MemItem mi = items.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009998 pw.print(prefix); pw.printf("%7d kB: ", mi.pss); pw.println(mi.label);
Dianne Hackborna4bacb82011-08-24 15:12:38 -07009999 if (mi.subitems != null) {
10000 dumpMemItems(pw, prefix + " ", mi.subitems, true);
10001 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010002 }
10003 }
10004
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010005 // These are in KB.
10006 static final long[] DUMP_MEM_BUCKETS = new long[] {
10007 5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024,
10008 120*1024, 160*1024, 200*1024,
10009 250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024,
10010 1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024
10011 };
10012
Dianne Hackborn672342c2011-11-29 11:29:02 -080010013 static final void appendMemBucket(StringBuilder out, long memKB, String label,
10014 boolean stackLike) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010015 int start = label.lastIndexOf('.');
10016 if (start >= 0) start++;
10017 else start = 0;
10018 int end = label.length();
10019 for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) {
10020 if (DUMP_MEM_BUCKETS[i] >= memKB) {
10021 long bucket = DUMP_MEM_BUCKETS[i]/1024;
10022 out.append(bucket);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010023 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010024 out.append(label, start, end);
10025 return;
10026 }
10027 }
10028 out.append(memKB/1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010029 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010030 out.append(label, start, end);
10031 }
10032
10033 static final int[] DUMP_MEM_OOM_ADJ = new int[] {
10034 ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ, ProcessList.FOREGROUND_APP_ADJ,
10035 ProcessList.VISIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ,
10036 ProcessList.BACKUP_APP_ADJ, ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ,
10037 ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.HIDDEN_APP_MAX_ADJ
10038 };
10039 static final String[] DUMP_MEM_OOM_LABEL = new String[] {
10040 "System", "Persistent", "Foreground",
10041 "Visible", "Perceptible", "Heavy Weight",
10042 "Backup", "A Services", "Home", "Previous",
10043 "B Services", "Background"
10044 };
10045
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010046 final void dumpApplicationMemoryUsage(FileDescriptor fd,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010047 PrintWriter pw, String prefix, String[] args, boolean brief,
Dianne Hackborn672342c2011-11-29 11:29:02 -080010048 PrintWriter categoryPw, StringBuilder outTag, StringBuilder outStack) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010049 boolean dumpAll = false;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010050 boolean oomOnly = false;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010051
10052 int opti = 0;
10053 while (opti < args.length) {
10054 String opt = args[opti];
10055 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
10056 break;
10057 }
10058 opti++;
10059 if ("-a".equals(opt)) {
10060 dumpAll = true;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010061 } else if ("--oom".equals(opt)) {
10062 oomOnly = true;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010063 } else if ("-h".equals(opt)) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010064 pw.println("meminfo dump options: [-a] [--oom] [process]");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010065 pw.println(" -a: include all available information for each process.");
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010066 pw.println(" --oom: only show processes organized by oom adj.");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010067 pw.println("If [process] is specified it can be the name or ");
10068 pw.println("pid of a specific process to dump.");
10069 return;
10070 } else {
10071 pw.println("Unknown argument: " + opt + "; use -h for help");
10072 }
10073 }
10074
10075 ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010076 if (procs == null) {
10077 return;
10078 }
10079
Dianne Hackborn6447ca32009-04-07 19:50:08 -070010080 final boolean isCheckinRequest = scanArgs(args, "--checkin");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010081 long uptime = SystemClock.uptimeMillis();
10082 long realtime = SystemClock.elapsedRealtime();
Dianne Hackbornb437e092011-08-05 17:50:29 -070010083
10084 if (procs.size() == 1 || isCheckinRequest) {
10085 dumpAll = true;
10086 }
10087
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010088 if (isCheckinRequest) {
10089 // short checkin version
10090 pw.println(uptime + "," + realtime);
10091 pw.flush();
10092 } else {
10093 pw.println("Applications Memory Usage (kB):");
10094 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10095 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010096
Dianne Hackbornb437e092011-08-05 17:50:29 -070010097 String[] innerArgs = new String[args.length-opti];
10098 System.arraycopy(args, opti, innerArgs, 0, args.length-opti);
10099
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010100 ArrayList<MemItem> procMems = new ArrayList<MemItem>();
10101 long nativePss=0, dalvikPss=0, otherPss=0;
10102 long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
10103
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010104 long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length];
10105 ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[])
10106 new ArrayList[DUMP_MEM_OOM_LABEL.length];
Dianne Hackbornb437e092011-08-05 17:50:29 -070010107
10108 long totalPss = 0;
10109
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010110 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10111 ProcessRecord r = procs.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010112 if (r.thread != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010113 if (!isCheckinRequest && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010114 pw.println("\n** MEMINFO in pid " + r.pid + " [" + r.processName + "] **");
10115 pw.flush();
10116 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010117 Debug.MemoryInfo mi = null;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010118 if (dumpAll) {
10119 try {
10120 mi = r.thread.dumpMemInfo(fd, isCheckinRequest, dumpAll, innerArgs);
10121 } catch (RemoteException e) {
10122 if (!isCheckinRequest) {
10123 pw.println("Got RemoteException!");
10124 pw.flush();
10125 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010126 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010127 } else {
10128 mi = new Debug.MemoryInfo();
10129 Debug.getMemoryInfo(r.pid, mi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010130 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010131
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010132 if (!isCheckinRequest && mi != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010133 long myTotalPss = mi.getTotalPss();
10134 totalPss += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010135 MemItem pssItem = new MemItem(r.processName + " (pid " + r.pid + ")",
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010136 r.processName, myTotalPss, 0);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010137 procMems.add(pssItem);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010138
10139 nativePss += mi.nativePss;
10140 dalvikPss += mi.dalvikPss;
10141 otherPss += mi.otherPss;
10142 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
10143 long mem = mi.getOtherPss(j);
10144 miscPss[j] += mem;
10145 otherPss -= mem;
10146 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010147
10148 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010149 if (r.setAdj <= DUMP_MEM_OOM_ADJ[oomIndex]
10150 || oomIndex == (oomPss.length-1)) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010151 oomPss[oomIndex] += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010152 if (oomProcs[oomIndex] == null) {
10153 oomProcs[oomIndex] = new ArrayList<MemItem>();
10154 }
10155 oomProcs[oomIndex].add(pssItem);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010156 break;
10157 }
10158 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010159 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010160 }
10161 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010162
10163 if (!isCheckinRequest && procs.size() > 1) {
10164 ArrayList<MemItem> catMems = new ArrayList<MemItem>();
10165
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010166 catMems.add(new MemItem("Native", "Native", nativePss, -1));
10167 catMems.add(new MemItem("Dalvik", "Dalvik", dalvikPss, -2));
10168 catMems.add(new MemItem("Unknown", "Unknown", otherPss, -3));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010169 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010170 String label = Debug.MemoryInfo.getOtherLabel(j);
10171 catMems.add(new MemItem(label, label, miscPss[j], j));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010172 }
10173
Dianne Hackbornb437e092011-08-05 17:50:29 -070010174 ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
10175 for (int j=0; j<oomPss.length; j++) {
10176 if (oomPss[j] != 0) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010177 String label = DUMP_MEM_OOM_LABEL[j];
10178 MemItem item = new MemItem(label, label, oomPss[j],
10179 DUMP_MEM_OOM_ADJ[j]);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010180 item.subitems = oomProcs[j];
10181 oomMems.add(item);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010182 }
10183 }
10184
Dianne Hackborn672342c2011-11-29 11:29:02 -080010185 if (outTag != null || outStack != null) {
10186 if (outTag != null) {
10187 appendMemBucket(outTag, totalPss, "total", false);
10188 }
10189 if (outStack != null) {
10190 appendMemBucket(outStack, totalPss, "total", true);
10191 }
10192 boolean firstLine = true;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010193 for (int i=0; i<oomMems.size(); i++) {
10194 MemItem miCat = oomMems.get(i);
10195 if (miCat.subitems == null || miCat.subitems.size() < 1) {
10196 continue;
10197 }
10198 if (miCat.id < ProcessList.SERVICE_ADJ
10199 || miCat.id == ProcessList.HOME_APP_ADJ
10200 || miCat.id == ProcessList.PREVIOUS_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010201 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10202 outTag.append(" / ");
10203 }
10204 if (outStack != null) {
10205 if (miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10206 if (firstLine) {
10207 outStack.append(":");
10208 firstLine = false;
10209 }
10210 outStack.append("\n\t at ");
10211 } else {
10212 outStack.append("$");
10213 }
10214 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010215 for (int j=0; j<miCat.subitems.size(); j++) {
10216 MemItem mi = miCat.subitems.get(j);
10217 if (j > 0) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010218 if (outTag != null) {
10219 outTag.append(" ");
10220 }
10221 if (outStack != null) {
10222 outStack.append("$");
10223 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010224 }
Dianne Hackborn672342c2011-11-29 11:29:02 -080010225 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10226 appendMemBucket(outTag, mi.pss, mi.shortLabel, false);
10227 }
10228 if (outStack != null) {
10229 appendMemBucket(outStack, mi.pss, mi.shortLabel, true);
10230 }
10231 }
10232 if (outStack != null && miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10233 outStack.append("(");
10234 for (int k=0; k<DUMP_MEM_OOM_ADJ.length; k++) {
10235 if (DUMP_MEM_OOM_ADJ[k] == miCat.id) {
10236 outStack.append(DUMP_MEM_OOM_LABEL[k]);
10237 outStack.append(":");
10238 outStack.append(DUMP_MEM_OOM_ADJ[k]);
10239 }
10240 }
10241 outStack.append(")");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010242 }
10243 }
10244 }
10245 }
10246
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010247 if (!brief && !oomOnly) {
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010248 pw.println();
10249 pw.println("Total PSS by process:");
10250 dumpMemItems(pw, " ", procMems, true);
10251 pw.println();
10252 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010253 pw.println("Total PSS by OOM adjustment:");
10254 dumpMemItems(pw, " ", oomMems, false);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010255 if (!oomOnly) {
10256 PrintWriter out = categoryPw != null ? categoryPw : pw;
10257 out.println();
10258 out.println("Total PSS by category:");
10259 dumpMemItems(out, " ", catMems, true);
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010260 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010261 pw.println();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010262 pw.print("Total PSS: "); pw.print(totalPss); pw.println(" kB");
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010263 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010264 }
10265
10266 /**
10267 * Searches array of arguments for the specified string
10268 * @param args array of argument strings
10269 * @param value value to search for
10270 * @return true if the value is contained in the array
10271 */
10272 private static boolean scanArgs(String[] args, String value) {
10273 if (args != null) {
10274 for (String arg : args) {
10275 if (value.equals(arg)) {
10276 return true;
10277 }
10278 }
10279 }
10280 return false;
10281 }
10282
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010283 private final void killServicesLocked(ProcessRecord app,
10284 boolean allowRestart) {
10285 // Report disconnected services.
10286 if (false) {
10287 // XXX we are letting the client link to the service for
10288 // death notifications.
10289 if (app.services.size() > 0) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010290 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010291 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010292 ServiceRecord r = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010293 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010294 Iterator<ArrayList<ConnectionRecord>> jt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010295 = r.connections.values().iterator();
10296 while (jt.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010297 ArrayList<ConnectionRecord> cl = jt.next();
10298 for (int i=0; i<cl.size(); i++) {
10299 ConnectionRecord c = cl.get(i);
10300 if (c.binding.client != app) {
10301 try {
10302 //c.conn.connected(r.className, null);
10303 } catch (Exception e) {
10304 // todo: this should be asynchronous!
10305 Slog.w(TAG, "Exception thrown disconnected servce "
10306 + r.shortName
10307 + " from app " + app.processName, e);
10308 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010309 }
10310 }
10311 }
10312 }
10313 }
10314 }
10315 }
10316
10317 // Clean up any connections this application has to other services.
10318 if (app.connections.size() > 0) {
10319 Iterator<ConnectionRecord> it = app.connections.iterator();
10320 while (it.hasNext()) {
10321 ConnectionRecord r = it.next();
10322 removeConnectionLocked(r, app, null);
10323 }
10324 }
10325 app.connections.clear();
10326
10327 if (app.services.size() != 0) {
10328 // Any services running in the application need to be placed
10329 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -070010330 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010331 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010332 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010333 synchronized (sr.stats.getBatteryStats()) {
10334 sr.stats.stopLaunchedLocked();
10335 }
10336 sr.app = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010337 sr.isolatedProc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010338 sr.executeNesting = 0;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010339 if (mStoppingServices.remove(sr)) {
10340 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
10341 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010342
10343 boolean hasClients = sr.bindings.size() > 0;
10344 if (hasClients) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010345 Iterator<IntentBindRecord> bindings
10346 = sr.bindings.values().iterator();
10347 while (bindings.hasNext()) {
10348 IntentBindRecord b = bindings.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -080010349 if (DEBUG_SERVICE) Slog.v(TAG, "Killing binding " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010350 + ": shouldUnbind=" + b.hasBound);
10351 b.binder = null;
10352 b.requested = b.received = b.hasBound = false;
10353 }
10354 }
10355
Dianne Hackborn070783f2010-12-29 16:46:28 -080010356 if (sr.crashCount >= 2 && (sr.serviceInfo.applicationInfo.flags
10357 &ApplicationInfo.FLAG_PERSISTENT) == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010358 Slog.w(TAG, "Service crashed " + sr.crashCount
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010359 + " times, stopping: " + sr);
Doug Zongker2bec3d42009-12-04 12:52:44 -080010360 EventLog.writeEvent(EventLogTags.AM_SERVICE_CRASHED_TOO_MUCH,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010361 sr.crashCount, sr.shortName, app.pid);
10362 bringDownServiceLocked(sr, true);
10363 } else if (!allowRestart) {
10364 bringDownServiceLocked(sr, true);
10365 } else {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010366 boolean canceled = scheduleServiceRestartLocked(sr, true);
10367
10368 // Should the service remain running? Note that in the
10369 // extreme case of so many attempts to deliver a command
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010370 // that it failed we also will stop it here.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010371 if (sr.startRequested && (sr.stopIfKilled || canceled)) {
10372 if (sr.pendingStarts.size() == 0) {
10373 sr.startRequested = false;
10374 if (!hasClients) {
10375 // Whoops, no reason to restart!
10376 bringDownServiceLocked(sr, true);
10377 }
10378 }
10379 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010380 }
10381 }
10382
10383 if (!allowRestart) {
10384 app.services.clear();
10385 }
10386 }
10387
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010388 // Make sure we have no more records on the stopping list.
10389 int i = mStoppingServices.size();
10390 while (i > 0) {
10391 i--;
10392 ServiceRecord sr = mStoppingServices.get(i);
10393 if (sr.app == app) {
10394 mStoppingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010395 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010396 }
10397 }
10398
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010399 app.executingServices.clear();
10400 }
10401
10402 private final void removeDyingProviderLocked(ProcessRecord proc,
10403 ContentProviderRecord cpr) {
10404 synchronized (cpr) {
10405 cpr.launchingApp = null;
10406 cpr.notifyAll();
10407 }
10408
Amith Yamasani742a6712011-05-04 14:49:28 -070010409 mProviderMap.removeProviderByClass(cpr.name, UserId.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010410 String names[] = cpr.info.authority.split(";");
10411 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010412 mProviderMap.removeProviderByName(names[j], UserId.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010413 }
10414
10415 Iterator<ProcessRecord> cit = cpr.clients.iterator();
10416 while (cit.hasNext()) {
10417 ProcessRecord capp = cit.next();
10418 if (!capp.persistent && capp.thread != null
10419 && capp.pid != 0
10420 && capp.pid != MY_PID) {
Dianne Hackborn8633e682010-04-22 16:03:41 -070010421 Slog.i(TAG, "Kill " + capp.processName
10422 + " (pid " + capp.pid + "): provider " + cpr.info.name
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010423 + " in dying process " + (proc != null ? proc.processName : "??"));
Dianne Hackborn8633e682010-04-22 16:03:41 -070010424 EventLog.writeEvent(EventLogTags.AM_KILL, capp.pid,
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010425 capp.processName, capp.setAdj, "dying provider "
10426 + cpr.name.toShortString());
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070010427 Process.killProcessQuiet(capp.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010428 }
10429 }
10430
10431 mLaunchingProviders.remove(cpr);
10432 }
10433
10434 /**
10435 * Main code for cleaning up a process when it has gone away. This is
10436 * called both as a result of the process dying, or directly when stopping
10437 * a process when running in single process mode.
10438 */
10439 private final void cleanUpApplicationRecordLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010440 boolean restarting, boolean allowRestart, int index) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010441 if (index >= 0) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010442 mLruProcesses.remove(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010443 }
10444
Dianne Hackborn36124872009-10-08 16:22:03 -070010445 mProcessesToGc.remove(app);
10446
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010447 // Dismiss any open dialogs.
10448 if (app.crashDialog != null) {
10449 app.crashDialog.dismiss();
10450 app.crashDialog = null;
10451 }
10452 if (app.anrDialog != null) {
10453 app.anrDialog.dismiss();
10454 app.anrDialog = null;
10455 }
10456 if (app.waitDialog != null) {
10457 app.waitDialog.dismiss();
10458 app.waitDialog = null;
10459 }
10460
10461 app.crashing = false;
10462 app.notResponding = false;
10463
10464 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -070010465 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010466 app.thread = null;
10467 app.forcingToForeground = null;
10468 app.foregroundServices = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010469 app.foregroundActivities = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070010470 app.hasShownUi = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010471 app.hasAboveClient = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010472
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010473 killServicesLocked(app, allowRestart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010474
10475 boolean restart = false;
10476
10477 int NL = mLaunchingProviders.size();
10478
10479 // Remove published content providers.
10480 if (!app.pubProviders.isEmpty()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010481 Iterator<ContentProviderRecord> it = app.pubProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010482 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010483 ContentProviderRecord cpr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010484 cpr.provider = null;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010485 cpr.proc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010486
10487 // See if someone is waiting for this provider... in which
10488 // case we don't remove it, but just let it restart.
10489 int i = 0;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010490 if (!app.bad && allowRestart) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010491 for (; i<NL; i++) {
10492 if (mLaunchingProviders.get(i) == cpr) {
10493 restart = true;
10494 break;
10495 }
10496 }
10497 } else {
10498 i = NL;
10499 }
10500
10501 if (i >= NL) {
10502 removeDyingProviderLocked(app, cpr);
10503 NL = mLaunchingProviders.size();
10504 }
10505 }
10506 app.pubProviders.clear();
10507 }
10508
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010509 // Take care of any launching providers waiting for this process.
10510 if (checkAppInLaunchingProvidersLocked(app, false)) {
10511 restart = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010512 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010513
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010514 // Unregister from connected content providers.
10515 if (!app.conProviders.isEmpty()) {
Dianne Hackborn0c3154d2009-10-06 17:18:05 -070010516 Iterator it = app.conProviders.keySet().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010517 while (it.hasNext()) {
10518 ContentProviderRecord cpr = (ContentProviderRecord)it.next();
10519 cpr.clients.remove(app);
10520 }
10521 app.conProviders.clear();
10522 }
10523
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010524 // At this point there may be remaining entries in mLaunchingProviders
10525 // where we were the only one waiting, so they are no longer of use.
10526 // Look for these and clean up if found.
10527 // XXX Commented out for now. Trying to figure out a way to reproduce
10528 // the actual situation to identify what is actually going on.
10529 if (false) {
10530 for (int i=0; i<NL; i++) {
10531 ContentProviderRecord cpr = (ContentProviderRecord)
10532 mLaunchingProviders.get(i);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080010533 if (cpr.clients.size() <= 0 && !cpr.hasExternalProcessHandles()) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010534 synchronized (cpr) {
10535 cpr.launchingApp = null;
10536 cpr.notifyAll();
10537 }
10538 }
10539 }
10540 }
10541
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010542 skipCurrentReceiverLocked(app);
10543
10544 // Unregister any receivers.
10545 if (app.receivers.size() > 0) {
10546 Iterator<ReceiverList> it = app.receivers.iterator();
10547 while (it.hasNext()) {
10548 removeReceiverLocked(it.next());
10549 }
10550 app.receivers.clear();
10551 }
10552
Christopher Tate181fafa2009-05-14 11:12:14 -070010553 // If the app is undergoing backup, tell the backup manager about it
10554 if (mBackupTarget != null && app.pid == mBackupTarget.app.pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010555 if (DEBUG_BACKUP) Slog.d(TAG, "App " + mBackupTarget.appInfo + " died during backup");
Christopher Tate181fafa2009-05-14 11:12:14 -070010556 try {
10557 IBackupManager bm = IBackupManager.Stub.asInterface(
10558 ServiceManager.getService(Context.BACKUP_SERVICE));
10559 bm.agentDisconnected(app.info.packageName);
10560 } catch (RemoteException e) {
10561 // can't happen; backup manager is local
10562 }
10563 }
10564
Jeff Sharkey287bd832011-05-28 19:36:26 -070010565 mHandler.obtainMessage(DISPATCH_PROCESS_DIED, app.pid, app.info.uid, null).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010566
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010567 // If the caller is restarting this app, then leave it in its
10568 // current lists and let the caller take care of it.
10569 if (restarting) {
10570 return;
10571 }
10572
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010573 if (!app.persistent || app.isolated) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010574 if (DEBUG_PROCESSES) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010575 "Removing non-persistent process during cleanup: " + app);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010576 mProcessNames.remove(app.processName, app.uid);
10577 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -070010578 if (mHeavyWeightProcess == app) {
10579 mHeavyWeightProcess = null;
10580 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
10581 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010582 } else if (!app.removed) {
10583 // This app is persistent, so we need to keep its record around.
10584 // If it is not already on the pending app list, add it there
10585 // and start a new process for it.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010586 if (mPersistentStartingProcesses.indexOf(app) < 0) {
10587 mPersistentStartingProcesses.add(app);
10588 restart = true;
10589 }
10590 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070010591 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
10592 "Clean-up removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010593 mProcessesOnHold.remove(app);
10594
The Android Open Source Project4df24232009-03-05 14:34:35 -080010595 if (app == mHomeProcess) {
10596 mHomeProcess = null;
10597 }
Dianne Hackbornf35fe232011-11-01 19:25:20 -070010598 if (app == mPreviousProcess) {
10599 mPreviousProcess = null;
10600 }
10601
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010602 if (restart && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010603 // We have components that still need to be running in the
10604 // process, so re-launch it.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010605 mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010606 startProcessLocked(app, "restart", app.processName);
10607 } else if (app.pid > 0 && app.pid != MY_PID) {
10608 // Goodbye!
10609 synchronized (mPidsSelfLocked) {
10610 mPidsSelfLocked.remove(app.pid);
10611 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
10612 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010613 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010614 }
10615 }
10616
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010617 boolean checkAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) {
10618 // Look through the content providers we are waiting to have launched,
10619 // and if any run in this process then either schedule a restart of
10620 // the process or kill the client waiting for it if this process has
10621 // gone bad.
10622 int NL = mLaunchingProviders.size();
10623 boolean restart = false;
10624 for (int i=0; i<NL; i++) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010625 ContentProviderRecord cpr = mLaunchingProviders.get(i);
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010626 if (cpr.launchingApp == app) {
10627 if (!alwaysBad && !app.bad) {
10628 restart = true;
10629 } else {
10630 removeDyingProviderLocked(app, cpr);
10631 NL = mLaunchingProviders.size();
10632 }
10633 }
10634 }
10635 return restart;
10636 }
10637
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010638 // =========================================================
10639 // SERVICES
10640 // =========================================================
10641
10642 ActivityManager.RunningServiceInfo makeRunningServiceInfoLocked(ServiceRecord r) {
10643 ActivityManager.RunningServiceInfo info =
10644 new ActivityManager.RunningServiceInfo();
10645 info.service = r.name;
10646 if (r.app != null) {
10647 info.pid = r.app.pid;
10648 }
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010649 info.uid = r.appInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010650 info.process = r.processName;
10651 info.foreground = r.isForeground;
10652 info.activeSince = r.createTime;
10653 info.started = r.startRequested;
10654 info.clientCount = r.connections.size();
10655 info.crashCount = r.crashCount;
10656 info.lastActivityTime = r.lastActivity;
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010657 if (r.isForeground) {
10658 info.flags |= ActivityManager.RunningServiceInfo.FLAG_FOREGROUND;
10659 }
10660 if (r.startRequested) {
10661 info.flags |= ActivityManager.RunningServiceInfo.FLAG_STARTED;
10662 }
Dan Egnor42471dd2010-01-07 17:25:22 -080010663 if (r.app != null && r.app.pid == MY_PID) {
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010664 info.flags |= ActivityManager.RunningServiceInfo.FLAG_SYSTEM_PROCESS;
10665 }
10666 if (r.app != null && r.app.persistent) {
10667 info.flags |= ActivityManager.RunningServiceInfo.FLAG_PERSISTENT_PROCESS;
10668 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010669
10670 for (ArrayList<ConnectionRecord> connl : r.connections.values()) {
10671 for (int i=0; i<connl.size(); i++) {
10672 ConnectionRecord conn = connl.get(i);
10673 if (conn.clientLabel != 0) {
10674 info.clientPackage = conn.binding.client.info.packageName;
10675 info.clientLabel = conn.clientLabel;
10676 return info;
10677 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010678 }
10679 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010680 return info;
10681 }
10682
10683 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum,
10684 int flags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010685 enforceNotIsolatedCaller("getServices");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010686 synchronized (this) {
10687 ArrayList<ActivityManager.RunningServiceInfo> res
10688 = new ArrayList<ActivityManager.RunningServiceInfo>();
10689
Amith Yamasani742a6712011-05-04 14:49:28 -070010690 int userId = UserId.getUserId(Binder.getCallingUid());
10691 if (mServiceMap.getAllServices(userId).size() > 0) {
10692 Iterator<ServiceRecord> it
10693 = mServiceMap.getAllServices(userId).iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010694 while (it.hasNext() && res.size() < maxNum) {
10695 res.add(makeRunningServiceInfoLocked(it.next()));
10696 }
10697 }
10698
10699 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
10700 ServiceRecord r = mRestartingServices.get(i);
10701 ActivityManager.RunningServiceInfo info =
10702 makeRunningServiceInfoLocked(r);
10703 info.restarting = r.nextRestartTime;
10704 res.add(info);
10705 }
10706
10707 return res;
10708 }
10709 }
10710
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010711 public PendingIntent getRunningServiceControlPanel(ComponentName name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010712 enforceNotIsolatedCaller("getRunningServiceControlPanel");
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010713 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010714 int userId = UserId.getUserId(Binder.getCallingUid());
10715 ServiceRecord r = mServiceMap.getServiceByName(name, userId);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010716 if (r != null) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010717 for (ArrayList<ConnectionRecord> conn : r.connections.values()) {
10718 for (int i=0; i<conn.size(); i++) {
10719 if (conn.get(i).clientIntent != null) {
10720 return conn.get(i).clientIntent;
10721 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010722 }
10723 }
10724 }
10725 }
10726 return null;
10727 }
10728
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010729 private final ServiceRecord findServiceLocked(ComponentName name,
10730 IBinder token) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010731 ServiceRecord r = mServiceMap.getServiceByName(name, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010732 return r == token ? r : null;
10733 }
10734
10735 private final class ServiceLookupResult {
10736 final ServiceRecord record;
10737 final String permission;
10738
10739 ServiceLookupResult(ServiceRecord _record, String _permission) {
10740 record = _record;
10741 permission = _permission;
10742 }
10743 };
10744
10745 private ServiceLookupResult findServiceLocked(Intent service,
Amith Yamasani483f3b02012-03-13 16:08:00 -070010746 String resolvedType, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010747 ServiceRecord r = null;
10748 if (service.getComponent() != null) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070010749 r = mServiceMap.getServiceByName(service.getComponent(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010750 }
10751 if (r == null) {
10752 Intent.FilterComparison filter = new Intent.FilterComparison(service);
Amith Yamasani483f3b02012-03-13 16:08:00 -070010753 r = mServiceMap.getServiceByIntent(filter, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010754 }
10755
10756 if (r == null) {
10757 try {
10758 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070010759 AppGlobals.getPackageManager().resolveService(
Amith Yamasani483f3b02012-03-13 16:08:00 -070010760 service, resolvedType, 0, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010761 ServiceInfo sInfo =
10762 rInfo != null ? rInfo.serviceInfo : null;
10763 if (sInfo == null) {
10764 return null;
10765 }
10766
10767 ComponentName name = new ComponentName(
10768 sInfo.applicationInfo.packageName, sInfo.name);
Amith Yamasani742a6712011-05-04 14:49:28 -070010769 r = mServiceMap.getServiceByName(name, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010770 } catch (RemoteException ex) {
10771 // pm is in same process, this will never happen.
10772 }
10773 }
10774 if (r != null) {
10775 int callingPid = Binder.getCallingPid();
10776 int callingUid = Binder.getCallingUid();
10777 if (checkComponentPermission(r.permission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010778 callingPid, callingUid, r.appInfo.uid, r.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010779 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010780 if (!r.exported) {
10781 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
10782 + " from pid=" + callingPid
10783 + ", uid=" + callingUid
10784 + " that is not exported from uid " + r.appInfo.uid);
10785 return new ServiceLookupResult(null, "not exported from uid "
10786 + r.appInfo.uid);
10787 }
Joe Onorato8a9b2202010-02-26 18:56:32 -080010788 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010789 + " from pid=" + callingPid
10790 + ", uid=" + callingUid
10791 + " requires " + r.permission);
10792 return new ServiceLookupResult(null, r.permission);
10793 }
10794 return new ServiceLookupResult(r, null);
10795 }
10796 return null;
10797 }
10798
10799 private class ServiceRestarter implements Runnable {
10800 private ServiceRecord mService;
10801
10802 void setService(ServiceRecord service) {
10803 mService = service;
10804 }
10805
10806 public void run() {
10807 synchronized(ActivityManagerService.this) {
10808 performServiceRestartLocked(mService);
10809 }
10810 }
10811 }
10812
10813 private ServiceLookupResult retrieveServiceLocked(Intent service,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010814 String resolvedType, int callingPid, int callingUid, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010815 ServiceRecord r = null;
Amith Yamasani742a6712011-05-04 14:49:28 -070010816 if (DEBUG_SERVICE)
10817 Slog.v(TAG, "retrieveServiceLocked: " + service + " type=" + resolvedType
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010818 + " callingUid=" + callingUid);
Amith Yamasani742a6712011-05-04 14:49:28 -070010819
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010820 if (service.getComponent() != null) {
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010821 r = mServiceMap.getServiceByName(service.getComponent(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010822 }
Amith Yamasani742a6712011-05-04 14:49:28 -070010823 if (r == null) {
10824 Intent.FilterComparison filter = new Intent.FilterComparison(service);
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010825 r = mServiceMap.getServiceByIntent(filter, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -070010826 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010827 if (r == null) {
10828 try {
10829 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070010830 AppGlobals.getPackageManager().resolveService(
Amith Yamasani483f3b02012-03-13 16:08:00 -070010831 service, resolvedType, STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010832 ServiceInfo sInfo =
10833 rInfo != null ? rInfo.serviceInfo : null;
10834 if (sInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010835 Slog.w(TAG, "Unable to start service " + service +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010836 ": not found");
10837 return null;
10838 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010839 if (userId > 0) {
10840 sInfo.applicationInfo = getAppInfoForUser(sInfo.applicationInfo, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -070010841 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010842 ComponentName name = new ComponentName(
10843 sInfo.applicationInfo.packageName, sInfo.name);
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010844 r = mServiceMap.getServiceByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010845 if (r == null) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010846 Intent.FilterComparison filter = new Intent.FilterComparison(
10847 service.cloneFilter());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010848 ServiceRestarter res = new ServiceRestarter();
10849 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
10850 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
10851 synchronized (stats) {
10852 ss = stats.getServiceStatsLocked(
10853 sInfo.applicationInfo.uid, sInfo.packageName,
10854 sInfo.name);
10855 }
Dianne Hackbornb1c4a2a2010-01-19 15:36:42 -080010856 r = new ServiceRecord(this, ss, name, filter, sInfo, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010857 res.setService(r);
Amith Yamasani742a6712011-05-04 14:49:28 -070010858 mServiceMap.putServiceByName(name, UserId.getUserId(r.appInfo.uid), r);
10859 mServiceMap.putServiceByIntent(filter, UserId.getUserId(r.appInfo.uid), r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010860
10861 // Make sure this component isn't in the pending list.
10862 int N = mPendingServices.size();
10863 for (int i=0; i<N; i++) {
10864 ServiceRecord pr = mPendingServices.get(i);
10865 if (pr.name.equals(name)) {
10866 mPendingServices.remove(i);
10867 i--;
10868 N--;
10869 }
10870 }
10871 }
10872 } catch (RemoteException ex) {
10873 // pm is in same process, this will never happen.
10874 }
10875 }
10876 if (r != null) {
10877 if (checkComponentPermission(r.permission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010878 callingPid, callingUid, r.appInfo.uid, r.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010879 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010880 if (!r.exported) {
10881 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
10882 + " from pid=" + callingPid
10883 + ", uid=" + callingUid
10884 + " that is not exported from uid " + r.appInfo.uid);
10885 return new ServiceLookupResult(null, "not exported from uid "
10886 + r.appInfo.uid);
10887 }
Joe Onorato8a9b2202010-02-26 18:56:32 -080010888 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010889 + " from pid=" + callingPid
10890 + ", uid=" + callingUid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010891 + " requires " + r.permission);
10892 return new ServiceLookupResult(null, r.permission);
10893 }
10894 return new ServiceLookupResult(r, null);
10895 }
10896 return null;
10897 }
10898
Dianne Hackborn287952c2010-09-22 22:34:31 -070010899 private final void bumpServiceExecutingLocked(ServiceRecord r, String why) {
10900 if (DEBUG_SERVICE) Log.v(TAG, ">>> EXECUTING "
10901 + why + " of " + r + " in app " + r.app);
10902 else if (DEBUG_SERVICE_EXECUTING) Log.v(TAG, ">>> EXECUTING "
10903 + why + " of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010904 long now = SystemClock.uptimeMillis();
10905 if (r.executeNesting == 0 && r.app != null) {
10906 if (r.app.executingServices.size() == 0) {
10907 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
10908 msg.obj = r.app;
10909 mHandler.sendMessageAtTime(msg, now+SERVICE_TIMEOUT);
10910 }
10911 r.app.executingServices.add(r);
10912 }
10913 r.executeNesting++;
10914 r.executingStart = now;
10915 }
10916
10917 private final void sendServiceArgsLocked(ServiceRecord r,
10918 boolean oomAdjusted) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010919 final int N = r.pendingStarts.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010920 if (N == 0) {
10921 return;
10922 }
10923
Dianne Hackborn39792d22010-08-19 18:01:52 -070010924 while (r.pendingStarts.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010925 try {
Dianne Hackborn39792d22010-08-19 18:01:52 -070010926 ServiceRecord.StartItem si = r.pendingStarts.remove(0);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010927 if (DEBUG_SERVICE) Slog.v(TAG, "Sending arguments to: "
10928 + r + " " + r.intent + " args=" + si.intent);
Dianne Hackborn3a28f222011-03-01 12:25:54 -080010929 if (si.intent == null && N > 1) {
10930 // If somehow we got a dummy null intent in the middle,
10931 // then skip it. DO NOT skip a null intent when it is
10932 // the only one in the list -- this is to support the
10933 // onStartCommand(null) case.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010934 continue;
10935 }
Dianne Hackborn39792d22010-08-19 18:01:52 -070010936 si.deliveredTime = SystemClock.uptimeMillis();
10937 r.deliveredStarts.add(si);
10938 si.deliveryCount++;
Dianne Hackborn21c241e2012-03-08 13:57:23 -080010939 if (si.neededGrants != null) {
10940 grantUriPermissionUncheckedFromIntentLocked(si.neededGrants,
10941 si.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -070010942 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070010943 bumpServiceExecutingLocked(r, "start");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010944 if (!oomAdjusted) {
10945 oomAdjusted = true;
10946 updateOomAdjLocked(r.app);
10947 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010948 int flags = 0;
10949 if (si.deliveryCount > 0) {
10950 flags |= Service.START_FLAG_RETRY;
10951 }
10952 if (si.doneExecutingCount > 0) {
10953 flags |= Service.START_FLAG_REDELIVERY;
10954 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070010955 r.app.thread.scheduleServiceArgs(r, si.taskRemoved, si.id, flags, si.intent);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010956 } catch (RemoteException e) {
10957 // Remote process gone... we'll let the normal cleanup take
10958 // care of this.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010959 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while scheduling start: " + r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010960 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010961 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010962 Slog.w(TAG, "Unexpected exception", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010963 break;
10964 }
10965 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010966 }
10967
10968 private final boolean requestServiceBindingLocked(ServiceRecord r,
10969 IntentBindRecord i, boolean rebind) {
10970 if (r.app == null || r.app.thread == null) {
10971 // If service is not currently running, can't yet bind.
10972 return false;
10973 }
10974 if ((!i.requested || rebind) && i.apps.size() > 0) {
10975 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070010976 bumpServiceExecutingLocked(r, "bind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010977 r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind);
10978 if (!rebind) {
10979 i.requested = true;
10980 }
10981 i.hasBound = true;
10982 i.doRebind = false;
10983 } catch (RemoteException e) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010984 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while binding " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010985 return false;
10986 }
10987 }
10988 return true;
10989 }
10990
10991 private final void requestServiceBindingsLocked(ServiceRecord r) {
10992 Iterator<IntentBindRecord> bindings = r.bindings.values().iterator();
10993 while (bindings.hasNext()) {
10994 IntentBindRecord i = bindings.next();
10995 if (!requestServiceBindingLocked(r, i, false)) {
10996 break;
10997 }
10998 }
10999 }
11000
11001 private final void realStartServiceLocked(ServiceRecord r,
11002 ProcessRecord app) throws RemoteException {
11003 if (app.thread == null) {
11004 throw new RemoteException();
11005 }
Amith Yamasani742a6712011-05-04 14:49:28 -070011006 if (DEBUG_MU)
11007 Slog.v(TAG_MU, "realStartServiceLocked, ServiceRecord.uid = " + r.appInfo.uid
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011008 + ", ProcessRecord.uid = " + app.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011009 r.app = app;
The Android Open Source Project10592532009-03-18 17:39:46 -070011010 r.restartTime = r.lastActivity = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011011
11012 app.services.add(r);
Dianne Hackborn287952c2010-09-22 22:34:31 -070011013 bumpServiceExecutingLocked(r, "create");
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011014 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011015
11016 boolean created = false;
11017 try {
Dianne Hackborna33e3f72009-09-29 17:28:24 -070011018 mStringBuilder.setLength(0);
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011019 r.intent.getIntent().toShortString(mStringBuilder, true, false, true, false);
Doug Zongker2bec3d42009-12-04 12:52:44 -080011020 EventLog.writeEvent(EventLogTags.AM_CREATE_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011021 System.identityHashCode(r), r.shortName,
Dianne Hackborna33e3f72009-09-29 17:28:24 -070011022 mStringBuilder.toString(), r.app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011023 synchronized (r.stats.getBatteryStats()) {
11024 r.stats.startLaunchedLocked();
11025 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -070011026 ensurePackageDexOpt(r.serviceInfo.packageName);
Dianne Hackborne2515ee2011-04-27 18:52:56 -040011027 app.thread.scheduleCreateService(r, r.serviceInfo,
11028 compatibilityInfoForPackageLocked(r.serviceInfo.applicationInfo));
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011029 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011030 created = true;
11031 } finally {
11032 if (!created) {
11033 app.services.remove(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011034 scheduleServiceRestartLocked(r, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011035 }
11036 }
11037
11038 requestServiceBindingsLocked(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011039
11040 // If the service is in the started state, and there are no
11041 // pending arguments, then fake up one so its onStartCommand() will
11042 // be called.
11043 if (r.startRequested && r.callStart && r.pendingStarts.size() == 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011044 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011045 null, null));
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011046 }
11047
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011048 sendServiceArgsLocked(r, true);
11049 }
11050
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011051 private final boolean scheduleServiceRestartLocked(ServiceRecord r,
11052 boolean allowCancel) {
11053 boolean canceled = false;
11054
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011055 final long now = SystemClock.uptimeMillis();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011056 long minDuration = SERVICE_RESTART_DURATION;
Dianne Hackborn6ccd2af2009-08-27 12:26:44 -070011057 long resetTime = SERVICE_RESET_RUN_DURATION;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011058
Dianne Hackborn070783f2010-12-29 16:46:28 -080011059 if ((r.serviceInfo.applicationInfo.flags
11060 &ApplicationInfo.FLAG_PERSISTENT) != 0) {
11061 minDuration /= 4;
11062 }
11063
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011064 // Any delivered but not yet finished starts should be put back
11065 // on the pending list.
11066 final int N = r.deliveredStarts.size();
11067 if (N > 0) {
11068 for (int i=N-1; i>=0; i--) {
11069 ServiceRecord.StartItem si = r.deliveredStarts.get(i);
Dianne Hackborn39792d22010-08-19 18:01:52 -070011070 si.removeUriPermissionsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011071 if (si.intent == null) {
11072 // We'll generate this again if needed.
11073 } else if (!allowCancel || (si.deliveryCount < ServiceRecord.MAX_DELIVERY_COUNT
11074 && si.doneExecutingCount < ServiceRecord.MAX_DONE_EXECUTING_COUNT)) {
11075 r.pendingStarts.add(0, si);
11076 long dur = SystemClock.uptimeMillis() - si.deliveredTime;
11077 dur *= 2;
11078 if (minDuration < dur) minDuration = dur;
11079 if (resetTime < dur) resetTime = dur;
11080 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011081 Slog.w(TAG, "Canceling start item " + si.intent + " in service "
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011082 + r.name);
11083 canceled = true;
11084 }
11085 }
11086 r.deliveredStarts.clear();
11087 }
11088
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011089 r.totalRestartCount++;
11090 if (r.restartDelay == 0) {
11091 r.restartCount++;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011092 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011093 } else {
11094 // If it has been a "reasonably long time" since the service
11095 // was started, then reset our restart duration back to
11096 // the beginning, so we don't infinitely increase the duration
11097 // on a service that just occasionally gets killed (which is
11098 // a normal case, due to process being killed to reclaim memory).
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011099 if (now > (r.restartTime+resetTime)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011100 r.restartCount = 1;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011101 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011102 } else {
Dianne Hackborn070783f2010-12-29 16:46:28 -080011103 if ((r.serviceInfo.applicationInfo.flags
11104 &ApplicationInfo.FLAG_PERSISTENT) != 0) {
11105 // Services in peristent processes will restart much more
11106 // quickly, since they are pretty important. (Think SystemUI).
11107 r.restartDelay += minDuration/2;
11108 } else {
11109 r.restartDelay *= SERVICE_RESTART_DURATION_FACTOR;
11110 if (r.restartDelay < minDuration) {
11111 r.restartDelay = minDuration;
11112 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011113 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011114 }
11115 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011116
11117 r.nextRestartTime = now + r.restartDelay;
11118
11119 // Make sure that we don't end up restarting a bunch of services
11120 // all at the same time.
11121 boolean repeat;
11122 do {
11123 repeat = false;
11124 for (int i=mRestartingServices.size()-1; i>=0; i--) {
11125 ServiceRecord r2 = mRestartingServices.get(i);
11126 if (r2 != r && r.nextRestartTime
11127 >= (r2.nextRestartTime-SERVICE_MIN_RESTART_TIME_BETWEEN)
11128 && r.nextRestartTime
11129 < (r2.nextRestartTime+SERVICE_MIN_RESTART_TIME_BETWEEN)) {
11130 r.nextRestartTime = r2.nextRestartTime + SERVICE_MIN_RESTART_TIME_BETWEEN;
11131 r.restartDelay = r.nextRestartTime - now;
11132 repeat = true;
11133 break;
11134 }
11135 }
11136 } while (repeat);
11137
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011138 if (!mRestartingServices.contains(r)) {
11139 mRestartingServices.add(r);
11140 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011141
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011142 r.cancelNotification();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011143
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011144 mHandler.removeCallbacks(r.restarter);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011145 mHandler.postAtTime(r.restarter, r.nextRestartTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011146 r.nextRestartTime = SystemClock.uptimeMillis() + r.restartDelay;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011147 Slog.w(TAG, "Scheduling restart of crashed service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011148 + r.shortName + " in " + r.restartDelay + "ms");
Doug Zongker2bec3d42009-12-04 12:52:44 -080011149 EventLog.writeEvent(EventLogTags.AM_SCHEDULE_SERVICE_RESTART,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011150 r.shortName, r.restartDelay);
11151
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011152 return canceled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011153 }
11154
11155 final void performServiceRestartLocked(ServiceRecord r) {
11156 if (!mRestartingServices.contains(r)) {
11157 return;
11158 }
11159 bringUpServiceLocked(r, r.intent.getIntent().getFlags(), true);
11160 }
11161
11162 private final boolean unscheduleServiceRestartLocked(ServiceRecord r) {
11163 if (r.restartDelay == 0) {
11164 return false;
11165 }
11166 r.resetRestartCounter();
11167 mRestartingServices.remove(r);
11168 mHandler.removeCallbacks(r.restarter);
11169 return true;
11170 }
11171
11172 private final boolean bringUpServiceLocked(ServiceRecord r,
11173 int intentFlags, boolean whileRestarting) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011174 //Slog.i(TAG, "Bring up service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011175 //r.dump(" ");
11176
Dianne Hackborn36124872009-10-08 16:22:03 -070011177 if (r.app != null && r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011178 sendServiceArgsLocked(r, false);
11179 return true;
11180 }
11181
11182 if (!whileRestarting && r.restartDelay > 0) {
11183 // If waiting for a restart, then do nothing.
11184 return true;
11185 }
11186
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011187 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing up " + r + " " + r.intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011188
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011189 // We are now bringing the service up, so no longer in the
11190 // restarting state.
11191 mRestartingServices.remove(r);
11192
Dianne Hackborne7f97212011-02-24 14:40:20 -080011193 // Service is now being launched, its package can't be stopped.
11194 try {
11195 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -070011196 r.packageName, false, r.userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -080011197 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080011198 } catch (IllegalArgumentException e) {
11199 Slog.w(TAG, "Failed trying to unstop package "
11200 + r.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080011201 }
11202
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011203 final boolean isolated = (r.serviceInfo.flags&ServiceInfo.FLAG_ISOLATED_PROCESS) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011204 final String appName = r.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011205 ProcessRecord app;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011206
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011207 if (!isolated) {
11208 app = getProcessRecordLocked(appName, r.appInfo.uid);
11209 if (DEBUG_MU)
11210 Slog.v(TAG_MU, "bringUpServiceLocked: appInfo.uid=" + r.appInfo.uid + " app=" + app);
11211 if (app != null && app.thread != null) {
11212 try {
11213 app.addPackage(r.appInfo.packageName);
11214 realStartServiceLocked(r, app);
11215 return true;
11216 } catch (RemoteException e) {
11217 Slog.w(TAG, "Exception when starting service " + r.shortName, e);
11218 }
11219
11220 // If a dead object exception was thrown -- fall through to
11221 // restart the application.
11222 }
11223 } else {
11224 // If this service runs in an isolated process, then each time
11225 // we call startProcessLocked() we will get a new isolated
11226 // process, starting another process if we are currently waiting
11227 // for a previous process to come up. To deal with this, we store
11228 // in the service any current isolated process it is running in or
11229 // waiting to have come up.
11230 app = r.isolatedProc;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011231 }
11232
Dianne Hackborn36124872009-10-08 16:22:03 -070011233 // Not running -- get it started, and enqueue this service record
11234 // to be executed when the app comes up.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011235 if (app == null) {
11236 if ((app=startProcessLocked(appName, r.appInfo, true, intentFlags,
11237 "service", r.name, false, isolated)) == null) {
11238 Slog.w(TAG, "Unable to launch app "
11239 + r.appInfo.packageName + "/"
11240 + r.appInfo.uid + " for service "
11241 + r.intent.getIntent() + ": process is bad");
11242 bringDownServiceLocked(r, true);
11243 return false;
11244 }
11245 if (isolated) {
11246 r.isolatedProc = app;
11247 }
Dianne Hackborn36124872009-10-08 16:22:03 -070011248 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011249
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011250 if (!mPendingServices.contains(r)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011251 mPendingServices.add(r);
11252 }
Dianne Hackborn36124872009-10-08 16:22:03 -070011253
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011254 return true;
11255 }
11256
11257 private final void bringDownServiceLocked(ServiceRecord r, boolean force) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011258 //Slog.i(TAG, "Bring down service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011259 //r.dump(" ");
11260
11261 // Does it still need to run?
11262 if (!force && r.startRequested) {
11263 return;
11264 }
11265 if (r.connections.size() > 0) {
11266 if (!force) {
11267 // XXX should probably keep a count of the number of auto-create
11268 // connections directly in the service.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011269 Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011270 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011271 ArrayList<ConnectionRecord> cr = it.next();
11272 for (int i=0; i<cr.size(); i++) {
11273 if ((cr.get(i).flags&Context.BIND_AUTO_CREATE) != 0) {
11274 return;
11275 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011276 }
11277 }
11278 }
11279
11280 // Report to all of the connections that the service is no longer
11281 // available.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011282 Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011283 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011284 ArrayList<ConnectionRecord> c = it.next();
11285 for (int i=0; i<c.size(); i++) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011286 ConnectionRecord cr = c.get(i);
11287 // There is still a connection to the service that is
11288 // being brought down. Mark it as dead.
11289 cr.serviceDead = true;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011290 try {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011291 cr.conn.connected(r.name, null);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011292 } catch (Exception e) {
11293 Slog.w(TAG, "Failure disconnecting service " + r.name +
11294 " to connection " + c.get(i).conn.asBinder() +
11295 " (in " + c.get(i).binding.client.processName + ")", e);
11296 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011297 }
11298 }
11299 }
11300
11301 // Tell the service that it has been unbound.
11302 if (r.bindings.size() > 0 && r.app != null && r.app.thread != null) {
11303 Iterator<IntentBindRecord> it = r.bindings.values().iterator();
11304 while (it.hasNext()) {
11305 IntentBindRecord ibr = it.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -080011306 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down binding " + ibr
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011307 + ": hasBound=" + ibr.hasBound);
11308 if (r.app != null && r.app.thread != null && ibr.hasBound) {
11309 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011310 bumpServiceExecutingLocked(r, "bring down unbind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011311 updateOomAdjLocked(r.app);
11312 ibr.hasBound = false;
11313 r.app.thread.scheduleUnbindService(r,
11314 ibr.intent.getIntent());
11315 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011316 Slog.w(TAG, "Exception when unbinding service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011317 + r.shortName, e);
11318 serviceDoneExecutingLocked(r, true);
11319 }
11320 }
11321 }
11322 }
11323
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011324 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down " + r + " " + r.intent);
Doug Zongker2bec3d42009-12-04 12:52:44 -080011325 EventLog.writeEvent(EventLogTags.AM_DESTROY_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011326 System.identityHashCode(r), r.shortName,
11327 (r.app != null) ? r.app.pid : -1);
11328
Amith Yamasani742a6712011-05-04 14:49:28 -070011329 mServiceMap.removeServiceByName(r.name, r.userId);
11330 mServiceMap.removeServiceByIntent(r.intent, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011331 r.totalRestartCount = 0;
11332 unscheduleServiceRestartLocked(r);
11333
11334 // Also make sure it is not on the pending list.
11335 int N = mPendingServices.size();
11336 for (int i=0; i<N; i++) {
11337 if (mPendingServices.get(i) == r) {
11338 mPendingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011339 if (DEBUG_SERVICE) Slog.v(TAG, "Removed pending: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011340 i--;
11341 N--;
11342 }
11343 }
11344
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011345 r.cancelNotification();
11346 r.isForeground = false;
11347 r.foregroundId = 0;
11348 r.foregroundNoti = null;
11349
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011350 // Clear start entries.
Dianne Hackborn39792d22010-08-19 18:01:52 -070011351 r.clearDeliveredStartsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011352 r.pendingStarts.clear();
11353
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011354 if (r.app != null) {
11355 synchronized (r.stats.getBatteryStats()) {
11356 r.stats.stopLaunchedLocked();
11357 }
11358 r.app.services.remove(r);
11359 if (r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011360 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011361 bumpServiceExecutingLocked(r, "stop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011362 mStoppingServices.add(r);
11363 updateOomAdjLocked(r.app);
11364 r.app.thread.scheduleStopService(r);
11365 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011366 Slog.w(TAG, "Exception when stopping service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011367 + r.shortName, e);
11368 serviceDoneExecutingLocked(r, true);
11369 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011370 updateServiceForegroundLocked(r.app, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011371 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011372 if (DEBUG_SERVICE) Slog.v(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011373 TAG, "Removed service that has no process: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011374 }
11375 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011376 if (DEBUG_SERVICE) Slog.v(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011377 TAG, "Removed service that is not running: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011378 }
Vairavan Srinivasana207ce22010-12-23 13:51:48 -080011379
11380 if (r.bindings.size() > 0) {
11381 r.bindings.clear();
11382 }
11383
11384 if (r.restarter instanceof ServiceRestarter) {
11385 ((ServiceRestarter)r.restarter).setService(null);
11386 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011387 }
11388
11389 ComponentName startServiceLocked(IApplicationThread caller,
11390 Intent service, String resolvedType,
11391 int callingPid, int callingUid) {
11392 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011393 if (DEBUG_SERVICE) Slog.v(TAG, "startService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011394 + " type=" + resolvedType + " args=" + service.getExtras());
11395
11396 if (caller != null) {
11397 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11398 if (callerApp == null) {
11399 throw new SecurityException(
11400 "Unable to find app for caller " + caller
11401 + " (pid=" + Binder.getCallingPid()
11402 + ") when starting service " + service);
11403 }
11404 }
11405
11406 ServiceLookupResult res =
11407 retrieveServiceLocked(service, resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011408 callingPid, callingUid, UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011409 if (res == null) {
11410 return null;
11411 }
11412 if (res.record == null) {
11413 return new ComponentName("!", res.permission != null
11414 ? res.permission : "private to package");
11415 }
11416 ServiceRecord r = res.record;
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011417 NeededUriGrants neededGrants = checkGrantUriPermissionFromIntentLocked(
11418 callingUid, r.packageName, service, service.getFlags(), null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011419 if (unscheduleServiceRestartLocked(r)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011420 if (DEBUG_SERVICE) Slog.v(TAG, "START SERVICE WHILE RESTART PENDING: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011421 }
11422 r.startRequested = true;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011423 r.callStart = false;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011424 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011425 service, neededGrants));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011426 r.lastActivity = SystemClock.uptimeMillis();
11427 synchronized (r.stats.getBatteryStats()) {
11428 r.stats.startRunningLocked();
11429 }
11430 if (!bringUpServiceLocked(r, service.getFlags(), false)) {
11431 return new ComponentName("!", "Service process is bad");
11432 }
11433 return r.name;
11434 }
11435 }
11436
11437 public ComponentName startService(IApplicationThread caller, Intent service,
11438 String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011439 enforceNotIsolatedCaller("startService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011440 // Refuse possible leaked file descriptors
11441 if (service != null && service.hasFileDescriptors() == true) {
11442 throw new IllegalArgumentException("File descriptors passed in Intent");
11443 }
11444
Amith Yamasani742a6712011-05-04 14:49:28 -070011445 if (DEBUG_SERVICE)
11446 Slog.v(TAG, "startService: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011447 synchronized(this) {
11448 final int callingPid = Binder.getCallingPid();
11449 final int callingUid = Binder.getCallingUid();
11450 final long origId = Binder.clearCallingIdentity();
11451 ComponentName res = startServiceLocked(caller, service,
11452 resolvedType, callingPid, callingUid);
11453 Binder.restoreCallingIdentity(origId);
11454 return res;
11455 }
11456 }
11457
11458 ComponentName startServiceInPackage(int uid,
11459 Intent service, String resolvedType) {
11460 synchronized(this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070011461 if (DEBUG_SERVICE)
11462 Slog.v(TAG, "startServiceInPackage: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011463 final long origId = Binder.clearCallingIdentity();
11464 ComponentName res = startServiceLocked(null, service,
11465 resolvedType, -1, uid);
11466 Binder.restoreCallingIdentity(origId);
11467 return res;
11468 }
11469 }
11470
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011471 private void stopServiceLocked(ServiceRecord service) {
11472 synchronized (service.stats.getBatteryStats()) {
11473 service.stats.stopRunningLocked();
11474 }
11475 service.startRequested = false;
11476 service.callStart = false;
11477 bringDownServiceLocked(service, false);
11478 }
11479
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011480 public int stopService(IApplicationThread caller, Intent service,
11481 String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011482 enforceNotIsolatedCaller("stopService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011483 // Refuse possible leaked file descriptors
11484 if (service != null && service.hasFileDescriptors() == true) {
11485 throw new IllegalArgumentException("File descriptors passed in Intent");
11486 }
11487
11488 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011489 if (DEBUG_SERVICE) Slog.v(TAG, "stopService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011490 + " type=" + resolvedType);
11491
11492 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11493 if (caller != null && callerApp == null) {
11494 throw new SecurityException(
11495 "Unable to find app for caller " + caller
11496 + " (pid=" + Binder.getCallingPid()
11497 + ") when stopping service " + service);
11498 }
11499
11500 // If this service is active, make sure it is stopped.
Amith Yamasani483f3b02012-03-13 16:08:00 -070011501 ServiceLookupResult r = findServiceLocked(service, resolvedType,
11502 callerApp == null ? UserId.getCallingUserId() : callerApp.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011503 if (r != null) {
11504 if (r.record != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011505 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011506 try {
11507 stopServiceLocked(r.record);
11508 } finally {
11509 Binder.restoreCallingIdentity(origId);
11510 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011511 return 1;
11512 }
11513 return -1;
11514 }
11515 }
11516
11517 return 0;
11518 }
11519
11520 public IBinder peekService(Intent service, String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011521 enforceNotIsolatedCaller("peekService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011522 // Refuse possible leaked file descriptors
11523 if (service != null && service.hasFileDescriptors() == true) {
11524 throw new IllegalArgumentException("File descriptors passed in Intent");
11525 }
11526
11527 IBinder ret = null;
11528
11529 synchronized(this) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070011530 ServiceLookupResult r = findServiceLocked(service, resolvedType,
11531 UserId.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011532
11533 if (r != null) {
11534 // r.record is null if findServiceLocked() failed the caller permission check
11535 if (r.record == null) {
11536 throw new SecurityException(
11537 "Permission Denial: Accessing service " + r.record.name
11538 + " from pid=" + Binder.getCallingPid()
11539 + ", uid=" + Binder.getCallingUid()
11540 + " requires " + r.permission);
11541 }
11542 IntentBindRecord ib = r.record.bindings.get(r.record.intent);
11543 if (ib != null) {
11544 ret = ib.binder;
11545 }
11546 }
11547 }
11548
11549 return ret;
11550 }
11551
11552 public boolean stopServiceToken(ComponentName className, IBinder token,
11553 int startId) {
11554 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011555 if (DEBUG_SERVICE) Slog.v(TAG, "stopServiceToken: " + className
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011556 + " " + token + " startId=" + startId);
11557 ServiceRecord r = findServiceLocked(className, token);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011558 if (r != null) {
11559 if (startId >= 0) {
11560 // Asked to only stop if done with all work. Note that
11561 // to avoid leaks, we will take this as dropping all
11562 // start items up to and including this one.
11563 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
11564 if (si != null) {
11565 while (r.deliveredStarts.size() > 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -070011566 ServiceRecord.StartItem cur = r.deliveredStarts.remove(0);
11567 cur.removeUriPermissionsLocked();
11568 if (cur == si) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011569 break;
11570 }
11571 }
11572 }
11573
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011574 if (r.getLastStartId() != startId) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011575 return false;
11576 }
11577
11578 if (r.deliveredStarts.size() > 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011579 Slog.w(TAG, "stopServiceToken startId " + startId
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011580 + " is last, but have " + r.deliveredStarts.size()
11581 + " remaining args");
11582 }
11583 }
11584
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011585 synchronized (r.stats.getBatteryStats()) {
11586 r.stats.stopRunningLocked();
11587 r.startRequested = false;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011588 r.callStart = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011589 }
11590 final long origId = Binder.clearCallingIdentity();
11591 bringDownServiceLocked(r, false);
11592 Binder.restoreCallingIdentity(origId);
11593 return true;
11594 }
11595 }
11596 return false;
11597 }
11598
11599 public void setServiceForeground(ComponentName className, IBinder token,
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011600 int id, Notification notification, boolean removeNotification) {
11601 final long origId = Binder.clearCallingIdentity();
11602 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011603 synchronized(this) {
11604 ServiceRecord r = findServiceLocked(className, token);
11605 if (r != null) {
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011606 if (id != 0) {
11607 if (notification == null) {
11608 throw new IllegalArgumentException("null notification");
11609 }
11610 if (r.foregroundId != id) {
11611 r.cancelNotification();
11612 r.foregroundId = id;
11613 }
11614 notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
11615 r.foregroundNoti = notification;
11616 r.isForeground = true;
11617 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011618 if (r.app != null) {
11619 updateServiceForegroundLocked(r.app, true);
11620 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011621 } else {
11622 if (r.isForeground) {
11623 r.isForeground = false;
11624 if (r.app != null) {
Dianne Hackborn8633e682010-04-22 16:03:41 -070011625 updateLruProcessLocked(r.app, false, true);
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011626 updateServiceForegroundLocked(r.app, true);
11627 }
11628 }
11629 if (removeNotification) {
11630 r.cancelNotification();
11631 r.foregroundId = 0;
11632 r.foregroundNoti = null;
11633 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011634 }
11635 }
11636 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011637 } finally {
11638 Binder.restoreCallingIdentity(origId);
11639 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011640 }
11641
11642 public void updateServiceForegroundLocked(ProcessRecord proc, boolean oomAdj) {
11643 boolean anyForeground = false;
Dianne Hackborn860755f2010-06-03 18:47:52 -070011644 for (ServiceRecord sr : proc.services) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011645 if (sr.isForeground) {
11646 anyForeground = true;
11647 break;
11648 }
11649 }
11650 if (anyForeground != proc.foregroundServices) {
11651 proc.foregroundServices = anyForeground;
11652 if (oomAdj) {
11653 updateOomAdjLocked();
11654 }
11655 }
11656 }
11657
11658 public int bindService(IApplicationThread caller, IBinder token,
11659 Intent service, String resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011660 IServiceConnection connection, int flags, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011661 enforceNotIsolatedCaller("bindService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011662 // Refuse possible leaked file descriptors
11663 if (service != null && service.hasFileDescriptors() == true) {
11664 throw new IllegalArgumentException("File descriptors passed in Intent");
11665 }
11666
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011667 checkValidCaller(Binder.getCallingUid(), userId);
11668
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011669 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011670 if (DEBUG_SERVICE) Slog.v(TAG, "bindService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011671 + " type=" + resolvedType + " conn=" + connection.asBinder()
11672 + " flags=0x" + Integer.toHexString(flags));
Amith Yamasani742a6712011-05-04 14:49:28 -070011673 if (DEBUG_MU)
11674 Slog.i(TAG_MU, "bindService uid=" + Binder.getCallingUid() + " origUid="
11675 + Binder.getOrigCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011676 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11677 if (callerApp == null) {
11678 throw new SecurityException(
11679 "Unable to find app for caller " + caller
11680 + " (pid=" + Binder.getCallingPid()
11681 + ") when binding service " + service);
11682 }
11683
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011684 ActivityRecord activity = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011685 if (token != null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070011686 activity = mMainStack.isInStackLocked(token);
11687 if (activity == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011688 Slog.w(TAG, "Binding with unknown activity: " + token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011689 return 0;
11690 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011691 }
11692
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011693 int clientLabel = 0;
11694 PendingIntent clientIntent = null;
11695
11696 if (callerApp.info.uid == Process.SYSTEM_UID) {
11697 // Hacky kind of thing -- allow system stuff to tell us
11698 // what they are, so we can report this elsewhere for
11699 // others to know why certain services are running.
11700 try {
11701 clientIntent = (PendingIntent)service.getParcelableExtra(
11702 Intent.EXTRA_CLIENT_INTENT);
11703 } catch (RuntimeException e) {
11704 }
11705 if (clientIntent != null) {
11706 clientLabel = service.getIntExtra(Intent.EXTRA_CLIENT_LABEL, 0);
11707 if (clientLabel != 0) {
11708 // There are no useful extras in the intent, trash them.
11709 // System code calling with this stuff just needs to know
11710 // this will happen.
11711 service = service.cloneFilter();
11712 }
11713 }
11714 }
11715
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011716 ServiceLookupResult res =
11717 retrieveServiceLocked(service, resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011718 Binder.getCallingPid(), Binder.getCallingUid(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011719 if (res == null) {
11720 return 0;
11721 }
11722 if (res.record == null) {
11723 return -1;
11724 }
11725 ServiceRecord s = res.record;
11726
11727 final long origId = Binder.clearCallingIdentity();
11728
11729 if (unscheduleServiceRestartLocked(s)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011730 if (DEBUG_SERVICE) Slog.v(TAG, "BIND SERVICE WHILE RESTART PENDING: "
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011731 + s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011732 }
11733
11734 AppBindRecord b = s.retrieveAppBindingLocked(service, callerApp);
11735 ConnectionRecord c = new ConnectionRecord(b, activity,
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011736 connection, flags, clientLabel, clientIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011737
11738 IBinder binder = connection.asBinder();
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011739 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
11740 if (clist == null) {
11741 clist = new ArrayList<ConnectionRecord>();
11742 s.connections.put(binder, clist);
11743 }
11744 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011745 b.connections.add(c);
11746 if (activity != null) {
11747 if (activity.connections == null) {
11748 activity.connections = new HashSet<ConnectionRecord>();
11749 }
11750 activity.connections.add(c);
11751 }
11752 b.client.connections.add(c);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070011753 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
11754 b.client.hasAboveClient = true;
11755 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011756 clist = mServiceConnections.get(binder);
11757 if (clist == null) {
11758 clist = new ArrayList<ConnectionRecord>();
11759 mServiceConnections.put(binder, clist);
11760 }
11761 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011762
11763 if ((flags&Context.BIND_AUTO_CREATE) != 0) {
11764 s.lastActivity = SystemClock.uptimeMillis();
11765 if (!bringUpServiceLocked(s, service.getFlags(), false)) {
11766 return 0;
11767 }
11768 }
11769
11770 if (s.app != null) {
11771 // This could have made the service more important.
11772 updateOomAdjLocked(s.app);
11773 }
11774
Joe Onorato8a9b2202010-02-26 18:56:32 -080011775 if (DEBUG_SERVICE) Slog.v(TAG, "Bind " + s + " with " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011776 + ": received=" + b.intent.received
11777 + " apps=" + b.intent.apps.size()
11778 + " doRebind=" + b.intent.doRebind);
11779
11780 if (s.app != null && b.intent.received) {
11781 // Service is already running, so we can immediately
11782 // publish the connection.
11783 try {
11784 c.conn.connected(s.name, b.intent.binder);
11785 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011786 Slog.w(TAG, "Failure sending service " + s.shortName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011787 + " to connection " + c.conn.asBinder()
11788 + " (in " + c.binding.client.processName + ")", e);
11789 }
11790
11791 // If this is the first app connected back to this binding,
11792 // and the service had previously asked to be told when
11793 // rebound, then do so.
11794 if (b.intent.apps.size() == 1 && b.intent.doRebind) {
11795 requestServiceBindingLocked(s, b.intent, true);
11796 }
11797 } else if (!b.intent.requested) {
11798 requestServiceBindingLocked(s, b.intent, false);
11799 }
11800
11801 Binder.restoreCallingIdentity(origId);
11802 }
11803
11804 return 1;
11805 }
11806
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070011807 void removeConnectionLocked(
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011808 ConnectionRecord c, ProcessRecord skipApp, ActivityRecord skipAct) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011809 IBinder binder = c.conn.asBinder();
11810 AppBindRecord b = c.binding;
11811 ServiceRecord s = b.service;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011812 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
11813 if (clist != null) {
11814 clist.remove(c);
11815 if (clist.size() == 0) {
11816 s.connections.remove(binder);
11817 }
11818 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011819 b.connections.remove(c);
11820 if (c.activity != null && c.activity != skipAct) {
11821 if (c.activity.connections != null) {
11822 c.activity.connections.remove(c);
11823 }
11824 }
11825 if (b.client != skipApp) {
11826 b.client.connections.remove(c);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070011827 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
11828 b.client.updateHasAboveClientLocked();
11829 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011830 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011831 clist = mServiceConnections.get(binder);
11832 if (clist != null) {
11833 clist.remove(c);
11834 if (clist.size() == 0) {
11835 mServiceConnections.remove(binder);
11836 }
11837 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011838
11839 if (b.connections.size() == 0) {
11840 b.intent.apps.remove(b.client);
11841 }
11842
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011843 if (!c.serviceDead) {
11844 if (DEBUG_SERVICE) Slog.v(TAG, "Disconnecting binding " + b.intent
11845 + ": shouldUnbind=" + b.intent.hasBound);
11846 if (s.app != null && s.app.thread != null && b.intent.apps.size() == 0
11847 && b.intent.hasBound) {
11848 try {
11849 bumpServiceExecutingLocked(s, "unbind");
11850 updateOomAdjLocked(s.app);
11851 b.intent.hasBound = false;
11852 // Assume the client doesn't want to know about a rebind;
11853 // we will deal with that later if it asks for one.
11854 b.intent.doRebind = false;
11855 s.app.thread.scheduleUnbindService(s, b.intent.intent.getIntent());
11856 } catch (Exception e) {
11857 Slog.w(TAG, "Exception when unbinding service " + s.shortName, e);
11858 serviceDoneExecutingLocked(s, true);
11859 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011860 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011861
11862 if ((c.flags&Context.BIND_AUTO_CREATE) != 0) {
11863 bringDownServiceLocked(s, false);
11864 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011865 }
11866 }
11867
11868 public boolean unbindService(IServiceConnection connection) {
11869 synchronized (this) {
11870 IBinder binder = connection.asBinder();
Joe Onorato8a9b2202010-02-26 18:56:32 -080011871 if (DEBUG_SERVICE) Slog.v(TAG, "unbindService: conn=" + binder);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011872 ArrayList<ConnectionRecord> clist = mServiceConnections.get(binder);
11873 if (clist == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011874 Slog.w(TAG, "Unbind failed: could not find connection for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011875 + connection.asBinder());
11876 return false;
11877 }
11878
11879 final long origId = Binder.clearCallingIdentity();
11880
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011881 while (clist.size() > 0) {
11882 ConnectionRecord r = clist.get(0);
11883 removeConnectionLocked(r, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011884
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011885 if (r.binding.service.app != null) {
11886 // This could have made the service less important.
11887 updateOomAdjLocked(r.binding.service.app);
11888 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011889 }
11890
11891 Binder.restoreCallingIdentity(origId);
11892 }
11893
11894 return true;
11895 }
11896
11897 public void publishService(IBinder token, Intent intent, IBinder service) {
11898 // Refuse possible leaked file descriptors
11899 if (intent != null && intent.hasFileDescriptors() == true) {
11900 throw new IllegalArgumentException("File descriptors passed in Intent");
11901 }
11902
11903 synchronized(this) {
11904 if (!(token instanceof ServiceRecord)) {
11905 throw new IllegalArgumentException("Invalid service token");
11906 }
11907 ServiceRecord r = (ServiceRecord)token;
11908
11909 final long origId = Binder.clearCallingIdentity();
11910
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011911 if (DEBUG_SERVICE) Slog.v(TAG, "PUBLISHING " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011912 + " " + intent + ": " + service);
11913 if (r != null) {
11914 Intent.FilterComparison filter
11915 = new Intent.FilterComparison(intent);
11916 IntentBindRecord b = r.bindings.get(filter);
11917 if (b != null && !b.received) {
11918 b.binder = service;
11919 b.requested = true;
11920 b.received = true;
11921 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011922 Iterator<ArrayList<ConnectionRecord>> it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011923 = r.connections.values().iterator();
11924 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011925 ArrayList<ConnectionRecord> clist = it.next();
11926 for (int i=0; i<clist.size(); i++) {
11927 ConnectionRecord c = clist.get(i);
11928 if (!filter.equals(c.binding.intent.intent)) {
11929 if (DEBUG_SERVICE) Slog.v(
11930 TAG, "Not publishing to: " + c);
11931 if (DEBUG_SERVICE) Slog.v(
11932 TAG, "Bound intent: " + c.binding.intent.intent);
11933 if (DEBUG_SERVICE) Slog.v(
11934 TAG, "Published intent: " + intent);
11935 continue;
11936 }
11937 if (DEBUG_SERVICE) Slog.v(TAG, "Publishing to: " + c);
11938 try {
11939 c.conn.connected(r.name, service);
11940 } catch (Exception e) {
11941 Slog.w(TAG, "Failure sending service " + r.name +
11942 " to connection " + c.conn.asBinder() +
11943 " (in " + c.binding.client.processName + ")", e);
11944 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011945 }
11946 }
11947 }
11948 }
11949
11950 serviceDoneExecutingLocked(r, mStoppingServices.contains(r));
11951
11952 Binder.restoreCallingIdentity(origId);
11953 }
11954 }
11955 }
11956
11957 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
11958 // Refuse possible leaked file descriptors
11959 if (intent != null && intent.hasFileDescriptors() == true) {
11960 throw new IllegalArgumentException("File descriptors passed in Intent");
11961 }
11962
11963 synchronized(this) {
11964 if (!(token instanceof ServiceRecord)) {
11965 throw new IllegalArgumentException("Invalid service token");
11966 }
11967 ServiceRecord r = (ServiceRecord)token;
11968
11969 final long origId = Binder.clearCallingIdentity();
11970
11971 if (r != null) {
11972 Intent.FilterComparison filter
11973 = new Intent.FilterComparison(intent);
11974 IntentBindRecord b = r.bindings.get(filter);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011975 if (DEBUG_SERVICE) Slog.v(TAG, "unbindFinished in " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011976 + " at " + b + ": apps="
11977 + (b != null ? b.apps.size() : 0));
Per Edelberg78f9fff2010-08-30 20:01:35 +020011978
11979 boolean inStopping = mStoppingServices.contains(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011980 if (b != null) {
Per Edelberg78f9fff2010-08-30 20:01:35 +020011981 if (b.apps.size() > 0 && !inStopping) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011982 // Applications have already bound since the last
11983 // unbind, so just rebind right here.
11984 requestServiceBindingLocked(r, b, true);
11985 } else {
11986 // Note to tell the service the next time there is
11987 // a new client.
11988 b.doRebind = true;
11989 }
11990 }
11991
Per Edelberg78f9fff2010-08-30 20:01:35 +020011992 serviceDoneExecutingLocked(r, inStopping);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011993
11994 Binder.restoreCallingIdentity(origId);
11995 }
11996 }
11997 }
11998
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011999 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012000 synchronized(this) {
12001 if (!(token instanceof ServiceRecord)) {
12002 throw new IllegalArgumentException("Invalid service token");
12003 }
12004 ServiceRecord r = (ServiceRecord)token;
12005 boolean inStopping = mStoppingServices.contains(token);
12006 if (r != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012007 if (r != token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012008 Slog.w(TAG, "Done executing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012009 + " with incorrect token: given " + token
12010 + ", expected " + r);
12011 return;
12012 }
12013
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012014 if (type == 1) {
12015 // This is a call from a service start... take care of
12016 // book-keeping.
12017 r.callStart = true;
12018 switch (res) {
12019 case Service.START_STICKY_COMPATIBILITY:
12020 case Service.START_STICKY: {
12021 // We are done with the associated start arguments.
12022 r.findDeliveredStart(startId, true);
12023 // Don't stop if killed.
12024 r.stopIfKilled = false;
12025 break;
12026 }
12027 case Service.START_NOT_STICKY: {
12028 // We are done with the associated start arguments.
12029 r.findDeliveredStart(startId, true);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070012030 if (r.getLastStartId() == startId) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012031 // There is no more work, and this service
12032 // doesn't want to hang around if killed.
12033 r.stopIfKilled = true;
12034 }
12035 break;
12036 }
12037 case Service.START_REDELIVER_INTENT: {
12038 // We'll keep this item until they explicitly
12039 // call stop for it, but keep track of the fact
12040 // that it was delivered.
12041 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
12042 if (si != null) {
12043 si.deliveryCount = 0;
12044 si.doneExecutingCount++;
12045 // Don't stop if killed.
12046 r.stopIfKilled = true;
12047 }
12048 break;
12049 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070012050 case Service.START_TASK_REMOVED_COMPLETE: {
12051 // Special processing for onTaskRemoved(). Don't
12052 // impact normal onStartCommand() processing.
12053 r.findDeliveredStart(startId, true);
12054 break;
12055 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012056 default:
12057 throw new IllegalArgumentException(
12058 "Unknown service start result: " + res);
12059 }
12060 if (res == Service.START_STICKY_COMPATIBILITY) {
12061 r.callStart = false;
12062 }
12063 }
Amith Yamasani742a6712011-05-04 14:49:28 -070012064 if (DEBUG_MU)
12065 Slog.v(TAG_MU, "before serviceDontExecutingLocked, uid="
12066 + Binder.getOrigCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012067 final long origId = Binder.clearCallingIdentity();
12068 serviceDoneExecutingLocked(r, inStopping);
12069 Binder.restoreCallingIdentity(origId);
12070 } else {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012071 Slog.w(TAG, "Done executing unknown service from pid "
12072 + Binder.getCallingPid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012073 }
12074 }
12075 }
12076
12077 public void serviceDoneExecutingLocked(ServiceRecord r, boolean inStopping) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012078 if (DEBUG_SERVICE) Slog.v(TAG, "<<< DONE EXECUTING " + r
12079 + ": nesting=" + r.executeNesting
12080 + ", inStopping=" + inStopping + ", app=" + r.app);
Dianne Hackborn287952c2010-09-22 22:34:31 -070012081 else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG, "<<< DONE EXECUTING " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012082 r.executeNesting--;
12083 if (r.executeNesting <= 0 && r.app != null) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012084 if (DEBUG_SERVICE) Slog.v(TAG,
12085 "Nesting at 0 of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012086 r.app.executingServices.remove(r);
12087 if (r.app.executingServices.size() == 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012088 if (DEBUG_SERVICE || DEBUG_SERVICE_EXECUTING) Slog.v(TAG,
12089 "No more executingServices of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012090 mHandler.removeMessages(SERVICE_TIMEOUT_MSG, r.app);
12091 }
12092 if (inStopping) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012093 if (DEBUG_SERVICE) Slog.v(TAG,
12094 "doneExecuting remove stopping " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012095 mStoppingServices.remove(r);
Mattias Petersson3996b412010-10-27 09:32:51 +020012096 r.bindings.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012097 }
12098 updateOomAdjLocked(r.app);
12099 }
12100 }
12101
12102 void serviceTimeout(ProcessRecord proc) {
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012103 String anrMessage = null;
12104
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012105 synchronized(this) {
12106 if (proc.executingServices.size() == 0 || proc.thread == null) {
12107 return;
12108 }
12109 long maxTime = SystemClock.uptimeMillis() - SERVICE_TIMEOUT;
12110 Iterator<ServiceRecord> it = proc.executingServices.iterator();
12111 ServiceRecord timeout = null;
12112 long nextTime = 0;
12113 while (it.hasNext()) {
12114 ServiceRecord sr = it.next();
12115 if (sr.executingStart < maxTime) {
12116 timeout = sr;
12117 break;
12118 }
12119 if (sr.executingStart > nextTime) {
12120 nextTime = sr.executingStart;
12121 }
12122 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012123 if (timeout != null && mLruProcesses.contains(proc)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012124 Slog.w(TAG, "Timeout executing service: " + timeout);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012125 anrMessage = "Executing service " + timeout.shortName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012126 } else {
12127 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
12128 msg.obj = proc;
12129 mHandler.sendMessageAtTime(msg, nextTime+SERVICE_TIMEOUT);
12130 }
12131 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012132
12133 if (anrMessage != null) {
12134 appNotResponding(proc, null, null, anrMessage);
12135 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012136 }
12137
12138 // =========================================================
Christopher Tate181fafa2009-05-14 11:12:14 -070012139 // BACKUP AND RESTORE
12140 // =========================================================
12141
12142 // Cause the target app to be launched if necessary and its backup agent
12143 // instantiated. The backup agent will invoke backupAgentCreated() on the
12144 // activity manager to announce its creation.
12145 public boolean bindBackupAgent(ApplicationInfo app, int backupMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012146 if (DEBUG_BACKUP) Slog.v(TAG, "startBackupAgent: app=" + app + " mode=" + backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070012147 enforceCallingPermission("android.permission.BACKUP", "startBackupAgent");
12148
12149 synchronized(this) {
12150 // !!! TODO: currently no check here that we're already bound
12151 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
12152 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
12153 synchronized (stats) {
12154 ss = stats.getServiceStatsLocked(app.uid, app.packageName, app.name);
12155 }
12156
Dianne Hackborne7f97212011-02-24 14:40:20 -080012157 // Backup agent is now in use, its package can't be stopped.
12158 try {
12159 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -070012160 app.packageName, false, UserId.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -080012161 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080012162 } catch (IllegalArgumentException e) {
12163 Slog.w(TAG, "Failed trying to unstop package "
12164 + app.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080012165 }
12166
Christopher Tate181fafa2009-05-14 11:12:14 -070012167 BackupRecord r = new BackupRecord(ss, app, backupMode);
Christopher Tate4a627c72011-04-01 14:43:32 -070012168 ComponentName hostingName = (backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL)
12169 ? new ComponentName(app.packageName, app.backupAgentName)
12170 : new ComponentName("android", "FullBackupAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -070012171 // startProcessLocked() returns existing proc's record if it's already running
12172 ProcessRecord proc = startProcessLocked(app.processName, app,
Dianne Hackborna0c283e2012-02-09 10:47:01 -080012173 false, 0, "backup", hostingName, false, false);
Christopher Tate181fafa2009-05-14 11:12:14 -070012174 if (proc == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012175 Slog.e(TAG, "Unable to start backup agent process " + r);
Christopher Tate181fafa2009-05-14 11:12:14 -070012176 return false;
12177 }
12178
12179 r.app = proc;
12180 mBackupTarget = r;
12181 mBackupAppName = app.packageName;
12182
Christopher Tate6fa95972009-06-05 18:43:55 -070012183 // Try not to kill the process during backup
12184 updateOomAdjLocked(proc);
12185
Christopher Tate181fafa2009-05-14 11:12:14 -070012186 // If the process is already attached, schedule the creation of the backup agent now.
12187 // If it is not yet live, this will be done when it attaches to the framework.
12188 if (proc.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012189 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc already running: " + proc);
Christopher Tate181fafa2009-05-14 11:12:14 -070012190 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040012191 proc.thread.scheduleCreateBackupAgent(app,
12192 compatibilityInfoForPackageLocked(app), backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070012193 } catch (RemoteException e) {
Christopher Tate436344a2009-09-30 16:17:37 -070012194 // Will time out on the backup manager side
Christopher Tate181fafa2009-05-14 11:12:14 -070012195 }
12196 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012197 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc not running, waiting for attach");
Christopher Tate181fafa2009-05-14 11:12:14 -070012198 }
12199 // Invariants: at this point, the target app process exists and the application
12200 // is either already running or in the process of coming up. mBackupTarget and
12201 // mBackupAppName describe the app, so that when it binds back to the AM we
12202 // know that it's scheduled for a backup-agent operation.
12203 }
12204
12205 return true;
12206 }
12207
12208 // A backup agent has just come up
12209 public void backupAgentCreated(String agentPackageName, IBinder agent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012210 if (DEBUG_BACKUP) Slog.v(TAG, "backupAgentCreated: " + agentPackageName
Christopher Tate181fafa2009-05-14 11:12:14 -070012211 + " = " + agent);
12212
12213 synchronized(this) {
12214 if (!agentPackageName.equals(mBackupAppName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012215 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
Christopher Tate181fafa2009-05-14 11:12:14 -070012216 return;
12217 }
Dianne Hackborn06740692010-09-22 22:46:21 -070012218 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012219
Dianne Hackborn06740692010-09-22 22:46:21 -070012220 long oldIdent = Binder.clearCallingIdentity();
12221 try {
12222 IBackupManager bm = IBackupManager.Stub.asInterface(
12223 ServiceManager.getService(Context.BACKUP_SERVICE));
12224 bm.agentConnected(agentPackageName, agent);
12225 } catch (RemoteException e) {
12226 // can't happen; the backup manager service is local
12227 } catch (Exception e) {
12228 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: ");
12229 e.printStackTrace();
12230 } finally {
12231 Binder.restoreCallingIdentity(oldIdent);
Christopher Tate181fafa2009-05-14 11:12:14 -070012232 }
12233 }
12234
12235 // done with this agent
12236 public void unbindBackupAgent(ApplicationInfo appInfo) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012237 if (DEBUG_BACKUP) Slog.v(TAG, "unbindBackupAgent: " + appInfo);
Christopher Tate8a27f922009-06-26 11:49:18 -070012238 if (appInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012239 Slog.w(TAG, "unbind backup agent for null app");
Christopher Tate8a27f922009-06-26 11:49:18 -070012240 return;
12241 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012242
12243 synchronized(this) {
Christopher Tate8a27f922009-06-26 11:49:18 -070012244 if (mBackupAppName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012245 Slog.w(TAG, "Unbinding backup agent with no active backup");
Christopher Tate8a27f922009-06-26 11:49:18 -070012246 return;
12247 }
12248
Christopher Tate181fafa2009-05-14 11:12:14 -070012249 if (!mBackupAppName.equals(appInfo.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012250 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
Christopher Tate181fafa2009-05-14 11:12:14 -070012251 return;
12252 }
12253
Christopher Tate6fa95972009-06-05 18:43:55 -070012254 ProcessRecord proc = mBackupTarget.app;
12255 mBackupTarget = null;
12256 mBackupAppName = null;
12257
12258 // Not backing this app up any more; reset its OOM adjustment
12259 updateOomAdjLocked(proc);
12260
Christopher Tatec7b31e32009-06-10 15:49:30 -070012261 // If the app crashed during backup, 'thread' will be null here
12262 if (proc.thread != null) {
12263 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040012264 proc.thread.scheduleDestroyBackupAgent(appInfo,
12265 compatibilityInfoForPackageLocked(appInfo));
Christopher Tatec7b31e32009-06-10 15:49:30 -070012266 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012267 Slog.e(TAG, "Exception when unbinding backup agent:");
Christopher Tatec7b31e32009-06-10 15:49:30 -070012268 e.printStackTrace();
12269 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012270 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012271 }
12272 }
12273 // =========================================================
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012274 // BROADCASTS
12275 // =========================================================
12276
Josh Bartel7f208742010-02-25 11:01:44 -060012277 private final List getStickiesLocked(String action, IntentFilter filter,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012278 List cur) {
12279 final ContentResolver resolver = mContext.getContentResolver();
12280 final ArrayList<Intent> list = mStickyBroadcasts.get(action);
12281 if (list == null) {
12282 return cur;
12283 }
12284 int N = list.size();
12285 for (int i=0; i<N; i++) {
12286 Intent intent = list.get(i);
12287 if (filter.match(resolver, intent, true, TAG) >= 0) {
12288 if (cur == null) {
12289 cur = new ArrayList<Intent>();
12290 }
12291 cur.add(intent);
12292 }
12293 }
12294 return cur;
12295 }
12296
Christopher Tatef46723b2012-01-26 14:19:24 -080012297 boolean isPendingBroadcastProcessLocked(int pid) {
12298 return mFgBroadcastQueue.isPendingBroadcastProcessLocked(pid)
12299 || mBgBroadcastQueue.isPendingBroadcastProcessLocked(pid);
12300 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012301
Christopher Tatef46723b2012-01-26 14:19:24 -080012302 void skipPendingBroadcastLocked(int pid) {
12303 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
12304 for (BroadcastQueue queue : mBroadcastQueues) {
12305 queue.skipPendingBroadcastLocked(pid);
12306 }
12307 }
12308
12309 // The app just attached; send any pending broadcasts that it should receive
12310 boolean sendPendingBroadcastsLocked(ProcessRecord app) {
12311 boolean didSomething = false;
12312 for (BroadcastQueue queue : mBroadcastQueues) {
12313 didSomething |= queue.sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012314 }
Christopher Tatef46723b2012-01-26 14:19:24 -080012315 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012316 }
12317
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012318 public Intent registerReceiver(IApplicationThread caller, String callerPackage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012319 IIntentReceiver receiver, IntentFilter filter, String permission) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012320 enforceNotIsolatedCaller("registerReceiver");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012321 synchronized(this) {
12322 ProcessRecord callerApp = null;
12323 if (caller != null) {
12324 callerApp = getRecordForAppLocked(caller);
12325 if (callerApp == null) {
12326 throw new SecurityException(
12327 "Unable to find app for caller " + caller
12328 + " (pid=" + Binder.getCallingPid()
12329 + ") when registering receiver " + receiver);
12330 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012331 if (callerApp.info.uid != Process.SYSTEM_UID &&
12332 !callerApp.pkgList.contains(callerPackage)) {
12333 throw new SecurityException("Given caller package " + callerPackage
12334 + " is not running in process " + callerApp);
12335 }
12336 } else {
12337 callerPackage = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012338 }
12339
12340 List allSticky = null;
12341
12342 // Look for any matching sticky broadcasts...
12343 Iterator actions = filter.actionsIterator();
12344 if (actions != null) {
12345 while (actions.hasNext()) {
12346 String action = (String)actions.next();
Josh Bartel7f208742010-02-25 11:01:44 -060012347 allSticky = getStickiesLocked(action, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012348 }
12349 } else {
Josh Bartel7f208742010-02-25 11:01:44 -060012350 allSticky = getStickiesLocked(null, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012351 }
12352
12353 // The first sticky in the list is returned directly back to
12354 // the client.
12355 Intent sticky = allSticky != null ? (Intent)allSticky.get(0) : null;
12356
Joe Onorato8a9b2202010-02-26 18:56:32 -080012357 if (DEBUG_BROADCAST) Slog.v(TAG, "Register receiver " + filter
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012358 + ": " + sticky);
12359
12360 if (receiver == null) {
12361 return sticky;
12362 }
12363
12364 ReceiverList rl
12365 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
12366 if (rl == null) {
12367 rl = new ReceiverList(this, callerApp,
12368 Binder.getCallingPid(),
12369 Binder.getCallingUid(), receiver);
12370 if (rl.app != null) {
12371 rl.app.receivers.add(rl);
12372 } else {
12373 try {
12374 receiver.asBinder().linkToDeath(rl, 0);
12375 } catch (RemoteException e) {
12376 return sticky;
12377 }
12378 rl.linkedToDeath = true;
12379 }
12380 mRegisteredReceivers.put(receiver.asBinder(), rl);
12381 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012382 BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage, permission);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012383 rl.add(bf);
12384 if (!bf.debugCheck()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012385 Slog.w(TAG, "==> For Dynamic broadast");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012386 }
12387 mReceiverResolver.addFilter(bf);
12388
12389 // Enqueue broadcasts for all existing stickies that match
12390 // this filter.
12391 if (allSticky != null) {
12392 ArrayList receivers = new ArrayList();
12393 receivers.add(bf);
12394
12395 int N = allSticky.size();
12396 for (int i=0; i<N; i++) {
12397 Intent intent = (Intent)allSticky.get(i);
Christopher Tatef46723b2012-01-26 14:19:24 -080012398 BroadcastQueue queue = broadcastQueueForIntent(intent);
12399 BroadcastRecord r = new BroadcastRecord(queue, intent, null,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012400 null, -1, -1, null, receivers, null, 0, null, null,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012401 false, true, true);
Christopher Tatef46723b2012-01-26 14:19:24 -080012402 queue.enqueueParallelBroadcastLocked(r);
12403 queue.scheduleBroadcastsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012404 }
12405 }
12406
12407 return sticky;
12408 }
12409 }
12410
12411 public void unregisterReceiver(IIntentReceiver receiver) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012412 if (DEBUG_BROADCAST) Slog.v(TAG, "Unregister receiver: " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012413
Christopher Tatef46723b2012-01-26 14:19:24 -080012414 final long origId = Binder.clearCallingIdentity();
12415 try {
12416 boolean doTrim = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012417
Christopher Tatef46723b2012-01-26 14:19:24 -080012418 synchronized(this) {
12419 ReceiverList rl
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012420 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
Christopher Tatef46723b2012-01-26 14:19:24 -080012421 if (rl != null) {
12422 if (rl.curBroadcast != null) {
12423 BroadcastRecord r = rl.curBroadcast;
12424 final boolean doNext = finishReceiverLocked(
12425 receiver.asBinder(), r.resultCode, r.resultData,
12426 r.resultExtras, r.resultAbort, true);
12427 if (doNext) {
12428 doTrim = true;
12429 r.queue.processNextBroadcast(false);
12430 }
12431 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012432
Christopher Tatef46723b2012-01-26 14:19:24 -080012433 if (rl.app != null) {
12434 rl.app.receivers.remove(rl);
12435 }
12436 removeReceiverLocked(rl);
12437 if (rl.linkedToDeath) {
12438 rl.linkedToDeath = false;
12439 rl.receiver.asBinder().unlinkToDeath(rl, 0);
12440 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012441 }
12442 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012443
Christopher Tatef46723b2012-01-26 14:19:24 -080012444 // If we actually concluded any broadcasts, we might now be able
12445 // to trim the recipients' apps from our working set
12446 if (doTrim) {
12447 trimApplications();
12448 return;
12449 }
12450
12451 } finally {
12452 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012453 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012454 }
12455
12456 void removeReceiverLocked(ReceiverList rl) {
12457 mRegisteredReceivers.remove(rl.receiver.asBinder());
12458 int N = rl.size();
12459 for (int i=0; i<N; i++) {
12460 mReceiverResolver.removeFilter(rl.get(i));
12461 }
12462 }
12463
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012464 private final void sendPackageBroadcastLocked(int cmd, String[] packages) {
12465 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
12466 ProcessRecord r = mLruProcesses.get(i);
12467 if (r.thread != null) {
12468 try {
12469 r.thread.dispatchPackageBroadcast(cmd, packages);
12470 } catch (RemoteException ex) {
12471 }
12472 }
12473 }
12474 }
12475
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012476 private final int broadcastIntentLocked(ProcessRecord callerApp,
12477 String callerPackage, Intent intent, String resolvedType,
12478 IIntentReceiver resultTo, int resultCode, String resultData,
12479 Bundle map, String requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070012480 boolean ordered, boolean sticky, int callingPid, int callingUid,
12481 int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012482 intent = new Intent(intent);
12483
Dianne Hackborne7f97212011-02-24 14:40:20 -080012484 // By default broadcasts do not go to stopped apps.
12485 intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
12486
Joe Onorato8a9b2202010-02-26 18:56:32 -080012487 if (DEBUG_BROADCAST_LIGHT) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012488 TAG, (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
Amith Yamasani13593602012-03-22 16:16:17 -070012489 + " ordered=" + ordered + " userid=" + userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012490 if ((resultTo != null) && !ordered) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012491 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012492 }
12493
12494 // Handle special intents: if this broadcast is from the package
12495 // manager about a package being removed, we need to remove all of
12496 // its activities from the history stack.
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012497 final boolean uidRemoved = Intent.ACTION_UID_REMOVED.equals(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012498 intent.getAction());
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012499 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())
12500 || Intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction())
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080012501 || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012502 || uidRemoved) {
12503 if (checkComponentPermission(
12504 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080012505 callingPid, callingUid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012506 == PackageManager.PERMISSION_GRANTED) {
12507 if (uidRemoved) {
12508 final Bundle intentExtras = intent.getExtras();
12509 final int uid = intentExtras != null
12510 ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
12511 if (uid >= 0) {
12512 BatteryStatsImpl bs = mBatteryStatsService.getActiveStatistics();
12513 synchronized (bs) {
12514 bs.removeUidStatsLocked(uid);
12515 }
12516 }
12517 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012518 // If resources are unvailble just force stop all
12519 // those packages and flush the attribute cache as well.
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080012520 if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012521 String list[] = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
12522 if (list != null && (list.length > 0)) {
12523 for (String pkg : list) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070012524 forceStopPackageLocked(pkg, -1, false, true, true, false, userId);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012525 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012526 sendPackageBroadcastLocked(
12527 IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE, list);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012528 }
12529 } else {
12530 Uri data = intent.getData();
12531 String ssp;
12532 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
12533 if (!intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false)) {
12534 forceStopPackageLocked(ssp,
Amith Yamasani483f3b02012-03-13 16:08:00 -070012535 intent.getIntExtra(Intent.EXTRA_UID, -1), false, true, true,
12536 false, userId);
Dianne Hackbornde7faf62009-06-30 13:27:30 -070012537 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012538 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012539 sendPackageBroadcastLocked(IApplicationThread.PACKAGE_REMOVED,
12540 new String[] {ssp});
12541 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012542 }
12543 }
12544 }
12545 } else {
12546 String msg = "Permission Denial: " + intent.getAction()
12547 + " broadcast from " + callerPackage + " (pid=" + callingPid
12548 + ", uid=" + callingUid + ")"
12549 + " requires "
12550 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012551 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012552 throw new SecurityException(msg);
12553 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012554
12555 // Special case for adding a package: by default turn on compatibility
12556 // mode.
12557 } else if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -070012558 Uri data = intent.getData();
12559 String ssp;
12560 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
12561 mCompatModePackages.handlePackageAddedLocked(ssp,
12562 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false));
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012563 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012564 }
12565
12566 /*
12567 * If this is the time zone changed action, queue up a message that will reset the timezone
12568 * of all currently running processes. This message will get queued up before the broadcast
12569 * happens.
12570 */
12571 if (intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) {
12572 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
12573 }
12574
Robert Greenwalt03595d02010-11-02 14:08:23 -070012575 if (intent.ACTION_CLEAR_DNS_CACHE.equals(intent.getAction())) {
12576 mHandler.sendEmptyMessage(CLEAR_DNS_CACHE);
12577 }
12578
Robert Greenwalt434203a2010-10-11 16:00:27 -070012579 if (Proxy.PROXY_CHANGE_ACTION.equals(intent.getAction())) {
12580 ProxyProperties proxy = intent.getParcelableExtra("proxy");
12581 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY, proxy));
12582 }
12583
Dianne Hackborn854060af2009-07-09 18:14:31 -070012584 /*
12585 * Prevent non-system code (defined here to be non-persistent
12586 * processes) from sending protected broadcasts.
12587 */
12588 if (callingUid == Process.SYSTEM_UID || callingUid == Process.PHONE_UID
12589 || callingUid == Process.SHELL_UID || callingUid == 0) {
12590 // Always okay.
12591 } else if (callerApp == null || !callerApp.persistent) {
12592 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012593 if (AppGlobals.getPackageManager().isProtectedBroadcast(
Dianne Hackborn854060af2009-07-09 18:14:31 -070012594 intent.getAction())) {
12595 String msg = "Permission Denial: not allowed to send broadcast "
12596 + intent.getAction() + " from pid="
12597 + callingPid + ", uid=" + callingUid;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012598 Slog.w(TAG, msg);
Dianne Hackborn854060af2009-07-09 18:14:31 -070012599 throw new SecurityException(msg);
12600 }
12601 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012602 Slog.w(TAG, "Remote exception", e);
Dianne Hackborna4972e92012-03-14 10:38:05 -070012603 return ActivityManager.BROADCAST_SUCCESS;
Dianne Hackborn854060af2009-07-09 18:14:31 -070012604 }
12605 }
12606
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012607 // Add to the sticky list if requested.
12608 if (sticky) {
12609 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
12610 callingPid, callingUid)
12611 != PackageManager.PERMISSION_GRANTED) {
12612 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
12613 + callingPid + ", uid=" + callingUid
12614 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012615 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012616 throw new SecurityException(msg);
12617 }
12618 if (requiredPermission != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012619 Slog.w(TAG, "Can't broadcast sticky intent " + intent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012620 + " and enforce permission " + requiredPermission);
Dianne Hackborna4972e92012-03-14 10:38:05 -070012621 return ActivityManager.BROADCAST_STICKY_CANT_HAVE_PERMISSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012622 }
12623 if (intent.getComponent() != null) {
12624 throw new SecurityException(
12625 "Sticky broadcasts can't target a specific component");
12626 }
12627 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
12628 if (list == null) {
12629 list = new ArrayList<Intent>();
12630 mStickyBroadcasts.put(intent.getAction(), list);
12631 }
12632 int N = list.size();
12633 int i;
12634 for (i=0; i<N; i++) {
12635 if (intent.filterEquals(list.get(i))) {
12636 // This sticky already exists, replace it.
12637 list.set(i, new Intent(intent));
12638 break;
12639 }
12640 }
12641 if (i >= N) {
12642 list.add(new Intent(intent));
12643 }
12644 }
12645
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012646 // Figure out who all will receive this broadcast.
12647 List receivers = null;
12648 List<BroadcastFilter> registeredReceivers = null;
12649 try {
12650 if (intent.getComponent() != null) {
12651 // Broadcast is going to one specific receiver class...
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012652 ActivityInfo ai = AppGlobals.getPackageManager().
Amith Yamasani483f3b02012-03-13 16:08:00 -070012653 getReceiverInfo(intent.getComponent(), STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012654 if (ai != null) {
12655 receivers = new ArrayList();
12656 ResolveInfo ri = new ResolveInfo();
Amith Yamasani742a6712011-05-04 14:49:28 -070012657 ri.activityInfo = getActivityInfoForUser(ai, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012658 receivers.add(ri);
12659 }
12660 } else {
12661 // Need to resolve the intent to interested receivers...
12662 if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
12663 == 0) {
12664 receivers =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012665 AppGlobals.getPackageManager().queryIntentReceivers(
Amith Yamasani483f3b02012-03-13 16:08:00 -070012666 intent, resolvedType, STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012667 }
Amith Yamasani483f3b02012-03-13 16:08:00 -070012668 registeredReceivers = mReceiverResolver.queryIntent(intent, resolvedType, false,
12669 userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012670 }
12671 } catch (RemoteException ex) {
12672 // pm is in same process, this will never happen.
12673 }
12674
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012675 final boolean replacePending =
12676 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
12677
Joe Onorato8a9b2202010-02-26 18:56:32 -080012678 if (DEBUG_BROADCAST) Slog.v(TAG, "Enqueing broadcast: " + intent.getAction()
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012679 + " replacePending=" + replacePending);
12680
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012681 int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
12682 if (!ordered && NR > 0) {
12683 // If we are not serializing this broadcast, then send the
12684 // registered receivers separately so they don't wait for the
12685 // components to be launched.
Christopher Tatef46723b2012-01-26 14:19:24 -080012686 final BroadcastQueue queue = broadcastQueueForIntent(intent);
12687 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012688 callerPackage, callingPid, callingUid, requiredPermission,
12689 registeredReceivers, resultTo, resultCode, resultData, map,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012690 ordered, sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012691 if (DEBUG_BROADCAST) Slog.v(
Christopher Tatef46723b2012-01-26 14:19:24 -080012692 TAG, "Enqueueing parallel broadcast " + r);
12693 final boolean replaced = replacePending && queue.replaceParallelBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012694 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012695 queue.enqueueParallelBroadcastLocked(r);
12696 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012697 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012698 registeredReceivers = null;
12699 NR = 0;
12700 }
12701
12702 // Merge into one list.
12703 int ir = 0;
12704 if (receivers != null) {
12705 // A special case for PACKAGE_ADDED: do not allow the package
12706 // being added to see this broadcast. This prevents them from
12707 // using this as a back door to get run as soon as they are
12708 // installed. Maybe in the future we want to have a special install
12709 // broadcast or such for apps, but we'd like to deliberately make
12710 // this decision.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012711 String skipPackages[] = null;
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012712 if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
12713 || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
12714 || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012715 Uri data = intent.getData();
12716 if (data != null) {
12717 String pkgName = data.getSchemeSpecificPart();
12718 if (pkgName != null) {
12719 skipPackages = new String[] { pkgName };
12720 }
12721 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012722 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012723 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
The Android Open Source Project10592532009-03-18 17:39:46 -070012724 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012725 if (skipPackages != null && (skipPackages.length > 0)) {
12726 for (String skipPackage : skipPackages) {
12727 if (skipPackage != null) {
12728 int NT = receivers.size();
12729 for (int it=0; it<NT; it++) {
12730 ResolveInfo curt = (ResolveInfo)receivers.get(it);
12731 if (curt.activityInfo.packageName.equals(skipPackage)) {
12732 receivers.remove(it);
12733 it--;
12734 NT--;
12735 }
12736 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012737 }
12738 }
12739 }
12740
12741 int NT = receivers != null ? receivers.size() : 0;
12742 int it = 0;
12743 ResolveInfo curt = null;
12744 BroadcastFilter curr = null;
12745 while (it < NT && ir < NR) {
12746 if (curt == null) {
12747 curt = (ResolveInfo)receivers.get(it);
12748 }
12749 if (curr == null) {
12750 curr = registeredReceivers.get(ir);
12751 }
12752 if (curr.getPriority() >= curt.priority) {
12753 // Insert this broadcast record into the final list.
12754 receivers.add(it, curr);
12755 ir++;
12756 curr = null;
12757 it++;
12758 NT++;
12759 } else {
12760 // Skip to the next ResolveInfo in the final list.
12761 it++;
12762 curt = null;
12763 }
12764 }
12765 }
12766 while (ir < NR) {
12767 if (receivers == null) {
12768 receivers = new ArrayList();
12769 }
12770 receivers.add(registeredReceivers.get(ir));
12771 ir++;
12772 }
12773
12774 if ((receivers != null && receivers.size() > 0)
12775 || resultTo != null) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012776 BroadcastQueue queue = broadcastQueueForIntent(intent);
12777 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012778 callerPackage, callingPid, callingUid, requiredPermission,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012779 receivers, resultTo, resultCode, resultData, map, ordered,
12780 sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012781 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012782 TAG, "Enqueueing ordered broadcast " + r
Christopher Tatef46723b2012-01-26 14:19:24 -080012783 + ": prev had " + queue.mOrderedBroadcasts.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012784 if (DEBUG_BROADCAST) {
12785 int seq = r.intent.getIntExtra("seq", -1);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012786 Slog.i(TAG, "Enqueueing broadcast " + r.intent.getAction() + " seq=" + seq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012787 }
Christopher Tatef46723b2012-01-26 14:19:24 -080012788 boolean replaced = replacePending && queue.replaceOrderedBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012789 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012790 queue.enqueueOrderedBroadcastLocked(r);
12791 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012792 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012793 }
12794
Dianne Hackborna4972e92012-03-14 10:38:05 -070012795 return ActivityManager.BROADCAST_SUCCESS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012796 }
12797
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012798 final Intent verifyBroadcastLocked(Intent intent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012799 // Refuse possible leaked file descriptors
12800 if (intent != null && intent.hasFileDescriptors() == true) {
12801 throw new IllegalArgumentException("File descriptors passed in Intent");
12802 }
12803
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012804 int flags = intent.getFlags();
12805
12806 if (!mProcessesReady) {
12807 // if the caller really truly claims to know what they're doing, go
12808 // ahead and allow the broadcast without launching any receivers
12809 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
12810 intent = new Intent(intent);
12811 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
12812 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
12813 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
12814 + " before boot completion");
12815 throw new IllegalStateException("Cannot broadcast before boot completed");
12816 }
12817 }
12818
12819 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
12820 throw new IllegalArgumentException(
12821 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
12822 }
12823
12824 return intent;
12825 }
12826
12827 public final int broadcastIntent(IApplicationThread caller,
12828 Intent intent, String resolvedType, IIntentReceiver resultTo,
12829 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070012830 String requiredPermission, boolean serialized, boolean sticky, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012831 enforceNotIsolatedCaller("broadcastIntent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012832 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012833 intent = verifyBroadcastLocked(intent);
Dianne Hackborn9acc0302009-08-25 00:27:12 -070012834
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012835 final ProcessRecord callerApp = getRecordForAppLocked(caller);
12836 final int callingPid = Binder.getCallingPid();
12837 final int callingUid = Binder.getCallingUid();
12838 final long origId = Binder.clearCallingIdentity();
12839 int res = broadcastIntentLocked(callerApp,
12840 callerApp != null ? callerApp.info.packageName : null,
12841 intent, resolvedType, resultTo,
Amith Yamasani742a6712011-05-04 14:49:28 -070012842 resultCode, resultData, map, requiredPermission, serialized, sticky,
12843 callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012844 Binder.restoreCallingIdentity(origId);
12845 return res;
12846 }
12847 }
12848
12849 int broadcastIntentInPackage(String packageName, int uid,
12850 Intent intent, String resolvedType, IIntentReceiver resultTo,
12851 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070012852 String requiredPermission, boolean serialized, boolean sticky, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012853 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012854 intent = verifyBroadcastLocked(intent);
12855
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012856 final long origId = Binder.clearCallingIdentity();
12857 int res = broadcastIntentLocked(null, packageName, intent, resolvedType,
12858 resultTo, resultCode, resultData, map, requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070012859 serialized, sticky, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012860 Binder.restoreCallingIdentity(origId);
12861 return res;
12862 }
12863 }
12864
Amith Yamasani742a6712011-05-04 14:49:28 -070012865 // TODO: Use the userId; maybe mStickyBroadcasts need to be tied to the user.
12866 public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012867 // Refuse possible leaked file descriptors
12868 if (intent != null && intent.hasFileDescriptors() == true) {
12869 throw new IllegalArgumentException("File descriptors passed in Intent");
12870 }
12871
12872 synchronized(this) {
12873 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
12874 != PackageManager.PERMISSION_GRANTED) {
12875 String msg = "Permission Denial: unbroadcastIntent() from pid="
12876 + Binder.getCallingPid()
12877 + ", uid=" + Binder.getCallingUid()
12878 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012879 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012880 throw new SecurityException(msg);
12881 }
12882 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
12883 if (list != null) {
12884 int N = list.size();
12885 int i;
12886 for (i=0; i<N; i++) {
12887 if (intent.filterEquals(list.get(i))) {
12888 list.remove(i);
12889 break;
12890 }
12891 }
12892 }
12893 }
12894 }
12895
12896 private final boolean finishReceiverLocked(IBinder receiver, int resultCode,
12897 String resultData, Bundle resultExtras, boolean resultAbort,
12898 boolean explicit) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012899 final BroadcastRecord r = broadcastRecordForReceiverLocked(receiver);
12900 if (r == null) {
12901 Slog.w(TAG, "finishReceiver called but not found on queue");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012902 return false;
12903 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012904
Christopher Tatef46723b2012-01-26 14:19:24 -080012905 return r.queue.finishReceiverLocked(r, resultCode, resultData, resultExtras, resultAbort,
12906 explicit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012907 }
12908
12909 public void finishReceiver(IBinder who, int resultCode, String resultData,
12910 Bundle resultExtras, boolean resultAbort) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012911 if (DEBUG_BROADCAST) Slog.v(TAG, "Finish receiver: " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012912
12913 // Refuse possible leaked file descriptors
12914 if (resultExtras != null && resultExtras.hasFileDescriptors()) {
12915 throw new IllegalArgumentException("File descriptors passed in Bundle");
12916 }
12917
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012918 final long origId = Binder.clearCallingIdentity();
Christopher Tatef46723b2012-01-26 14:19:24 -080012919 try {
12920 boolean doNext = false;
12921 BroadcastRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012922
Christopher Tatef46723b2012-01-26 14:19:24 -080012923 synchronized(this) {
12924 r = broadcastRecordForReceiverLocked(who);
12925 if (r != null) {
12926 doNext = r.queue.finishReceiverLocked(r, resultCode,
12927 resultData, resultExtras, resultAbort, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012928 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012929 }
Jeff Brown4d94a762010-09-23 11:33:28 -070012930
Christopher Tatef46723b2012-01-26 14:19:24 -080012931 if (doNext) {
12932 r.queue.processNextBroadcast(false);
12933 }
12934 trimApplications();
12935 } finally {
12936 Binder.restoreCallingIdentity(origId);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012937 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012938 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012939
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012940 // =========================================================
12941 // INSTRUMENTATION
12942 // =========================================================
12943
12944 public boolean startInstrumentation(ComponentName className,
12945 String profileFile, int flags, Bundle arguments,
12946 IInstrumentationWatcher watcher) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012947 enforceNotIsolatedCaller("startInstrumentation");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012948 // Refuse possible leaked file descriptors
12949 if (arguments != null && arguments.hasFileDescriptors()) {
12950 throw new IllegalArgumentException("File descriptors passed in Bundle");
12951 }
12952
12953 synchronized(this) {
12954 InstrumentationInfo ii = null;
12955 ApplicationInfo ai = null;
12956 try {
12957 ii = mContext.getPackageManager().getInstrumentationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070012958 className, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012959 ai = mContext.getPackageManager().getApplicationInfo(
Amith Yamasani483f3b02012-03-13 16:08:00 -070012960 ii.targetPackage, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012961 } catch (PackageManager.NameNotFoundException e) {
12962 }
12963 if (ii == null) {
12964 reportStartInstrumentationFailure(watcher, className,
12965 "Unable to find instrumentation info for: " + className);
12966 return false;
12967 }
12968 if (ai == null) {
12969 reportStartInstrumentationFailure(watcher, className,
12970 "Unable to find instrumentation target package: " + ii.targetPackage);
12971 return false;
12972 }
12973
12974 int match = mContext.getPackageManager().checkSignatures(
12975 ii.targetPackage, ii.packageName);
12976 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
12977 String msg = "Permission Denial: starting instrumentation "
12978 + className + " from pid="
12979 + Binder.getCallingPid()
12980 + ", uid=" + Binder.getCallingPid()
12981 + " not allowed because package " + ii.packageName
12982 + " does not have a signature matching the target "
12983 + ii.targetPackage;
12984 reportStartInstrumentationFailure(watcher, className, msg);
12985 throw new SecurityException(msg);
12986 }
12987
Amith Yamasani483f3b02012-03-13 16:08:00 -070012988 int userId = UserId.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012989 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -070012990 // Instrumentation can kill and relaunch even persistent processes
Amith Yamasani483f3b02012-03-13 16:08:00 -070012991 forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true, userId);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080012992 ProcessRecord app = addAppLocked(ai, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012993 app.instrumentationClass = className;
Dianne Hackborn1655be42009-05-08 14:29:01 -070012994 app.instrumentationInfo = ai;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012995 app.instrumentationProfileFile = profileFile;
12996 app.instrumentationArguments = arguments;
12997 app.instrumentationWatcher = watcher;
12998 app.instrumentationResultClass = className;
12999 Binder.restoreCallingIdentity(origId);
13000 }
13001
13002 return true;
13003 }
13004
13005 /**
13006 * Report errors that occur while attempting to start Instrumentation. Always writes the
13007 * error to the logs, but if somebody is watching, send the report there too. This enables
13008 * the "am" command to report errors with more information.
13009 *
13010 * @param watcher The IInstrumentationWatcher. Null if there isn't one.
13011 * @param cn The component name of the instrumentation.
13012 * @param report The error report.
13013 */
13014 private void reportStartInstrumentationFailure(IInstrumentationWatcher watcher,
13015 ComponentName cn, String report) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013016 Slog.w(TAG, report);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013017 try {
13018 if (watcher != null) {
13019 Bundle results = new Bundle();
13020 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
13021 results.putString("Error", report);
13022 watcher.instrumentationStatus(cn, -1, results);
13023 }
13024 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013025 Slog.w(TAG, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013026 }
13027 }
13028
13029 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
13030 if (app.instrumentationWatcher != null) {
13031 try {
13032 // NOTE: IInstrumentationWatcher *must* be oneway here
13033 app.instrumentationWatcher.instrumentationFinished(
13034 app.instrumentationClass,
13035 resultCode,
13036 results);
13037 } catch (RemoteException e) {
13038 }
13039 }
13040 app.instrumentationWatcher = null;
13041 app.instrumentationClass = null;
Dianne Hackborn1655be42009-05-08 14:29:01 -070013042 app.instrumentationInfo = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013043 app.instrumentationProfileFile = null;
13044 app.instrumentationArguments = null;
13045
Amith Yamasani483f3b02012-03-13 16:08:00 -070013046 forceStopPackageLocked(app.processName, -1, false, false, true, true, app.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013047 }
13048
13049 public void finishInstrumentation(IApplicationThread target,
13050 int resultCode, Bundle results) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070013051 int userId = UserId.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013052 // Refuse possible leaked file descriptors
13053 if (results != null && results.hasFileDescriptors()) {
13054 throw new IllegalArgumentException("File descriptors passed in Intent");
13055 }
13056
13057 synchronized(this) {
13058 ProcessRecord app = getRecordForAppLocked(target);
13059 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013060 Slog.w(TAG, "finishInstrumentation: no app for " + target);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013061 return;
13062 }
13063 final long origId = Binder.clearCallingIdentity();
13064 finishInstrumentationLocked(app, resultCode, results);
13065 Binder.restoreCallingIdentity(origId);
13066 }
13067 }
13068
13069 // =========================================================
13070 // CONFIGURATION
13071 // =========================================================
13072
13073 public ConfigurationInfo getDeviceConfigurationInfo() {
13074 ConfigurationInfo config = new ConfigurationInfo();
13075 synchronized (this) {
13076 config.reqTouchScreen = mConfiguration.touchscreen;
13077 config.reqKeyboardType = mConfiguration.keyboard;
13078 config.reqNavigation = mConfiguration.navigation;
Dianne Hackbornfae76f52009-07-16 13:41:23 -070013079 if (mConfiguration.navigation == Configuration.NAVIGATION_DPAD
13080 || mConfiguration.navigation == Configuration.NAVIGATION_TRACKBALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013081 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
13082 }
Dianne Hackbornfae76f52009-07-16 13:41:23 -070013083 if (mConfiguration.keyboard != Configuration.KEYBOARD_UNDEFINED
13084 && mConfiguration.keyboard != Configuration.KEYBOARD_NOKEYS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013085 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
13086 }
Jack Palevichb90d28c2009-07-22 15:35:24 -070013087 config.reqGlEsVersion = GL_ES_VERSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013088 }
13089 return config;
13090 }
13091
13092 public Configuration getConfiguration() {
13093 Configuration ci;
13094 synchronized(this) {
13095 ci = new Configuration(mConfiguration);
13096 }
13097 return ci;
13098 }
13099
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013100 public void updatePersistentConfiguration(Configuration values) {
13101 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
13102 "updateConfiguration()");
13103 enforceCallingPermission(android.Manifest.permission.WRITE_SETTINGS,
13104 "updateConfiguration()");
13105 if (values == null) {
13106 throw new NullPointerException("Configuration must not be null");
13107 }
13108
13109 synchronized(this) {
13110 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn813075a62011-11-14 17:45:19 -080013111 updateConfigurationLocked(values, null, true, false);
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013112 Binder.restoreCallingIdentity(origId);
13113 }
13114 }
13115
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013116 public void updateConfiguration(Configuration values) {
13117 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
13118 "updateConfiguration()");
13119
13120 synchronized(this) {
13121 if (values == null && mWindowManager != null) {
13122 // sentinel: fetch the current configuration from the window manager
13123 values = mWindowManager.computeNewConfiguration();
13124 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013125
13126 if (mWindowManager != null) {
13127 mProcessList.applyDisplaySize(mWindowManager);
13128 }
13129
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013130 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013131 if (values != null) {
13132 Settings.System.clearConfiguration(values);
13133 }
Dianne Hackborn813075a62011-11-14 17:45:19 -080013134 updateConfigurationLocked(values, null, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013135 Binder.restoreCallingIdentity(origId);
13136 }
13137 }
13138
13139 /**
13140 * Do either or both things: (1) change the current configuration, and (2)
13141 * make sure the given activity is running with the (now) current
13142 * configuration. Returns true if the activity has been left running, or
13143 * false if <var>starting</var> is being destroyed to match the new
13144 * configuration.
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013145 * @param persistent TODO
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013146 */
Dianne Hackborna573f6a2012-02-09 16:12:18 -080013147 boolean updateConfigurationLocked(Configuration values,
Dianne Hackborn813075a62011-11-14 17:45:19 -080013148 ActivityRecord starting, boolean persistent, boolean initLocale) {
Mike Lockwood3a74bd32011-08-12 13:55:22 -070013149 // do nothing if we are headless
13150 if (mHeadless) return true;
13151
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013152 int changes = 0;
13153
13154 boolean kept = true;
13155
13156 if (values != null) {
13157 Configuration newConfig = new Configuration(mConfiguration);
13158 changes = newConfig.updateFrom(values);
13159 if (changes != 0) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013160 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013161 Slog.i(TAG, "Updating configuration to: " + values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013162 }
13163
Doug Zongker2bec3d42009-12-04 12:52:44 -080013164 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013165
Dianne Hackborn813075a62011-11-14 17:45:19 -080013166 if (values.locale != null && !initLocale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013167 saveLocaleLocked(values.locale,
13168 !values.locale.equals(mConfiguration.locale),
13169 values.userSetLocale);
13170 }
13171
Dianne Hackborne36d6e22010-02-17 19:46:25 -080013172 mConfigurationSeq++;
13173 if (mConfigurationSeq <= 0) {
13174 mConfigurationSeq = 1;
13175 }
13176 newConfig.seq = mConfigurationSeq;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013177 mConfiguration = newConfig;
Joe Onorato8a9b2202010-02-26 18:56:32 -080013178 Slog.i(TAG, "Config changed: " + newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013179
13180 final Configuration configCopy = new Configuration(mConfiguration);
Joe Onorato54a4a412011-11-02 20:50:08 -070013181
13182 // TODO: If our config changes, should we auto dismiss any currently
13183 // showing dialogs?
13184 mShowDialogs = shouldShowDialogs(newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013185
Dianne Hackborn826d17c2009-11-12 12:55:51 -080013186 AttributeCache ac = AttributeCache.instance();
13187 if (ac != null) {
Dianne Hackborn813075a62011-11-14 17:45:19 -080013188 ac.updateConfiguration(configCopy);
Dianne Hackborn826d17c2009-11-12 12:55:51 -080013189 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013190
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070013191 // Make sure all resources in our process are updated
13192 // right now, so that anyone who is going to retrieve
13193 // resource values after we return will be sure to get
13194 // the new ones. This is especially important during
13195 // boot, where the first config change needs to guarantee
13196 // all resources have that config before following boot
13197 // code is executed.
Dianne Hackborn813075a62011-11-14 17:45:19 -080013198 mSystemThread.applyConfigurationToResources(configCopy);
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070013199
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013200 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080013201 Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013202 msg.obj = new Configuration(configCopy);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080013203 mHandler.sendMessage(msg);
13204 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013205
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013206 for (int i=mLruProcesses.size()-1; i>=0; i--) {
13207 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013208 try {
13209 if (app.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013210 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending to proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013211 + app.processName + " new config " + mConfiguration);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013212 app.thread.scheduleConfigurationChanged(configCopy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013213 }
13214 } catch (Exception e) {
13215 }
13216 }
13217 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080013218 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
13219 | Intent.FLAG_RECEIVER_REPLACE_PENDING);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013220 broadcastIntentLocked(null, null, intent, null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070013221 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080013222 if ((changes&ActivityInfo.CONFIG_LOCALE) != 0) {
13223 broadcastIntentLocked(null, null,
13224 new Intent(Intent.ACTION_LOCALE_CHANGED),
13225 null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070013226 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080013227 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013228 }
13229 }
13230
13231 if (changes != 0 && starting == null) {
13232 // If the configuration changed, and the caller is not already
13233 // in the process of starting an activity, then find the top
13234 // activity to check if its configuration needs to change.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013235 starting = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013236 }
13237
13238 if (starting != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013239 kept = mMainStack.ensureActivityConfigurationLocked(starting, changes);
Dianne Hackborn5f4d6432010-12-21 20:40:11 -080013240 // And we need to make sure at this point that all other activities
13241 // are made visible with the correct configuration.
13242 mMainStack.ensureActivitiesVisibleLocked(starting, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013243 }
13244
Dianne Hackborne36d6e22010-02-17 19:46:25 -080013245 if (values != null && mWindowManager != null) {
13246 mWindowManager.setNewConfiguration(mConfiguration);
13247 }
13248
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013249 return kept;
13250 }
Joe Onorato54a4a412011-11-02 20:50:08 -070013251
13252 /**
13253 * Decide based on the configuration whether we should shouw the ANR,
13254 * crash, etc dialogs. The idea is that if there is no affordnace to
13255 * press the on-screen buttons, we shouldn't show the dialog.
13256 *
13257 * A thought: SystemUI might also want to get told about this, the Power
13258 * dialog / global actions also might want different behaviors.
13259 */
13260 private static final boolean shouldShowDialogs(Configuration config) {
13261 return !(config.keyboard == Configuration.KEYBOARD_NOKEYS
13262 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH);
13263 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013264
13265 /**
13266 * Save the locale. You must be inside a synchronized (this) block.
13267 */
13268 private void saveLocaleLocked(Locale l, boolean isDiff, boolean isPersist) {
13269 if(isDiff) {
13270 SystemProperties.set("user.language", l.getLanguage());
13271 SystemProperties.set("user.region", l.getCountry());
13272 }
13273
13274 if(isPersist) {
13275 SystemProperties.set("persist.sys.language", l.getLanguage());
13276 SystemProperties.set("persist.sys.country", l.getCountry());
13277 SystemProperties.set("persist.sys.localevar", l.getVariant());
13278 }
13279 }
13280
13281 // =========================================================
13282 // LIFETIME MANAGEMENT
13283 // =========================================================
13284
Christopher Tatef46723b2012-01-26 14:19:24 -080013285 // Returns which broadcast queue the app is the current [or imminent] receiver
13286 // on, or 'null' if the app is not an active broadcast recipient.
13287 private BroadcastQueue isReceivingBroadcast(ProcessRecord app) {
13288 BroadcastRecord r = app.curReceiver;
13289 if (r != null) {
13290 return r.queue;
13291 }
13292
13293 // It's not the current receiver, but it might be starting up to become one
13294 synchronized (this) {
13295 for (BroadcastQueue queue : mBroadcastQueues) {
13296 r = queue.mPendingBroadcast;
13297 if (r != null && r.curApp == app) {
13298 // found it; report which queue it's in
13299 return queue;
13300 }
13301 }
13302 }
13303
13304 return null;
13305 }
13306
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013307 private final int computeOomAdjLocked(ProcessRecord app, int hiddenAdj,
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013308 ProcessRecord TOP_APP, boolean recursed, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013309 if (mAdjSeq == app.adjSeq) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013310 // This adjustment has already been computed. If we are calling
13311 // from the top, we may have already computed our adjustment with
13312 // an earlier hidden adjustment that isn't really for us... if
13313 // so, use the new hidden adjustment.
13314 if (!recursed && app.hidden) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013315 app.curAdj = app.curRawAdj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013316 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013317 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013318 }
13319
13320 if (app.thread == null) {
13321 app.adjSeq = mAdjSeq;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013322 app.curSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013323 return (app.curAdj=ProcessList.HIDDEN_APP_MAX_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013324 }
13325
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013326 app.adjTypeCode = ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN;
13327 app.adjSource = null;
13328 app.adjTarget = null;
13329 app.empty = false;
13330 app.hidden = false;
13331
13332 final int activitiesSize = app.activities.size();
13333
Dianne Hackborn7d608422011-08-07 16:24:18 -070013334 if (app.maxAdj <= ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013335 // The max adjustment doesn't allow this app to be anything
13336 // below foreground, so it is not worth doing work for it.
13337 app.adjType = "fixed";
13338 app.adjSeq = mAdjSeq;
13339 app.curRawAdj = app.maxAdj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013340 app.foregroundActivities = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013341 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013342 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013343 // System process can do UI, and when they do we want to have
13344 // them trim their memory after the user leaves the UI. To
13345 // facilitate this, here we need to determine whether or not it
13346 // is currently showing UI.
13347 app.systemNoUi = true;
13348 if (app == TOP_APP) {
13349 app.systemNoUi = false;
13350 } else if (activitiesSize > 0) {
13351 for (int j = 0; j < activitiesSize; j++) {
13352 final ActivityRecord r = app.activities.get(j);
13353 if (r.visible) {
13354 app.systemNoUi = false;
13355 break;
13356 }
13357 }
13358 }
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013359 return (app.curAdj=app.maxAdj);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013360 }
13361
13362 final boolean hadForegroundActivities = app.foregroundActivities;
13363
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013364 app.foregroundActivities = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013365 app.keeping = false;
13366 app.systemNoUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013367
The Android Open Source Project4df24232009-03-05 14:34:35 -080013368 // Determine the importance of the process, starting with most
13369 // important to least, and assign an appropriate OOM adjustment.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013370 int adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013371 int schedGroup;
Christopher Tatef46723b2012-01-26 14:19:24 -080013372 BroadcastQueue queue;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013373 if (app == TOP_APP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013374 // The last app on the list is the foreground app.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013375 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013376 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013377 app.adjType = "top-activity";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013378 app.foregroundActivities = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013379 } else if (app.instrumentationClass != null) {
13380 // Don't want to kill running instrumentation.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013381 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013382 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013383 app.adjType = "instrumentation";
Christopher Tatef46723b2012-01-26 14:19:24 -080013384 } else if ((queue = isReceivingBroadcast(app)) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013385 // An app that is currently receiving a broadcast also
Christopher Tatef46723b2012-01-26 14:19:24 -080013386 // counts as being in the foreground for OOM killer purposes.
13387 // It's placed in a sched group based on the nature of the
13388 // broadcast as reflected by which queue it's active in.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013389 adj = ProcessList.FOREGROUND_APP_ADJ;
Christopher Tatef46723b2012-01-26 14:19:24 -080013390 schedGroup = (queue == mFgBroadcastQueue)
13391 ? Process.THREAD_GROUP_DEFAULT : Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013392 app.adjType = "broadcast";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013393 } else if (app.executingServices.size() > 0) {
13394 // An app that is currently executing a service callback also
13395 // counts as being in the foreground.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013396 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013397 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013398 app.adjType = "exec-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013399 } else if (activitiesSize > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013400 // This app is in the background with paused activities.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013401 // We inspect activities to potentially upgrade adjustment further below.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013402 adj = hiddenAdj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013403 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013404 app.hidden = true;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013405 app.adjType = "bg-activities";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013406 } else {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013407 // A very not-needed process. If this is lower in the lru list,
13408 // we will push it in to the empty bucket.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013409 adj = hiddenAdj;
13410 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013411 app.hidden = true;
13412 app.empty = true;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013413 app.adjType = "bg-empty";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013414 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013415
13416 // Examine all activities if not already foreground.
13417 if (!app.foregroundActivities && activitiesSize > 0) {
13418 for (int j = 0; j < activitiesSize; j++) {
13419 final ActivityRecord r = app.activities.get(j);
13420 if (r.visible) {
13421 // App has a visible activity; only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013422 if (adj > ProcessList.VISIBLE_APP_ADJ) {
13423 adj = ProcessList.VISIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013424 app.adjType = "visible";
13425 }
13426 schedGroup = Process.THREAD_GROUP_DEFAULT;
13427 app.hidden = false;
13428 app.foregroundActivities = true;
13429 break;
13430 } else if (r.state == ActivityState.PAUSING || r.state == ActivityState.PAUSED
13431 || r.state == ActivityState.STOPPING) {
13432 // Only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013433 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13434 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013435 app.adjType = "stopping";
13436 }
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -080013437 app.hidden = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013438 app.foregroundActivities = true;
13439 }
13440 }
13441 }
13442
Dianne Hackborn7d608422011-08-07 16:24:18 -070013443 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013444 if (app.foregroundServices) {
13445 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013446 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013447 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013448 app.adjType = "foreground-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013449 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013450 } else if (app.forcingToForeground != null) {
13451 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013452 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013453 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013454 app.adjType = "force-foreground";
13455 app.adjSource = app.forcingToForeground;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013456 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013457 }
13458 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013459
Dianne Hackborn7d608422011-08-07 16:24:18 -070013460 if (adj > ProcessList.HEAVY_WEIGHT_APP_ADJ && app == mHeavyWeightProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013461 // We don't want to kill the current heavy-weight process.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013462 adj = ProcessList.HEAVY_WEIGHT_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013463 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013464 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013465 app.adjType = "heavy";
13466 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013467
Dianne Hackborn7d608422011-08-07 16:24:18 -070013468 if (adj > ProcessList.HOME_APP_ADJ && app == mHomeProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013469 // This process is hosting what we currently consider to be the
13470 // home app, so we don't want to let it go into the background.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013471 adj = ProcessList.HOME_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013472 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013473 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013474 app.adjType = "home";
13475 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013476
Dianne Hackbornf35fe232011-11-01 19:25:20 -070013477 if (adj > ProcessList.PREVIOUS_APP_ADJ && app == mPreviousProcess
13478 && app.activities.size() > 0) {
13479 // This was the previous process that showed UI to the user.
13480 // We want to try to keep it around more aggressively, to give
13481 // a good experience around switching between two apps.
13482 adj = ProcessList.PREVIOUS_APP_ADJ;
13483 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
13484 app.hidden = false;
13485 app.adjType = "previous";
13486 }
13487
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013488 if (false) Slog.i(TAG, "OOM " + app + ": initial adj=" + adj
13489 + " reason=" + app.adjType);
13490
The Android Open Source Project4df24232009-03-05 14:34:35 -080013491 // By default, we use the computed adjustment. It may be changed if
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013492 // there are applications dependent on our services or providers, but
13493 // this gives us a baseline and makes sure we don't get into an
13494 // infinite recursion.
13495 app.adjSeq = mAdjSeq;
13496 app.curRawAdj = adj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013497
Christopher Tate6fa95972009-06-05 18:43:55 -070013498 if (mBackupTarget != null && app == mBackupTarget.app) {
13499 // If possible we want to avoid killing apps while they're being backed up
Dianne Hackborn7d608422011-08-07 16:24:18 -070013500 if (adj > ProcessList.BACKUP_APP_ADJ) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013501 if (DEBUG_BACKUP) Slog.v(TAG, "oom BACKUP_APP_ADJ for " + app);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013502 adj = ProcessList.BACKUP_APP_ADJ;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013503 app.adjType = "backup";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013504 app.hidden = false;
Christopher Tate6fa95972009-06-05 18:43:55 -070013505 }
13506 }
13507
Dianne Hackborn7d608422011-08-07 16:24:18 -070013508 if (app.services.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013509 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013510 final long now = SystemClock.uptimeMillis();
13511 // This process is more important if the top activity is
13512 // bound to the service.
Dianne Hackborn860755f2010-06-03 18:47:52 -070013513 Iterator<ServiceRecord> jt = app.services.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013514 while (jt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013515 ServiceRecord s = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013516 if (s.startRequested) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013517 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013518 // If this process has shown some UI, let it immediately
13519 // go to the LRU list because it may be pretty heavy with
13520 // UI stuff. We'll tag it with a label just to help
13521 // debug and understand what is going on.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013522 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013523 app.adjType = "started-bg-ui-services";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013524 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013525 } else {
13526 if (now < (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
13527 // This service has seen some activity within
13528 // recent memory, so we will keep its process ahead
13529 // of the background processes.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013530 if (adj > ProcessList.SERVICE_ADJ) {
13531 adj = ProcessList.SERVICE_ADJ;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013532 app.adjType = "started-services";
13533 app.hidden = false;
13534 }
13535 }
13536 // If we have let the service slide into the background
13537 // state, still have some text describing what it is doing
13538 // even though the service no longer has an impact.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013539 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013540 app.adjType = "started-bg-services";
13541 }
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080013542 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013543 // Don't kill this process because it is doing work; it
13544 // has said it is doing work.
13545 app.keeping = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013546 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013547 if (s.connections.size() > 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013548 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013549 Iterator<ArrayList<ConnectionRecord>> kt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013550 = s.connections.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013551 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013552 ArrayList<ConnectionRecord> clist = kt.next();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013553 for (int i=0; i<clist.size() && adj > ProcessList.FOREGROUND_APP_ADJ; i++) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013554 // XXX should compute this based on the max of
13555 // all connected clients.
13556 ConnectionRecord cr = clist.get(i);
13557 if (cr.binding.client == app) {
13558 // Binding to ourself is not interesting.
13559 continue;
13560 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013561 if ((cr.flags&Context.BIND_WAIVE_PRIORITY) == 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013562 ProcessRecord client = cr.binding.client;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013563 int clientAdj = adj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013564 int myHiddenAdj = hiddenAdj;
13565 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013566 if (client.hiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013567 myHiddenAdj = client.hiddenAdj;
13568 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013569 myHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013570 }
13571 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013572 clientAdj = computeOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013573 client, myHiddenAdj, TOP_APP, true, doingAll);
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013574 String adjType = null;
13575 if ((cr.flags&Context.BIND_ALLOW_OOM_MANAGEMENT) != 0) {
13576 // Not doing bind OOM management, so treat
13577 // this guy more like a started service.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013578 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013579 // If this process has shown some UI, let it immediately
13580 // go to the LRU list because it may be pretty heavy with
13581 // UI stuff. We'll tag it with a label just to help
13582 // debug and understand what is going on.
13583 if (adj > clientAdj) {
13584 adjType = "bound-bg-ui-services";
13585 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013586 app.hidden = false;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013587 clientAdj = adj;
13588 } else {
13589 if (now >= (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
13590 // This service has not seen activity within
13591 // recent memory, so allow it to drop to the
13592 // LRU list if there is no other reason to keep
13593 // it around. We'll also tag it with a label just
13594 // to help debug and undertand what is going on.
13595 if (adj > clientAdj) {
13596 adjType = "bound-bg-services";
13597 }
13598 clientAdj = adj;
13599 }
13600 }
13601 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013602 if (adj > clientAdj) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013603 // If this process has recently shown UI, and
13604 // the process that is binding to it is less
13605 // important than being visible, then we don't
13606 // care about the binding as much as we care
13607 // about letting this process get into the LRU
13608 // list to be killed and restarted if needed for
13609 // memory.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013610 if (app.hasShownUi && app != mHomeProcess
13611 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013612 adjType = "bound-bg-ui-services";
13613 } else {
13614 if ((cr.flags&(Context.BIND_ABOVE_CLIENT
13615 |Context.BIND_IMPORTANT)) != 0) {
13616 adj = clientAdj;
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070013617 } else if ((cr.flags&Context.BIND_NOT_VISIBLE) != 0
13618 && clientAdj < ProcessList.PERCEPTIBLE_APP_ADJ
13619 && adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13620 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13621 } else if (clientAdj > ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013622 adj = clientAdj;
13623 } else {
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070013624 app.pendingUiClean = true;
13625 if (adj > ProcessList.VISIBLE_APP_ADJ) {
13626 adj = ProcessList.VISIBLE_APP_ADJ;
13627 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013628 }
13629 if (!client.hidden) {
13630 app.hidden = false;
13631 }
13632 if (client.keeping) {
13633 app.keeping = true;
13634 }
13635 adjType = "service";
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013636 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013637 }
13638 if (adjType != null) {
13639 app.adjType = adjType;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013640 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13641 .REASON_SERVICE_IN_USE;
13642 app.adjSource = cr.binding.client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013643 app.adjSourceOom = clientAdj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013644 app.adjTarget = s.name;
13645 }
13646 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
13647 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
13648 schedGroup = Process.THREAD_GROUP_DEFAULT;
13649 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013650 }
13651 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013652 if ((cr.flags&Context.BIND_ADJUST_WITH_ACTIVITY) != 0) {
13653 ActivityRecord a = cr.activity;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013654 if (a != null && adj > ProcessList.FOREGROUND_APP_ADJ &&
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013655 (a.visible || a.state == ActivityState.RESUMED
13656 || a.state == ActivityState.PAUSING)) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013657 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013658 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
13659 schedGroup = Process.THREAD_GROUP_DEFAULT;
13660 }
13661 app.hidden = false;
13662 app.adjType = "service";
13663 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13664 .REASON_SERVICE_IN_USE;
13665 app.adjSource = a;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013666 app.adjSourceOom = adj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013667 app.adjTarget = s.name;
13668 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013669 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013670 }
13671 }
13672 }
13673 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013674
Dianne Hackborn287952c2010-09-22 22:34:31 -070013675 // Finally, if this process has active services running in it, we
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013676 // would like to avoid killing it unless it would prevent the current
13677 // application from running. By default we put the process in
13678 // with the rest of the background processes; as we scan through
13679 // its services we may bump it up from there.
13680 if (adj > hiddenAdj) {
13681 adj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013682 app.hidden = false;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013683 app.adjType = "bg-services";
13684 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013685 }
13686
Dianne Hackborn7d608422011-08-07 16:24:18 -070013687 if (app.pubProviders.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013688 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013689 Iterator<ContentProviderRecord> jt = app.pubProviders.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013690 while (jt.hasNext() && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013691 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013692 ContentProviderRecord cpr = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013693 if (cpr.clients.size() != 0) {
13694 Iterator<ProcessRecord> kt = cpr.clients.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013695 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013696 ProcessRecord client = kt.next();
The Android Open Source Project10592532009-03-18 17:39:46 -070013697 if (client == app) {
13698 // Being our own client is not interesting.
13699 continue;
13700 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013701 int myHiddenAdj = hiddenAdj;
13702 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013703 if (client.hiddenAdj > ProcessList.FOREGROUND_APP_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013704 myHiddenAdj = client.hiddenAdj;
13705 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013706 myHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013707 }
13708 }
13709 int clientAdj = computeOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013710 client, myHiddenAdj, TOP_APP, true, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013711 if (adj > clientAdj) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013712 if (app.hasShownUi && app != mHomeProcess
13713 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013714 app.adjType = "bg-ui-provider";
13715 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013716 adj = clientAdj > ProcessList.FOREGROUND_APP_ADJ
13717 ? clientAdj : ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013718 app.adjType = "provider";
13719 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013720 if (!client.hidden) {
13721 app.hidden = false;
13722 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013723 if (client.keeping) {
13724 app.keeping = true;
13725 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070013726 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13727 .REASON_PROVIDER_IN_USE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013728 app.adjSource = client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013729 app.adjSourceOom = clientAdj;
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070013730 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013731 }
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013732 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
13733 schedGroup = Process.THREAD_GROUP_DEFAULT;
13734 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013735 }
13736 }
13737 // If the provider has external (non-framework) process
13738 // dependencies, ensure that its adjustment is at least
13739 // FOREGROUND_APP_ADJ.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080013740 if (cpr.hasExternalProcessHandles()) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013741 if (adj > ProcessList.FOREGROUND_APP_ADJ) {
13742 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013743 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013744 app.hidden = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013745 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013746 app.adjType = "provider";
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070013747 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013748 }
13749 }
13750 }
13751 }
13752
13753 app.curRawAdj = adj;
13754
Joe Onorato8a9b2202010-02-26 18:56:32 -080013755 //Slog.i(TAG, "OOM ADJ " + app + ": pid=" + app.pid +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013756 // " adj=" + adj + " curAdj=" + app.curAdj + " maxAdj=" + app.maxAdj);
13757 if (adj > app.maxAdj) {
13758 adj = app.maxAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013759 if (app.maxAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013760 schedGroup = Process.THREAD_GROUP_DEFAULT;
13761 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013762 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013763 if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070013764 app.keeping = true;
13765 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013766
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013767 if (app.hasAboveClient) {
13768 // If this process has bound to any services with BIND_ABOVE_CLIENT,
13769 // then we need to drop its adjustment to be lower than the service's
13770 // in order to honor the request. We want to drop it by one adjustment
13771 // level... but there is special meaning applied to various levels so
13772 // we will skip some of them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013773 if (adj < ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013774 // System process will not get dropped, ever
Dianne Hackborn7d608422011-08-07 16:24:18 -070013775 } else if (adj < ProcessList.VISIBLE_APP_ADJ) {
13776 adj = ProcessList.VISIBLE_APP_ADJ;
13777 } else if (adj < ProcessList.PERCEPTIBLE_APP_ADJ) {
13778 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13779 } else if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
13780 adj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013781 } else if (adj < ProcessList.HIDDEN_APP_MAX_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013782 adj++;
13783 }
13784 }
13785
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013786 if (adj == ProcessList.SERVICE_ADJ) {
13787 if (doingAll) {
13788 app.serviceb = mNewNumServiceProcs > (mNumServiceProcs/3);
13789 mNewNumServiceProcs++;
13790 }
13791 if (app.serviceb) {
13792 adj = ProcessList.SERVICE_B_ADJ;
13793 }
13794 } else {
13795 app.serviceb = false;
13796 }
13797
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013798 app.curAdj = adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013799 app.curSchedGroup = schedGroup;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013800
13801 if (hadForegroundActivities != app.foregroundActivities) {
Jeff Sharkey287bd832011-05-28 19:36:26 -070013802 mHandler.obtainMessage(DISPATCH_FOREGROUND_ACTIVITIES_CHANGED, app.pid, app.info.uid,
13803 app.foregroundActivities).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013804 }
13805
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013806 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013807 }
13808
13809 /**
13810 * Ask a given process to GC right now.
13811 */
13812 final void performAppGcLocked(ProcessRecord app) {
13813 try {
13814 app.lastRequestedGc = SystemClock.uptimeMillis();
13815 if (app.thread != null) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013816 if (app.reportLowMemory) {
13817 app.reportLowMemory = false;
13818 app.thread.scheduleLowMemory();
13819 } else {
13820 app.thread.processInBackground();
13821 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013822 }
13823 } catch (Exception e) {
13824 // whatever.
13825 }
13826 }
13827
13828 /**
13829 * Returns true if things are idle enough to perform GCs.
13830 */
Josh Bartel7f208742010-02-25 11:01:44 -060013831 private final boolean canGcNowLocked() {
Christopher Tatef46723b2012-01-26 14:19:24 -080013832 boolean processingBroadcasts = false;
13833 for (BroadcastQueue q : mBroadcastQueues) {
13834 if (q.mParallelBroadcasts.size() != 0 || q.mOrderedBroadcasts.size() != 0) {
13835 processingBroadcasts = true;
13836 }
13837 }
13838 return !processingBroadcasts
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013839 && (mSleeping || (mMainStack.mResumedActivity != null &&
13840 mMainStack.mResumedActivity.idle));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013841 }
13842
13843 /**
13844 * Perform GCs on all processes that are waiting for it, but only
13845 * if things are idle.
13846 */
13847 final void performAppGcsLocked() {
13848 final int N = mProcessesToGc.size();
13849 if (N <= 0) {
13850 return;
13851 }
Josh Bartel7f208742010-02-25 11:01:44 -060013852 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013853 while (mProcessesToGc.size() > 0) {
13854 ProcessRecord proc = mProcessesToGc.remove(0);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013855 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013856 if ((proc.lastRequestedGc+GC_MIN_INTERVAL)
13857 <= SystemClock.uptimeMillis()) {
13858 // To avoid spamming the system, we will GC processes one
13859 // at a time, waiting a few seconds between each.
13860 performAppGcLocked(proc);
13861 scheduleAppGcsLocked();
13862 return;
13863 } else {
13864 // It hasn't been long enough since we last GCed this
13865 // process... put it in the list to wait for its time.
13866 addProcessToGcListLocked(proc);
13867 break;
13868 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013869 }
13870 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013871
13872 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013873 }
13874 }
13875
13876 /**
13877 * If all looks good, perform GCs on all processes waiting for them.
13878 */
13879 final void performAppGcsIfAppropriateLocked() {
Josh Bartel7f208742010-02-25 11:01:44 -060013880 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013881 performAppGcsLocked();
13882 return;
13883 }
13884 // Still not idle, wait some more.
13885 scheduleAppGcsLocked();
13886 }
13887
13888 /**
13889 * Schedule the execution of all pending app GCs.
13890 */
13891 final void scheduleAppGcsLocked() {
13892 mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013893
13894 if (mProcessesToGc.size() > 0) {
13895 // Schedule a GC for the time to the next process.
13896 ProcessRecord proc = mProcessesToGc.get(0);
13897 Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG);
13898
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013899 long when = proc.lastRequestedGc + GC_MIN_INTERVAL;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013900 long now = SystemClock.uptimeMillis();
13901 if (when < (now+GC_TIMEOUT)) {
13902 when = now + GC_TIMEOUT;
13903 }
13904 mHandler.sendMessageAtTime(msg, when);
13905 }
13906 }
13907
13908 /**
13909 * Add a process to the array of processes waiting to be GCed. Keeps the
13910 * list in sorted order by the last GC time. The process can't already be
13911 * on the list.
13912 */
13913 final void addProcessToGcListLocked(ProcessRecord proc) {
13914 boolean added = false;
13915 for (int i=mProcessesToGc.size()-1; i>=0; i--) {
13916 if (mProcessesToGc.get(i).lastRequestedGc <
13917 proc.lastRequestedGc) {
13918 added = true;
13919 mProcessesToGc.add(i+1, proc);
13920 break;
13921 }
13922 }
13923 if (!added) {
13924 mProcessesToGc.add(0, proc);
13925 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013926 }
13927
13928 /**
13929 * Set up to ask a process to GC itself. This will either do it
13930 * immediately, or put it on the list of processes to gc the next
13931 * time things are idle.
13932 */
13933 final void scheduleAppGcLocked(ProcessRecord app) {
13934 long now = SystemClock.uptimeMillis();
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013935 if ((app.lastRequestedGc+GC_MIN_INTERVAL) > now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013936 return;
13937 }
13938 if (!mProcessesToGc.contains(app)) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013939 addProcessToGcListLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013940 scheduleAppGcsLocked();
13941 }
13942 }
13943
Dianne Hackborn287952c2010-09-22 22:34:31 -070013944 final void checkExcessivePowerUsageLocked(boolean doKills) {
13945 updateCpuStatsNow();
13946
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013947 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013948 boolean doWakeKills = doKills;
13949 boolean doCpuKills = doKills;
13950 if (mLastPowerCheckRealtime == 0) {
13951 doWakeKills = false;
13952 }
13953 if (mLastPowerCheckUptime == 0) {
13954 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013955 }
13956 if (stats.isScreenOn()) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070013957 doWakeKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013958 }
13959 final long curRealtime = SystemClock.elapsedRealtime();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013960 final long realtimeSince = curRealtime - mLastPowerCheckRealtime;
13961 final long curUptime = SystemClock.uptimeMillis();
13962 final long uptimeSince = curUptime - mLastPowerCheckUptime;
13963 mLastPowerCheckRealtime = curRealtime;
13964 mLastPowerCheckUptime = curUptime;
13965 if (realtimeSince < WAKE_LOCK_MIN_CHECK_DURATION) {
13966 doWakeKills = false;
13967 }
13968 if (uptimeSince < CPU_MIN_CHECK_DURATION) {
13969 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013970 }
13971 int i = mLruProcesses.size();
13972 while (i > 0) {
13973 i--;
13974 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013975 if (!app.keeping) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013976 long wtime;
13977 synchronized (stats) {
13978 wtime = stats.getProcessWakeTime(app.info.uid,
13979 app.pid, curRealtime);
13980 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013981 long wtimeUsed = wtime - app.lastWakeTime;
13982 long cputimeUsed = app.curCpuTime - app.lastCpuTime;
13983 if (DEBUG_POWER) {
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013984 StringBuilder sb = new StringBuilder(128);
13985 sb.append("Wake for ");
13986 app.toShortString(sb);
13987 sb.append(": over ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013988 TimeUtils.formatDuration(realtimeSince, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013989 sb.append(" used ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013990 TimeUtils.formatDuration(wtimeUsed, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013991 sb.append(" (");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013992 sb.append((wtimeUsed*100)/realtimeSince);
13993 sb.append("%)");
13994 Slog.i(TAG, sb.toString());
13995 sb.setLength(0);
13996 sb.append("CPU for ");
13997 app.toShortString(sb);
13998 sb.append(": over ");
13999 TimeUtils.formatDuration(uptimeSince, sb);
14000 sb.append(" used ");
14001 TimeUtils.formatDuration(cputimeUsed, sb);
14002 sb.append(" (");
14003 sb.append((cputimeUsed*100)/uptimeSince);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014004 sb.append("%)");
14005 Slog.i(TAG, sb.toString());
14006 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014007 // If a process has held a wake lock for more
14008 // than 50% of the time during this period,
14009 // that sounds pad. Kill!
Dianne Hackborn287952c2010-09-22 22:34:31 -070014010 if (doWakeKills && realtimeSince > 0
14011 && ((wtimeUsed*100)/realtimeSince) >= 50) {
14012 synchronized (stats) {
14013 stats.reportExcessiveWakeLocked(app.info.uid, app.processName,
14014 realtimeSince, wtimeUsed);
14015 }
14016 Slog.w(TAG, "Excessive wake lock in " + app.processName
14017 + " (pid " + app.pid + "): held " + wtimeUsed
14018 + " during " + realtimeSince);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014019 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14020 app.processName, app.setAdj, "excessive wake lock");
14021 Process.killProcessQuiet(app.pid);
Dianne Hackborn287952c2010-09-22 22:34:31 -070014022 } else if (doCpuKills && uptimeSince > 0
14023 && ((cputimeUsed*100)/uptimeSince) >= 50) {
14024 synchronized (stats) {
14025 stats.reportExcessiveCpuLocked(app.info.uid, app.processName,
14026 uptimeSince, cputimeUsed);
14027 }
14028 Slog.w(TAG, "Excessive CPU in " + app.processName
14029 + " (pid " + app.pid + "): used " + cputimeUsed
14030 + " during " + uptimeSince);
14031 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14032 app.processName, app.setAdj, "excessive cpu");
14033 Process.killProcessQuiet(app.pid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014034 } else {
14035 app.lastWakeTime = wtime;
Dianne Hackborn287952c2010-09-22 22:34:31 -070014036 app.lastCpuTime = app.curCpuTime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014037 }
14038 }
14039 }
14040 }
14041
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014042 private final boolean updateOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014043 ProcessRecord app, int hiddenAdj, ProcessRecord TOP_APP, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014044 app.hiddenAdj = hiddenAdj;
14045
14046 if (app.thread == null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014047 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014048 }
14049
Dianne Hackborn287952c2010-09-22 22:34:31 -070014050 final boolean wasKeeping = app.keeping;
14051
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014052 boolean success = true;
14053
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014054 computeOomAdjLocked(app, hiddenAdj, TOP_APP, false, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014055
Jeff Brown10e89712011-07-08 18:52:57 -070014056 if (app.curRawAdj != app.setRawAdj) {
Dianne Hackborn905577f2011-09-07 18:31:28 -070014057 if (false) {
14058 // Removing for now. Forcing GCs is not so useful anymore
14059 // with Dalvik, and the new memory level hint facility is
14060 // better for what we need to do these days.
14061 if (app.curRawAdj > ProcessList.FOREGROUND_APP_ADJ
14062 && app.setRawAdj <= ProcessList.FOREGROUND_APP_ADJ) {
14063 // If this app is transitioning from foreground to
14064 // non-foreground, have it do a gc.
14065 scheduleAppGcLocked(app);
14066 } else if (app.curRawAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
14067 && app.setRawAdj < ProcessList.HIDDEN_APP_MIN_ADJ) {
14068 // Likewise do a gc when an app is moving in to the
14069 // background (such as a service stopping).
14070 scheduleAppGcLocked(app);
14071 }
Jeff Brown10e89712011-07-08 18:52:57 -070014072 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070014073
Jeff Brown10e89712011-07-08 18:52:57 -070014074 if (wasKeeping && !app.keeping) {
14075 // This app is no longer something we want to keep. Note
14076 // its current wake lock time to later know to kill it if
14077 // it is not behaving well.
14078 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
14079 synchronized (stats) {
14080 app.lastWakeTime = stats.getProcessWakeTime(app.info.uid,
14081 app.pid, SystemClock.elapsedRealtime());
14082 }
14083 app.lastCpuTime = app.curCpuTime;
14084 }
14085
14086 app.setRawAdj = app.curRawAdj;
14087 }
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014088
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014089 if (app.curAdj != app.setAdj) {
14090 if (Process.setOomAdj(app.pid, app.curAdj)) {
Dianne Hackbornbbb09ac2011-11-30 11:31:29 -080014091 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014092 TAG, "Set " + app.pid + " " + app.processName +
14093 " adj " + app.curAdj + ": " + app.adjType);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014094 app.setAdj = app.curAdj;
Jeff Brown10e89712011-07-08 18:52:57 -070014095 } else {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014096 success = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014097 Slog.w(TAG, "Failed setting oom adj of " + app + " to " + app.curAdj);
Jeff Brown10e89712011-07-08 18:52:57 -070014098 }
14099 }
14100 if (app.setSchedGroup != app.curSchedGroup) {
14101 app.setSchedGroup = app.curSchedGroup;
14102 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
14103 "Setting process group of " + app.processName
14104 + " to " + app.curSchedGroup);
14105 if (app.waitingToKill != null &&
14106 app.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
14107 Slog.i(TAG, "Killing " + app.toShortString() + ": " + app.waitingToKill);
14108 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14109 app.processName, app.setAdj, app.waitingToKill);
14110 Process.killProcessQuiet(app.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014111 success = false;
Jeff Brown10e89712011-07-08 18:52:57 -070014112 } else {
14113 if (true) {
14114 long oldId = Binder.clearCallingIdentity();
14115 try {
14116 Process.setProcessGroup(app.pid, app.curSchedGroup);
14117 } catch (Exception e) {
14118 Slog.w(TAG, "Failed setting process group of " + app.pid
14119 + " to " + app.curSchedGroup);
14120 e.printStackTrace();
14121 } finally {
14122 Binder.restoreCallingIdentity(oldId);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014123 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014124 } else {
Jeff Brown10e89712011-07-08 18:52:57 -070014125 if (app.thread != null) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070014126 try {
Jeff Brown10e89712011-07-08 18:52:57 -070014127 app.thread.setSchedulingGroup(app.curSchedGroup);
14128 } catch (RemoteException e) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070014129 }
14130 }
14131 }
14132 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014133 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014134 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014135 }
14136
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014137 private final ActivityRecord resumedAppLocked() {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014138 ActivityRecord resumedActivity = mMainStack.mResumedActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014139 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -080014140 resumedActivity = mMainStack.mPausingActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014141 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014142 resumedActivity = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014143 }
14144 }
14145 return resumedActivity;
14146 }
14147
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014148 private final boolean updateOomAdjLocked(ProcessRecord app) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014149 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014150 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
14151 int curAdj = app.curAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070014152 final boolean wasHidden = curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
14153 && curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014154
14155 mAdjSeq++;
14156
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014157 boolean success = updateOomAdjLocked(app, app.hiddenAdj, TOP_APP, false);
Dianne Hackborn7d608422011-08-07 16:24:18 -070014158 final boolean nowHidden = app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
14159 && app.curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014160 if (nowHidden != wasHidden) {
14161 // Changed to/from hidden state, so apps after it in the LRU
14162 // list may also be changed.
14163 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014164 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014165 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014166 }
14167
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014168 final void updateOomAdjLocked() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014169 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014170 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
14171
14172 if (false) {
14173 RuntimeException e = new RuntimeException();
14174 e.fillInStackTrace();
Joe Onorato8a9b2202010-02-26 18:56:32 -080014175 Slog.i(TAG, "updateOomAdj: top=" + TOP_ACT, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014176 }
14177
14178 mAdjSeq++;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014179 mNewNumServiceProcs = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014180
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014181 // Let's determine how many processes we have running vs.
14182 // how many slots we have for background processes; we may want
14183 // to put multiple processes in a slot of there are enough of
14184 // them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014185 int numSlots = ProcessList.HIDDEN_APP_MAX_ADJ - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014186 int factor = (mLruProcesses.size()-4)/numSlots;
14187 if (factor < 1) factor = 1;
14188 int step = 0;
Dianne Hackborn8633e682010-04-22 16:03:41 -070014189 int numHidden = 0;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014190
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014191 // First update the OOM adjustment for each of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014192 // application processes based on their current state.
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014193 int i = mLruProcesses.size();
Dianne Hackborn7d608422011-08-07 16:24:18 -070014194 int curHiddenAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014195 while (i > 0) {
14196 i--;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014197 ProcessRecord app = mLruProcesses.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080014198 //Slog.i(TAG, "OOM " + app + ": cur hidden=" + curHiddenAdj);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014199 updateOomAdjLocked(app, curHiddenAdj, TOP_APP, true);
14200 if (curHiddenAdj < ProcessList.HIDDEN_APP_MAX_ADJ
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014201 && app.curAdj == curHiddenAdj) {
14202 step++;
14203 if (step >= factor) {
14204 step = 0;
14205 curHiddenAdj++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014206 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014207 }
14208 if (!app.killedBackground) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070014209 if (app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014210 numHidden++;
14211 if (numHidden > mProcessLimit) {
14212 Slog.i(TAG, "No longer want " + app.processName
14213 + " (pid " + app.pid + "): hidden #" + numHidden);
14214 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14215 app.processName, app.setAdj, "too many background");
14216 app.killedBackground = true;
14217 Process.killProcessQuiet(app.pid);
Dianne Hackborn8633e682010-04-22 16:03:41 -070014218 }
14219 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -080014220 if (!app.killedBackground && app.isolated && app.services.size() <= 0) {
14221 // If this is an isolated process, and there are no
14222 // services running in it, then the process is no longer
14223 // needed. We agressively kill these because we can by
14224 // definition not re-use the same process again, and it is
14225 // good to avoid having whatever code was running in them
14226 // left sitting around after no longer needed.
14227 Slog.i(TAG, "Isolated process " + app.processName
14228 + " (pid " + app.pid + ") no longer needed");
14229 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14230 app.processName, app.setAdj, "isolated not needed");
14231 app.killedBackground = true;
14232 Process.killProcessQuiet(app.pid);
14233 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014234 }
14235 }
14236
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014237 mNumServiceProcs = mNewNumServiceProcs;
14238
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014239 // Now determine the memory trimming level of background processes.
14240 // Unfortunately we need to start at the back of the list to do this
14241 // properly. We only do this if the number of background apps we
14242 // are managing to keep around is less than half the maximum we desire;
14243 // if we are keeping a good number around, we'll let them use whatever
14244 // memory they want.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014245 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/2)) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014246 final int N = mLruProcesses.size();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080014247 factor = numHidden/3;
14248 int minFactor = 2;
14249 if (mHomeProcess != null) minFactor++;
14250 if (mPreviousProcess != null) minFactor++;
14251 if (factor < minFactor) factor = minFactor;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014252 step = 0;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014253 int fgTrimLevel;
14254 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/5)) {
14255 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL;
14256 } else if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/3)) {
14257 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW;
14258 } else {
14259 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE;
14260 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014261 int curLevel = ComponentCallbacks2.TRIM_MEMORY_COMPLETE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014262 for (i=0; i<N; i++) {
14263 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080014264 if (app.curAdj >= ProcessList.HOME_APP_ADJ
14265 && app.curAdj != ProcessList.SERVICE_B_ADJ
14266 && !app.killedBackground) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014267 if (app.trimMemoryLevel < curLevel && app.thread != null) {
14268 try {
14269 app.thread.scheduleTrimMemory(curLevel);
14270 } catch (RemoteException e) {
14271 }
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080014272 if (false) {
14273 // For now we won't do this; our memory trimming seems
14274 // to be good enough at this point that destroying
14275 // activities causes more harm than good.
14276 if (curLevel >= ComponentCallbacks2.TRIM_MEMORY_COMPLETE
14277 && app != mHomeProcess && app != mPreviousProcess) {
14278 // For these apps we will also finish their activities
14279 // to help them free memory.
14280 mMainStack.destroyActivitiesLocked(app, false, "trim");
14281 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014282 }
14283 }
14284 app.trimMemoryLevel = curLevel;
14285 step++;
14286 if (step >= factor) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014287 step = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014288 switch (curLevel) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014289 case ComponentCallbacks2.TRIM_MEMORY_COMPLETE:
14290 curLevel = ComponentCallbacks2.TRIM_MEMORY_MODERATE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014291 break;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014292 case ComponentCallbacks2.TRIM_MEMORY_MODERATE:
14293 curLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014294 break;
14295 }
14296 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070014297 } else if (app.curAdj == ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014298 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014299 && app.thread != null) {
14300 try {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014301 app.thread.scheduleTrimMemory(
14302 ComponentCallbacks2.TRIM_MEMORY_BACKGROUND);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014303 } catch (RemoteException e) {
14304 }
14305 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014306 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014307 } else {
14308 if ((app.curAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
14309 && app.pendingUiClean) {
14310 // If this application is now in the background and it
14311 // had done UI, then give it the special trim level to
14312 // have it free UI resources.
14313 final int level = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
14314 if (app.trimMemoryLevel < level && app.thread != null) {
14315 try {
14316 app.thread.scheduleTrimMemory(level);
14317 } catch (RemoteException e) {
14318 }
14319 }
14320 app.pendingUiClean = false;
14321 }
14322 if (app.trimMemoryLevel < fgTrimLevel && app.thread != null) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014323 try {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014324 app.thread.scheduleTrimMemory(fgTrimLevel);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014325 } catch (RemoteException e) {
14326 }
14327 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014328 app.trimMemoryLevel = fgTrimLevel;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014329 }
14330 }
14331 } else {
14332 final int N = mLruProcesses.size();
14333 for (i=0; i<N; i++) {
14334 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -070014335 if ((app.curAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014336 && app.pendingUiClean) {
14337 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
14338 && app.thread != null) {
14339 try {
14340 app.thread.scheduleTrimMemory(
14341 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
14342 } catch (RemoteException e) {
14343 }
14344 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014345 app.pendingUiClean = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014346 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014347 app.trimMemoryLevel = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014348 }
14349 }
14350
14351 if (mAlwaysFinishActivities) {
Dianne Hackborn28695e02011-11-02 21:59:51 -070014352 mMainStack.destroyActivitiesLocked(null, false, "always-finish");
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014353 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014354 }
14355
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014356 final void trimApplications() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014357 synchronized (this) {
14358 int i;
14359
14360 // First remove any unused application processes whose package
14361 // has been removed.
14362 for (i=mRemovedProcesses.size()-1; i>=0; i--) {
14363 final ProcessRecord app = mRemovedProcesses.get(i);
14364 if (app.activities.size() == 0
14365 && app.curReceiver == null && app.services.size() == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080014366 Slog.i(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014367 TAG, "Exiting empty application process "
14368 + app.processName + " ("
14369 + (app.thread != null ? app.thread.asBinder() : null)
14370 + ")\n");
14371 if (app.pid > 0 && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070014372 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14373 app.processName, app.setAdj, "empty");
14374 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014375 } else {
14376 try {
14377 app.thread.scheduleExit();
14378 } catch (Exception e) {
14379 // Ignore exceptions.
14380 }
14381 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070014382 cleanUpApplicationRecordLocked(app, false, true, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014383 mRemovedProcesses.remove(i);
14384
14385 if (app.persistent) {
14386 if (app.persistent) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080014387 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014388 }
14389 }
14390 }
14391 }
14392
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014393 // Now update the oom adj for all processes.
14394 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014395 }
14396 }
14397
14398 /** This method sends the specified signal to each of the persistent apps */
14399 public void signalPersistentProcesses(int sig) throws RemoteException {
14400 if (sig != Process.SIGNAL_USR1) {
14401 throw new SecurityException("Only SIGNAL_USR1 is allowed");
14402 }
14403
14404 synchronized (this) {
14405 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
14406 != PackageManager.PERMISSION_GRANTED) {
14407 throw new SecurityException("Requires permission "
14408 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
14409 }
14410
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014411 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
14412 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014413 if (r.thread != null && r.persistent) {
14414 Process.sendSignal(r.pid, sig);
14415 }
14416 }
14417 }
14418 }
14419
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014420 private void stopProfilerLocked(ProcessRecord proc, String path, int profileType) {
14421 if (proc == null || proc == mProfileProc) {
14422 proc = mProfileProc;
14423 path = mProfileFile;
14424 profileType = mProfileType;
14425 clearProfilerLocked();
14426 }
14427 if (proc == null) {
14428 return;
14429 }
14430 try {
14431 proc.thread.profilerControl(false, path, null, profileType);
14432 } catch (RemoteException e) {
14433 throw new IllegalStateException("Process disappeared");
14434 }
14435 }
14436
14437 private void clearProfilerLocked() {
14438 if (mProfileFd != null) {
14439 try {
14440 mProfileFd.close();
14441 } catch (IOException e) {
14442 }
14443 }
14444 mProfileApp = null;
14445 mProfileProc = null;
14446 mProfileFile = null;
14447 mProfileType = 0;
14448 mAutoStopProfiler = false;
14449 }
14450
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014451 public boolean profileControl(String process, boolean start,
Romain Guy7eabe552011-07-21 14:56:34 -070014452 String path, ParcelFileDescriptor fd, int profileType) throws RemoteException {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014453
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014454 try {
14455 synchronized (this) {
14456 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14457 // its own permission.
14458 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14459 != PackageManager.PERMISSION_GRANTED) {
14460 throw new SecurityException("Requires permission "
14461 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014462 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014463
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014464 if (start && fd == null) {
14465 throw new IllegalArgumentException("null fd");
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014466 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014467
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014468 ProcessRecord proc = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014469 if (process != null) {
14470 try {
14471 int pid = Integer.parseInt(process);
14472 synchronized (mPidsSelfLocked) {
14473 proc = mPidsSelfLocked.get(pid);
14474 }
14475 } catch (NumberFormatException e) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014476 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014477
14478 if (proc == null) {
14479 HashMap<String, SparseArray<ProcessRecord>> all
14480 = mProcessNames.getMap();
14481 SparseArray<ProcessRecord> procs = all.get(process);
14482 if (procs != null && procs.size() > 0) {
14483 proc = procs.valueAt(0);
14484 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014485 }
14486 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014487
14488 if (start && (proc == null || proc.thread == null)) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014489 throw new IllegalArgumentException("Unknown process: " + process);
14490 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014491
14492 if (start) {
14493 stopProfilerLocked(null, null, 0);
14494 setProfileApp(proc.info, proc.processName, path, fd, false);
14495 mProfileProc = proc;
14496 mProfileType = profileType;
14497 try {
14498 fd = fd.dup();
14499 } catch (IOException e) {
14500 fd = null;
14501 }
14502 proc.thread.profilerControl(start, path, fd, profileType);
14503 fd = null;
14504 mProfileFd = null;
14505 } else {
14506 stopProfilerLocked(proc, path, profileType);
14507 if (fd != null) {
14508 try {
14509 fd.close();
14510 } catch (IOException e) {
14511 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014512 }
14513 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014514
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014515 return true;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014516 }
14517 } catch (RemoteException e) {
14518 throw new IllegalStateException("Process disappeared");
14519 } finally {
14520 if (fd != null) {
14521 try {
14522 fd.close();
14523 } catch (IOException e) {
14524 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014525 }
14526 }
14527 }
Andy McFadden824c5102010-07-09 16:26:57 -070014528
14529 public boolean dumpHeap(String process, boolean managed,
14530 String path, ParcelFileDescriptor fd) throws RemoteException {
14531
14532 try {
14533 synchronized (this) {
14534 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14535 // its own permission (same as profileControl).
14536 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14537 != PackageManager.PERMISSION_GRANTED) {
14538 throw new SecurityException("Requires permission "
14539 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
14540 }
14541
14542 if (fd == null) {
14543 throw new IllegalArgumentException("null fd");
14544 }
14545
14546 ProcessRecord proc = null;
14547 try {
14548 int pid = Integer.parseInt(process);
14549 synchronized (mPidsSelfLocked) {
14550 proc = mPidsSelfLocked.get(pid);
14551 }
14552 } catch (NumberFormatException e) {
14553 }
14554
14555 if (proc == null) {
14556 HashMap<String, SparseArray<ProcessRecord>> all
14557 = mProcessNames.getMap();
14558 SparseArray<ProcessRecord> procs = all.get(process);
14559 if (procs != null && procs.size() > 0) {
14560 proc = procs.valueAt(0);
14561 }
14562 }
14563
14564 if (proc == null || proc.thread == null) {
14565 throw new IllegalArgumentException("Unknown process: " + process);
14566 }
14567
Dianne Hackbornf02e57b2011-03-01 22:21:04 -080014568 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
14569 if (!isDebuggable) {
Andy McFadden824c5102010-07-09 16:26:57 -070014570 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
14571 throw new SecurityException("Process not debuggable: " + proc);
14572 }
14573 }
14574
14575 proc.thread.dumpHeap(managed, path, fd);
14576 fd = null;
14577 return true;
14578 }
14579 } catch (RemoteException e) {
14580 throw new IllegalStateException("Process disappeared");
14581 } finally {
14582 if (fd != null) {
14583 try {
14584 fd.close();
14585 } catch (IOException e) {
14586 }
14587 }
14588 }
14589 }
14590
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014591 /** In this method we try to acquire our lock to make sure that we have not deadlocked */
14592 public void monitor() {
14593 synchronized (this) { }
14594 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014595
Dianne Hackborna573f6a2012-02-09 16:12:18 -080014596 void onCoreSettingsChange(Bundle settings) {
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014597 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
14598 ProcessRecord processRecord = mLruProcesses.get(i);
14599 try {
14600 if (processRecord.thread != null) {
14601 processRecord.thread.setCoreSettings(settings);
14602 }
14603 } catch (RemoteException re) {
14604 /* ignore */
14605 }
14606 }
14607 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014608
14609 // Multi-user methods
14610
Amith Yamasani742a6712011-05-04 14:49:28 -070014611 private int mCurrentUserId;
14612 private SparseIntArray mLoggedInUsers = new SparseIntArray(5);
14613
14614 public boolean switchUser(int userId) {
14615 final int callingUid = Binder.getCallingUid();
14616 if (callingUid != 0 && callingUid != Process.myUid()) {
14617 Slog.e(TAG, "Trying to switch user from unauthorized app");
14618 return false;
14619 }
14620 if (mCurrentUserId == userId)
14621 return true;
14622
14623 synchronized (this) {
14624 // Check if user is already logged in, otherwise check if user exists first before
14625 // adding to the list of logged in users.
14626 if (mLoggedInUsers.indexOfKey(userId) < 0) {
14627 if (!userExists(userId)) {
14628 return false;
14629 }
14630 mLoggedInUsers.append(userId, userId);
14631 }
14632
14633 mCurrentUserId = userId;
14634 boolean haveActivities = mMainStack.switchUser(userId);
14635 if (!haveActivities) {
14636 startHomeActivityLocked(userId);
14637 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014638
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014639 }
Amith Yamasani13593602012-03-22 16:16:17 -070014640
14641 // Inform of user switch
14642 Intent addedIntent = new Intent(Intent.ACTION_USER_SWITCHED);
14643 addedIntent.putExtra(Intent.EXTRA_USERID, userId);
14644 mContext.sendBroadcast(addedIntent, android.Manifest.permission.MANAGE_ACCOUNTS);
14645
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014646 return true;
14647 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014648
Amith Yamasani52f1d752012-03-28 18:19:29 -070014649 @Override
14650 public UserInfo getCurrentUser() throws RemoteException {
14651 final int callingUid = Binder.getCallingUid();
14652 if (callingUid != 0 && callingUid != Process.myUid()) {
14653 Slog.e(TAG, "Trying to get user from unauthorized app");
14654 return null;
14655 }
14656 return AppGlobals.getPackageManager().getUser(mCurrentUserId);
14657 }
14658
Amith Yamasani13593602012-03-22 16:16:17 -070014659 private void onUserRemoved(Intent intent) {
14660 int extraUserId = intent.getIntExtra(Intent.EXTRA_USERID, -1);
14661 if (extraUserId < 1) return;
14662
14663 // Kill all the processes for the user
14664 ArrayList<Pair<String, Integer>> pkgAndUids = new ArrayList<Pair<String,Integer>>();
14665 synchronized (this) {
14666 HashMap<String,SparseArray<ProcessRecord>> map = mProcessNames.getMap();
14667 for (Entry<String, SparseArray<ProcessRecord>> uidMap : map.entrySet()) {
14668 SparseArray<ProcessRecord> uids = uidMap.getValue();
14669 for (int i = 0; i < uids.size(); i++) {
14670 if (UserId.getUserId(uids.keyAt(i)) == extraUserId) {
14671 pkgAndUids.add(new Pair<String,Integer>(uidMap.getKey(), uids.keyAt(i)));
14672 }
14673 }
14674 }
14675
14676 for (Pair<String,Integer> pkgAndUid : pkgAndUids) {
14677 forceStopPackageLocked(pkgAndUid.first, pkgAndUid.second,
14678 false, false, true, true, extraUserId);
14679 }
14680 }
14681 }
14682
Amith Yamasani742a6712011-05-04 14:49:28 -070014683 private boolean userExists(int userId) {
14684 try {
Amith Yamasani13593602012-03-22 16:16:17 -070014685 UserInfo user = AppGlobals.getPackageManager().getUser(userId);
14686 return user != null;
Amith Yamasani742a6712011-05-04 14:49:28 -070014687 } catch (RemoteException re) {
14688 // Won't happen, in same process
14689 }
14690
14691 return false;
14692 }
14693
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014694 private void checkValidCaller(int uid, int userId) {
14695 if (UserId.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) return;
14696
14697 throw new SecurityException("Caller uid=" + uid
14698 + " is not privileged to communicate with user=" + userId);
14699 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014700
14701 private int applyUserId(int uid, int userId) {
14702 return UserId.getUid(userId, uid);
14703 }
14704
14705 private ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080014706 if (info == null) return null;
Amith Yamasani742a6712011-05-04 14:49:28 -070014707 ApplicationInfo newInfo = new ApplicationInfo(info);
14708 newInfo.uid = applyUserId(info.uid, userId);
14709 if (newInfo.uid >= Process.FIRST_APPLICATION_UID) {
14710 newInfo.dataDir = USER_DATA_DIR + userId + "/"
14711 + info.packageName;
14712 }
14713 return newInfo;
14714 }
14715
14716 ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080014717 if (aInfo == null || aInfo.applicationInfo.uid < Process.FIRST_APPLICATION_UID
Amith Yamasani742a6712011-05-04 14:49:28 -070014718 || userId < 1) {
14719 return aInfo;
14720 }
14721
14722 ActivityInfo info = new ActivityInfo(aInfo);
14723 info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId);
14724 return info;
14725 }
14726
14727 static class ServiceMap {
14728
14729 private final SparseArray<HashMap<ComponentName, ServiceRecord>> mServicesByNamePerUser
14730 = new SparseArray<HashMap<ComponentName, ServiceRecord>>();
14731 private final SparseArray<HashMap<Intent.FilterComparison, ServiceRecord>>
14732 mServicesByIntentPerUser = new SparseArray<
14733 HashMap<Intent.FilterComparison, ServiceRecord>>();
14734
14735 ServiceRecord getServiceByName(ComponentName name, int callingUser) {
14736 // TODO: Deal with global services
14737 if (DEBUG_MU)
14738 Slog.v(TAG_MU, "getServiceByName(" + name + "), callingUser = " + callingUser);
14739 return getServices(callingUser).get(name);
14740 }
14741
14742 ServiceRecord getServiceByName(ComponentName name) {
14743 return getServiceByName(name, -1);
14744 }
14745
14746 ServiceRecord getServiceByIntent(Intent.FilterComparison filter, int callingUser) {
14747 // TODO: Deal with global services
14748 if (DEBUG_MU)
14749 Slog.v(TAG_MU, "getServiceByIntent(" + filter + "), callingUser = " + callingUser);
14750 return getServicesByIntent(callingUser).get(filter);
14751 }
14752
14753 ServiceRecord getServiceByIntent(Intent.FilterComparison filter) {
14754 return getServiceByIntent(filter, -1);
14755 }
14756
14757 void putServiceByName(ComponentName name, int callingUser, ServiceRecord value) {
14758 // TODO: Deal with global services
14759 getServices(callingUser).put(name, value);
14760 }
14761
14762 void putServiceByIntent(Intent.FilterComparison filter, int callingUser,
14763 ServiceRecord value) {
14764 // TODO: Deal with global services
14765 getServicesByIntent(callingUser).put(filter, value);
14766 }
14767
14768 void removeServiceByName(ComponentName name, int callingUser) {
14769 // TODO: Deal with global services
14770 ServiceRecord removed = getServices(callingUser).remove(name);
14771 if (DEBUG_MU)
14772 Slog.v(TAG, "removeServiceByName user=" + callingUser + " name=" + name
14773 + " removed=" + removed);
14774 }
14775
14776 void removeServiceByIntent(Intent.FilterComparison filter, int callingUser) {
14777 // TODO: Deal with global services
14778 ServiceRecord removed = getServicesByIntent(callingUser).remove(filter);
14779 if (DEBUG_MU)
14780 Slog.v(TAG_MU, "removeServiceByIntent user=" + callingUser + " intent=" + filter
14781 + " removed=" + removed);
14782 }
14783
14784 Collection<ServiceRecord> getAllServices(int callingUser) {
14785 // TODO: Deal with global services
14786 return getServices(callingUser).values();
14787 }
14788
14789 private HashMap<ComponentName, ServiceRecord> getServices(int callingUser) {
14790 HashMap map = mServicesByNamePerUser.get(callingUser);
14791 if (map == null) {
14792 map = new HashMap<ComponentName, ServiceRecord>();
14793 mServicesByNamePerUser.put(callingUser, map);
14794 }
14795 return map;
14796 }
14797
14798 private HashMap<Intent.FilterComparison, ServiceRecord> getServicesByIntent(
14799 int callingUser) {
14800 HashMap map = mServicesByIntentPerUser.get(callingUser);
14801 if (map == null) {
14802 map = new HashMap<Intent.FilterComparison, ServiceRecord>();
14803 mServicesByIntentPerUser.put(callingUser, map);
14804 }
14805 return map;
14806 }
14807 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014808}