blob: 143f77d2d25b403fda661dc743ebd29002849768 [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) {
1797 if (uid == Process.SYSTEM_UID) {
Amith Yamasani52f1d752012-03-28 18:19:29 -07001798 SparseArray<ProcessRecord> procs = mProcessNames.getMap().get(processName);
1799 if (procs == null) return null;
1800 int N = procs.size();
1801 for (int i = 0; i < N; i++) {
1802 if (UserId.isSameUser(procs.keyAt(i), uid)) {
1803 return procs.valueAt(i);
1804 }
1805 }
1806 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001807 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001808 // uid = applyUserId(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001809 ProcessRecord proc = mProcessNames.get(processName, uid);
1810 return proc;
1811 }
1812
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001813 void ensurePackageDexOpt(String packageName) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001814 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001815 try {
1816 if (pm.performDexOpt(packageName)) {
1817 mDidDexOpt = true;
1818 }
1819 } catch (RemoteException e) {
1820 }
1821 }
1822
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001823 boolean isNextTransitionForward() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001824 int transit = mWindowManager.getPendingAppTransition();
1825 return transit == WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
1826 || transit == WindowManagerPolicy.TRANSIT_TASK_OPEN
1827 || transit == WindowManagerPolicy.TRANSIT_TASK_TO_FRONT;
1828 }
1829
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001830 final ProcessRecord startProcessLocked(String processName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001831 ApplicationInfo info, boolean knownToBeDead, int intentFlags,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001832 String hostingType, ComponentName hostingName, boolean allowWhileBooting,
1833 boolean isolated) {
1834 ProcessRecord app;
1835 if (!isolated) {
1836 app = getProcessRecordLocked(processName, info.uid);
1837 } else {
1838 // If this is an isolated process, it can't re-use an existing process.
1839 app = null;
1840 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001841 // We don't have to do anything more if:
1842 // (1) There is an existing application record; and
1843 // (2) The caller doesn't think it is dead, OR there is no thread
1844 // object attached to it so we know it couldn't have crashed; and
1845 // (3) There is a pid assigned to it, so it is either starting or
1846 // already running.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001847 if (DEBUG_PROCESSES) Slog.v(TAG, "startProcess: name=" + processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001848 + " app=" + app + " knownToBeDead=" + knownToBeDead
1849 + " thread=" + (app != null ? app.thread : null)
1850 + " pid=" + (app != null ? app.pid : -1));
Magnus Edlund7bb25812010-02-24 15:45:06 +01001851 if (app != null && app.pid > 0) {
1852 if (!knownToBeDead || app.thread == null) {
Dianne Hackborn20cb56e2010-03-04 00:58:29 -08001853 // We already have the app running, or are waiting for it to
1854 // come up (we have a pid but not yet its thread), so keep it.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001855 if (DEBUG_PROCESSES) Slog.v(TAG, "App already running: " + app);
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001856 // If this is a new package in the process, add the package to the list
1857 app.addPackage(info.packageName);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001858 return app;
1859 } else {
1860 // An application record is attached to a previous process,
1861 // clean it up now.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001862 if (DEBUG_PROCESSES) Slog.v(TAG, "App died: " + app);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07001863 handleAppDiedLocked(app, true, true);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001864 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001865 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01001866
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001867 String hostingNameStr = hostingName != null
1868 ? hostingName.flattenToShortString() : null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001869
1870 if (!isolated) {
1871 if ((intentFlags&Intent.FLAG_FROM_BACKGROUND) != 0) {
1872 // If we are in the background, then check to see if this process
1873 // is bad. If so, we will just silently fail.
1874 if (mBadProcesses.get(info.processName, info.uid) != null) {
1875 if (DEBUG_PROCESSES) Slog.v(TAG, "Bad process: " + info.uid
1876 + "/" + info.processName);
1877 return null;
1878 }
1879 } else {
1880 // When the user is explicitly starting a process, then clear its
1881 // crash count so that we won't make it bad until they see at
1882 // least one crash dialog again, and make the process good again
1883 // if it had been bad.
1884 if (DEBUG_PROCESSES) Slog.v(TAG, "Clearing bad process: " + info.uid
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001885 + "/" + info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001886 mProcessCrashTimes.remove(info.processName, info.uid);
1887 if (mBadProcesses.get(info.processName, info.uid) != null) {
1888 EventLog.writeEvent(EventLogTags.AM_PROC_GOOD, info.uid,
1889 info.processName);
1890 mBadProcesses.remove(info.processName, info.uid);
1891 if (app != null) {
1892 app.bad = false;
1893 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001894 }
1895 }
1896 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001897
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001898 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001899 app = newProcessRecordLocked(null, info, processName, isolated);
1900 if (app == null) {
1901 Slog.w(TAG, "Failed making new process record for "
1902 + processName + "/" + info.uid + " isolated=" + isolated);
1903 return null;
1904 }
1905 mProcessNames.put(processName, app.uid, app);
1906 if (isolated) {
1907 mIsolatedProcesses.put(app.uid, app);
1908 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001909 } else {
1910 // If this is a new package in the process, add the package to the list
1911 app.addPackage(info.packageName);
1912 }
1913
1914 // If the system is not ready yet, then hold off on starting this
1915 // process until it is.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001916 if (!mProcessesReady
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001917 && !isAllowedWhileBooting(info)
1918 && !allowWhileBooting) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001919 if (!mProcessesOnHold.contains(app)) {
1920 mProcessesOnHold.add(app);
1921 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001922 if (DEBUG_PROCESSES) Slog.v(TAG, "System not ready, putting on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001923 return app;
1924 }
1925
1926 startProcessLocked(app, hostingType, hostingNameStr);
1927 return (app.pid != 0) ? app : null;
1928 }
1929
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001930 boolean isAllowedWhileBooting(ApplicationInfo ai) {
1931 return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0;
1932 }
1933
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001934 private final void startProcessLocked(ProcessRecord app,
1935 String hostingType, String hostingNameStr) {
1936 if (app.pid > 0 && app.pid != MY_PID) {
1937 synchronized (mPidsSelfLocked) {
1938 mPidsSelfLocked.remove(app.pid);
1939 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
1940 }
1941 app.pid = 0;
1942 }
1943
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001944 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
1945 "startProcessLocked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001946 mProcessesOnHold.remove(app);
1947
1948 updateCpuStats();
1949
1950 System.arraycopy(mProcDeaths, 0, mProcDeaths, 1, mProcDeaths.length-1);
1951 mProcDeaths[0] = 0;
1952
1953 try {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001954 int uid = app.uid;
Amith Yamasani742a6712011-05-04 14:49:28 -07001955
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001956 int[] gids = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001957 if (!app.isolated) {
1958 try {
1959 gids = mContext.getPackageManager().getPackageGids(
1960 app.info.packageName);
1961 } catch (PackageManager.NameNotFoundException e) {
1962 Slog.w(TAG, "Unable to retrieve gids", e);
1963 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001964 }
1965 if (mFactoryTest != SystemServer.FACTORY_TEST_OFF) {
1966 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
1967 && mTopComponent != null
1968 && app.processName.equals(mTopComponent.getPackageName())) {
1969 uid = 0;
1970 }
1971 if (mFactoryTest == SystemServer.FACTORY_TEST_HIGH_LEVEL
1972 && (app.info.flags&ApplicationInfo.FLAG_FACTORY_TEST) != 0) {
1973 uid = 0;
1974 }
1975 }
1976 int debugFlags = 0;
1977 if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
1978 debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;
Elliott Hughesfa36aee2011-06-17 14:39:41 -07001979 // Also turn on CheckJNI for debuggable apps. It's quite
1980 // awkward to turn on otherwise.
1981 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001982 }
Ben Cheng6c0afff2010-02-14 16:18:56 -08001983 // Run the app in safe mode if its manifest requests so or the
1984 // system is booted in safe mode.
1985 if ((app.info.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0 ||
1986 Zygote.systemInSafeMode == true) {
Ben Cheng23085b72010-02-08 16:06:32 -08001987 debugFlags |= Zygote.DEBUG_ENABLE_SAFEMODE;
1988 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001989 if ("1".equals(SystemProperties.get("debug.checkjni"))) {
1990 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
1991 }
Elliott Hughesae07ecf2011-07-06 17:33:27 -07001992 if ("1".equals(SystemProperties.get("debug.jni.logging"))) {
1993 debugFlags |= Zygote.DEBUG_ENABLE_JNI_LOGGING;
1994 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001995 if ("1".equals(SystemProperties.get("debug.assert"))) {
1996 debugFlags |= Zygote.DEBUG_ENABLE_ASSERT;
1997 }
Jeff Brown3f9dd282011-07-08 20:02:19 -07001998
1999 // Start the process. It will either succeed and return a result containing
2000 // the PID of the new process, or else throw a RuntimeException.
2001 Process.ProcessStartResult startResult = Process.start("android.app.ActivityThread",
Elliott Hughese1dfcb72011-07-08 11:08:07 -07002002 app.processName, uid, uid, gids, debugFlags,
2003 app.info.targetSdkVersion, null);
Jeff Brown3f9dd282011-07-08 20:02:19 -07002004
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002005 BatteryStatsImpl bs = app.batteryStats.getBatteryStats();
2006 synchronized (bs) {
2007 if (bs.isOnBattery()) {
2008 app.batteryStats.incStartsLocked();
2009 }
2010 }
2011
Jeff Brown3f9dd282011-07-08 20:02:19 -07002012 EventLog.writeEvent(EventLogTags.AM_PROC_START, startResult.pid, uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002013 app.processName, hostingType,
2014 hostingNameStr != null ? hostingNameStr : "");
2015
2016 if (app.persistent) {
Jeff Brown3f9dd282011-07-08 20:02:19 -07002017 Watchdog.getInstance().processStarted(app.processName, startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002018 }
2019
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07002020 StringBuilder buf = mStringBuilder;
2021 buf.setLength(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002022 buf.append("Start proc ");
2023 buf.append(app.processName);
2024 buf.append(" for ");
2025 buf.append(hostingType);
2026 if (hostingNameStr != null) {
2027 buf.append(" ");
2028 buf.append(hostingNameStr);
2029 }
2030 buf.append(": pid=");
Jeff Brown3f9dd282011-07-08 20:02:19 -07002031 buf.append(startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002032 buf.append(" uid=");
2033 buf.append(uid);
2034 buf.append(" gids={");
2035 if (gids != null) {
2036 for (int gi=0; gi<gids.length; gi++) {
2037 if (gi != 0) buf.append(", ");
2038 buf.append(gids[gi]);
2039
2040 }
2041 }
2042 buf.append("}");
Joe Onorato8a9b2202010-02-26 18:56:32 -08002043 Slog.i(TAG, buf.toString());
Jeff Brown3f9dd282011-07-08 20:02:19 -07002044 app.pid = startResult.pid;
2045 app.usingWrapper = startResult.usingWrapper;
2046 app.removed = false;
2047 synchronized (mPidsSelfLocked) {
2048 this.mPidsSelfLocked.put(startResult.pid, app);
2049 Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
2050 msg.obj = app;
2051 mHandler.sendMessageDelayed(msg, startResult.usingWrapper
2052 ? PROC_START_TIMEOUT_WITH_WRAPPER : PROC_START_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002053 }
2054 } catch (RuntimeException e) {
2055 // XXX do better error recovery.
2056 app.pid = 0;
Joe Onorato8a9b2202010-02-26 18:56:32 -08002057 Slog.e(TAG, "Failure starting process " + app.processName, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002058 }
2059 }
2060
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002061 void updateUsageStats(ActivityRecord resumedComponent, boolean resumed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002062 if (resumed) {
2063 mUsageStatsService.noteResumeComponent(resumedComponent.realActivity);
2064 } else {
2065 mUsageStatsService.notePauseComponent(resumedComponent.realActivity);
2066 }
2067 }
2068
Amith Yamasani742a6712011-05-04 14:49:28 -07002069 boolean startHomeActivityLocked(int userId) {
Mike Lockwooda8f767a2011-08-31 14:32:37 -04002070 if (mHeadless) {
2071 // Added because none of the other calls to ensureBootCompleted seem to fire
2072 // when running headless.
2073 ensureBootCompleted();
2074 return false;
2075 }
2076
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002077 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2078 && mTopAction == null) {
2079 // We are running in factory test mode, but unable to find
2080 // the factory test app, so just sit around displaying the
2081 // error message and don't try to start anything.
2082 return false;
2083 }
2084 Intent intent = new Intent(
2085 mTopAction,
2086 mTopData != null ? Uri.parse(mTopData) : null);
2087 intent.setComponent(mTopComponent);
2088 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
2089 intent.addCategory(Intent.CATEGORY_HOME);
2090 }
2091 ActivityInfo aInfo =
2092 intent.resolveActivityInfo(mContext.getPackageManager(),
2093 STOCK_PM_FLAGS);
2094 if (aInfo != null) {
2095 intent.setComponent(new ComponentName(
2096 aInfo.applicationInfo.packageName, aInfo.name));
2097 // Don't do this if the home app is currently being
2098 // instrumented.
Amith Yamasani742a6712011-05-04 14:49:28 -07002099 aInfo = new ActivityInfo(aInfo);
2100 aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002101 ProcessRecord app = getProcessRecordLocked(aInfo.processName,
2102 aInfo.applicationInfo.uid);
2103 if (app == null || app.instrumentationClass == null) {
2104 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002105 mMainStack.startActivityLocked(null, intent, null, aInfo,
2106 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002107 }
2108 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002109
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002110 return true;
2111 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002112
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002113 /**
2114 * Starts the "new version setup screen" if appropriate.
2115 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002116 void startSetupActivityLocked() {
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002117 // Only do this once per boot.
2118 if (mCheckedForSetup) {
2119 return;
2120 }
2121
2122 // We will show this screen if the current one is a different
2123 // version than the last one shown, and we are not running in
2124 // low-level factory test mode.
2125 final ContentResolver resolver = mContext.getContentResolver();
2126 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL &&
2127 Settings.Secure.getInt(resolver,
2128 Settings.Secure.DEVICE_PROVISIONED, 0) != 0) {
2129 mCheckedForSetup = true;
2130
2131 // See if we should be showing the platform update setup UI.
2132 Intent intent = new Intent(Intent.ACTION_UPGRADE_SETUP);
2133 List<ResolveInfo> ris = mSelf.mContext.getPackageManager()
2134 .queryIntentActivities(intent, PackageManager.GET_META_DATA);
2135
2136 // We don't allow third party apps to replace this.
2137 ResolveInfo ri = null;
2138 for (int i=0; ris != null && i<ris.size(); i++) {
2139 if ((ris.get(i).activityInfo.applicationInfo.flags
2140 & ApplicationInfo.FLAG_SYSTEM) != 0) {
2141 ri = ris.get(i);
2142 break;
2143 }
2144 }
2145
2146 if (ri != null) {
2147 String vers = ri.activityInfo.metaData != null
2148 ? ri.activityInfo.metaData.getString(Intent.METADATA_SETUP_VERSION)
2149 : null;
2150 if (vers == null && ri.activityInfo.applicationInfo.metaData != null) {
2151 vers = ri.activityInfo.applicationInfo.metaData.getString(
2152 Intent.METADATA_SETUP_VERSION);
2153 }
2154 String lastVers = Settings.Secure.getString(
2155 resolver, Settings.Secure.LAST_SETUP_SHOWN);
2156 if (vers != null && !vers.equals(lastVers)) {
2157 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2158 intent.setComponent(new ComponentName(
2159 ri.activityInfo.packageName, ri.activityInfo.name));
Dianne Hackborna4972e92012-03-14 10:38:05 -07002160 mMainStack.startActivityLocked(null, intent, null, ri.activityInfo,
2161 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002162 }
2163 }
2164 }
2165 }
2166
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002167 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002168 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002169 }
2170
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002171 void enforceNotIsolatedCaller(String caller) {
2172 if (UserId.isIsolated(Binder.getCallingUid())) {
2173 throw new SecurityException("Isolated process not allowed to call " + caller);
2174 }
2175 }
2176
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002177 public int getFrontActivityScreenCompatMode() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002178 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002179 synchronized (this) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002180 return mCompatModePackages.getFrontActivityScreenCompatModeLocked();
2181 }
2182 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002183
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002184 public void setFrontActivityScreenCompatMode(int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002185 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2186 "setFrontActivityScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002187 synchronized (this) {
2188 mCompatModePackages.setFrontActivityScreenCompatModeLocked(mode);
2189 }
2190 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002191
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002192 public int getPackageScreenCompatMode(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002193 enforceNotIsolatedCaller("getPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002194 synchronized (this) {
2195 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
2196 }
2197 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002198
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002199 public void setPackageScreenCompatMode(String packageName, int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002200 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2201 "setPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002202 synchronized (this) {
2203 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002204 }
2205 }
2206
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002207 public boolean getPackageAskScreenCompat(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002208 enforceNotIsolatedCaller("getPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002209 synchronized (this) {
2210 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
2211 }
2212 }
2213
2214 public void setPackageAskScreenCompat(String packageName, boolean ask) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002215 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2216 "setPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002217 synchronized (this) {
2218 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
2219 }
2220 }
2221
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002222 void reportResumedActivityLocked(ActivityRecord r) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002223 //Slog.i(TAG, "**** REPORT RESUME: " + r);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002224
2225 final int identHash = System.identityHashCode(r);
2226 updateUsageStats(r, true);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002227 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002228
Jeff Sharkeya4620792011-05-20 15:29:23 -07002229 private void dispatchForegroundActivitiesChanged(int pid, int uid, boolean foregroundActivities) {
2230 int i = mProcessObservers.beginBroadcast();
2231 while (i > 0) {
2232 i--;
2233 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2234 if (observer != null) {
2235 try {
2236 observer.onForegroundActivitiesChanged(pid, uid, foregroundActivities);
2237 } catch (RemoteException e) {
2238 }
2239 }
2240 }
2241 mProcessObservers.finishBroadcast();
2242 }
2243
2244 private void dispatchProcessDied(int pid, int uid) {
2245 int i = mProcessObservers.beginBroadcast();
2246 while (i > 0) {
2247 i--;
2248 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2249 if (observer != null) {
2250 try {
2251 observer.onProcessDied(pid, uid);
2252 } catch (RemoteException e) {
2253 }
2254 }
2255 }
2256 mProcessObservers.finishBroadcast();
2257 }
2258
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002259 final void doPendingActivityLaunchesLocked(boolean doResume) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002260 final int N = mPendingActivityLaunches.size();
2261 if (N <= 0) {
2262 return;
2263 }
2264 for (int i=0; i<N; i++) {
2265 PendingActivityLaunch pal = mPendingActivityLaunches.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002266 mMainStack.startActivityUncheckedLocked(pal.r, pal.sourceRecord,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002267 pal.startFlags, doResume && i == (N-1), null);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002268 }
2269 mPendingActivityLaunches.clear();
2270 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002271
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002272 public final int startActivity(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002273 Intent intent, String resolvedType, IBinder resultTo,
2274 String resultWho, int requestCode, int startFlags,
2275 String profileFile, ParcelFileDescriptor profileFd, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002276 enforceNotIsolatedCaller("startActivity");
Amith Yamasani742a6712011-05-04 14:49:28 -07002277 int userId = 0;
2278 if (intent.getCategories() != null && intent.getCategories().contains(Intent.CATEGORY_HOME)) {
2279 // Requesting home, set the identity to the current user
2280 // HACK!
2281 userId = mCurrentUserId;
2282 } else {
2283 // TODO: Fix this in a better way - calls coming from SystemUI should probably carry
2284 // the current user's userId
2285 if (Binder.getCallingUid() < Process.FIRST_APPLICATION_UID) {
2286 userId = 0;
2287 } else {
2288 userId = Binder.getOrigCallingUser();
2289 }
2290 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002291 return mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002292 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
2293 null, null, options, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002294 }
2295
2296 public final WaitResult startActivityAndWait(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002297 Intent intent, String resolvedType, IBinder resultTo,
2298 String resultWho, int requestCode, int startFlags, String profileFile,
2299 ParcelFileDescriptor profileFd, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002300 enforceNotIsolatedCaller("startActivityAndWait");
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002301 WaitResult res = new WaitResult();
Amith Yamasani742a6712011-05-04 14:49:28 -07002302 int userId = Binder.getOrigCallingUser();
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002303 mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002304 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
2305 res, null, options, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002306 return res;
2307 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08002308
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002309 public final int startActivityWithConfig(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002310 Intent intent, String resolvedType, IBinder resultTo,
2311 String resultWho, int requestCode, int startFlags, Configuration config,
2312 Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002313 enforceNotIsolatedCaller("startActivityWithConfig");
Amith Yamasani742a6712011-05-04 14:49:28 -07002314 int ret = mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002315 resultTo, resultWho, requestCode, startFlags,
2316 null, null, null, config, options, Binder.getOrigCallingUser());
Amith Yamasani742a6712011-05-04 14:49:28 -07002317 return ret;
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002318 }
2319
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002320 public int startActivityIntentSender(IApplicationThread caller,
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002321 IntentSender intent, Intent fillInIntent, String resolvedType,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002322 IBinder resultTo, String resultWho, int requestCode,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002323 int flagsMask, int flagsValues, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002324 enforceNotIsolatedCaller("startActivityIntentSender");
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002325 // Refuse possible leaked file descriptors
2326 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
2327 throw new IllegalArgumentException("File descriptors passed in Intent");
2328 }
2329
2330 IIntentSender sender = intent.getTarget();
2331 if (!(sender instanceof PendingIntentRecord)) {
2332 throw new IllegalArgumentException("Bad PendingIntent object");
2333 }
2334
2335 PendingIntentRecord pir = (PendingIntentRecord)sender;
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002336
2337 synchronized (this) {
2338 // If this is coming from the currently resumed activity, it is
2339 // effectively saying that app switches are allowed at this point.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002340 if (mMainStack.mResumedActivity != null
2341 && mMainStack.mResumedActivity.info.applicationInfo.uid ==
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002342 Binder.getCallingUid()) {
2343 mAppSwitchesAllowedTime = 0;
2344 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002345 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002346 int ret = pir.sendInner(0, fillInIntent, resolvedType, null, null,
2347 resultTo, resultWho, requestCode, flagsMask, flagsValues, options);
Amith Yamasani742a6712011-05-04 14:49:28 -07002348 return ret;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002349 }
2350
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002351 public boolean startNextMatchingActivity(IBinder callingActivity,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002352 Intent intent, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002353 // Refuse possible leaked file descriptors
2354 if (intent != null && intent.hasFileDescriptors() == true) {
2355 throw new IllegalArgumentException("File descriptors passed in Intent");
2356 }
2357
2358 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002359 ActivityRecord r = mMainStack.isInStackLocked(callingActivity);
2360 if (r == null) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002361 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002362 return false;
2363 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002364 if (r.app == null || r.app.thread == null) {
2365 // The caller is not running... d'oh!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002366 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002367 return false;
2368 }
2369 intent = new Intent(intent);
2370 // The caller is not allowed to change the data.
2371 intent.setDataAndType(r.intent.getData(), r.intent.getType());
2372 // And we are resetting to find the next component...
2373 intent.setComponent(null);
2374
2375 ActivityInfo aInfo = null;
2376 try {
2377 List<ResolveInfo> resolves =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002378 AppGlobals.getPackageManager().queryIntentActivities(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002379 intent, r.resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002380 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
2381 UserId.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002382
2383 // Look for the original activity in the list...
2384 final int N = resolves != null ? resolves.size() : 0;
2385 for (int i=0; i<N; i++) {
2386 ResolveInfo rInfo = resolves.get(i);
2387 if (rInfo.activityInfo.packageName.equals(r.packageName)
2388 && rInfo.activityInfo.name.equals(r.info.name)) {
2389 // We found the current one... the next matching is
2390 // after it.
2391 i++;
2392 if (i<N) {
2393 aInfo = resolves.get(i).activityInfo;
2394 }
2395 break;
2396 }
2397 }
2398 } catch (RemoteException e) {
2399 }
2400
2401 if (aInfo == null) {
2402 // Nobody who is next!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002403 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002404 return false;
2405 }
2406
2407 intent.setComponent(new ComponentName(
2408 aInfo.applicationInfo.packageName, aInfo.name));
2409 intent.setFlags(intent.getFlags()&~(
2410 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
2411 Intent.FLAG_ACTIVITY_CLEAR_TOP|
2412 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
2413 Intent.FLAG_ACTIVITY_NEW_TASK));
2414
2415 // Okay now we need to start the new activity, replacing the
2416 // currently running activity. This is a little tricky because
2417 // we want to start the new one as if the current one is finished,
2418 // but not finish the current one first so that there is no flicker.
2419 // And thus...
2420 final boolean wasFinishing = r.finishing;
2421 r.finishing = true;
2422
2423 // Propagate reply information over to the new activity.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002424 final ActivityRecord resultTo = r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002425 final String resultWho = r.resultWho;
2426 final int requestCode = r.requestCode;
2427 r.resultTo = null;
2428 if (resultTo != null) {
2429 resultTo.removeResultsLocked(r, resultWho, requestCode);
2430 }
2431
2432 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002433 int res = mMainStack.startActivityLocked(r.app.thread, intent,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002434 r.resolvedType, aInfo, resultTo != null ? resultTo.appToken : null,
2435 resultWho, requestCode, -1, r.launchedFromUid, 0,
2436 options, false, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002437 Binder.restoreCallingIdentity(origId);
2438
2439 r.finishing = wasFinishing;
Dianne Hackborna4972e92012-03-14 10:38:05 -07002440 if (res != ActivityManager.START_SUCCESS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002441 return false;
2442 }
2443 return true;
2444 }
2445 }
2446
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002447 public final int startActivityInPackage(int uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002448 Intent intent, String resolvedType, IBinder resultTo,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002449 String resultWho, int requestCode, int startFlags, Bundle options) {
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002450
2451 // This is so super not safe, that only the system (or okay root)
2452 // can do it.
Amith Yamasani742a6712011-05-04 14:49:28 -07002453 int userId = Binder.getOrigCallingUser();
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002454 final int callingUid = Binder.getCallingUid();
2455 if (callingUid != 0 && callingUid != Process.myUid()) {
2456 throw new SecurityException(
2457 "startActivityInPackage only available to the system");
2458 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002459
Amith Yamasani742a6712011-05-04 14:49:28 -07002460 int ret = mMainStack.startActivityMayWait(null, uid, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002461 resultTo, resultWho, requestCode, startFlags,
2462 null, null, null, null, options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002463 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002464 }
2465
2466 public final int startActivities(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002467 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002468 enforceNotIsolatedCaller("startActivities");
Amith Yamasani742a6712011-05-04 14:49:28 -07002469 int ret = mMainStack.startActivities(caller, -1, intents, resolvedTypes, resultTo,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002470 options, Binder.getOrigCallingUser());
Amith Yamasani742a6712011-05-04 14:49:28 -07002471 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002472 }
2473
2474 public final int startActivitiesInPackage(int uid,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002475 Intent[] intents, String[] resolvedTypes, IBinder resultTo,
2476 Bundle options) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002477
2478 // This is so super not safe, that only the system (or okay root)
2479 // can do it.
2480 final int callingUid = Binder.getCallingUid();
2481 if (callingUid != 0 && callingUid != Process.myUid()) {
2482 throw new SecurityException(
2483 "startActivityInPackage only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002484 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002485 int ret = mMainStack.startActivities(null, uid, intents, resolvedTypes, resultTo,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002486 options, UserId.getUserId(uid));
Amith Yamasani742a6712011-05-04 14:49:28 -07002487 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002488 }
2489
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002490 final void addRecentTaskLocked(TaskRecord task) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002491 int N = mRecentTasks.size();
Dianne Hackborn7c0e75e2010-12-21 19:15:40 -08002492 // Quick case: check if the top-most recent task is the same.
2493 if (N > 0 && mRecentTasks.get(0) == task) {
2494 return;
2495 }
2496 // Remove any existing entries that are the same kind of task.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002497 for (int i=0; i<N; i++) {
2498 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07002499 if (task.userId == tr.userId
2500 && ((task.affinity != null && task.affinity.equals(tr.affinity))
2501 || (task.intent != null && task.intent.filterEquals(tr.intent)))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002502 mRecentTasks.remove(i);
2503 i--;
2504 N--;
2505 if (task.intent == null) {
2506 // If the new recent task we are adding is not fully
2507 // specified, then replace it with the existing recent task.
2508 task = tr;
2509 }
2510 }
2511 }
2512 if (N >= MAX_RECENT_TASKS) {
2513 mRecentTasks.remove(N-1);
2514 }
2515 mRecentTasks.add(0, task);
2516 }
2517
2518 public void setRequestedOrientation(IBinder token,
2519 int requestedOrientation) {
2520 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002521 ActivityRecord r = mMainStack.isInStackLocked(token);
2522 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002523 return;
2524 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002525 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornbe707852011-11-11 14:32:10 -08002526 mWindowManager.setAppOrientation(r.appToken, requestedOrientation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002527 Configuration config = mWindowManager.updateOrientationFromAppTokens(
The Android Open Source Project10592532009-03-18 17:39:46 -07002528 mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -08002529 r.mayFreezeScreenLocked(r.app) ? r.appToken : null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002530 if (config != null) {
2531 r.frozenBeforeDestroy = true;
Dianne Hackborn813075a62011-11-14 17:45:19 -08002532 if (!updateConfigurationLocked(config, r, false, false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002533 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002534 }
2535 }
2536 Binder.restoreCallingIdentity(origId);
2537 }
2538 }
2539
2540 public int getRequestedOrientation(IBinder token) {
2541 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002542 ActivityRecord r = mMainStack.isInStackLocked(token);
2543 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002544 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
2545 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08002546 return mWindowManager.getAppOrientation(r.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002547 }
2548 }
2549
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002550 /**
2551 * This is the internal entry point for handling Activity.finish().
2552 *
2553 * @param token The Binder token referencing the Activity we want to finish.
2554 * @param resultCode Result code, if any, from this Activity.
2555 * @param resultData Result data (Intent), if any, from this Activity.
2556 *
Alexey Tarasov83bad3d2009-08-12 15:05:43 +11002557 * @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 -08002558 */
2559 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData) {
2560 // Refuse possible leaked file descriptors
2561 if (resultData != null && resultData.hasFileDescriptors() == true) {
2562 throw new IllegalArgumentException("File descriptors passed in Intent");
2563 }
2564
2565 synchronized(this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002566 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002567 // Find the first activity that is not finishing.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002568 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002569 if (next != null) {
2570 // ask watcher if this is allowed
2571 boolean resumeOK = true;
2572 try {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002573 resumeOK = mController.activityResuming(next.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002574 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002575 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002576 }
2577
2578 if (!resumeOK) {
2579 return false;
2580 }
2581 }
2582 }
2583 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002584 boolean res = mMainStack.requestFinishActivityLocked(token, resultCode,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002585 resultData, "app-request");
2586 Binder.restoreCallingIdentity(origId);
2587 return res;
2588 }
2589 }
2590
Dianne Hackborn860755f2010-06-03 18:47:52 -07002591 public final void finishHeavyWeightApp() {
2592 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2593 != PackageManager.PERMISSION_GRANTED) {
2594 String msg = "Permission Denial: finishHeavyWeightApp() from pid="
2595 + Binder.getCallingPid()
2596 + ", uid=" + Binder.getCallingUid()
2597 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2598 Slog.w(TAG, msg);
2599 throw new SecurityException(msg);
2600 }
2601
2602 synchronized(this) {
2603 if (mHeavyWeightProcess == null) {
2604 return;
2605 }
2606
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002607 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>(
Dianne Hackborn860755f2010-06-03 18:47:52 -07002608 mHeavyWeightProcess.activities);
2609 for (int i=0; i<activities.size(); i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002610 ActivityRecord r = activities.get(i);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002611 if (!r.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002612 int index = mMainStack.indexOfTokenLocked(r.appToken);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002613 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002614 mMainStack.finishActivityLocked(r, index, Activity.RESULT_CANCELED,
Dianne Hackborn860755f2010-06-03 18:47:52 -07002615 null, "finish-heavy");
2616 }
2617 }
2618 }
2619
2620 mHeavyWeightProcess = null;
2621 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
2622 }
2623 }
2624
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002625 public void crashApplication(int uid, int initialPid, String packageName,
2626 String message) {
2627 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2628 != PackageManager.PERMISSION_GRANTED) {
2629 String msg = "Permission Denial: crashApplication() from pid="
2630 + Binder.getCallingPid()
2631 + ", uid=" + Binder.getCallingUid()
2632 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2633 Slog.w(TAG, msg);
2634 throw new SecurityException(msg);
2635 }
2636
2637 synchronized(this) {
2638 ProcessRecord proc = null;
2639
2640 // Figure out which process to kill. We don't trust that initialPid
2641 // still has any relation to current pids, so must scan through the
2642 // list.
2643 synchronized (mPidsSelfLocked) {
2644 for (int i=0; i<mPidsSelfLocked.size(); i++) {
2645 ProcessRecord p = mPidsSelfLocked.valueAt(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002646 if (p.uid != uid) {
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002647 continue;
2648 }
2649 if (p.pid == initialPid) {
2650 proc = p;
2651 break;
2652 }
2653 for (String str : p.pkgList) {
2654 if (str.equals(packageName)) {
2655 proc = p;
2656 }
2657 }
2658 }
2659 }
2660
2661 if (proc == null) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07002662 Slog.w(TAG, "crashApplication: nothing for uid=" + uid
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002663 + " initialPid=" + initialPid
2664 + " packageName=" + packageName);
2665 return;
2666 }
2667
2668 if (proc.thread != null) {
Dianne Hackborn9f531192010-08-04 17:48:03 -07002669 if (proc.pid == Process.myPid()) {
2670 Log.w(TAG, "crashApplication: trying to crash self!");
2671 return;
2672 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002673 long ident = Binder.clearCallingIdentity();
2674 try {
2675 proc.thread.scheduleCrash(message);
2676 } catch (RemoteException e) {
2677 }
2678 Binder.restoreCallingIdentity(ident);
2679 }
2680 }
2681 }
2682
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002683 public final void finishSubActivity(IBinder token, String resultWho,
2684 int requestCode) {
2685 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002686 ActivityRecord self = mMainStack.isInStackLocked(token);
2687 if (self == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002688 return;
2689 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002690
2691 final long origId = Binder.clearCallingIdentity();
2692
2693 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002694 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2695 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002696 if (r.resultTo == self && r.requestCode == requestCode) {
2697 if ((r.resultWho == null && resultWho == null) ||
2698 (r.resultWho != null && r.resultWho.equals(resultWho))) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002699 mMainStack.finishActivityLocked(r, i,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002700 Activity.RESULT_CANCELED, null, "request-sub");
2701 }
2702 }
2703 }
2704
2705 Binder.restoreCallingIdentity(origId);
2706 }
2707 }
2708
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002709 public boolean willActivityBeVisible(IBinder token) {
2710 synchronized(this) {
2711 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002712 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2713 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08002714 if (r.appToken == token) {
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002715 return true;
2716 }
2717 if (r.fullscreen && !r.finishing) {
2718 return false;
2719 }
2720 }
2721 return true;
2722 }
2723 }
2724
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002725 public void overridePendingTransition(IBinder token, String packageName,
2726 int enterAnim, int exitAnim) {
2727 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002728 ActivityRecord self = mMainStack.isInStackLocked(token);
2729 if (self == null) {
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002730 return;
2731 }
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002732
2733 final long origId = Binder.clearCallingIdentity();
2734
2735 if (self.state == ActivityState.RESUMED
2736 || self.state == ActivityState.PAUSING) {
2737 mWindowManager.overridePendingAppTransition(packageName,
2738 enterAnim, exitAnim);
2739 }
2740
2741 Binder.restoreCallingIdentity(origId);
2742 }
2743 }
2744
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002745 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002746 * Main function for removing an existing process from the activity manager
2747 * as a result of that process going away. Clears out all connections
2748 * to the process.
2749 */
2750 private final void handleAppDiedLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002751 boolean restarting, boolean allowRestart) {
2752 cleanUpApplicationRecordLocked(app, restarting, allowRestart, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002753 if (!restarting) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002754 mLruProcesses.remove(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002755 }
2756
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002757 if (mProfileProc == app) {
2758 clearProfilerLocked();
2759 }
2760
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002761 // Just in case...
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002762 if (mMainStack.mPausingActivity != null && mMainStack.mPausingActivity.app == app) {
2763 if (DEBUG_PAUSE) Slog.v(TAG, "App died while pausing: " +mMainStack.mPausingActivity);
2764 mMainStack.mPausingActivity = null;
2765 }
2766 if (mMainStack.mLastPausedActivity != null && mMainStack.mLastPausedActivity.app == app) {
2767 mMainStack.mLastPausedActivity = null;
2768 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002769
2770 // Remove this application's activities from active lists.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002771 mMainStack.removeHistoryRecordsForAppLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002772
2773 boolean atTop = true;
2774 boolean hasVisibleActivities = false;
2775
2776 // Clean out the history list.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002777 int i = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08002778 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002779 TAG, "Removing app " + app + " from history with " + i + " entries");
2780 while (i > 0) {
2781 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002782 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002783 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002784 TAG, "Record #" + i + " " + r + ": app=" + r.app);
2785 if (r.app == app) {
2786 if ((!r.haveState && !r.stateNotNeeded) || r.finishing) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002787 if (ActivityStack.DEBUG_ADD_REMOVE) {
2788 RuntimeException here = new RuntimeException("here");
2789 here.fillInStackTrace();
2790 Slog.i(TAG, "Removing activity " + r + " from stack at " + i
2791 + ": haveState=" + r.haveState
2792 + " stateNotNeeded=" + r.stateNotNeeded
2793 + " finishing=" + r.finishing
2794 + " state=" + r.state, here);
2795 }
2796 if (!r.finishing) {
2797 Slog.w(TAG, "Force removing " + r + ": app died, no saved state");
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -08002798 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
2799 System.identityHashCode(r),
2800 r.task.taskId, r.shortComponentName,
2801 "proc died without state saved");
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002802 }
Dianne Hackborn5c607432012-02-28 14:44:19 -08002803 mMainStack.removeActivityFromHistoryLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002804
2805 } else {
2806 // We have the current state for this activity, so
2807 // it can be restarted later when needed.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002808 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002809 TAG, "Keeping entry, setting app to null");
2810 if (r.visible) {
2811 hasVisibleActivities = true;
2812 }
2813 r.app = null;
2814 r.nowVisible = false;
2815 if (!r.haveState) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002816 if (ActivityStack.DEBUG_SAVED_STATE) Slog.i(TAG,
2817 "App died, clearing saved state of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002818 r.icicle = null;
2819 }
2820 }
2821
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002822 r.stack.cleanUpActivityLocked(r, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002823 }
2824 atTop = false;
2825 }
2826
2827 app.activities.clear();
2828
2829 if (app.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002830 Slog.w(TAG, "Crash of app " + app.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002831 + " running instrumentation " + app.instrumentationClass);
2832 Bundle info = new Bundle();
2833 info.putString("shortMsg", "Process crashed.");
2834 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
2835 }
2836
2837 if (!restarting) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002838 if (!mMainStack.resumeTopActivityLocked(null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002839 // If there was nothing to resume, and we are not already
2840 // restarting this process, but there is a visible activity that
2841 // is hosted by the process... then make sure all visible
2842 // activities are running, taking care of restarting this
2843 // process.
2844 if (hasVisibleActivities) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002845 mMainStack.ensureActivitiesVisibleLocked(null, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002846 }
2847 }
2848 }
2849 }
2850
2851 private final int getLRURecordIndexForAppLocked(IApplicationThread thread) {
2852 IBinder threadBinder = thread.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002853 // Find the application record.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002854 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2855 ProcessRecord rec = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002856 if (rec.thread != null && rec.thread.asBinder() == threadBinder) {
2857 return i;
2858 }
2859 }
2860 return -1;
2861 }
2862
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002863 final ProcessRecord getRecordForAppLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002864 IApplicationThread thread) {
2865 if (thread == null) {
2866 return null;
2867 }
2868
2869 int appIndex = getLRURecordIndexForAppLocked(thread);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002870 return appIndex >= 0 ? mLruProcesses.get(appIndex) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002871 }
2872
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002873 final void appDiedLocked(ProcessRecord app, int pid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002874 IApplicationThread thread) {
2875
2876 mProcDeaths[0]++;
2877
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002878 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
2879 synchronized (stats) {
2880 stats.noteProcessDiedLocked(app.info.uid, pid);
2881 }
2882
Magnus Edlund7bb25812010-02-24 15:45:06 +01002883 // Clean up already done if the process has been re-started.
2884 if (app.pid == pid && app.thread != null &&
2885 app.thread.asBinder() == thread.asBinder()) {
Dianne Hackborn906497c2010-05-10 15:57:38 -07002886 if (!app.killedBackground) {
2887 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
2888 + ") has died.");
2889 }
Doug Zongker2bec3d42009-12-04 12:52:44 -08002890 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002891 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002892 TAG, "Dying app: " + app + ", pid: " + pid
2893 + ", thread: " + thread.asBinder());
2894 boolean doLowMem = app.instrumentationClass == null;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002895 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002896
2897 if (doLowMem) {
2898 // If there are no longer any background processes running,
2899 // and the app that died was not running instrumentation,
2900 // then tell everyone we are now low on memory.
2901 boolean haveBg = false;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002902 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2903 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -07002904 if (rec.thread != null && rec.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002905 haveBg = true;
2906 break;
2907 }
2908 }
2909
2910 if (!haveBg) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002911 EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mLruProcesses.size());
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002912 long now = SystemClock.uptimeMillis();
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002913 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2914 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn36124872009-10-08 16:22:03 -07002915 if (rec != app && rec.thread != null &&
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002916 (rec.lastLowMemory+GC_MIN_INTERVAL) <= now) {
2917 // The low memory report is overriding any current
2918 // state for a GC request. Make sure to do
Dianne Hackborn32907cf2010-06-10 17:50:20 -07002919 // heavy/important/visible/foreground processes first.
Dianne Hackborn7d608422011-08-07 16:24:18 -07002920 if (rec.setAdj <= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002921 rec.lastRequestedGc = 0;
2922 } else {
2923 rec.lastRequestedGc = rec.lastLowMemory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002924 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002925 rec.reportLowMemory = true;
2926 rec.lastLowMemory = now;
2927 mProcessesToGc.remove(rec);
2928 addProcessToGcListLocked(rec);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002929 }
2930 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07002931 mHandler.sendEmptyMessage(REPORT_MEM_USAGE);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002932 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002933 }
2934 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01002935 } else if (app.pid != pid) {
2936 // A new process has already been started.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002937 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
Magnus Edlund7bb25812010-02-24 15:45:06 +01002938 + ") has died and restarted (pid " + app.pid + ").");
Dianne Hackborn28a8c2b2010-03-01 11:30:02 -08002939 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08002940 } else if (DEBUG_PROCESSES) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002941 Slog.d(TAG, "Received spurious death notification for thread "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002942 + thread.asBinder());
2943 }
2944 }
2945
Dan Egnor42471dd2010-01-07 17:25:22 -08002946 /**
2947 * If a stack trace dump file is configured, dump process stack traces.
Christopher Tate6ee412d2010-05-28 12:01:56 -07002948 * @param clearTraces causes the dump file to be erased prior to the new
2949 * traces being written, if true; when false, the new traces will be
2950 * appended to any existing file content.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002951 * @param firstPids of dalvik VM processes to dump stack traces for first
2952 * @param lastPids of dalvik VM processes to dump stack traces for last
Dan Egnor42471dd2010-01-07 17:25:22 -08002953 * @return file containing stack traces, or null if no dump file is configured
2954 */
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002955 public static File dumpStackTraces(boolean clearTraces, ArrayList<Integer> firstPids,
2956 ProcessStats processStats, SparseArray<Boolean> lastPids) {
Dan Egnor42471dd2010-01-07 17:25:22 -08002957 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
2958 if (tracesPath == null || tracesPath.length() == 0) {
2959 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002960 }
Dan Egnor42471dd2010-01-07 17:25:22 -08002961
2962 File tracesFile = new File(tracesPath);
2963 try {
2964 File tracesDir = tracesFile.getParentFile();
2965 if (!tracesDir.exists()) tracesFile.mkdirs();
2966 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
2967
Christopher Tate6ee412d2010-05-28 12:01:56 -07002968 if (clearTraces && tracesFile.exists()) tracesFile.delete();
Dan Egnor42471dd2010-01-07 17:25:22 -08002969 tracesFile.createNewFile();
2970 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
2971 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002972 Slog.w(TAG, "Unable to prepare ANR traces file: " + tracesPath, e);
Dan Egnor42471dd2010-01-07 17:25:22 -08002973 return null;
2974 }
2975
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07002976 dumpStackTraces(tracesPath, firstPids, processStats, lastPids);
2977 return tracesFile;
2978 }
2979
2980 private static void dumpStackTraces(String tracesPath, ArrayList<Integer> firstPids,
2981 ProcessStats processStats, SparseArray<Boolean> lastPids) {
Dan Egnor42471dd2010-01-07 17:25:22 -08002982 // Use a FileObserver to detect when traces finish writing.
2983 // The order of traces is considered important to maintain for legibility.
2984 FileObserver observer = new FileObserver(tracesPath, FileObserver.CLOSE_WRITE) {
2985 public synchronized void onEvent(int event, String path) { notify(); }
2986 };
2987
2988 try {
2989 observer.startWatching();
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002990
2991 // First collect all of the stacks of the most important pids.
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07002992 if (firstPids != null) {
2993 try {
2994 int num = firstPids.size();
2995 for (int i = 0; i < num; i++) {
2996 synchronized (observer) {
2997 Process.sendSignal(firstPids.get(i), Process.SIGNAL_QUIT);
2998 observer.wait(200); // Wait for write-close, give up after 200msec
2999 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003000 }
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003001 } catch (InterruptedException e) {
3002 Log.wtf(TAG, e);
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003003 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003004 }
3005
3006 // Next measure CPU usage.
3007 if (processStats != null) {
3008 processStats.init();
3009 System.gc();
3010 processStats.update();
3011 try {
3012 synchronized (processStats) {
3013 processStats.wait(500); // measure over 1/2 second.
3014 }
3015 } catch (InterruptedException e) {
3016 }
3017 processStats.update();
3018
3019 // We'll take the stack crawls of just the top apps using CPU.
3020 final int N = processStats.countWorkingStats();
3021 int numProcs = 0;
3022 for (int i=0; i<N && numProcs<5; i++) {
3023 ProcessStats.Stats stats = processStats.getWorkingStats(i);
3024 if (lastPids.indexOfKey(stats.pid) >= 0) {
3025 numProcs++;
3026 try {
3027 synchronized (observer) {
3028 Process.sendSignal(stats.pid, Process.SIGNAL_QUIT);
3029 observer.wait(200); // Wait for write-close, give up after 200msec
3030 }
3031 } catch (InterruptedException e) {
3032 Log.wtf(TAG, e);
3033 }
3034
3035 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003036 }
3037 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003038
Dan Egnor42471dd2010-01-07 17:25:22 -08003039 } finally {
3040 observer.stopWatching();
3041 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003042 }
3043
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003044 final void logAppTooSlow(ProcessRecord app, long startTime, String msg) {
Dianne Hackborn69dc66e2012-03-26 10:50:54 -07003045 if (true || IS_USER_BUILD) {
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003046 return;
3047 }
3048 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
3049 if (tracesPath == null || tracesPath.length() == 0) {
3050 return;
3051 }
3052
3053 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
3054 StrictMode.allowThreadDiskWrites();
3055 try {
3056 final File tracesFile = new File(tracesPath);
3057 final File tracesDir = tracesFile.getParentFile();
3058 final File tracesTmp = new File(tracesDir, "__tmp__");
3059 try {
3060 if (!tracesDir.exists()) tracesFile.mkdirs();
3061 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
3062
3063 if (tracesFile.exists()) {
3064 tracesTmp.delete();
3065 tracesFile.renameTo(tracesTmp);
3066 }
3067 StringBuilder sb = new StringBuilder();
3068 Time tobj = new Time();
3069 tobj.set(System.currentTimeMillis());
3070 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
3071 sb.append(": ");
3072 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
3073 sb.append(" since ");
3074 sb.append(msg);
3075 FileOutputStream fos = new FileOutputStream(tracesFile);
3076 fos.write(sb.toString().getBytes());
3077 if (app == null) {
3078 fos.write("\n*** No application process!".getBytes());
3079 }
3080 fos.close();
3081 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
3082 } catch (IOException e) {
3083 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesPath, e);
3084 return;
3085 }
3086
3087 if (app != null) {
3088 ArrayList<Integer> firstPids = new ArrayList<Integer>();
3089 firstPids.add(app.pid);
3090 dumpStackTraces(tracesPath, firstPids, null, null);
3091 }
3092
3093 File lastTracesFile = null;
3094 File curTracesFile = null;
3095 for (int i=9; i>=0; i--) {
3096 String name = String.format("slow%02d.txt", i);
3097 curTracesFile = new File(tracesDir, name);
3098 if (curTracesFile.exists()) {
3099 if (lastTracesFile != null) {
3100 curTracesFile.renameTo(lastTracesFile);
3101 } else {
3102 curTracesFile.delete();
3103 }
3104 }
3105 lastTracesFile = curTracesFile;
3106 }
3107 tracesFile.renameTo(curTracesFile);
3108 if (tracesTmp.exists()) {
3109 tracesTmp.renameTo(tracesFile);
3110 }
3111 } finally {
3112 StrictMode.setThreadPolicy(oldPolicy);
3113 }
3114 }
3115
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003116 final void appNotResponding(ProcessRecord app, ActivityRecord activity,
3117 ActivityRecord parent, final String annotation) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003118 ArrayList<Integer> firstPids = new ArrayList<Integer>(5);
3119 SparseArray<Boolean> lastPids = new SparseArray<Boolean>(20);
3120
Dianne Hackborn287952c2010-09-22 22:34:31 -07003121 if (mController != null) {
3122 try {
3123 // 0 == continue, -1 = kill process immediately
3124 int res = mController.appEarlyNotResponding(app.processName, app.pid, annotation);
3125 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3126 } catch (RemoteException e) {
3127 mController = null;
3128 }
3129 }
3130
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003131 long anrTime = SystemClock.uptimeMillis();
3132 if (MONITOR_CPU_USAGE) {
3133 updateCpuStatsNow();
3134 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003135
3136 synchronized (this) {
3137 // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down.
3138 if (mShuttingDown) {
3139 Slog.i(TAG, "During shutdown skipping ANR: " + app + " " + annotation);
3140 return;
3141 } else if (app.notResponding) {
3142 Slog.i(TAG, "Skipping duplicate ANR: " + app + " " + annotation);
3143 return;
3144 } else if (app.crashing) {
3145 Slog.i(TAG, "Crashing app skipping ANR: " + app + " " + annotation);
3146 return;
3147 }
3148
3149 // In case we come through here for the same app before completing
3150 // this one, mark as anring now so we will bail out.
3151 app.notResponding = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08003152
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003153 // Log the ANR to the event log.
3154 EventLog.writeEvent(EventLogTags.AM_ANR, app.pid, app.processName, app.info.flags,
3155 annotation);
Dan Egnor42471dd2010-01-07 17:25:22 -08003156
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003157 // Dump thread traces as quickly as we can, starting with "interesting" processes.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003158 firstPids.add(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003159
3160 int parentPid = app.pid;
3161 if (parent != null && parent.app != null && parent.app.pid > 0) parentPid = parent.app.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003162 if (parentPid != app.pid) firstPids.add(parentPid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003163
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003164 if (MY_PID != app.pid && MY_PID != parentPid) firstPids.add(MY_PID);
Dan Egnor42471dd2010-01-07 17:25:22 -08003165
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003166 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
3167 ProcessRecord r = mLruProcesses.get(i);
3168 if (r != null && r.thread != null) {
3169 int pid = r.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003170 if (pid > 0 && pid != app.pid && pid != parentPid && pid != MY_PID) {
3171 if (r.persistent) {
3172 firstPids.add(pid);
3173 } else {
3174 lastPids.put(pid, Boolean.TRUE);
3175 }
3176 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003177 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003178 }
3179 }
3180
Dan Egnor42471dd2010-01-07 17:25:22 -08003181 // Log the ANR to the main log.
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07003182 StringBuilder info = mStringBuilder;
3183 info.setLength(0);
Dan Egnor42471dd2010-01-07 17:25:22 -08003184 info.append("ANR in ").append(app.processName);
3185 if (activity != null && activity.shortComponentName != null) {
3186 info.append(" (").append(activity.shortComponentName).append(")");
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07003187 }
Eric Rowe6f4f6192010-02-17 18:29:04 -08003188 info.append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003189 if (annotation != null) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003190 info.append("Reason: ").append(annotation).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003191 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003192 if (parent != null && parent != activity) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003193 info.append("Parent: ").append(parent.shortComponentName).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003194 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003195
Dianne Hackborn287952c2010-09-22 22:34:31 -07003196 final ProcessStats processStats = new ProcessStats(true);
3197
3198 File tracesFile = dumpStackTraces(true, firstPids, processStats, lastPids);
3199
Dan Egnor42471dd2010-01-07 17:25:22 -08003200 String cpuInfo = null;
3201 if (MONITOR_CPU_USAGE) {
3202 updateCpuStatsNow();
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003203 synchronized (mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003204 cpuInfo = mProcessStats.printCurrentState(anrTime);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003205 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003206 info.append(processStats.printCurrentLoad());
Dan Egnor42471dd2010-01-07 17:25:22 -08003207 info.append(cpuInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003208 }
3209
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003210 info.append(processStats.printCurrentState(anrTime));
3211
Joe Onorato8a9b2202010-02-26 18:56:32 -08003212 Slog.e(TAG, info.toString());
Dan Egnor42471dd2010-01-07 17:25:22 -08003213 if (tracesFile == null) {
3214 // There is no trace file, so dump (only) the alleged culprit's threads to the log
3215 Process.sendSignal(app.pid, Process.SIGNAL_QUIT);
3216 }
3217
Jeff Sharkeya353d262011-10-28 11:12:06 -07003218 addErrorToDropBox("anr", app, app.processName, activity, parent, annotation,
3219 cpuInfo, tracesFile, null);
Dan Egnor42471dd2010-01-07 17:25:22 -08003220
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003221 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003222 try {
Dan Egnor42471dd2010-01-07 17:25:22 -08003223 // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately
3224 int res = mController.appNotResponding(app.processName, app.pid, info.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003225 if (res != 0) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003226 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3227 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003228 }
3229 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003230 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003231 }
3232 }
3233
Dan Egnor42471dd2010-01-07 17:25:22 -08003234 // Unless configured otherwise, swallow ANRs in background processes & kill the process.
3235 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
3236 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003237
3238 synchronized (this) {
3239 if (!showBackground && !app.isInterestingToUserLocked() && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003240 Slog.w(TAG, "Killing " + app + ": background ANR");
3241 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
3242 app.processName, app.setAdj, "background ANR");
3243 Process.killProcessQuiet(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003244 return;
3245 }
3246
3247 // Set the app's notResponding state, and look up the errorReportReceiver
3248 makeAppNotRespondingLocked(app,
3249 activity != null ? activity.shortComponentName : null,
3250 annotation != null ? "ANR " + annotation : "ANR",
3251 info.toString());
3252
3253 // Bring up the infamous App Not Responding dialog
3254 Message msg = Message.obtain();
3255 HashMap map = new HashMap();
3256 msg.what = SHOW_NOT_RESPONDING_MSG;
3257 msg.obj = map;
3258 map.put("app", app);
3259 if (activity != null) {
3260 map.put("activity", activity);
3261 }
3262
3263 mHandler.sendMessage(msg);
Dan Egnor42471dd2010-01-07 17:25:22 -08003264 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003265 }
3266
Dianne Hackborn0dad3642010-09-09 21:25:35 -07003267 final void showLaunchWarningLocked(final ActivityRecord cur, final ActivityRecord next) {
3268 if (!mLaunchWarningShown) {
3269 mLaunchWarningShown = true;
3270 mHandler.post(new Runnable() {
3271 @Override
3272 public void run() {
3273 synchronized (ActivityManagerService.this) {
3274 final Dialog d = new LaunchWarningWindow(mContext, cur, next);
3275 d.show();
3276 mHandler.postDelayed(new Runnable() {
3277 @Override
3278 public void run() {
3279 synchronized (ActivityManagerService.this) {
3280 d.dismiss();
3281 mLaunchWarningShown = false;
3282 }
3283 }
3284 }, 4000);
3285 }
3286 }
3287 });
3288 }
3289 }
3290
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003291 public boolean clearApplicationUserData(final String packageName,
Amith Yamasani742a6712011-05-04 14:49:28 -07003292 final IPackageDataObserver observer, final int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003293 enforceNotIsolatedCaller("clearApplicationUserData");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003294 int uid = Binder.getCallingUid();
3295 int pid = Binder.getCallingPid();
3296 long callingId = Binder.clearCallingIdentity();
3297 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003298 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003299 int pkgUid = -1;
3300 synchronized(this) {
3301 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003302 pkgUid = pm.getPackageUid(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003303 } catch (RemoteException e) {
3304 }
3305 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003306 Slog.w(TAG, "Invalid packageName:" + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003307 return false;
3308 }
3309 if (uid == pkgUid || checkComponentPermission(
3310 android.Manifest.permission.CLEAR_APP_USER_DATA,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08003311 pid, uid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003312 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003313 forceStopPackageLocked(packageName, pkgUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003314 } else {
3315 throw new SecurityException(pid+" does not have permission:"+
3316 android.Manifest.permission.CLEAR_APP_USER_DATA+" to clear data" +
3317 "for process:"+packageName);
3318 }
3319 }
3320
3321 try {
3322 //clear application user data
Amith Yamasani483f3b02012-03-13 16:08:00 -07003323 pm.clearApplicationUserData(packageName, observer, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003324 Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED,
3325 Uri.fromParts("package", packageName, null));
3326 intent.putExtra(Intent.EXTRA_UID, pkgUid);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003327 broadcastIntentInPackage("android", Process.SYSTEM_UID, intent,
Amith Yamasani742a6712011-05-04 14:49:28 -07003328 null, null, 0, null, null, null, false, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003329 } catch (RemoteException e) {
3330 }
3331 } finally {
3332 Binder.restoreCallingIdentity(callingId);
3333 }
3334 return true;
3335 }
3336
Dianne Hackborn03abb812010-01-04 18:43:19 -08003337 public void killBackgroundProcesses(final String packageName) {
3338 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3339 != PackageManager.PERMISSION_GRANTED &&
3340 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES)
3341 != PackageManager.PERMISSION_GRANTED) {
3342 String msg = "Permission Denial: killBackgroundProcesses() from pid="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003343 + Binder.getCallingPid()
3344 + ", uid=" + Binder.getCallingUid()
Dianne Hackborn03abb812010-01-04 18:43:19 -08003345 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003346 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003347 throw new SecurityException(msg);
3348 }
3349
Amith Yamasani483f3b02012-03-13 16:08:00 -07003350 int userId = UserId.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003351 long callingId = Binder.clearCallingIdentity();
3352 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003353 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003354 int pkgUid = -1;
3355 synchronized(this) {
3356 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003357 pkgUid = pm.getPackageUid(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003358 } catch (RemoteException e) {
3359 }
3360 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003361 Slog.w(TAG, "Invalid packageName: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003362 return;
3363 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003364 killPackageProcessesLocked(packageName, pkgUid,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003365 ProcessList.SERVICE_ADJ, false, true, true, false, "kill background");
3366 }
3367 } finally {
3368 Binder.restoreCallingIdentity(callingId);
3369 }
3370 }
3371
3372 public void killAllBackgroundProcesses() {
3373 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3374 != PackageManager.PERMISSION_GRANTED) {
3375 String msg = "Permission Denial: killAllBackgroundProcesses() from pid="
3376 + Binder.getCallingPid()
3377 + ", uid=" + Binder.getCallingUid()
3378 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
3379 Slog.w(TAG, msg);
3380 throw new SecurityException(msg);
3381 }
3382
3383 long callingId = Binder.clearCallingIdentity();
3384 try {
3385 synchronized(this) {
3386 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
3387 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3388 final int NA = apps.size();
3389 for (int ia=0; ia<NA; ia++) {
3390 ProcessRecord app = apps.valueAt(ia);
3391 if (app.persistent) {
3392 // we don't kill persistent processes
3393 continue;
3394 }
3395 if (app.removed) {
3396 procs.add(app);
3397 } else if (app.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
3398 app.removed = true;
3399 procs.add(app);
3400 }
3401 }
3402 }
3403
3404 int N = procs.size();
3405 for (int i=0; i<N; i++) {
3406 removeProcessLocked(procs.get(i), false, true, "kill all background");
3407 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003408 }
3409 } finally {
3410 Binder.restoreCallingIdentity(callingId);
3411 }
3412 }
3413
3414 public void forceStopPackage(final String packageName) {
3415 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3416 != PackageManager.PERMISSION_GRANTED) {
3417 String msg = "Permission Denial: forceStopPackage() from pid="
3418 + Binder.getCallingPid()
3419 + ", uid=" + Binder.getCallingUid()
3420 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003421 Slog.w(TAG, msg);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003422 throw new SecurityException(msg);
3423 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07003424 final int userId = UserId.getCallingUserId();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003425 long callingId = Binder.clearCallingIdentity();
3426 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003427 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003428 int pkgUid = -1;
3429 synchronized(this) {
3430 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003431 pkgUid = pm.getPackageUid(packageName, userId);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003432 } catch (RemoteException e) {
3433 }
3434 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003435 Slog.w(TAG, "Invalid packageName: " + packageName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003436 return;
3437 }
3438 forceStopPackageLocked(packageName, pkgUid);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003439 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003440 pm.setPackageStoppedState(packageName, true, userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003441 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08003442 } catch (IllegalArgumentException e) {
3443 Slog.w(TAG, "Failed trying to unstop package "
3444 + packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003445 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003446 }
3447 } finally {
3448 Binder.restoreCallingIdentity(callingId);
3449 }
3450 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003451
3452 /*
3453 * The pkg name and uid have to be specified.
3454 * @see android.app.IActivityManager#killApplicationWithUid(java.lang.String, int)
3455 */
3456 public void killApplicationWithUid(String pkg, int uid) {
3457 if (pkg == null) {
3458 return;
3459 }
3460 // Make sure the uid is valid.
3461 if (uid < 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003462 Slog.w(TAG, "Invalid uid specified for pkg : " + pkg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003463 return;
3464 }
3465 int callerUid = Binder.getCallingUid();
3466 // Only the system server can kill an application
3467 if (callerUid == Process.SYSTEM_UID) {
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07003468 // Post an aysnc message to kill the application
3469 Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG);
3470 msg.arg1 = uid;
3471 msg.arg2 = 0;
3472 msg.obj = pkg;
Suchi Amalapurapud50066f2009-08-18 16:57:41 -07003473 mHandler.sendMessage(msg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003474 } else {
3475 throw new SecurityException(callerUid + " cannot kill pkg: " +
3476 pkg);
3477 }
3478 }
3479
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003480 public void closeSystemDialogs(String reason) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003481 enforceNotIsolatedCaller("closeSystemDialogs");
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003482 Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003483 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003484 if (reason != null) {
3485 intent.putExtra("reason", reason);
3486 }
3487
3488 final int uid = Binder.getCallingUid();
3489 final long origId = Binder.clearCallingIdentity();
3490 synchronized (this) {
Dianne Hackbornffa42482009-09-23 22:20:11 -07003491 mWindowManager.closeSystemDialogs(reason);
3492
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08003493 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003494 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornffa42482009-09-23 22:20:11 -07003495 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003496 r.stack.finishActivityLocked(r, i,
Dianne Hackbornffa42482009-09-23 22:20:11 -07003497 Activity.RESULT_CANCELED, null, "close-sys");
3498 }
3499 }
3500
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003501 broadcastIntentLocked(null, null, intent, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07003502 null, 0, null, null, null, false, false, -1, uid, 0 /* TODO: Verify */);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003503 }
3504 Binder.restoreCallingIdentity(origId);
3505 }
3506
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003507 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids)
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003508 throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003509 enforceNotIsolatedCaller("getProcessMemoryInfo");
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003510 Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length];
3511 for (int i=pids.length-1; i>=0; i--) {
3512 infos[i] = new Debug.MemoryInfo();
3513 Debug.getMemoryInfo(pids[i], infos[i]);
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003514 }
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003515 return infos;
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003516 }
Christopher Tate5e1ab332009-09-01 20:32:49 -07003517
Dianne Hackbornb437e092011-08-05 17:50:29 -07003518 public long[] getProcessPss(int[] pids) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003519 enforceNotIsolatedCaller("getProcessPss");
Dianne Hackbornb437e092011-08-05 17:50:29 -07003520 long[] pss = new long[pids.length];
3521 for (int i=pids.length-1; i>=0; i--) {
3522 pss[i] = Debug.getPss(pids[i]);
3523 }
3524 return pss;
3525 }
3526
Christopher Tate5e1ab332009-09-01 20:32:49 -07003527 public void killApplicationProcess(String processName, int uid) {
3528 if (processName == null) {
3529 return;
3530 }
3531
3532 int callerUid = Binder.getCallingUid();
3533 // Only the system server can kill an application
3534 if (callerUid == Process.SYSTEM_UID) {
3535 synchronized (this) {
3536 ProcessRecord app = getProcessRecordLocked(processName, uid);
Christopher Tate4a627c72011-04-01 14:43:32 -07003537 if (app != null && app.thread != null) {
Christopher Tate5e1ab332009-09-01 20:32:49 -07003538 try {
3539 app.thread.scheduleSuicide();
3540 } catch (RemoteException e) {
3541 // If the other end already died, then our work here is done.
3542 }
3543 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003544 Slog.w(TAG, "Process/uid not found attempting kill of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07003545 + processName + " / " + uid);
3546 }
3547 }
3548 } else {
3549 throw new SecurityException(callerUid + " cannot kill app process: " +
3550 processName);
3551 }
3552 }
3553
Dianne Hackborn03abb812010-01-04 18:43:19 -08003554 private void forceStopPackageLocked(final String packageName, int uid) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003555 forceStopPackageLocked(packageName, uid, false, false, true, false, UserId.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003556 Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED,
3557 Uri.fromParts("package", packageName, null));
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003558 if (!mProcessesReady) {
3559 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3560 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003561 intent.putExtra(Intent.EXTRA_UID, uid);
3562 broadcastIntentLocked(null, null, intent,
3563 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07003564 false, false,
3565 MY_PID, Process.SYSTEM_UID, UserId.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003566 }
3567
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003568 private final boolean killPackageProcessesLocked(String packageName, int uid,
Christopher Tate3dacd842011-08-19 14:56:15 -07003569 int minOomAdj, boolean callerWillRestart, boolean allowRestart, boolean doit,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003570 boolean evenPersistent, String reason) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003571 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003572
Dianne Hackborn03abb812010-01-04 18:43:19 -08003573 // Remove all processes this package may have touched: all with the
3574 // same UID (except for the system or root user), and all whose name
3575 // matches the package name.
3576 final String procNamePrefix = packageName + ":";
3577 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3578 final int NA = apps.size();
3579 for (int ia=0; ia<NA; ia++) {
3580 ProcessRecord app = apps.valueAt(ia);
Christopher Tate3dacd842011-08-19 14:56:15 -07003581 if (app.persistent && !evenPersistent) {
Christopher Tate064d8422011-07-26 15:38:07 -07003582 // we don't kill persistent processes
3583 continue;
3584 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003585 if (app.removed) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003586 if (doit) {
3587 procs.add(app);
3588 }
Amith Yamasani13593602012-03-22 16:16:17 -07003589 // If uid is specified and the uid and process name match
3590 // Or, the uid is not specified and the process name matches
3591 } else if (((uid > 0 && uid != Process.SYSTEM_UID && app.info.uid == uid)
3592 && (app.processName.equals(packageName)
3593 || app.processName.startsWith(procNamePrefix)))
3594 || (uid < 0
3595 && (app.processName.equals(packageName)
3596 || app.processName.startsWith(procNamePrefix)))) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003597 if (app.setAdj >= minOomAdj) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003598 if (!doit) {
3599 return true;
3600 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003601 app.removed = true;
3602 procs.add(app);
3603 }
3604 }
3605 }
3606 }
3607
3608 int N = procs.size();
3609 for (int i=0; i<N; i++) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003610 removeProcessLocked(procs.get(i), callerWillRestart, allowRestart, reason);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003611 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003612 return N > 0;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003613 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003614
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003615 private final boolean forceStopPackageLocked(String name, int uid,
Christopher Tate3dacd842011-08-19 14:56:15 -07003616 boolean callerWillRestart, boolean purgeCache, boolean doit,
Amith Yamasani483f3b02012-03-13 16:08:00 -07003617 boolean evenPersistent, int userId) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003618 int i;
3619 int N;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003620
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003621 if (uid < 0) {
3622 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003623 uid = AppGlobals.getPackageManager().getPackageUid(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003624 } catch (RemoteException e) {
3625 }
3626 }
3627
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003628 if (doit) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003629 Slog.i(TAG, "Force stopping package " + name + " uid=" + uid);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003630
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003631 Iterator<SparseArray<Long>> badApps = mProcessCrashTimes.getMap().values().iterator();
3632 while (badApps.hasNext()) {
3633 SparseArray<Long> ba = badApps.next();
3634 if (ba.get(uid) != null) {
3635 badApps.remove();
3636 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003637 }
3638 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003639
3640 boolean didSomething = killPackageProcessesLocked(name, uid, -100,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003641 callerWillRestart, false, doit, evenPersistent, "force stop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003642
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003643 TaskRecord lastTask = null;
3644 for (i=0; i<mMainStack.mHistory.size(); i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003645 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003646 final boolean samePackage = r.packageName.equals(name);
Amith Yamasani13593602012-03-22 16:16:17 -07003647 if (r.userId == userId
3648 && (samePackage || r.task == lastTask)
Christopher Tate3dacd842011-08-19 14:56:15 -07003649 && (r.app == null || evenPersistent || !r.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003650 if (!doit) {
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003651 if (r.finishing) {
3652 // If this activity is just finishing, then it is not
3653 // interesting as far as something to stop.
3654 continue;
3655 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003656 return true;
3657 }
3658 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003659 Slog.i(TAG, " Force finishing activity " + r);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003660 if (samePackage) {
3661 if (r.app != null) {
3662 r.app.removed = true;
3663 }
3664 r.app = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003665 }
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003666 lastTask = r.task;
3667 if (r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003668 null, "force-stop", true)) {
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003669 i--;
3670 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003671 }
3672 }
3673
3674 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
Amith Yamasani742a6712011-05-04 14:49:28 -07003675 for (ServiceRecord service : mServiceMap.getAllServices(userId)) {
Christopher Tate064d8422011-07-26 15:38:07 -07003676 if (service.packageName.equals(name)
Christopher Tate3dacd842011-08-19 14:56:15 -07003677 && (service.app == null || evenPersistent || !service.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003678 if (!doit) {
3679 return true;
3680 }
3681 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003682 Slog.i(TAG, " Force stopping service " + service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003683 if (service.app != null) {
3684 service.app.removed = true;
3685 }
3686 service.app = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003687 service.isolatedProc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003688 services.add(service);
3689 }
3690 }
3691
3692 N = services.size();
3693 for (i=0; i<N; i++) {
3694 bringDownServiceLocked(services.get(i), true);
3695 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003696
3697 ArrayList<ContentProviderRecord> providers = new ArrayList<ContentProviderRecord>();
Amith Yamasani13593602012-03-22 16:16:17 -07003698 for (ContentProviderRecord provider : mProviderMap.getProvidersByClass(userId).values()) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003699 if (provider.info.packageName.equals(name)
3700 && (provider.proc == null || evenPersistent || !provider.proc.persistent)) {
3701 if (!doit) {
3702 return true;
3703 }
3704 didSomething = true;
3705 providers.add(provider);
3706 }
3707 }
3708
3709 N = providers.size();
3710 for (i=0; i<N; i++) {
3711 removeDyingProviderLocked(null, providers.get(i));
3712 }
3713
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003714 if (doit) {
3715 if (purgeCache) {
3716 AttributeCache ac = AttributeCache.instance();
3717 if (ac != null) {
3718 ac.removePackage(name);
3719 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003720 }
Dianne Hackborn38cc8962011-10-13 11:33:55 -07003721 if (mBooted) {
3722 mMainStack.resumeTopActivityLocked(null);
3723 mMainStack.scheduleIdleLocked();
3724 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003725 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003726
3727 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003728 }
3729
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003730 private final boolean removeProcessLocked(ProcessRecord app,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003731 boolean callerWillRestart, boolean allowRestart, String reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003732 final String name = app.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003733 final int uid = app.uid;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003734 if (DEBUG_PROCESSES) Slog.d(
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003735 TAG, "Force removing proc " + app.toShortString() + " (" + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003736 + "/" + uid + ")");
3737
3738 mProcessNames.remove(name, uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003739 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003740 if (mHeavyWeightProcess == app) {
3741 mHeavyWeightProcess = null;
3742 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3743 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003744 boolean needRestart = false;
3745 if (app.pid > 0 && app.pid != MY_PID) {
3746 int pid = app.pid;
3747 synchronized (mPidsSelfLocked) {
3748 mPidsSelfLocked.remove(pid);
3749 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3750 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003751 Slog.i(TAG, "Killing proc " + app.toShortString() + ": " + reason);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003752 handleAppDiedLocked(app, true, allowRestart);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003753 mLruProcesses.remove(app);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003754 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003755
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003756 if (app.persistent && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003757 if (!callerWillRestart) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003758 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003759 } else {
3760 needRestart = true;
3761 }
3762 }
3763 } else {
3764 mRemovedProcesses.add(app);
3765 }
3766
3767 return needRestart;
3768 }
3769
3770 private final void processStartTimedOutLocked(ProcessRecord app) {
3771 final int pid = app.pid;
3772 boolean gone = false;
3773 synchronized (mPidsSelfLocked) {
3774 ProcessRecord knownApp = mPidsSelfLocked.get(pid);
3775 if (knownApp != null && knownApp.thread == null) {
3776 mPidsSelfLocked.remove(pid);
3777 gone = true;
3778 }
3779 }
3780
3781 if (gone) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003782 Slog.w(TAG, "Process " + app + " failed to attach");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003783 EventLog.writeEvent(EventLogTags.AM_PROCESS_START_TIMEOUT, pid, app.uid,
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003784 app.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003785 mProcessNames.remove(app.processName, app.uid);
3786 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003787 if (mHeavyWeightProcess == app) {
3788 mHeavyWeightProcess = null;
3789 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3790 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003791 // Take care of any launching providers waiting for this process.
3792 checkAppInLaunchingProvidersLocked(app, true);
3793 // Take care of any services that are waiting for the process.
3794 for (int i=0; i<mPendingServices.size(); i++) {
3795 ServiceRecord sr = mPendingServices.get(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003796 if ((app.uid == sr.appInfo.uid
3797 && app.processName.equals(sr.processName))
3798 || sr.isolatedProc == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003799 Slog.w(TAG, "Forcing bringing down service: " + sr);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003800 sr.isolatedProc = null;
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003801 mPendingServices.remove(i);
3802 i--;
3803 bringDownServiceLocked(sr, true);
3804 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003805 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003806 EventLog.writeEvent(EventLogTags.AM_KILL, pid,
3807 app.processName, app.setAdj, "start timeout");
3808 Process.killProcessQuiet(pid);
Christopher Tate181fafa2009-05-14 11:12:14 -07003809 if (mBackupTarget != null && mBackupTarget.app.pid == pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003810 Slog.w(TAG, "Unattached app died before backup, skipping");
Christopher Tate181fafa2009-05-14 11:12:14 -07003811 try {
3812 IBackupManager bm = IBackupManager.Stub.asInterface(
3813 ServiceManager.getService(Context.BACKUP_SERVICE));
3814 bm.agentDisconnected(app.info.packageName);
3815 } catch (RemoteException e) {
3816 // Can't happen; the backup manager is local
3817 }
3818 }
Christopher Tatef46723b2012-01-26 14:19:24 -08003819 if (isPendingBroadcastProcessLocked(pid)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003820 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
Christopher Tatef46723b2012-01-26 14:19:24 -08003821 skipPendingBroadcastLocked(pid);
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003822 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003823 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003824 Slog.w(TAG, "Spurious process start timeout - pid not known for " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003825 }
3826 }
3827
3828 private final boolean attachApplicationLocked(IApplicationThread thread,
3829 int pid) {
3830
3831 // Find the application record that is being attached... either via
3832 // the pid if we are running in multiple processes, or just pull the
3833 // next app record if we are emulating process with anonymous threads.
3834 ProcessRecord app;
3835 if (pid != MY_PID && pid >= 0) {
3836 synchronized (mPidsSelfLocked) {
3837 app = mPidsSelfLocked.get(pid);
3838 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003839 } else {
3840 app = null;
3841 }
3842
3843 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003844 Slog.w(TAG, "No pending application record for pid " + pid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003845 + " (IApplicationThread " + thread + "); dropping process");
Doug Zongker2bec3d42009-12-04 12:52:44 -08003846 EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003847 if (pid > 0 && pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003848 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003849 } else {
3850 try {
3851 thread.scheduleExit();
3852 } catch (Exception e) {
3853 // Ignore exceptions.
3854 }
3855 }
3856 return false;
3857 }
3858
3859 // If this application record is still attached to a previous
3860 // process, clean it up now.
3861 if (app.thread != null) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003862 handleAppDiedLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003863 }
3864
3865 // Tell the process all about itself.
3866
Joe Onorato8a9b2202010-02-26 18:56:32 -08003867 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003868 TAG, "Binding process pid " + pid + " to record " + app);
3869
3870 String processName = app.processName;
3871 try {
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07003872 AppDeathRecipient adr = new AppDeathRecipient(
3873 app, pid, thread);
3874 thread.asBinder().linkToDeath(adr, 0);
3875 app.deathRecipient = adr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003876 } catch (RemoteException e) {
3877 app.resetPackageList();
3878 startProcessLocked(app, "link fail", processName);
3879 return false;
3880 }
3881
Doug Zongker2bec3d42009-12-04 12:52:44 -08003882 EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.pid, app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003883
3884 app.thread = thread;
3885 app.curAdj = app.setAdj = -100;
Dianne Hackborn09c916b2009-12-08 14:50:51 -08003886 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
3887 app.setSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003888 app.forcingToForeground = null;
3889 app.foregroundServices = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07003890 app.hasShownUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003891 app.debugging = false;
3892
3893 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3894
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003895 boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003896 List providers = normalMode ? generateApplicationProvidersLocked(app) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003897
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003898 if (!normalMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003899 Slog.i(TAG, "Launching preboot mode app: " + app);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003900 }
3901
Joe Onorato8a9b2202010-02-26 18:56:32 -08003902 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003903 TAG, "New app record " + app
3904 + " thread=" + thread.asBinder() + " pid=" + pid);
3905 try {
3906 int testMode = IApplicationThread.DEBUG_OFF;
3907 if (mDebugApp != null && mDebugApp.equals(processName)) {
3908 testMode = mWaitForDebugger
3909 ? IApplicationThread.DEBUG_WAIT
3910 : IApplicationThread.DEBUG_ON;
3911 app.debugging = true;
3912 if (mDebugTransient) {
3913 mDebugApp = mOrigDebugApp;
3914 mWaitForDebugger = mOrigWaitForDebugger;
3915 }
3916 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003917 String profileFile = app.instrumentationProfileFile;
3918 ParcelFileDescriptor profileFd = null;
3919 boolean profileAutoStop = false;
3920 if (mProfileApp != null && mProfileApp.equals(processName)) {
3921 mProfileProc = app;
3922 profileFile = mProfileFile;
3923 profileFd = mProfileFd;
3924 profileAutoStop = mAutoStopProfiler;
3925 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08003926 boolean enableOpenGlTrace = false;
3927 if (mOpenGlTraceApp != null && mOpenGlTraceApp.equals(processName)) {
3928 enableOpenGlTrace = true;
3929 mOpenGlTraceApp = null;
3930 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003931
Christopher Tate181fafa2009-05-14 11:12:14 -07003932 // If the app is being launched for restore or full backup, set it up specially
3933 boolean isRestrictedBackupMode = false;
3934 if (mBackupTarget != null && mBackupAppName.equals(processName)) {
3935 isRestrictedBackupMode = (mBackupTarget.backupMode == BackupRecord.RESTORE)
Christopher Tate75a99702011-05-18 16:28:19 -07003936 || (mBackupTarget.backupMode == BackupRecord.RESTORE_FULL)
Christopher Tate181fafa2009-05-14 11:12:14 -07003937 || (mBackupTarget.backupMode == BackupRecord.BACKUP_FULL);
3938 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003939
Dianne Hackbornd7f6daa2009-06-22 17:06:35 -07003940 ensurePackageDexOpt(app.instrumentationInfo != null
3941 ? app.instrumentationInfo.packageName
3942 : app.info.packageName);
3943 if (app.instrumentationClass != null) {
3944 ensurePackageDexOpt(app.instrumentationClass.getPackageName());
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003945 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08003946 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Binding proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003947 + processName + " with config " + mConfiguration);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003948 ApplicationInfo appInfo = app.instrumentationInfo != null
3949 ? app.instrumentationInfo : app.info;
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -07003950 app.compat = compatibilityInfoForPackageLocked(appInfo);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003951 if (profileFd != null) {
3952 profileFd = profileFd.dup();
3953 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003954 thread.bindApplication(processName, appInfo, providers,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003955 app.instrumentationClass, profileFile, profileFd, profileAutoStop,
Siva Velusamy92a8b222012-03-09 16:24:04 -08003956 app.instrumentationArguments, app.instrumentationWatcher, testMode,
3957 enableOpenGlTrace, isRestrictedBackupMode || !normalMode, app.persistent,
Dianne Hackborn813075a62011-11-14 17:45:19 -08003958 new Configuration(mConfiguration), app.compat, getCommonServicesLocked(),
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08003959 mCoreSettingsObserver.getCoreSettingsLocked());
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003960 updateLruProcessLocked(app, false, true);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003961 app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003962 } catch (Exception e) {
3963 // todo: Yikes! What should we do? For now we will try to
3964 // start another process, but that could easily get us in
3965 // an infinite loop of restarting processes...
Joe Onorato8a9b2202010-02-26 18:56:32 -08003966 Slog.w(TAG, "Exception thrown during bind!", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003967
3968 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07003969 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003970 startProcessLocked(app, "bind fail", processName);
3971 return false;
3972 }
3973
3974 // Remove this record from the list of starting applications.
3975 mPersistentStartingProcesses.remove(app);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003976 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
3977 "Attach application locked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003978 mProcessesOnHold.remove(app);
3979
3980 boolean badApp = false;
3981 boolean didSomething = false;
3982
3983 // See if the top visible activity is waiting to run in this process...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003984 ActivityRecord hr = mMainStack.topRunningActivityLocked(null);
Christopher Tate04c0af82010-06-07 18:35:20 -07003985 if (hr != null && normalMode) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003986 if (hr.app == null && app.uid == hr.info.applicationInfo.uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003987 && processName.equals(hr.processName)) {
3988 try {
Mike Lockwood3a74bd32011-08-12 13:55:22 -07003989 if (mHeadless) {
3990 Slog.e(TAG, "Starting activities not supported on headless device: " + hr);
3991 } else if (mMainStack.realStartActivityLocked(hr, app, true, true)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003992 didSomething = true;
3993 }
3994 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003995 Slog.w(TAG, "Exception in new application when starting activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003996 + hr.intent.getComponent().flattenToShortString(), e);
3997 badApp = true;
3998 }
3999 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004000 mMainStack.ensureActivitiesVisibleLocked(hr, null, processName, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004001 }
4002 }
4003
4004 // Find any services that should be running in this process...
4005 if (!badApp && mPendingServices.size() > 0) {
4006 ServiceRecord sr = null;
4007 try {
4008 for (int i=0; i<mPendingServices.size(); i++) {
4009 sr = mPendingServices.get(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004010 if (app != sr.isolatedProc && (app.uid != sr.appInfo.uid
4011 || !processName.equals(sr.processName))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004012 continue;
4013 }
4014
4015 mPendingServices.remove(i);
4016 i--;
4017 realStartServiceLocked(sr, app);
4018 didSomething = true;
4019 }
4020 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004021 Slog.w(TAG, "Exception in new application when starting service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004022 + sr.shortName, e);
4023 badApp = true;
4024 }
4025 }
4026
Christopher Tatef46723b2012-01-26 14:19:24 -08004027 // Check if a next-broadcast receiver is in this process...
4028 if (!badApp && isPendingBroadcastProcessLocked(pid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004029 try {
Christopher Tatef46723b2012-01-26 14:19:24 -08004030 didSomething = sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004031 } catch (Exception e) {
Christopher Tatef46723b2012-01-26 14:19:24 -08004032 // If the app died trying to launch the receiver we declare it 'bad'
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004033 badApp = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004034 }
4035 }
4036
Christopher Tate181fafa2009-05-14 11:12:14 -07004037 // Check whether the next backup agent is in this process...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004038 if (!badApp && mBackupTarget != null && mBackupTarget.appInfo.uid == app.uid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004039 if (DEBUG_BACKUP) Slog.v(TAG, "New app is backup target, launching agent for " + app);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004040 ensurePackageDexOpt(mBackupTarget.appInfo.packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07004041 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004042 thread.scheduleCreateBackupAgent(mBackupTarget.appInfo,
4043 compatibilityInfoForPackageLocked(mBackupTarget.appInfo),
4044 mBackupTarget.backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -07004045 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004046 Slog.w(TAG, "Exception scheduling backup agent creation: ");
Christopher Tate181fafa2009-05-14 11:12:14 -07004047 e.printStackTrace();
4048 }
4049 }
4050
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004051 if (badApp) {
4052 // todo: Also need to kill application to deal with all
4053 // kinds of exceptions.
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004054 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004055 return false;
4056 }
4057
4058 if (!didSomething) {
4059 updateOomAdjLocked();
4060 }
4061
4062 return true;
4063 }
4064
4065 public final void attachApplication(IApplicationThread thread) {
4066 synchronized (this) {
4067 int callingPid = Binder.getCallingPid();
4068 final long origId = Binder.clearCallingIdentity();
4069 attachApplicationLocked(thread, callingPid);
4070 Binder.restoreCallingIdentity(origId);
4071 }
4072 }
4073
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004074 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004075 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004076 ActivityRecord r = mMainStack.activityIdleInternal(token, false, config);
4077 if (stopProfiling) {
4078 synchronized (this) {
4079 if (mProfileProc == r.app) {
4080 if (mProfileFd != null) {
4081 try {
4082 mProfileFd.close();
4083 } catch (IOException e) {
4084 }
4085 clearProfilerLocked();
4086 }
4087 }
4088 }
4089 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004090 Binder.restoreCallingIdentity(origId);
4091 }
4092
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004093 void enableScreenAfterBoot() {
Doug Zongker2bec3d42009-12-04 12:52:44 -08004094 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004095 SystemClock.uptimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004096 mWindowManager.enableScreenAfterBoot();
4097 }
4098
Dianne Hackborn661cd522011-08-22 00:26:20 -07004099 public void showBootMessage(final CharSequence msg, final boolean always) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004100 enforceNotIsolatedCaller("showBootMessage");
Dianne Hackborn661cd522011-08-22 00:26:20 -07004101 mWindowManager.showBootMessage(msg, always);
4102 }
4103
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004104 public void dismissKeyguardOnNextActivity() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004105 enforceNotIsolatedCaller("dismissKeyguardOnNextActivity");
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004106 synchronized (this) {
4107 mMainStack.dismissKeyguardOnNextActivityLocked();
4108 }
4109 }
4110
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004111 final void finishBooting() {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004112 IntentFilter pkgFilter = new IntentFilter();
4113 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
4114 pkgFilter.addDataScheme("package");
4115 mContext.registerReceiver(new BroadcastReceiver() {
4116 @Override
4117 public void onReceive(Context context, Intent intent) {
4118 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
4119 if (pkgs != null) {
4120 for (String pkg : pkgs) {
Vairavan Srinivasan61f07652010-07-22 13:36:40 -07004121 synchronized (ActivityManagerService.this) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07004122 if (forceStopPackageLocked(pkg, -1, false, false, false, false, 0)) {
4123 setResultCode(Activity.RESULT_OK);
4124 return;
4125 }
4126 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004127 }
4128 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004129 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004130 }, pkgFilter);
Amith Yamasani13593602012-03-22 16:16:17 -07004131
4132 IntentFilter userFilter = new IntentFilter();
4133 userFilter.addAction(Intent.ACTION_USER_REMOVED);
4134 mContext.registerReceiver(new BroadcastReceiver() {
4135 @Override
4136 public void onReceive(Context context, Intent intent) {
4137 onUserRemoved(intent);
4138 }
4139 }, userFilter);
4140
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004141 synchronized (this) {
4142 // Ensure that any processes we had put on hold are now started
4143 // up.
4144 final int NP = mProcessesOnHold.size();
4145 if (NP > 0) {
4146 ArrayList<ProcessRecord> procs =
4147 new ArrayList<ProcessRecord>(mProcessesOnHold);
4148 for (int ip=0; ip<NP; ip++) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004149 if (DEBUG_PROCESSES) Slog.v(TAG, "Starting process on hold: "
4150 + procs.get(ip));
4151 startProcessLocked(procs.get(ip), "on-hold", null);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004152 }
4153 }
4154
4155 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004156 // Start looking for apps that are abusing wake locks.
4157 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07004158 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004159 // Tell anyone interested that we are done booting!
Dianne Hackbornf4c454b2010-08-11 12:47:41 -07004160 SystemProperties.set("sys.boot_completed", "1");
Guang Zhu191713a2012-01-12 12:02:22 -08004161 SystemProperties.set("dev.bootcomplete", "1");
Amith Yamasani742a6712011-05-04 14:49:28 -07004162 /* TODO: Send this to all users that are to be logged in on startup */
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004163 broadcastIntentLocked(null, null,
4164 new Intent(Intent.ACTION_BOOT_COMPLETED, null),
4165 null, null, 0, null, null,
4166 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
Amith Yamasani742a6712011-05-04 14:49:28 -07004167 false, false, MY_PID, Process.SYSTEM_UID, Binder.getOrigCallingUser());
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004168 }
4169 }
4170 }
4171
4172 final void ensureBootCompleted() {
4173 boolean booting;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004174 boolean enableScreen;
4175 synchronized (this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004176 booting = mBooting;
4177 mBooting = false;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004178 enableScreen = !mBooted;
4179 mBooted = true;
4180 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004181
4182 if (booting) {
4183 finishBooting();
4184 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004185
4186 if (enableScreen) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004187 enableScreenAfterBoot();
4188 }
4189 }
4190
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004191 public final void activityPaused(IBinder token) {
4192 final long origId = Binder.clearCallingIdentity();
4193 mMainStack.activityPaused(token, false);
4194 Binder.restoreCallingIdentity(origId);
4195 }
4196
4197 public final void activityStopped(IBinder token, Bundle icicle, Bitmap thumbnail,
4198 CharSequence description) {
4199 if (localLOGV) Slog.v(
4200 TAG, "Activity stopped: token=" + token);
4201
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004202 // Refuse possible leaked file descriptors
4203 if (icicle != null && icicle.hasFileDescriptors()) {
4204 throw new IllegalArgumentException("File descriptors passed in Bundle");
4205 }
4206
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004207 ActivityRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004208
4209 final long origId = Binder.clearCallingIdentity();
4210
4211 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004212 r = mMainStack.isInStackLocked(token);
4213 if (r != null) {
4214 r.stack.activityStoppedLocked(r, icicle, thumbnail, description);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004215 }
4216 }
4217
4218 if (r != null) {
4219 sendPendingThumbnail(r, null, null, null, false);
4220 }
4221
4222 trimApplications();
4223
4224 Binder.restoreCallingIdentity(origId);
4225 }
4226
4227 public final void activityDestroyed(IBinder token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004228 if (DEBUG_SWITCH) Slog.v(TAG, "ACTIVITY DESTROYED: " + token);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004229 mMainStack.activityDestroyed(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004230 }
4231
4232 public String getCallingPackage(IBinder token) {
4233 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004234 ActivityRecord r = getCallingRecordLocked(token);
Dianne Hackborn9bbcb912009-10-20 15:42:38 -07004235 return r != null && r.app != null ? r.info.packageName : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004236 }
4237 }
4238
4239 public ComponentName getCallingActivity(IBinder token) {
4240 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004241 ActivityRecord r = getCallingRecordLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004242 return r != null ? r.intent.getComponent() : null;
4243 }
4244 }
4245
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004246 private ActivityRecord getCallingRecordLocked(IBinder token) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004247 ActivityRecord r = mMainStack.isInStackLocked(token);
4248 if (r == null) {
4249 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004250 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004251 return r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004252 }
4253
4254 public ComponentName getActivityClassForToken(IBinder token) {
4255 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004256 ActivityRecord r = mMainStack.isInStackLocked(token);
4257 if (r == null) {
4258 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004259 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004260 return r.intent.getComponent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004261 }
4262 }
4263
4264 public String getPackageForToken(IBinder token) {
4265 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004266 ActivityRecord r = mMainStack.isInStackLocked(token);
4267 if (r == null) {
4268 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004269 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004270 return r.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004271 }
4272 }
4273
4274 public IIntentSender getIntentSender(int type,
4275 String packageName, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004276 int requestCode, Intent[] intents, String[] resolvedTypes,
4277 int flags, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004278 enforceNotIsolatedCaller("getIntentSender");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004279 // Refuse possible leaked file descriptors
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004280 if (intents != null) {
4281 if (intents.length < 1) {
4282 throw new IllegalArgumentException("Intents array length must be >= 1");
4283 }
4284 for (int i=0; i<intents.length; i++) {
4285 Intent intent = intents[i];
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004286 if (intent != null) {
4287 if (intent.hasFileDescriptors()) {
4288 throw new IllegalArgumentException("File descriptors passed in Intent");
4289 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07004290 if (type == ActivityManager.INTENT_SENDER_BROADCAST &&
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004291 (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
4292 throw new IllegalArgumentException(
4293 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
4294 }
4295 intents[i] = new Intent(intent);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004296 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004297 }
4298 if (resolvedTypes != null && resolvedTypes.length != intents.length) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004299 throw new IllegalArgumentException(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004300 "Intent array length does not match resolvedTypes length");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004301 }
4302 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004303 if (options != null) {
4304 if (options.hasFileDescriptors()) {
4305 throw new IllegalArgumentException("File descriptors passed in options");
4306 }
4307 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004308
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004309 synchronized(this) {
4310 int callingUid = Binder.getCallingUid();
4311 try {
Jeff Brown10e89712011-07-08 18:52:57 -07004312 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004313 int uid = AppGlobals.getPackageManager()
Amith Yamasani483f3b02012-03-13 16:08:00 -07004314 .getPackageUid(packageName, UserId.getUserId(callingUid));
4315 if (!UserId.isSameApp(callingUid, uid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004316 String msg = "Permission Denial: getIntentSender() from pid="
4317 + Binder.getCallingPid()
4318 + ", uid=" + Binder.getCallingUid()
4319 + ", (need uid=" + uid + ")"
4320 + " is not allowed to send as package " + packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004321 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004322 throw new SecurityException(msg);
4323 }
4324 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004325
Amith Yamasani742a6712011-05-04 14:49:28 -07004326 if (DEBUG_MU)
4327 Slog.i(TAG_MU, "Getting intent sender for origCallingUid="
4328 + Binder.getOrigCallingUid());
4329 return getIntentSenderLocked(type, packageName, Binder.getOrigCallingUid(),
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004330 token, resultWho, requestCode, intents, resolvedTypes, flags, options);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004331
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004332 } catch (RemoteException e) {
4333 throw new SecurityException(e);
4334 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004335 }
4336 }
4337
4338 IIntentSender getIntentSenderLocked(int type,
4339 String packageName, int callingUid, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004340 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
4341 Bundle options) {
Amith Yamasani742a6712011-05-04 14:49:28 -07004342 if (DEBUG_MU)
4343 Slog.v(TAG_MU, "getIntentSenderLocked(): uid=" + callingUid);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004344 ActivityRecord activity = null;
Dianne Hackborna4972e92012-03-14 10:38:05 -07004345 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004346 activity = mMainStack.isInStackLocked(token);
4347 if (activity == null) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004348 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004349 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004350 if (activity.finishing) {
4351 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004352 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004353 }
4354
4355 final boolean noCreate = (flags&PendingIntent.FLAG_NO_CREATE) != 0;
4356 final boolean cancelCurrent = (flags&PendingIntent.FLAG_CANCEL_CURRENT) != 0;
4357 final boolean updateCurrent = (flags&PendingIntent.FLAG_UPDATE_CURRENT) != 0;
4358 flags &= ~(PendingIntent.FLAG_NO_CREATE|PendingIntent.FLAG_CANCEL_CURRENT
4359 |PendingIntent.FLAG_UPDATE_CURRENT);
4360
4361 PendingIntentRecord.Key key = new PendingIntentRecord.Key(
4362 type, packageName, activity, resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004363 requestCode, intents, resolvedTypes, flags, options);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004364 WeakReference<PendingIntentRecord> ref;
4365 ref = mIntentSenderRecords.get(key);
4366 PendingIntentRecord rec = ref != null ? ref.get() : null;
4367 if (rec != null) {
4368 if (!cancelCurrent) {
4369 if (updateCurrent) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004370 if (rec.key.requestIntent != null) {
4371 rec.key.requestIntent.replaceExtras(intents != null ? intents[0] : null);
4372 }
4373 if (intents != null) {
4374 intents[intents.length-1] = rec.key.requestIntent;
4375 rec.key.allIntents = intents;
4376 rec.key.allResolvedTypes = resolvedTypes;
4377 } else {
4378 rec.key.allIntents = null;
4379 rec.key.allResolvedTypes = null;
4380 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004381 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004382 return rec;
4383 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004384 rec.canceled = true;
4385 mIntentSenderRecords.remove(key);
4386 }
4387 if (noCreate) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004388 return rec;
4389 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004390 rec = new PendingIntentRecord(this, key, callingUid);
4391 mIntentSenderRecords.put(key, rec.ref);
Dianne Hackborna4972e92012-03-14 10:38:05 -07004392 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004393 if (activity.pendingResults == null) {
4394 activity.pendingResults
4395 = new HashSet<WeakReference<PendingIntentRecord>>();
4396 }
4397 activity.pendingResults.add(rec.ref);
4398 }
4399 return rec;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004400 }
4401
4402 public void cancelIntentSender(IIntentSender sender) {
4403 if (!(sender instanceof PendingIntentRecord)) {
4404 return;
4405 }
4406 synchronized(this) {
4407 PendingIntentRecord rec = (PendingIntentRecord)sender;
4408 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004409 int uid = AppGlobals.getPackageManager()
Amith Yamasani483f3b02012-03-13 16:08:00 -07004410 .getPackageUid(rec.key.packageName, UserId.getCallingUserId());
Amith Yamasani04e0d262012-02-14 11:50:53 -08004411 if (!UserId.isSameApp(uid, Binder.getCallingUid())) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004412 String msg = "Permission Denial: cancelIntentSender() from pid="
4413 + Binder.getCallingPid()
4414 + ", uid=" + Binder.getCallingUid()
4415 + " is not allowed to cancel packges "
4416 + rec.key.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004417 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004418 throw new SecurityException(msg);
4419 }
4420 } catch (RemoteException e) {
4421 throw new SecurityException(e);
4422 }
4423 cancelIntentSenderLocked(rec, true);
4424 }
4425 }
4426
4427 void cancelIntentSenderLocked(PendingIntentRecord rec, boolean cleanActivity) {
4428 rec.canceled = true;
4429 mIntentSenderRecords.remove(rec.key);
4430 if (cleanActivity && rec.key.activity != null) {
4431 rec.key.activity.pendingResults.remove(rec.ref);
4432 }
4433 }
4434
4435 public String getPackageForIntentSender(IIntentSender pendingResult) {
4436 if (!(pendingResult instanceof PendingIntentRecord)) {
4437 return null;
4438 }
Brad Fitzpatrickb213d102010-04-19 11:58:52 -07004439 try {
4440 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4441 return res.key.packageName;
4442 } catch (ClassCastException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004443 }
4444 return null;
4445 }
4446
Dianne Hackborn6c418d52011-06-29 14:05:33 -07004447 public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) {
4448 if (!(pendingResult instanceof PendingIntentRecord)) {
4449 return false;
4450 }
4451 try {
4452 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4453 if (res.key.allIntents == null) {
4454 return false;
4455 }
4456 for (int i=0; i<res.key.allIntents.length; i++) {
4457 Intent intent = res.key.allIntents[i];
4458 if (intent.getPackage() != null && intent.getComponent() != null) {
4459 return false;
4460 }
4461 }
4462 return true;
4463 } catch (ClassCastException e) {
4464 }
4465 return false;
4466 }
4467
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004468 public void setProcessLimit(int max) {
4469 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4470 "setProcessLimit()");
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004471 synchronized (this) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07004472 mProcessLimit = max < 0 ? ProcessList.MAX_HIDDEN_APPS : max;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004473 mProcessLimitOverride = max;
4474 }
4475 trimApplications();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004476 }
4477
4478 public int getProcessLimit() {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004479 synchronized (this) {
4480 return mProcessLimitOverride;
4481 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004482 }
4483
4484 void foregroundTokenDied(ForegroundToken token) {
4485 synchronized (ActivityManagerService.this) {
4486 synchronized (mPidsSelfLocked) {
4487 ForegroundToken cur
4488 = mForegroundProcesses.get(token.pid);
4489 if (cur != token) {
4490 return;
4491 }
4492 mForegroundProcesses.remove(token.pid);
4493 ProcessRecord pr = mPidsSelfLocked.get(token.pid);
4494 if (pr == null) {
4495 return;
4496 }
4497 pr.forcingToForeground = null;
4498 pr.foregroundServices = false;
4499 }
4500 updateOomAdjLocked();
4501 }
4502 }
4503
4504 public void setProcessForeground(IBinder token, int pid, boolean isForeground) {
4505 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4506 "setProcessForeground()");
4507 synchronized(this) {
4508 boolean changed = false;
4509
4510 synchronized (mPidsSelfLocked) {
4511 ProcessRecord pr = mPidsSelfLocked.get(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004512 if (pr == null && isForeground) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004513 Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004514 return;
4515 }
4516 ForegroundToken oldToken = mForegroundProcesses.get(pid);
4517 if (oldToken != null) {
4518 oldToken.token.unlinkToDeath(oldToken, 0);
4519 mForegroundProcesses.remove(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004520 if (pr != null) {
4521 pr.forcingToForeground = null;
4522 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004523 changed = true;
4524 }
4525 if (isForeground && token != null) {
4526 ForegroundToken newToken = new ForegroundToken() {
4527 public void binderDied() {
4528 foregroundTokenDied(this);
4529 }
4530 };
4531 newToken.pid = pid;
4532 newToken.token = token;
4533 try {
4534 token.linkToDeath(newToken, 0);
4535 mForegroundProcesses.put(pid, newToken);
4536 pr.forcingToForeground = token;
4537 changed = true;
4538 } catch (RemoteException e) {
4539 // If the process died while doing this, we will later
4540 // do the cleanup with the process death link.
4541 }
4542 }
4543 }
4544
4545 if (changed) {
4546 updateOomAdjLocked();
4547 }
4548 }
4549 }
4550
4551 // =========================================================
4552 // PERMISSIONS
4553 // =========================================================
4554
4555 static class PermissionController extends IPermissionController.Stub {
4556 ActivityManagerService mActivityManagerService;
4557 PermissionController(ActivityManagerService activityManagerService) {
4558 mActivityManagerService = activityManagerService;
4559 }
4560
4561 public boolean checkPermission(String permission, int pid, int uid) {
4562 return mActivityManagerService.checkPermission(permission, pid,
4563 uid) == PackageManager.PERMISSION_GRANTED;
4564 }
4565 }
4566
4567 /**
4568 * This can be called with or without the global lock held.
4569 */
4570 int checkComponentPermission(String permission, int pid, int uid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004571 int owningUid, boolean exported) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004572 // We might be performing an operation on behalf of an indirect binder
4573 // invocation, e.g. via {@link #openContentUri}. Check and adjust the
4574 // client identity accordingly before proceeding.
4575 Identity tlsIdentity = sCallerIdentity.get();
4576 if (tlsIdentity != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004577 Slog.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004578 + tlsIdentity.pid + "," + tlsIdentity.uid + "}");
4579 uid = tlsIdentity.uid;
4580 pid = tlsIdentity.pid;
4581 }
4582
4583 // Root, system server and our own process get to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07004584 if (uid == 0 || uid == Process.SYSTEM_UID || pid == MY_PID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004585 return PackageManager.PERMISSION_GRANTED;
4586 }
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004587 // Isolated processes don't get any permissions.
4588 if (UserId.isIsolated(uid)) {
4589 return PackageManager.PERMISSION_DENIED;
4590 }
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004591 // If there is a uid that owns whatever is being accessed, it has
4592 // blanket access to it regardless of the permissions it requires.
Amith Yamasani742a6712011-05-04 14:49:28 -07004593 if (owningUid >= 0 && UserId.isSameApp(uid, owningUid)) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004594 return PackageManager.PERMISSION_GRANTED;
4595 }
4596 // If the target is not exported, then nobody else can get to it.
4597 if (!exported) {
4598 Slog.w(TAG, "Permission denied: checkComponentPermission() owningUid=" + owningUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004599 return PackageManager.PERMISSION_DENIED;
4600 }
4601 if (permission == null) {
4602 return PackageManager.PERMISSION_GRANTED;
4603 }
4604 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004605 return AppGlobals.getPackageManager()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004606 .checkUidPermission(permission, uid);
4607 } catch (RemoteException e) {
4608 // Should never happen, but if it does... deny!
Joe Onorato8a9b2202010-02-26 18:56:32 -08004609 Slog.e(TAG, "PackageManager is dead?!?", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004610 }
4611 return PackageManager.PERMISSION_DENIED;
4612 }
4613
4614 /**
4615 * As the only public entry point for permissions checking, this method
4616 * can enforce the semantic that requesting a check on a null global
4617 * permission is automatically denied. (Internally a null permission
4618 * string is used when calling {@link #checkComponentPermission} in cases
4619 * when only uid-based security is needed.)
4620 *
4621 * This can be called with or without the global lock held.
4622 */
4623 public int checkPermission(String permission, int pid, int uid) {
4624 if (permission == null) {
4625 return PackageManager.PERMISSION_DENIED;
4626 }
Amith Yamasani742a6712011-05-04 14:49:28 -07004627 return checkComponentPermission(permission, pid, UserId.getAppId(uid), -1, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004628 }
4629
4630 /**
4631 * Binder IPC calls go through the public entry point.
4632 * This can be called with or without the global lock held.
4633 */
4634 int checkCallingPermission(String permission) {
4635 return checkPermission(permission,
4636 Binder.getCallingPid(),
Amith Yamasani742a6712011-05-04 14:49:28 -07004637 UserId.getAppId(Binder.getCallingUid()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004638 }
4639
4640 /**
4641 * This can be called with or without the global lock held.
4642 */
4643 void enforceCallingPermission(String permission, String func) {
4644 if (checkCallingPermission(permission)
4645 == PackageManager.PERMISSION_GRANTED) {
4646 return;
4647 }
4648
4649 String msg = "Permission Denial: " + func + " from pid="
4650 + Binder.getCallingPid()
4651 + ", uid=" + Binder.getCallingUid()
4652 + " requires " + permission;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004653 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004654 throw new SecurityException(msg);
4655 }
4656
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004657 /**
4658 * Determine if UID is holding permissions required to access {@link Uri} in
4659 * the given {@link ProviderInfo}. Final permission checking is always done
4660 * in {@link ContentProvider}.
4661 */
4662 private final boolean checkHoldingPermissionsLocked(
4663 IPackageManager pm, ProviderInfo pi, Uri uri, int uid, int modeFlags) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004664 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4665 "checkHoldingPermissionsLocked: uri=" + uri + " uid=" + uid);
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004666
4667 if (pi.applicationInfo.uid == uid) {
4668 return true;
4669 } else if (!pi.exported) {
4670 return false;
4671 }
4672
4673 boolean readMet = (modeFlags & Intent.FLAG_GRANT_READ_URI_PERMISSION) == 0;
4674 boolean writeMet = (modeFlags & Intent.FLAG_GRANT_WRITE_URI_PERMISSION) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004675 try {
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004676 // check if target holds top-level <provider> permissions
4677 if (!readMet && pi.readPermission != null
4678 && (pm.checkUidPermission(pi.readPermission, uid) == PERMISSION_GRANTED)) {
4679 readMet = true;
4680 }
4681 if (!writeMet && pi.writePermission != null
4682 && (pm.checkUidPermission(pi.writePermission, uid) == PERMISSION_GRANTED)) {
4683 writeMet = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004684 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004685
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004686 // track if unprotected read/write is allowed; any denied
4687 // <path-permission> below removes this ability
4688 boolean allowDefaultRead = pi.readPermission == null;
4689 boolean allowDefaultWrite = pi.writePermission == null;
Dianne Hackborn48058e82010-09-27 16:53:23 -07004690
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004691 // check if target holds any <path-permission> that match uri
4692 final PathPermission[] pps = pi.pathPermissions;
4693 if (pps != null) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004694 final String path = uri.getPath();
4695 int i = pps.length;
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004696 while (i > 0 && (!readMet || !writeMet)) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004697 i--;
4698 PathPermission pp = pps[i];
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004699 if (pp.match(path)) {
4700 if (!readMet) {
4701 final String pprperm = pp.getReadPermission();
4702 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking read perm for "
4703 + pprperm + " for " + pp.getPath()
4704 + ": match=" + pp.match(path)
4705 + " check=" + pm.checkUidPermission(pprperm, uid));
4706 if (pprperm != null) {
4707 if (pm.checkUidPermission(pprperm, uid) == PERMISSION_GRANTED) {
4708 readMet = true;
4709 } else {
4710 allowDefaultRead = false;
4711 }
4712 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004713 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004714 if (!writeMet) {
4715 final String ppwperm = pp.getWritePermission();
4716 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking write perm "
4717 + ppwperm + " for " + pp.getPath()
4718 + ": match=" + pp.match(path)
4719 + " check=" + pm.checkUidPermission(ppwperm, uid));
4720 if (ppwperm != null) {
4721 if (pm.checkUidPermission(ppwperm, uid) == PERMISSION_GRANTED) {
4722 writeMet = true;
4723 } else {
4724 allowDefaultWrite = false;
4725 }
4726 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004727 }
4728 }
4729 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07004730 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004731
4732 // grant unprotected <provider> read/write, if not blocked by
4733 // <path-permission> above
4734 if (allowDefaultRead) readMet = true;
4735 if (allowDefaultWrite) writeMet = true;
4736
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004737 } catch (RemoteException e) {
4738 return false;
4739 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004740
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004741 return readMet && writeMet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004742 }
4743
4744 private final boolean checkUriPermissionLocked(Uri uri, int uid,
4745 int modeFlags) {
4746 // Root gets to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07004747 if (uid == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004748 return true;
4749 }
4750 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(uid);
4751 if (perms == null) return false;
4752 UriPermission perm = perms.get(uri);
4753 if (perm == null) return false;
4754 return (modeFlags&perm.modeFlags) == modeFlags;
4755 }
4756
4757 public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004758 enforceNotIsolatedCaller("checkUriPermission");
4759
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004760 // Another redirected-binder-call permissions check as in
4761 // {@link checkComponentPermission}.
4762 Identity tlsIdentity = sCallerIdentity.get();
4763 if (tlsIdentity != null) {
4764 uid = tlsIdentity.uid;
4765 pid = tlsIdentity.pid;
4766 }
4767
Amith Yamasani742a6712011-05-04 14:49:28 -07004768 uid = UserId.getAppId(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004769 // Our own process gets to do everything.
4770 if (pid == MY_PID) {
4771 return PackageManager.PERMISSION_GRANTED;
4772 }
4773 synchronized(this) {
4774 return checkUriPermissionLocked(uri, uid, modeFlags)
4775 ? PackageManager.PERMISSION_GRANTED
4776 : PackageManager.PERMISSION_DENIED;
4777 }
4778 }
4779
Dianne Hackborn39792d22010-08-19 18:01:52 -07004780 /**
4781 * Check if the targetPkg can be granted permission to access uri by
4782 * the callingUid using the given modeFlags. Throws a security exception
4783 * if callingUid is not allowed to do this. Returns the uid of the target
4784 * if the URI permission grant should be performed; returns -1 if it is not
4785 * needed (for example targetPkg already has permission to access the URI).
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004786 * If you already know the uid of the target, you can supply it in
4787 * lastTargetUid else set that to -1.
Dianne Hackborn39792d22010-08-19 18:01:52 -07004788 */
4789 int checkGrantUriPermissionLocked(int callingUid, String targetPkg,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004790 Uri uri, int modeFlags, int lastTargetUid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004791 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4792 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4793 if (modeFlags == 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004794 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004795 }
4796
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004797 if (targetPkg != null) {
4798 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4799 "Checking grant " + targetPkg + " permission to " + uri);
4800 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004801
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004802 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004803
4804 // If this is not a content: uri, we can't do anything with it.
4805 if (!ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004806 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004807 "Can't grant URI permission for non-content URI: " + uri);
Dianne Hackborn39792d22010-08-19 18:01:52 -07004808 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004809 }
4810
4811 String name = uri.getAuthority();
4812 ProviderInfo pi = null;
Amith Yamasani742a6712011-05-04 14:49:28 -07004813 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
4814 UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004815 if (cpr != null) {
4816 pi = cpr.info;
4817 } else {
4818 try {
4819 pi = pm.resolveContentProvider(name,
Amith Yamasani483f3b02012-03-13 16:08:00 -07004820 PackageManager.GET_URI_PERMISSION_PATTERNS, UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004821 } catch (RemoteException ex) {
4822 }
4823 }
4824 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07004825 Slog.w(TAG, "No content provider found for permission check: " + uri.toSafeString());
Dianne Hackborn39792d22010-08-19 18:01:52 -07004826 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004827 }
4828
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004829 int targetUid = lastTargetUid;
4830 if (targetUid < 0 && targetPkg != null) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004831 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07004832 targetUid = pm.getPackageUid(targetPkg, UserId.getUserId(callingUid));
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004833 if (targetUid < 0) {
4834 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4835 "Can't grant URI permission no uid for: " + targetPkg);
4836 return -1;
4837 }
4838 } catch (RemoteException ex) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004839 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004840 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004841 }
4842
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004843 if (targetUid >= 0) {
4844 // First... does the target actually need this permission?
4845 if (checkHoldingPermissionsLocked(pm, pi, uri, targetUid, modeFlags)) {
4846 // No need to grant the target this permission.
4847 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4848 "Target " + targetPkg + " already has full permission to " + uri);
4849 return -1;
4850 }
4851 } else {
4852 // First... there is no target package, so can anyone access it?
4853 boolean allowed = pi.exported;
4854 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
4855 if (pi.readPermission != null) {
4856 allowed = false;
4857 }
4858 }
4859 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
4860 if (pi.writePermission != null) {
4861 allowed = false;
4862 }
4863 }
4864 if (allowed) {
4865 return -1;
4866 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004867 }
4868
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004869 // Second... is the provider allowing granting of URI permissions?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004870 if (!pi.grantUriPermissions) {
4871 throw new SecurityException("Provider " + pi.packageName
4872 + "/" + pi.name
4873 + " does not allow granting of Uri permissions (uri "
4874 + uri + ")");
4875 }
4876 if (pi.uriPermissionPatterns != null) {
4877 final int N = pi.uriPermissionPatterns.length;
4878 boolean allowed = false;
4879 for (int i=0; i<N; i++) {
4880 if (pi.uriPermissionPatterns[i] != null
4881 && pi.uriPermissionPatterns[i].match(uri.getPath())) {
4882 allowed = true;
4883 break;
4884 }
4885 }
4886 if (!allowed) {
4887 throw new SecurityException("Provider " + pi.packageName
4888 + "/" + pi.name
4889 + " does not allow granting of permission to path of Uri "
4890 + uri);
4891 }
4892 }
4893
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004894 // Third... does the caller itself have permission to access
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004895 // this uri?
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004896 if (callingUid != Process.myUid()) {
4897 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
4898 if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
4899 throw new SecurityException("Uid " + callingUid
4900 + " does not have permission to uri " + uri);
4901 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004902 }
4903 }
4904
Dianne Hackborn39792d22010-08-19 18:01:52 -07004905 return targetUid;
4906 }
4907
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004908 public int checkGrantUriPermission(int callingUid, String targetPkg,
4909 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004910 enforceNotIsolatedCaller("checkGrantUriPermission");
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004911 synchronized(this) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004912 return checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004913 }
4914 }
4915
Dianne Hackborn39792d22010-08-19 18:01:52 -07004916 void grantUriPermissionUncheckedLocked(int targetUid, String targetPkg,
4917 Uri uri, int modeFlags, UriPermissionOwner owner) {
4918 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4919 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4920 if (modeFlags == 0) {
4921 return;
4922 }
4923
4924 // So here we are: the caller has the assumed permission
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004925 // to the uri, and the target doesn't. Let's now give this to
4926 // the target.
4927
Joe Onorato8a9b2202010-02-26 18:56:32 -08004928 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn39792d22010-08-19 18:01:52 -07004929 "Granting " + targetPkg + "/" + targetUid + " permission to " + uri);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004930
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004931 HashMap<Uri, UriPermission> targetUris
4932 = mGrantedUriPermissions.get(targetUid);
4933 if (targetUris == null) {
4934 targetUris = new HashMap<Uri, UriPermission>();
4935 mGrantedUriPermissions.put(targetUid, targetUris);
4936 }
4937
4938 UriPermission perm = targetUris.get(uri);
4939 if (perm == null) {
4940 perm = new UriPermission(targetUid, uri);
4941 targetUris.put(uri, perm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004942 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07004943
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004944 perm.modeFlags |= modeFlags;
Dianne Hackborn39792d22010-08-19 18:01:52 -07004945 if (owner == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004946 perm.globalModeFlags |= modeFlags;
Vairavan Srinivasan91c12c22011-01-21 18:26:06 -08004947 } else {
4948 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
4949 perm.readOwners.add(owner);
4950 owner.addReadPermission(perm);
4951 }
4952 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
4953 perm.writeOwners.add(owner);
4954 owner.addWritePermission(perm);
4955 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004956 }
4957 }
4958
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004959 void grantUriPermissionLocked(int callingUid, String targetPkg, Uri uri,
4960 int modeFlags, UriPermissionOwner owner) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004961 if (targetPkg == null) {
4962 throw new NullPointerException("targetPkg");
4963 }
4964
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004965 int targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn39792d22010-08-19 18:01:52 -07004966 if (targetUid < 0) {
4967 return;
4968 }
4969
4970 grantUriPermissionUncheckedLocked(targetUid, targetPkg, uri, modeFlags, owner);
4971 }
4972
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004973 static class NeededUriGrants extends ArrayList<Uri> {
4974 final String targetPkg;
4975 final int targetUid;
4976 final int flags;
4977
4978 NeededUriGrants(String _targetPkg, int _targetUid, int _flags) {
4979 targetPkg = _targetPkg;
4980 targetUid = _targetUid;
4981 flags = _flags;
4982 }
4983 }
4984
Dianne Hackborn39792d22010-08-19 18:01:52 -07004985 /**
4986 * Like checkGrantUriPermissionLocked, but takes an Intent.
4987 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004988 NeededUriGrants checkGrantUriPermissionFromIntentLocked(int callingUid,
4989 String targetPkg, Intent intent, int mode, NeededUriGrants needed) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07004990 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004991 "Checking URI perm to data=" + (intent != null ? intent.getData() : null)
4992 + " clip=" + (intent != null ? intent.getClipData() : null)
Dianne Hackbornb424b632010-08-18 15:59:05 -07004993 + " from " + intent + "; flags=0x"
4994 + Integer.toHexString(intent != null ? intent.getFlags() : 0));
4995
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004996 if (targetPkg == null) {
4997 throw new NullPointerException("targetPkg");
4998 }
4999
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005000 if (intent == null) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005001 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005002 }
5003 Uri data = intent.getData();
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005004 ClipData clip = intent.getClipData();
5005 if (data == null && clip == null) {
5006 return null;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005007 }
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005008 if (data != null) {
5009 int target = checkGrantUriPermissionLocked(callingUid, targetPkg, data,
5010 mode, needed != null ? needed.targetUid : -1);
5011 if (target > 0) {
5012 if (needed == null) {
5013 needed = new NeededUriGrants(targetPkg, target, mode);
5014 }
5015 needed.add(data);
5016 }
5017 }
5018 if (clip != null) {
5019 for (int i=0; i<clip.getItemCount(); i++) {
5020 Uri uri = clip.getItemAt(i).getUri();
5021 if (uri != null) {
5022 int target = -1;
5023 target = checkGrantUriPermissionLocked(callingUid, targetPkg, uri,
5024 mode, needed != null ? needed.targetUid : -1);
5025 if (target > 0) {
5026 if (needed == null) {
5027 needed = new NeededUriGrants(targetPkg, target, mode);
5028 }
5029 needed.add(uri);
5030 }
5031 } else {
5032 Intent clipIntent = clip.getItemAt(i).getIntent();
5033 if (clipIntent != null) {
5034 NeededUriGrants newNeeded = checkGrantUriPermissionFromIntentLocked(
5035 callingUid, targetPkg, clipIntent, mode, needed);
5036 if (newNeeded != null) {
5037 needed = newNeeded;
5038 }
5039 }
5040 }
5041 }
5042 }
5043
5044 return needed;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005045 }
5046
5047 /**
5048 * Like grantUriPermissionUncheckedLocked, but takes an Intent.
5049 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005050 void grantUriPermissionUncheckedFromIntentLocked(NeededUriGrants needed,
5051 UriPermissionOwner owner) {
5052 if (needed != null) {
5053 for (int i=0; i<needed.size(); i++) {
5054 grantUriPermissionUncheckedLocked(needed.targetUid, needed.targetPkg,
5055 needed.get(i), needed.flags, owner);
5056 }
5057 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005058 }
5059
5060 void grantUriPermissionFromIntentLocked(int callingUid,
5061 String targetPkg, Intent intent, UriPermissionOwner owner) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005062 NeededUriGrants needed = checkGrantUriPermissionFromIntentLocked(callingUid, targetPkg,
Dianne Hackbornd9781fe2012-03-08 18:04:18 -08005063 intent, intent != null ? intent.getFlags() : 0, null);
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005064 if (needed == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005065 return;
5066 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005067
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005068 grantUriPermissionUncheckedFromIntentLocked(needed, owner);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005069 }
5070
5071 public void grantUriPermission(IApplicationThread caller, String targetPkg,
5072 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005073 enforceNotIsolatedCaller("grantUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005074 synchronized(this) {
5075 final ProcessRecord r = getRecordForAppLocked(caller);
5076 if (r == null) {
5077 throw new SecurityException("Unable to find app for caller "
5078 + caller
5079 + " when granting permission to uri " + uri);
5080 }
5081 if (targetPkg == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005082 throw new IllegalArgumentException("null target");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005083 }
5084 if (uri == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005085 throw new IllegalArgumentException("null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005086 }
5087
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005088 grantUriPermissionLocked(r.uid, targetPkg, uri, modeFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005089 null);
5090 }
5091 }
5092
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005093 void removeUriPermissionIfNeededLocked(UriPermission perm) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005094 if ((perm.modeFlags&(Intent.FLAG_GRANT_READ_URI_PERMISSION
5095 |Intent.FLAG_GRANT_WRITE_URI_PERMISSION)) == 0) {
5096 HashMap<Uri, UriPermission> perms
5097 = mGrantedUriPermissions.get(perm.uid);
5098 if (perms != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005099 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005100 "Removing " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005101 perms.remove(perm.uri);
5102 if (perms.size() == 0) {
5103 mGrantedUriPermissions.remove(perm.uid);
5104 }
5105 }
5106 }
5107 }
5108
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005109 private void revokeUriPermissionLocked(int callingUid, Uri uri,
5110 int modeFlags) {
5111 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5112 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5113 if (modeFlags == 0) {
5114 return;
5115 }
5116
Joe Onorato8a9b2202010-02-26 18:56:32 -08005117 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005118 "Revoking all granted permissions to " + uri);
5119
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005120 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005121
5122 final String authority = uri.getAuthority();
5123 ProviderInfo pi = null;
Amith Yamasani483f3b02012-03-13 16:08:00 -07005124 int userId = UserId.getUserId(callingUid);
5125 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005126 if (cpr != null) {
5127 pi = cpr.info;
5128 } else {
5129 try {
5130 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005131 PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005132 } catch (RemoteException ex) {
5133 }
5134 }
5135 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005136 Slog.w(TAG, "No content provider found for permission revoke: " + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005137 return;
5138 }
5139
5140 // Does the caller have this permission on the URI?
Dianne Hackborn48058e82010-09-27 16:53:23 -07005141 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005142 // Right now, if you are not the original owner of the permission,
5143 // you are not allowed to revoke it.
5144 //if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5145 throw new SecurityException("Uid " + callingUid
5146 + " does not have permission to uri " + uri);
5147 //}
5148 }
5149
5150 // Go through all of the permissions and remove any that match.
5151 final List<String> SEGMENTS = uri.getPathSegments();
5152 if (SEGMENTS != null) {
5153 final int NS = SEGMENTS.size();
5154 int N = mGrantedUriPermissions.size();
5155 for (int i=0; i<N; i++) {
5156 HashMap<Uri, UriPermission> perms
5157 = mGrantedUriPermissions.valueAt(i);
5158 Iterator<UriPermission> it = perms.values().iterator();
5159 toploop:
5160 while (it.hasNext()) {
5161 UriPermission perm = it.next();
5162 Uri targetUri = perm.uri;
5163 if (!authority.equals(targetUri.getAuthority())) {
5164 continue;
5165 }
5166 List<String> targetSegments = targetUri.getPathSegments();
5167 if (targetSegments == null) {
5168 continue;
5169 }
5170 if (targetSegments.size() < NS) {
5171 continue;
5172 }
5173 for (int j=0; j<NS; j++) {
5174 if (!SEGMENTS.get(j).equals(targetSegments.get(j))) {
5175 continue toploop;
5176 }
5177 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08005178 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005179 "Revoking " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005180 perm.clearModes(modeFlags);
5181 if (perm.modeFlags == 0) {
5182 it.remove();
5183 }
5184 }
5185 if (perms.size() == 0) {
5186 mGrantedUriPermissions.remove(
5187 mGrantedUriPermissions.keyAt(i));
5188 N--;
5189 i--;
5190 }
5191 }
5192 }
5193 }
5194
5195 public void revokeUriPermission(IApplicationThread caller, Uri uri,
5196 int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005197 enforceNotIsolatedCaller("revokeUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005198 synchronized(this) {
5199 final ProcessRecord r = getRecordForAppLocked(caller);
5200 if (r == null) {
5201 throw new SecurityException("Unable to find app for caller "
5202 + caller
5203 + " when revoking permission to uri " + uri);
5204 }
5205 if (uri == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005206 Slog.w(TAG, "revokeUriPermission: null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005207 return;
5208 }
5209
5210 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5211 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5212 if (modeFlags == 0) {
5213 return;
5214 }
5215
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005216 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005217
5218 final String authority = uri.getAuthority();
5219 ProviderInfo pi = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005220 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005221 if (cpr != null) {
5222 pi = cpr.info;
5223 } else {
5224 try {
5225 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005226 PackageManager.GET_URI_PERMISSION_PATTERNS, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005227 } catch (RemoteException ex) {
5228 }
5229 }
5230 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005231 Slog.w(TAG, "No content provider found for permission revoke: "
5232 + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005233 return;
5234 }
5235
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005236 revokeUriPermissionLocked(r.uid, uri, modeFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005237 }
5238 }
5239
Dianne Hackborn7e269642010-08-25 19:50:20 -07005240 @Override
5241 public IBinder newUriPermissionOwner(String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005242 enforceNotIsolatedCaller("newUriPermissionOwner");
Dianne Hackborn7e269642010-08-25 19:50:20 -07005243 synchronized(this) {
5244 UriPermissionOwner owner = new UriPermissionOwner(this, name);
5245 return owner.getExternalTokenLocked();
5246 }
5247 }
5248
5249 @Override
5250 public void grantUriPermissionFromOwner(IBinder token, int fromUid, String targetPkg,
5251 Uri uri, int modeFlags) {
5252 synchronized(this) {
5253 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5254 if (owner == null) {
5255 throw new IllegalArgumentException("Unknown owner: " + token);
5256 }
5257 if (fromUid != Binder.getCallingUid()) {
5258 if (Binder.getCallingUid() != Process.myUid()) {
5259 // Only system code can grant URI permissions on behalf
5260 // of other users.
5261 throw new SecurityException("nice try");
5262 }
5263 }
5264 if (targetPkg == null) {
5265 throw new IllegalArgumentException("null target");
5266 }
5267 if (uri == null) {
5268 throw new IllegalArgumentException("null uri");
5269 }
5270
5271 grantUriPermissionLocked(fromUid, targetPkg, uri, modeFlags, owner);
5272 }
5273 }
5274
5275 @Override
5276 public void revokeUriPermissionFromOwner(IBinder token, Uri uri, int mode) {
5277 synchronized(this) {
5278 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5279 if (owner == null) {
5280 throw new IllegalArgumentException("Unknown owner: " + token);
5281 }
5282
5283 if (uri == null) {
5284 owner.removeUriPermissionsLocked(mode);
5285 } else {
5286 owner.removeUriPermissionLocked(uri, mode);
5287 }
5288 }
5289 }
5290
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005291 public void showWaitingForDebugger(IApplicationThread who, boolean waiting) {
5292 synchronized (this) {
5293 ProcessRecord app =
5294 who != null ? getRecordForAppLocked(who) : null;
5295 if (app == null) return;
5296
5297 Message msg = Message.obtain();
5298 msg.what = WAIT_FOR_DEBUGGER_MSG;
5299 msg.obj = app;
5300 msg.arg1 = waiting ? 1 : 0;
5301 mHandler.sendMessage(msg);
5302 }
5303 }
5304
5305 public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07005306 final long homeAppMem = mProcessList.getMemLevel(ProcessList.HOME_APP_ADJ);
5307 final long hiddenAppMem = mProcessList.getMemLevel(ProcessList.HIDDEN_APP_MIN_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005308 outInfo.availMem = Process.getFreeMemory();
Dianne Hackborn7d608422011-08-07 16:24:18 -07005309 outInfo.threshold = homeAppMem;
5310 outInfo.lowMemory = outInfo.availMem < (homeAppMem + ((hiddenAppMem-homeAppMem)/2));
5311 outInfo.hiddenAppThreshold = hiddenAppMem;
5312 outInfo.secondaryServerThreshold = mProcessList.getMemLevel(
Dianne Hackborne02c88a2011-10-28 13:58:15 -07005313 ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07005314 outInfo.visibleAppThreshold = mProcessList.getMemLevel(
5315 ProcessList.VISIBLE_APP_ADJ);
5316 outInfo.foregroundAppThreshold = mProcessList.getMemLevel(
5317 ProcessList.FOREGROUND_APP_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005318 }
5319
5320 // =========================================================
5321 // TASK MANAGEMENT
5322 // =========================================================
5323
5324 public List getTasks(int maxNum, int flags,
5325 IThumbnailReceiver receiver) {
5326 ArrayList list = new ArrayList();
5327
5328 PendingThumbnailsRecord pending = null;
5329 IApplicationThread topThumbnail = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005330 ActivityRecord topRecord = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005331
5332 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005333 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005334 TAG, "getTasks: max=" + maxNum + ", flags=" + flags
5335 + ", receiver=" + receiver);
5336
5337 if (checkCallingPermission(android.Manifest.permission.GET_TASKS)
5338 != PackageManager.PERMISSION_GRANTED) {
5339 if (receiver != null) {
5340 // If the caller wants to wait for pending thumbnails,
5341 // it ain't gonna get them.
5342 try {
5343 receiver.finished();
5344 } catch (RemoteException ex) {
5345 }
5346 }
5347 String msg = "Permission Denial: getTasks() from pid="
5348 + Binder.getCallingPid()
5349 + ", uid=" + Binder.getCallingUid()
5350 + " requires " + android.Manifest.permission.GET_TASKS;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005351 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005352 throw new SecurityException(msg);
5353 }
5354
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005355 int pos = mMainStack.mHistory.size()-1;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005356 ActivityRecord next =
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005357 pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005358 ActivityRecord top = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005359 TaskRecord curTask = null;
5360 int numActivities = 0;
5361 int numRunning = 0;
5362 while (pos >= 0 && maxNum > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005363 final ActivityRecord r = next;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005364 pos--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005365 next = pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005366
5367 // Initialize state for next task if needed.
5368 if (top == null ||
5369 (top.state == ActivityState.INITIALIZING
5370 && top.task == r.task)) {
5371 top = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005372 curTask = r.task;
5373 numActivities = numRunning = 0;
5374 }
5375
5376 // Add 'r' into the current task.
5377 numActivities++;
5378 if (r.app != null && r.app.thread != null) {
5379 numRunning++;
5380 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005381
Joe Onorato8a9b2202010-02-26 18:56:32 -08005382 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005383 TAG, r.intent.getComponent().flattenToShortString()
5384 + ": task=" + r.task);
5385
5386 // If the next one is a different task, generate a new
5387 // TaskInfo entry for what we have.
5388 if (next == null || next.task != curTask) {
5389 ActivityManager.RunningTaskInfo ci
5390 = new ActivityManager.RunningTaskInfo();
5391 ci.id = curTask.taskId;
5392 ci.baseActivity = r.intent.getComponent();
5393 ci.topActivity = top.intent.getComponent();
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005394 if (top.thumbHolder != null) {
5395 ci.description = top.thumbHolder.lastDescription;
5396 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005397 ci.numActivities = numActivities;
5398 ci.numRunning = numRunning;
5399 //System.out.println(
5400 // "#" + maxNum + ": " + " descr=" + ci.description);
5401 if (ci.thumbnail == null && receiver != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005402 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005403 TAG, "State=" + top.state + "Idle=" + top.idle
5404 + " app=" + top.app
5405 + " thr=" + (top.app != null ? top.app.thread : null));
5406 if (top.state == ActivityState.RESUMED
5407 || top.state == ActivityState.PAUSING) {
5408 if (top.idle && top.app != null
5409 && top.app.thread != null) {
5410 topRecord = top;
5411 topThumbnail = top.app.thread;
5412 } else {
5413 top.thumbnailNeeded = true;
5414 }
5415 }
5416 if (pending == null) {
5417 pending = new PendingThumbnailsRecord(receiver);
5418 }
5419 pending.pendingRecords.add(top);
5420 }
5421 list.add(ci);
5422 maxNum--;
5423 top = null;
5424 }
5425 }
5426
5427 if (pending != null) {
5428 mPendingThumbnails.add(pending);
5429 }
5430 }
5431
Joe Onorato8a9b2202010-02-26 18:56:32 -08005432 if (localLOGV) Slog.v(TAG, "We have pending thumbnails: " + pending);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005433
5434 if (topThumbnail != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005435 if (localLOGV) Slog.v(TAG, "Requesting top thumbnail");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005436 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08005437 topThumbnail.requestThumbnail(topRecord.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005438 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005439 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005440 sendPendingThumbnail(null, topRecord.appToken, null, null, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005441 }
5442 }
5443
5444 if (pending == null && receiver != null) {
5445 // In this case all thumbnails were available and the client
5446 // is being asked to be told when the remaining ones come in...
5447 // which is unusually, since the top-most currently running
5448 // activity should never have a canned thumbnail! Oh well.
5449 try {
5450 receiver.finished();
5451 } catch (RemoteException ex) {
5452 }
5453 }
5454
5455 return list;
5456 }
5457
5458 public List<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum,
5459 int flags) {
Amith Yamasani742a6712011-05-04 14:49:28 -07005460 final int callingUid = Binder.getCallingUid();
5461 // If it's the system uid asking, then use the current user id.
5462 // TODO: Make sure that there aren't any other legitimate calls from the system uid that
5463 // require the entire list.
5464 final int callingUserId = callingUid == Process.SYSTEM_UID
5465 ? mCurrentUserId : UserId.getUserId(callingUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005466 synchronized (this) {
5467 enforceCallingPermission(android.Manifest.permission.GET_TASKS,
5468 "getRecentTasks()");
5469
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005470 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005471
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005472 final int N = mRecentTasks.size();
5473 ArrayList<ActivityManager.RecentTaskInfo> res
5474 = new ArrayList<ActivityManager.RecentTaskInfo>(
5475 maxNum < N ? maxNum : N);
5476 for (int i=0; i<N && maxNum > 0; i++) {
5477 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005478 // Only add calling user's recent tasks
5479 if (tr.userId != callingUserId) continue;
Dianne Hackborn905577f2011-09-07 18:31:28 -07005480 // Return the entry if desired by the caller. We always return
5481 // the first entry, because callers always expect this to be the
Amith Yamasani742a6712011-05-04 14:49:28 -07005482 // foreground app. We may filter others if the caller has
Dianne Hackborn905577f2011-09-07 18:31:28 -07005483 // not supplied RECENT_WITH_EXCLUDED and there is some reason
5484 // we should exclude the entry.
Amith Yamasani742a6712011-05-04 14:49:28 -07005485
Dianne Hackborn905577f2011-09-07 18:31:28 -07005486 if (i == 0
5487 || ((flags&ActivityManager.RECENT_WITH_EXCLUDED) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005488 || (tr.intent == null)
5489 || ((tr.intent.getFlags()
5490 &Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) == 0)) {
5491 ActivityManager.RecentTaskInfo rti
5492 = new ActivityManager.RecentTaskInfo();
5493 rti.id = tr.numActivities > 0 ? tr.taskId : -1;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005494 rti.persistentId = tr.taskId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005495 rti.baseIntent = new Intent(
5496 tr.intent != null ? tr.intent : tr.affinityIntent);
5497 rti.origActivity = tr.origActivity;
Dianne Hackbornd2835932010-12-13 16:28:46 -08005498 rti.description = tr.lastDescription;
5499
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005500 if ((flags&ActivityManager.RECENT_IGNORE_UNAVAILABLE) != 0) {
5501 // Check whether this activity is currently available.
5502 try {
5503 if (rti.origActivity != null) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07005504 if (pm.getActivityInfo(rti.origActivity, 0, callingUserId)
5505 == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005506 continue;
5507 }
5508 } else if (rti.baseIntent != null) {
5509 if (pm.queryIntentActivities(rti.baseIntent,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005510 null, 0, callingUserId) == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005511 continue;
5512 }
5513 }
5514 } catch (RemoteException e) {
5515 // Will never happen.
5516 }
5517 }
5518
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005519 res.add(rti);
5520 maxNum--;
5521 }
5522 }
5523 return res;
5524 }
5525 }
5526
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005527 private TaskRecord taskForIdLocked(int id) {
5528 final int N = mRecentTasks.size();
5529 for (int i=0; i<N; i++) {
5530 TaskRecord tr = mRecentTasks.get(i);
5531 if (tr.taskId == id) {
5532 return tr;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005533 }
5534 }
5535 return null;
5536 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005537
5538 public ActivityManager.TaskThumbnails getTaskThumbnails(int id) {
5539 synchronized (this) {
5540 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
5541 "getTaskThumbnails()");
5542 TaskRecord tr = taskForIdLocked(id);
5543 if (tr != null) {
5544 return mMainStack.getTaskThumbnailsLocked(tr);
5545 }
5546 }
5547 return null;
5548 }
5549
5550 public boolean removeSubTask(int taskId, int subTaskIndex) {
5551 synchronized (this) {
5552 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5553 "removeSubTask()");
5554 long ident = Binder.clearCallingIdentity();
5555 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005556 return mMainStack.removeTaskActivitiesLocked(taskId, subTaskIndex,
5557 true) != null;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005558 } finally {
5559 Binder.restoreCallingIdentity(ident);
5560 }
5561 }
5562 }
5563
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005564 private void cleanUpRemovedTaskLocked(TaskRecord tr, int flags) {
5565 final boolean killProcesses = (flags&ActivityManager.REMOVE_TASK_KILL_PROCESS) != 0;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005566 Intent baseIntent = new Intent(
5567 tr.intent != null ? tr.intent : tr.affinityIntent);
5568 ComponentName component = baseIntent.getComponent();
5569 if (component == null) {
5570 Slog.w(TAG, "Now component for base intent of task: " + tr);
5571 return;
5572 }
5573
5574 // Find any running services associated with this app.
5575 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005576 for (ServiceRecord sr : mServiceMap.getAllServices(tr.userId)) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005577 if (sr.packageName.equals(component.getPackageName())) {
5578 services.add(sr);
5579 }
5580 }
5581
5582 // Take care of any running services associated with the app.
5583 for (int i=0; i<services.size(); i++) {
5584 ServiceRecord sr = services.get(i);
5585 if (sr.startRequested) {
5586 if ((sr.serviceInfo.flags&ServiceInfo.FLAG_STOP_WITH_TASK) != 0) {
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005587 Slog.i(TAG, "Stopping service " + sr.shortName + ": remove task");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005588 stopServiceLocked(sr);
5589 } else {
5590 sr.pendingStarts.add(new ServiceRecord.StartItem(sr, true,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005591 sr.makeNextStartId(), baseIntent, null));
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005592 if (sr.app != null && sr.app.thread != null) {
5593 sendServiceArgsLocked(sr, false);
5594 }
5595 }
5596 }
5597 }
5598
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005599 if (killProcesses) {
5600 // Find any running processes associated with this app.
5601 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
5602 SparseArray<ProcessRecord> appProcs
5603 = mProcessNames.getMap().get(component.getPackageName());
5604 if (appProcs != null) {
5605 for (int i=0; i<appProcs.size(); i++) {
5606 procs.add(appProcs.valueAt(i));
5607 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005608 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005609
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005610 // Kill the running processes.
5611 for (int i=0; i<procs.size(); i++) {
5612 ProcessRecord pr = procs.get(i);
5613 if (pr.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
5614 Slog.i(TAG, "Killing " + pr.toShortString() + ": remove task");
5615 EventLog.writeEvent(EventLogTags.AM_KILL, pr.pid,
5616 pr.processName, pr.setAdj, "remove task");
5617 Process.killProcessQuiet(pr.pid);
5618 } else {
5619 pr.waitingToKill = "remove task";
5620 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005621 }
5622 }
5623 }
5624
5625 public boolean removeTask(int taskId, int flags) {
5626 synchronized (this) {
5627 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5628 "removeTask()");
5629 long ident = Binder.clearCallingIdentity();
5630 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005631 ActivityRecord r = mMainStack.removeTaskActivitiesLocked(taskId, -1,
5632 false);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005633 if (r != null) {
5634 mRecentTasks.remove(r.task);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005635 cleanUpRemovedTaskLocked(r.task, flags);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005636 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005637 } else {
5638 TaskRecord tr = null;
5639 int i=0;
5640 while (i < mRecentTasks.size()) {
5641 TaskRecord t = mRecentTasks.get(i);
5642 if (t.taskId == taskId) {
5643 tr = t;
5644 break;
5645 }
5646 i++;
5647 }
5648 if (tr != null) {
5649 if (tr.numActivities <= 0) {
5650 // Caller is just removing a recent task that is
5651 // not actively running. That is easy!
5652 mRecentTasks.remove(i);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005653 cleanUpRemovedTaskLocked(tr, flags);
5654 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005655 } else {
5656 Slog.w(TAG, "removeTask: task " + taskId
5657 + " does not have activities to remove, "
5658 + " but numActivities=" + tr.numActivities
5659 + ": " + tr);
5660 }
5661 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005662 }
5663 } finally {
5664 Binder.restoreCallingIdentity(ident);
5665 }
5666 }
5667 return false;
5668 }
Dianne Hackbornd94df452011-02-16 18:53:31 -08005669
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005670 private final int findAffinityTaskTopLocked(int startIndex, String affinity) {
5671 int j;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005672 TaskRecord startTask = ((ActivityRecord)mMainStack.mHistory.get(startIndex)).task;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005673 TaskRecord jt = startTask;
5674
5675 // First look backwards
5676 for (j=startIndex-1; j>=0; j--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005677 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005678 if (r.task != jt) {
5679 jt = r.task;
5680 if (affinity.equals(jt.affinity)) {
5681 return j;
5682 }
5683 }
5684 }
5685
5686 // Now look forwards
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005687 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005688 jt = startTask;
5689 for (j=startIndex+1; j<N; j++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005690 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005691 if (r.task != jt) {
5692 if (affinity.equals(jt.affinity)) {
5693 return j;
5694 }
5695 jt = r.task;
5696 }
5697 }
5698
5699 // Might it be at the top?
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005700 if (affinity.equals(((ActivityRecord)mMainStack.mHistory.get(N-1)).task.affinity)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005701 return N-1;
5702 }
5703
5704 return -1;
5705 }
5706
5707 /**
Dianne Hackbornb06ea702009-07-13 13:07:51 -07005708 * TODO: Add mController hook
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005709 */
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005710 public void moveTaskToFront(int task, int flags, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005711 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5712 "moveTaskToFront()");
5713
5714 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005715 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5716 Binder.getCallingUid(), "Task to front")) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005717 ActivityOptions.abort(options);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005718 return;
5719 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005720 final long origId = Binder.clearCallingIdentity();
5721 try {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005722 TaskRecord tr = taskForIdLocked(task);
5723 if (tr != null) {
5724 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5725 mMainStack.mUserLeaving = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005726 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005727 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5728 // Caller wants the home activity moved with it. To accomplish this,
5729 // we'll just move the home task to the top first.
5730 mMainStack.moveHomeToFrontLocked();
5731 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005732 mMainStack.moveTaskToFrontLocked(tr, null, options);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005733 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005734 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005735 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
5736 ActivityRecord hr = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005737 if (hr.task.taskId == task) {
Dianne Hackbornd94df452011-02-16 18:53:31 -08005738 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5739 mMainStack.mUserLeaving = true;
5740 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005741 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5742 // Caller wants the home activity moved with it. To accomplish this,
5743 // we'll just move the home task to the top first.
5744 mMainStack.moveHomeToFrontLocked();
5745 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005746 mMainStack.moveTaskToFrontLocked(hr.task, null, options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005747 return;
5748 }
5749 }
5750 } finally {
5751 Binder.restoreCallingIdentity(origId);
5752 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005753 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005754 }
5755 }
5756
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005757 public void moveTaskToBack(int task) {
5758 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5759 "moveTaskToBack()");
5760
5761 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005762 if (mMainStack.mResumedActivity != null
5763 && mMainStack.mResumedActivity.task.taskId == task) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005764 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5765 Binder.getCallingUid(), "Task to back")) {
5766 return;
5767 }
5768 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005769 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005770 mMainStack.moveTaskToBackLocked(task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005771 Binder.restoreCallingIdentity(origId);
5772 }
5773 }
5774
5775 /**
5776 * Moves an activity, and all of the other activities within the same task, to the bottom
5777 * of the history stack. The activity's order within the task is unchanged.
5778 *
5779 * @param token A reference to the activity we wish to move
5780 * @param nonRoot If false then this only works if the activity is the root
5781 * of a task; if true it will work for any activity in a task.
5782 * @return Returns true if the move completed, false if not.
5783 */
5784 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005785 enforceNotIsolatedCaller("moveActivityTaskToBack");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005786 synchronized(this) {
5787 final long origId = Binder.clearCallingIdentity();
5788 int taskId = getTaskForActivityLocked(token, !nonRoot);
5789 if (taskId >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005790 return mMainStack.moveTaskToBackLocked(taskId, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005791 }
5792 Binder.restoreCallingIdentity(origId);
5793 }
5794 return false;
5795 }
5796
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005797 public void moveTaskBackwards(int task) {
5798 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5799 "moveTaskBackwards()");
5800
5801 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005802 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5803 Binder.getCallingUid(), "Task backwards")) {
5804 return;
5805 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005806 final long origId = Binder.clearCallingIdentity();
5807 moveTaskBackwardsLocked(task);
5808 Binder.restoreCallingIdentity(origId);
5809 }
5810 }
5811
5812 private final void moveTaskBackwardsLocked(int task) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005813 Slog.e(TAG, "moveTaskBackwards not yet implemented!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005814 }
5815
5816 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
5817 synchronized(this) {
5818 return getTaskForActivityLocked(token, onlyRoot);
5819 }
5820 }
5821
5822 int getTaskForActivityLocked(IBinder token, boolean onlyRoot) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005823 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005824 TaskRecord lastTask = null;
5825 for (int i=0; i<N; i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005826 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005827 if (r.appToken == token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005828 if (!onlyRoot || lastTask != r.task) {
5829 return r.task.taskId;
5830 }
5831 return -1;
5832 }
5833 lastTask = r.task;
5834 }
5835
5836 return -1;
5837 }
5838
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005839 // =========================================================
5840 // THUMBNAILS
5841 // =========================================================
5842
5843 public void reportThumbnail(IBinder token,
5844 Bitmap thumbnail, CharSequence description) {
5845 //System.out.println("Report thumbnail for " + token + ": " + thumbnail);
5846 final long origId = Binder.clearCallingIdentity();
5847 sendPendingThumbnail(null, token, thumbnail, description, true);
5848 Binder.restoreCallingIdentity(origId);
5849 }
5850
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005851 final void sendPendingThumbnail(ActivityRecord r, IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005852 Bitmap thumbnail, CharSequence description, boolean always) {
5853 TaskRecord task = null;
5854 ArrayList receivers = null;
5855
5856 //System.out.println("Send pending thumbnail: " + r);
5857
5858 synchronized(this) {
5859 if (r == null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07005860 r = mMainStack.isInStackLocked(token);
5861 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005862 return;
5863 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005864 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005865 if (thumbnail == null && r.thumbHolder != null) {
5866 thumbnail = r.thumbHolder.lastThumbnail;
5867 description = r.thumbHolder.lastDescription;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005868 }
5869 if (thumbnail == null && !always) {
5870 // If there is no thumbnail, and this entry is not actually
5871 // going away, then abort for now and pick up the next
5872 // thumbnail we get.
5873 return;
5874 }
5875 task = r.task;
5876
5877 int N = mPendingThumbnails.size();
5878 int i=0;
5879 while (i<N) {
5880 PendingThumbnailsRecord pr =
5881 (PendingThumbnailsRecord)mPendingThumbnails.get(i);
5882 //System.out.println("Looking in " + pr.pendingRecords);
5883 if (pr.pendingRecords.remove(r)) {
5884 if (receivers == null) {
5885 receivers = new ArrayList();
5886 }
5887 receivers.add(pr);
5888 if (pr.pendingRecords.size() == 0) {
5889 pr.finished = true;
5890 mPendingThumbnails.remove(i);
5891 N--;
5892 continue;
5893 }
5894 }
5895 i++;
5896 }
5897 }
5898
5899 if (receivers != null) {
5900 final int N = receivers.size();
5901 for (int i=0; i<N; i++) {
5902 try {
5903 PendingThumbnailsRecord pr =
5904 (PendingThumbnailsRecord)receivers.get(i);
5905 pr.receiver.newThumbnail(
5906 task != null ? task.taskId : -1, thumbnail, description);
5907 if (pr.finished) {
5908 pr.receiver.finished();
5909 }
5910 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005911 Slog.w(TAG, "Exception thrown when sending thumbnail", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005912 }
5913 }
5914 }
5915 }
5916
5917 // =========================================================
5918 // CONTENT PROVIDERS
5919 // =========================================================
5920
Jeff Brown10e89712011-07-08 18:52:57 -07005921 private final List<ProviderInfo> generateApplicationProvidersLocked(ProcessRecord app) {
5922 List<ProviderInfo> providers = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005923 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005924 providers = AppGlobals.getPackageManager().
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005925 queryContentProviders(app.processName, app.uid,
Dianne Hackborn1655be42009-05-08 14:29:01 -07005926 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005927 } catch (RemoteException ex) {
5928 }
Amith Yamasani742a6712011-05-04 14:49:28 -07005929 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005930 Slog.v(TAG_MU, "generateApplicationProvidersLocked, app.info.uid = " + app.uid);
5931 int userId = app.userId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005932 if (providers != null) {
5933 final int N = providers.size();
5934 for (int i=0; i<N; i++) {
5935 ProviderInfo cpi =
5936 (ProviderInfo)providers.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005937
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07005938 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07005939 ContentProviderRecord cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005940 if (cpr == null) {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08005941 cpr = new ContentProviderRecord(this, cpi, app.info, comp);
Amith Yamasani742a6712011-05-04 14:49:28 -07005942 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005943 }
Amith Yamasani742a6712011-05-04 14:49:28 -07005944 if (DEBUG_MU)
5945 Slog.v(TAG_MU, "generateApplicationProvidersLocked, cpi.uid = " + cpr.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005946 app.pubProviders.put(cpi.name, cpr);
5947 app.addPackage(cpi.applicationInfo.packageName);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07005948 ensurePackageDexOpt(cpi.applicationInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005949 }
5950 }
5951 return providers;
5952 }
5953
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005954 /**
5955 * Check if {@link ProcessRecord} has a possible chance at accessing the
5956 * given {@link ProviderInfo}. Final permission checking is always done
5957 * in {@link ContentProvider}.
5958 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005959 private final String checkContentProviderPermissionLocked(
Dianne Hackbornb424b632010-08-18 15:59:05 -07005960 ProviderInfo cpi, ProcessRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005961 final int callingPid = (r != null) ? r.pid : Binder.getCallingPid();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005962 final int callingUid = (r != null) ? r.uid : Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005963 if (checkComponentPermission(cpi.readPermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005964 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005965 == PackageManager.PERMISSION_GRANTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005966 return null;
5967 }
5968 if (checkComponentPermission(cpi.writePermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005969 cpi.applicationInfo.uid, cpi.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005970 == PackageManager.PERMISSION_GRANTED) {
5971 return null;
5972 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07005973
5974 PathPermission[] pps = cpi.pathPermissions;
5975 if (pps != null) {
5976 int i = pps.length;
5977 while (i > 0) {
5978 i--;
5979 PathPermission pp = pps[i];
5980 if (checkComponentPermission(pp.getReadPermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005981 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005982 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07005983 return null;
5984 }
5985 if (checkComponentPermission(pp.getWritePermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005986 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackborn2af632f2009-07-08 14:56:37 -07005987 == PackageManager.PERMISSION_GRANTED) {
5988 return null;
5989 }
5990 }
5991 }
5992
Dianne Hackbornb424b632010-08-18 15:59:05 -07005993 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(callingUid);
5994 if (perms != null) {
5995 for (Map.Entry<Uri, UriPermission> uri : perms.entrySet()) {
5996 if (uri.getKey().getAuthority().equals(cpi.authority)) {
5997 return null;
5998 }
5999 }
6000 }
6001
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006002 String msg;
6003 if (!cpi.exported) {
6004 msg = "Permission Denial: opening provider " + cpi.name
6005 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6006 + ", uid=" + callingUid + ") that is not exported from uid "
6007 + cpi.applicationInfo.uid;
6008 } else {
6009 msg = "Permission Denial: opening provider " + cpi.name
6010 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6011 + ", uid=" + callingUid + ") requires "
6012 + cpi.readPermission + " or " + cpi.writePermission;
6013 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08006014 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006015 return msg;
6016 }
6017
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006018 boolean incProviderCount(ProcessRecord r, final ContentProviderRecord cpr,
6019 IBinder externalProcessToken) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006020 if (r != null) {
6021 Integer cnt = r.conProviders.get(cpr);
6022 if (DEBUG_PROVIDER) Slog.v(TAG,
6023 "Adding provider requested by "
6024 + r.processName + " from process "
6025 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
6026 + " cnt=" + (cnt == null ? 1 : cnt));
6027 if (cnt == null) {
6028 cpr.clients.add(r);
6029 r.conProviders.put(cpr, new Integer(1));
6030 return true;
6031 } else {
6032 r.conProviders.put(cpr, new Integer(cnt.intValue()+1));
6033 }
6034 } else {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006035 cpr.addExternalProcessHandleLocked(externalProcessToken);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006036 }
6037 return false;
6038 }
6039
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006040 boolean decProviderCount(ProcessRecord r, final ContentProviderRecord cpr,
6041 IBinder externalProcessToken) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006042 if (r != null) {
6043 Integer cnt = r.conProviders.get(cpr);
6044 if (DEBUG_PROVIDER) Slog.v(TAG,
6045 "Removing provider requested by "
6046 + r.processName + " from process "
6047 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
6048 + " cnt=" + cnt);
6049 if (cnt == null || cnt.intValue() <= 1) {
6050 cpr.clients.remove(r);
6051 r.conProviders.remove(cpr);
6052 return true;
6053 } else {
6054 r.conProviders.put(cpr, new Integer(cnt.intValue()-1));
6055 }
6056 } else {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006057 cpr.removeExternalProcessHandleLocked(externalProcessToken);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006058 }
6059 return false;
6060 }
6061
Amith Yamasani742a6712011-05-04 14:49:28 -07006062 private final ContentProviderHolder getContentProviderImpl(IApplicationThread caller,
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006063 String name, IBinder token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006064 ContentProviderRecord cpr;
6065 ProviderInfo cpi = null;
6066
6067 synchronized(this) {
6068 ProcessRecord r = null;
6069 if (caller != null) {
6070 r = getRecordForAppLocked(caller);
6071 if (r == null) {
6072 throw new SecurityException(
6073 "Unable to find app for caller " + caller
6074 + " (pid=" + Binder.getCallingPid()
6075 + ") when getting content provider " + name);
6076 }
6077 }
6078
6079 // First check if this content provider has been published...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006080 int userId = UserId.getUserId(r != null ? r.uid : Binder.getCallingUid());
Amith Yamasani742a6712011-05-04 14:49:28 -07006081 cpr = mProviderMap.getProviderByName(name, userId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006082 boolean providerRunning = cpr != null;
6083 if (providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006084 cpi = cpr.info;
Dianne Hackbornb424b632010-08-18 15:59:05 -07006085 String msg;
6086 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6087 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006088 }
6089
6090 if (r != null && cpr.canRunHere(r)) {
6091 // This provider has been published or is in the process
6092 // of being published... but it is also allowed to run
6093 // in the caller's process, so don't make a connection
6094 // and just let the caller instantiate its own instance.
6095 if (cpr.provider != null) {
6096 // don't give caller the provider object, it needs
6097 // to make its own.
6098 cpr = new ContentProviderRecord(cpr);
6099 }
6100 return cpr;
6101 }
6102
6103 final long origId = Binder.clearCallingIdentity();
6104
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006105 // In this case the provider instance already exists, so we can
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006106 // return it right away.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006107 final boolean countChanged = incProviderCount(r, cpr, token);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006108 if (countChanged) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006109 if (cpr.proc != null && r.setAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006110 // If this is a perceptible app accessing the provider,
Dianne Hackborn906497c2010-05-10 15:57:38 -07006111 // make sure to count it as being accessed and thus
6112 // back up on the LRU list. This is good because
6113 // content providers are often expensive to start.
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006114 updateLruProcessLocked(cpr.proc, false, true);
Dianne Hackborn906497c2010-05-10 15:57:38 -07006115 }
Dianne Hackborn6f86c0e2010-05-11 14:20:52 -07006116 }
6117
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006118 if (cpr.proc != null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006119 if (false) {
6120 if (cpr.name.flattenToShortString().equals(
6121 "com.android.providers.calendar/.CalendarProvider2")) {
6122 Slog.v(TAG, "****************** KILLING "
6123 + cpr.name.flattenToShortString());
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006124 Process.killProcess(cpr.proc.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006125 }
6126 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006127 boolean success = updateOomAdjLocked(cpr.proc);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006128 if (DEBUG_PROVIDER) Slog.i(TAG, "Adjust success: " + success);
6129 // NOTE: there is still a race here where a signal could be
6130 // pending on the process even though we managed to update its
6131 // adj level. Not sure what to do about this, but at least
6132 // the race is now smaller.
6133 if (!success) {
6134 // Uh oh... it looks like the provider's process
6135 // has been killed on us. We need to wait for a new
6136 // process to be started, and make sure its death
6137 // doesn't kill our process.
6138 Slog.i(TAG,
6139 "Existing provider " + cpr.name.flattenToShortString()
6140 + " is crashing; detaching " + r);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006141 boolean lastRef = decProviderCount(r, cpr, token);
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006142 appDiedLocked(cpr.proc, cpr.proc.pid, cpr.proc.thread);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006143 if (!lastRef) {
6144 // This wasn't the last ref our process had on
6145 // the provider... we have now been killed, bail.
6146 return null;
6147 }
6148 providerRunning = false;
6149 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006150 }
6151
6152 Binder.restoreCallingIdentity(origId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006153 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006154
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006155 if (!providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006156 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006157 cpi = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07006158 resolveContentProvider(name,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006159 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006160 } catch (RemoteException ex) {
6161 }
6162 if (cpi == null) {
6163 return null;
6164 }
6165
Amith Yamasani483f3b02012-03-13 16:08:00 -07006166 cpi.applicationInfo = getAppInfoForUser(cpi.applicationInfo, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07006167
Dianne Hackbornb424b632010-08-18 15:59:05 -07006168 String msg;
6169 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6170 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006171 }
6172
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07006173 if (!mProcessesReady && !mDidUpdate && !mWaitingUpdate
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006174 && !cpi.processName.equals("system")) {
6175 // If this content provider does not run in the system
6176 // process, and the system is not yet ready to run other
6177 // processes, then fail fast instead of hanging.
6178 throw new IllegalArgumentException(
6179 "Attempt to launch content provider before system ready");
6180 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006181
6182 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani483f3b02012-03-13 16:08:00 -07006183 cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006184 final boolean firstClass = cpr == null;
6185 if (firstClass) {
6186 try {
6187 ApplicationInfo ai =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006188 AppGlobals.getPackageManager().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006189 getApplicationInfo(
6190 cpi.applicationInfo.packageName,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006191 STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006192 if (ai == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006193 Slog.w(TAG, "No package info for content provider "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006194 + cpi.name);
6195 return null;
6196 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006197 ai = getAppInfoForUser(ai, userId);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006198 cpr = new ContentProviderRecord(this, cpi, ai, comp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006199 } catch (RemoteException ex) {
6200 // pm is in same process, this will never happen.
6201 }
6202 }
6203
6204 if (r != null && cpr.canRunHere(r)) {
6205 // If this is a multiprocess provider, then just return its
6206 // info and allow the caller to instantiate it. Only do
6207 // this if the provider is the same user as the caller's
6208 // process, or can run as root (so can be in any process).
6209 return cpr;
6210 }
6211
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006212 if (DEBUG_PROVIDER) {
6213 RuntimeException e = new RuntimeException("here");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006214 Slog.w(TAG, "LAUNCHING REMOTE PROVIDER (myuid " + r.uid
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006215 + " pruid " + cpr.appInfo.uid + "): " + cpr.info.name, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006216 }
6217
6218 // This is single process, and our app is now connecting to it.
6219 // See if we are already in the process of launching this
6220 // provider.
6221 final int N = mLaunchingProviders.size();
6222 int i;
6223 for (i=0; i<N; i++) {
6224 if (mLaunchingProviders.get(i) == cpr) {
6225 break;
6226 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006227 }
6228
6229 // If the provider is not already being launched, then get it
6230 // started.
6231 if (i >= N) {
6232 final long origId = Binder.clearCallingIdentity();
Dianne Hackborne7f97212011-02-24 14:40:20 -08006233
6234 try {
6235 // Content provider is now in use, its package can't be stopped.
6236 try {
6237 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07006238 cpr.appInfo.packageName, false, userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006239 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006240 } catch (IllegalArgumentException e) {
6241 Slog.w(TAG, "Failed trying to unstop package "
6242 + cpr.appInfo.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006243 }
6244
6245 ProcessRecord proc = startProcessLocked(cpi.processName,
6246 cpr.appInfo, false, 0, "content provider",
6247 new ComponentName(cpi.applicationInfo.packageName,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006248 cpi.name), false, false);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006249 if (proc == null) {
6250 Slog.w(TAG, "Unable to launch app "
6251 + cpi.applicationInfo.packageName + "/"
6252 + cpi.applicationInfo.uid + " for provider "
6253 + name + ": process is bad");
6254 return null;
6255 }
6256 cpr.launchingApp = proc;
6257 mLaunchingProviders.add(cpr);
6258 } finally {
6259 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006260 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006261 }
6262
6263 // Make sure the provider is published (the same provider class
6264 // may be published under multiple names).
6265 if (firstClass) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006266 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006267 }
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006268
Amith Yamasani742a6712011-05-04 14:49:28 -07006269 mProviderMap.putProviderByName(name, cpr);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006270 incProviderCount(r, cpr, token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006271 }
6272 }
6273
6274 // Wait for the provider to be published...
6275 synchronized (cpr) {
6276 while (cpr.provider == null) {
6277 if (cpr.launchingApp == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006278 Slog.w(TAG, "Unable to launch app "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006279 + cpi.applicationInfo.packageName + "/"
6280 + cpi.applicationInfo.uid + " for provider "
6281 + name + ": launching app became null");
Doug Zongker2bec3d42009-12-04 12:52:44 -08006282 EventLog.writeEvent(EventLogTags.AM_PROVIDER_LOST_PROCESS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006283 cpi.applicationInfo.packageName,
6284 cpi.applicationInfo.uid, name);
6285 return null;
6286 }
6287 try {
Amith Yamasani742a6712011-05-04 14:49:28 -07006288 if (DEBUG_MU) {
6289 Slog.v(TAG_MU, "Waiting to start provider " + cpr + " launchingApp="
6290 + cpr.launchingApp);
6291 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006292 cpr.wait();
6293 } catch (InterruptedException ex) {
6294 }
6295 }
6296 }
6297 return cpr;
6298 }
6299
6300 public final ContentProviderHolder getContentProvider(
6301 IApplicationThread caller, String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006302 enforceNotIsolatedCaller("getContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006303 if (caller == null) {
6304 String msg = "null IApplicationThread when getting content provider "
6305 + name;
Joe Onorato8a9b2202010-02-26 18:56:32 -08006306 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006307 throw new SecurityException(msg);
6308 }
6309
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006310 return getContentProviderImpl(caller, name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006311 }
6312
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006313 public ContentProviderHolder getContentProviderExternal(String name, IBinder token) {
6314 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6315 "Do not have permission in call getContentProviderExternal()");
6316 return getContentProviderExternalUnchecked(name, token);
6317 }
6318
6319 private ContentProviderHolder getContentProviderExternalUnchecked(String name,IBinder token) {
6320 return getContentProviderImpl(null, name, token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006321 }
6322
6323 /**
6324 * Drop a content provider from a ProcessRecord's bookkeeping
6325 * @param cpr
6326 */
6327 public void removeContentProvider(IApplicationThread caller, String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006328 enforceNotIsolatedCaller("removeContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006329 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006330 int userId = UserId.getUserId(Binder.getCallingUid());
6331 ContentProviderRecord cpr = mProviderMap.getProviderByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006332 if(cpr == null) {
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006333 // remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006334 if (DEBUG_PROVIDER) Slog.v(TAG, name +
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006335 " provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006336 return;
6337 }
6338 final ProcessRecord r = getRecordForAppLocked(caller);
6339 if (r == null) {
6340 throw new SecurityException(
6341 "Unable to find app for caller " + caller +
6342 " when removing content provider " + name);
6343 }
6344 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006345 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006346 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp, userId);
6347 if (DEBUG_PROVIDER) Slog.v(TAG, "Removing provider requested by "
6348 + r.info.processName + " from process "
6349 + localCpr.appInfo.processName);
6350 if (localCpr.launchingApp == r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006351 //should not happen. taken care of as a local provider
Joe Onorato8a9b2202010-02-26 18:56:32 -08006352 Slog.w(TAG, "removeContentProvider called on local provider: "
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006353 + cpr.info.name + " in process " + r.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006354 return;
6355 } else {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006356 if (decProviderCount(r, localCpr, null)) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006357 updateOomAdjLocked();
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07006358 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006359 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006360 }
6361 }
6362
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006363 public void removeContentProviderExternal(String name, IBinder token) {
6364 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6365 "Do not have permission in call removeContentProviderExternal()");
6366 removeContentProviderExternalUnchecked(name, token);
6367 }
6368
6369 private void removeContentProviderExternalUnchecked(String name, IBinder token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006370 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006371 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
6372 Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006373 if(cpr == null) {
6374 //remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006375 if(localLOGV) Slog.v(TAG, name+" content provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006376 return;
6377 }
6378
6379 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006380 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006381 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp,
6382 Binder.getOrigCallingUser());
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006383 if (localCpr.hasExternalProcessHandles()) {
6384 if (localCpr.removeExternalProcessHandleLocked(token)) {
6385 updateOomAdjLocked();
6386 } else {
6387 Slog.e(TAG, "Attmpt to remove content provider " + localCpr
6388 + " with no external reference for token: "
6389 + token + ".");
6390 }
6391 } else {
6392 Slog.e(TAG, "Attmpt to remove content provider: " + localCpr
6393 + " with no external references.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006394 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006395 }
6396 }
6397
6398 public final void publishContentProviders(IApplicationThread caller,
6399 List<ContentProviderHolder> providers) {
6400 if (providers == null) {
6401 return;
6402 }
6403
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006404 enforceNotIsolatedCaller("publishContentProviders");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006405 synchronized(this) {
6406 final ProcessRecord r = getRecordForAppLocked(caller);
Amith Yamasani742a6712011-05-04 14:49:28 -07006407 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006408 Slog.v(TAG_MU, "ProcessRecord uid = " + r.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006409 if (r == null) {
6410 throw new SecurityException(
6411 "Unable to find app for caller " + caller
6412 + " (pid=" + Binder.getCallingPid()
6413 + ") when publishing content providers");
6414 }
6415
6416 final long origId = Binder.clearCallingIdentity();
6417
6418 final int N = providers.size();
6419 for (int i=0; i<N; i++) {
6420 ContentProviderHolder src = providers.get(i);
6421 if (src == null || src.info == null || src.provider == null) {
6422 continue;
6423 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07006424 ContentProviderRecord dst = r.pubProviders.get(src.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006425 if (DEBUG_MU)
6426 Slog.v(TAG_MU, "ContentProviderRecord uid = " + dst.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006427 if (dst != null) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006428 ComponentName comp = new ComponentName(dst.info.packageName, dst.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006429 mProviderMap.putProviderByClass(comp, dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006430 String names[] = dst.info.authority.split(";");
6431 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006432 mProviderMap.putProviderByName(names[j], dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006433 }
6434
6435 int NL = mLaunchingProviders.size();
6436 int j;
6437 for (j=0; j<NL; j++) {
6438 if (mLaunchingProviders.get(j) == dst) {
6439 mLaunchingProviders.remove(j);
6440 j--;
6441 NL--;
6442 }
6443 }
6444 synchronized (dst) {
6445 dst.provider = src.provider;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006446 dst.proc = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006447 dst.notifyAll();
6448 }
6449 updateOomAdjLocked(r);
6450 }
6451 }
6452
6453 Binder.restoreCallingIdentity(origId);
6454 }
6455 }
6456
6457 public static final void installSystemProviders() {
Jeff Brown10e89712011-07-08 18:52:57 -07006458 List<ProviderInfo> providers;
Josh Bartel2ecce342010-02-25 10:55:48 -06006459 synchronized (mSelf) {
6460 ProcessRecord app = mSelf.mProcessNames.get("system", Process.SYSTEM_UID);
6461 providers = mSelf.generateApplicationProvidersLocked(app);
Dianne Hackborn5c83a5f2010-03-12 16:46:46 -08006462 if (providers != null) {
6463 for (int i=providers.size()-1; i>=0; i--) {
6464 ProviderInfo pi = (ProviderInfo)providers.get(i);
6465 if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6466 Slog.w(TAG, "Not installing system proc provider " + pi.name
6467 + ": not system .apk");
6468 providers.remove(i);
6469 }
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006470 }
6471 }
6472 }
Josh Bartel2ecce342010-02-25 10:55:48 -06006473 if (providers != null) {
6474 mSystemThread.installSystemProviders(providers);
6475 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08006476
6477 mSelf.mCoreSettingsObserver = new CoreSettingsObserver(mSelf);
Mark Brophyc6350272011-08-05 16:16:39 +01006478
6479 mSelf.mUsageStatsService.monitorPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006480 }
6481
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006482 /**
6483 * Allows app to retrieve the MIME type of a URI without having permission
6484 * to access its content provider.
6485 *
6486 * CTS tests for this functionality can be run with "runtest cts-appsecurity".
6487 *
6488 * Test cases are at cts/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/
6489 * src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java
6490 */
6491 public String getProviderMimeType(Uri uri) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006492 enforceNotIsolatedCaller("getProviderMimeType");
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006493 final String name = uri.getAuthority();
6494 final long ident = Binder.clearCallingIdentity();
6495 ContentProviderHolder holder = null;
6496
6497 try {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006498 holder = getContentProviderExternalUnchecked(name, null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006499 if (holder != null) {
6500 return holder.provider.getType(uri);
6501 }
6502 } catch (RemoteException e) {
6503 Log.w(TAG, "Content provider dead retrieving " + uri, e);
6504 return null;
6505 } finally {
6506 if (holder != null) {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006507 removeContentProviderExternalUnchecked(name, null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006508 }
6509 Binder.restoreCallingIdentity(ident);
6510 }
6511
6512 return null;
6513 }
6514
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006515 // =========================================================
6516 // GLOBAL MANAGEMENT
6517 // =========================================================
6518
6519 final ProcessRecord newProcessRecordLocked(IApplicationThread thread,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006520 ApplicationInfo info, String customProcess, boolean isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006521 String proc = customProcess != null ? customProcess : info.processName;
6522 BatteryStatsImpl.Uid.Proc ps = null;
6523 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006524 int uid = info.uid;
6525 if (isolated) {
6526 int userId = UserId.getUserId(uid);
6527 int stepsLeft = Process.LAST_ISOLATED_UID - Process.FIRST_ISOLATED_UID + 1;
6528 uid = 0;
6529 while (true) {
6530 if (mNextIsolatedProcessUid < Process.FIRST_ISOLATED_UID
6531 || mNextIsolatedProcessUid > Process.LAST_ISOLATED_UID) {
6532 mNextIsolatedProcessUid = Process.FIRST_ISOLATED_UID;
6533 }
6534 uid = UserId.getUid(userId, mNextIsolatedProcessUid);
6535 mNextIsolatedProcessUid++;
6536 if (mIsolatedProcesses.indexOfKey(uid) < 0) {
6537 // No process for this uid, use it.
6538 break;
6539 }
6540 stepsLeft--;
6541 if (stepsLeft <= 0) {
6542 return null;
6543 }
6544 }
6545 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006546 synchronized (stats) {
6547 ps = stats.getProcessStatsLocked(info.uid, proc);
6548 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006549 return new ProcessRecord(ps, thread, info, proc, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006550 }
6551
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006552 final ProcessRecord addAppLocked(ApplicationInfo info, boolean isolated) {
6553 ProcessRecord app;
6554 if (!isolated) {
6555 app = getProcessRecordLocked(info.processName, info.uid);
6556 } else {
6557 app = null;
6558 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006559
6560 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006561 app = newProcessRecordLocked(null, info, null, isolated);
6562 mProcessNames.put(info.processName, app.uid, app);
6563 if (isolated) {
6564 mIsolatedProcesses.put(app.uid, app);
6565 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08006566 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006567 }
6568
Dianne Hackborne7f97212011-02-24 14:40:20 -08006569 // This package really, really can not be stopped.
6570 try {
6571 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07006572 info.packageName, false, UserId.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -08006573 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006574 } catch (IllegalArgumentException e) {
6575 Slog.w(TAG, "Failed trying to unstop package "
6576 + info.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006577 }
6578
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006579 if ((info.flags&(ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT))
6580 == (ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT)) {
6581 app.persistent = true;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07006582 app.maxAdj = ProcessList.PERSISTENT_PROC_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006583 }
6584 if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) {
6585 mPersistentStartingProcesses.add(app);
6586 startProcessLocked(app, "added application", app.processName);
6587 }
6588
6589 return app;
6590 }
6591
6592 public void unhandledBack() {
6593 enforceCallingPermission(android.Manifest.permission.FORCE_BACK,
6594 "unhandledBack()");
6595
6596 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006597 int count = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08006598 if (DEBUG_SWITCH) Slog.d(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006599 TAG, "Performing unhandledBack(): stack size = " + count);
6600 if (count > 1) {
6601 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006602 mMainStack.finishActivityLocked((ActivityRecord)mMainStack.mHistory.get(count-1),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006603 count-1, Activity.RESULT_CANCELED, null, "unhandled-back");
6604 Binder.restoreCallingIdentity(origId);
6605 }
6606 }
6607 }
6608
6609 public ParcelFileDescriptor openContentUri(Uri uri) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006610 enforceNotIsolatedCaller("openContentUri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006611 String name = uri.getAuthority();
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006612 ContentProviderHolder cph = getContentProviderExternalUnchecked(name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006613 ParcelFileDescriptor pfd = null;
6614 if (cph != null) {
6615 // We record the binder invoker's uid in thread-local storage before
6616 // going to the content provider to open the file. Later, in the code
6617 // that handles all permissions checks, we look for this uid and use
6618 // that rather than the Activity Manager's own uid. The effect is that
6619 // we do the check against the caller's permissions even though it looks
6620 // to the content provider like the Activity Manager itself is making
6621 // the request.
6622 sCallerIdentity.set(new Identity(
6623 Binder.getCallingPid(), Binder.getCallingUid()));
6624 try {
6625 pfd = cph.provider.openFile(uri, "r");
6626 } catch (FileNotFoundException e) {
6627 // do nothing; pfd will be returned null
6628 } finally {
6629 // Ensure that whatever happens, we clean up the identity state
6630 sCallerIdentity.remove();
6631 }
6632
6633 // We've got the fd now, so we're done with the provider.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006634 removeContentProviderExternalUnchecked(name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006635 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006636 Slog.d(TAG, "Failed to get provider for authority '" + name + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006637 }
6638 return pfd;
6639 }
6640
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006641 // Actually is sleeping or shutting down or whatever else in the future
6642 // is an inactive state.
6643 public boolean isSleeping() {
6644 return mSleeping || mShuttingDown;
6645 }
6646
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006647 public void goingToSleep() {
6648 synchronized(this) {
6649 mSleeping = true;
6650 mWindowManager.setEventDispatching(false);
6651
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006652 mMainStack.stopIfSleepingLocked();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006653
6654 // Initialize the wake times of all processes.
Dianne Hackborn287952c2010-09-22 22:34:31 -07006655 checkExcessivePowerUsageLocked(false);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006656 mHandler.removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
6657 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07006658 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006659 }
6660 }
6661
Dianne Hackborn55280a92009-05-07 15:53:46 -07006662 public boolean shutdown(int timeout) {
6663 if (checkCallingPermission(android.Manifest.permission.SHUTDOWN)
6664 != PackageManager.PERMISSION_GRANTED) {
6665 throw new SecurityException("Requires permission "
6666 + android.Manifest.permission.SHUTDOWN);
6667 }
6668
6669 boolean timedout = false;
6670
6671 synchronized(this) {
6672 mShuttingDown = true;
6673 mWindowManager.setEventDispatching(false);
6674
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006675 if (mMainStack.mResumedActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006676 mMainStack.stopIfSleepingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07006677 final long endTime = System.currentTimeMillis() + timeout;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006678 while (mMainStack.mResumedActivity != null
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08006679 || mMainStack.mPausingActivity != null) {
Dianne Hackborn55280a92009-05-07 15:53:46 -07006680 long delay = endTime - System.currentTimeMillis();
6681 if (delay <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006682 Slog.w(TAG, "Activity manager shutdown timed out");
Dianne Hackborn55280a92009-05-07 15:53:46 -07006683 timedout = true;
6684 break;
6685 }
6686 try {
6687 this.wait();
6688 } catch (InterruptedException e) {
6689 }
6690 }
6691 }
6692 }
6693
6694 mUsageStatsService.shutdown();
6695 mBatteryStatsService.shutdown();
6696
6697 return timedout;
6698 }
6699
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006700 public final void activitySlept(IBinder token) {
6701 if (localLOGV) Slog.v(
6702 TAG, "Activity slept: token=" + token);
6703
6704 ActivityRecord r = null;
6705
6706 final long origId = Binder.clearCallingIdentity();
6707
6708 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006709 r = mMainStack.isInStackLocked(token);
6710 if (r != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006711 mMainStack.activitySleptLocked(r);
6712 }
6713 }
6714
6715 Binder.restoreCallingIdentity(origId);
6716 }
6717
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006718 public void wakingUp() {
6719 synchronized(this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006720 mWindowManager.setEventDispatching(true);
6721 mSleeping = false;
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006722 mMainStack.awakeFromSleepingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006723 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006724 }
6725 }
6726
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006727 public void stopAppSwitches() {
6728 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
6729 != PackageManager.PERMISSION_GRANTED) {
6730 throw new SecurityException("Requires permission "
6731 + android.Manifest.permission.STOP_APP_SWITCHES);
6732 }
6733
6734 synchronized(this) {
6735 mAppSwitchesAllowedTime = SystemClock.uptimeMillis()
6736 + APP_SWITCH_DELAY_TIME;
6737 mDidAppSwitch = false;
6738 mHandler.removeMessages(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
6739 Message msg = mHandler.obtainMessage(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
6740 mHandler.sendMessageDelayed(msg, APP_SWITCH_DELAY_TIME);
6741 }
6742 }
6743
6744 public void resumeAppSwitches() {
6745 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
6746 != PackageManager.PERMISSION_GRANTED) {
6747 throw new SecurityException("Requires permission "
6748 + android.Manifest.permission.STOP_APP_SWITCHES);
6749 }
6750
6751 synchronized(this) {
6752 // Note that we don't execute any pending app switches... we will
6753 // let those wait until either the timeout, or the next start
6754 // activity request.
6755 mAppSwitchesAllowedTime = 0;
6756 }
6757 }
6758
6759 boolean checkAppSwitchAllowedLocked(int callingPid, int callingUid,
6760 String name) {
6761 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
6762 return true;
6763 }
6764
6765 final int perm = checkComponentPermission(
6766 android.Manifest.permission.STOP_APP_SWITCHES, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006767 callingUid, -1, true);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006768 if (perm == PackageManager.PERMISSION_GRANTED) {
6769 return true;
6770 }
6771
Joe Onorato8a9b2202010-02-26 18:56:32 -08006772 Slog.w(TAG, name + " request from " + callingUid + " stopped");
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006773 return false;
6774 }
6775
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006776 public void setDebugApp(String packageName, boolean waitForDebugger,
6777 boolean persistent) {
6778 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
6779 "setDebugApp()");
6780
6781 // Note that this is not really thread safe if there are multiple
6782 // callers into it at the same time, but that's not a situation we
6783 // care about.
6784 if (persistent) {
6785 final ContentResolver resolver = mContext.getContentResolver();
6786 Settings.System.putString(
6787 resolver, Settings.System.DEBUG_APP,
6788 packageName);
6789 Settings.System.putInt(
6790 resolver, Settings.System.WAIT_FOR_DEBUGGER,
6791 waitForDebugger ? 1 : 0);
6792 }
6793
6794 synchronized (this) {
6795 if (!persistent) {
6796 mOrigDebugApp = mDebugApp;
6797 mOrigWaitForDebugger = mWaitForDebugger;
6798 }
6799 mDebugApp = packageName;
6800 mWaitForDebugger = waitForDebugger;
6801 mDebugTransient = !persistent;
6802 if (packageName != null) {
6803 final long origId = Binder.clearCallingIdentity();
Amith Yamasani483f3b02012-03-13 16:08:00 -07006804 forceStopPackageLocked(packageName, -1, false, false, true, true, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006805 Binder.restoreCallingIdentity(origId);
6806 }
6807 }
6808 }
6809
Siva Velusamy92a8b222012-03-09 16:24:04 -08006810 void setOpenGlTraceApp(ApplicationInfo app, String processName) {
6811 synchronized (this) {
6812 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
6813 if (!isDebuggable) {
6814 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
6815 throw new SecurityException("Process not debuggable: " + app.packageName);
6816 }
6817 }
6818
6819 mOpenGlTraceApp = processName;
6820 }
6821 }
6822
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07006823 void setProfileApp(ApplicationInfo app, String processName, String profileFile,
6824 ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
6825 synchronized (this) {
6826 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
6827 if (!isDebuggable) {
6828 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
6829 throw new SecurityException("Process not debuggable: " + app.packageName);
6830 }
6831 }
6832 mProfileApp = processName;
6833 mProfileFile = profileFile;
6834 if (mProfileFd != null) {
6835 try {
6836 mProfileFd.close();
6837 } catch (IOException e) {
6838 }
6839 mProfileFd = null;
6840 }
6841 mProfileFd = profileFd;
6842 mProfileType = 0;
6843 mAutoStopProfiler = autoStopProfiler;
6844 }
6845 }
6846
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006847 public void setAlwaysFinish(boolean enabled) {
6848 enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH,
6849 "setAlwaysFinish()");
6850
6851 Settings.System.putInt(
6852 mContext.getContentResolver(),
6853 Settings.System.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0);
6854
6855 synchronized (this) {
6856 mAlwaysFinishActivities = enabled;
6857 }
6858 }
6859
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006860 public void setActivityController(IActivityController controller) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006861 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006862 "setActivityController()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006863 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006864 mController = controller;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006865 }
6866 }
6867
Dianne Hackborn9327f4f2010-01-29 10:38:29 -08006868 public boolean isUserAMonkey() {
6869 // For now the fact that there is a controller implies
6870 // we have a monkey.
6871 synchronized (this) {
6872 return mController != null;
6873 }
6874 }
6875
Jeff Sharkeya4620792011-05-20 15:29:23 -07006876 public void registerProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08006877 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
6878 "registerProcessObserver()");
6879 synchronized (this) {
6880 mProcessObservers.register(observer);
6881 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07006882 }
6883
6884 public void unregisterProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08006885 synchronized (this) {
6886 mProcessObservers.unregister(observer);
6887 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07006888 }
6889
Daniel Sandler69a48172010-06-23 16:29:36 -04006890 public void setImmersive(IBinder token, boolean immersive) {
6891 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006892 ActivityRecord r = mMainStack.isInStackLocked(token);
6893 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04006894 throw new IllegalArgumentException();
6895 }
Daniel Sandler69a48172010-06-23 16:29:36 -04006896 r.immersive = immersive;
6897 }
6898 }
6899
6900 public boolean isImmersive(IBinder token) {
6901 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006902 ActivityRecord r = mMainStack.isInStackLocked(token);
6903 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04006904 throw new IllegalArgumentException();
6905 }
Daniel Sandler69a48172010-06-23 16:29:36 -04006906 return r.immersive;
6907 }
6908 }
6909
6910 public boolean isTopActivityImmersive() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006911 enforceNotIsolatedCaller("startActivity");
Daniel Sandler69a48172010-06-23 16:29:36 -04006912 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006913 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Daniel Sandler69a48172010-06-23 16:29:36 -04006914 return (r != null) ? r.immersive : false;
6915 }
6916 }
6917
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006918 public final void enterSafeMode() {
6919 synchronized(this) {
6920 // It only makes sense to do this before the system is ready
6921 // and started launching other packages.
6922 if (!mSystemReady) {
6923 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006924 AppGlobals.getPackageManager().enterSafeMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006925 } catch (RemoteException e) {
6926 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006927 }
6928 }
6929 }
6930
Jeff Brownb09abc12011-01-13 21:08:27 -08006931 public final void showSafeModeOverlay() {
6932 View v = LayoutInflater.from(mContext).inflate(
6933 com.android.internal.R.layout.safe_mode, null);
6934 WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
6935 lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
6936 lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
6937 lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
6938 lp.gravity = Gravity.BOTTOM | Gravity.LEFT;
6939 lp.format = v.getBackground().getOpacity();
6940 lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
6941 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
6942 ((WindowManager)mContext.getSystemService(
6943 Context.WINDOW_SERVICE)).addView(v, lp);
6944 }
6945
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006946 public void noteWakeupAlarm(IIntentSender sender) {
6947 if (!(sender instanceof PendingIntentRecord)) {
6948 return;
6949 }
6950 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
6951 synchronized (stats) {
6952 if (mBatteryStatsService.isOnBattery()) {
6953 mBatteryStatsService.enforceCallingPermission();
6954 PendingIntentRecord rec = (PendingIntentRecord)sender;
6955 int MY_UID = Binder.getCallingUid();
6956 int uid = rec.uid == MY_UID ? Process.SYSTEM_UID : rec.uid;
6957 BatteryStatsImpl.Uid.Pkg pkg =
6958 stats.getPackageStatsLocked(uid, rec.key.packageName);
6959 pkg.incWakeupsLocked();
6960 }
6961 }
6962 }
6963
Dianne Hackborn64825172011-03-02 21:32:58 -08006964 public boolean killPids(int[] pids, String pReason, boolean secure) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006965 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006966 throw new SecurityException("killPids only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006967 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006968 String reason = (pReason == null) ? "Unknown" : pReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006969 // XXX Note: don't acquire main activity lock here, because the window
6970 // manager calls in with its locks held.
6971
6972 boolean killed = false;
6973 synchronized (mPidsSelfLocked) {
6974 int[] types = new int[pids.length];
6975 int worstType = 0;
6976 for (int i=0; i<pids.length; i++) {
6977 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
6978 if (proc != null) {
6979 int type = proc.setAdj;
6980 types[i] = type;
6981 if (type > worstType) {
6982 worstType = type;
6983 }
6984 }
6985 }
6986
Dianne Hackborn64825172011-03-02 21:32:58 -08006987 // If the worst oom_adj is somewhere in the hidden proc LRU range,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006988 // then constrain it so we will kill all hidden procs.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07006989 if (worstType < ProcessList.HIDDEN_APP_MAX_ADJ
6990 && worstType > ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07006991 worstType = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006992 }
Dianne Hackborn64825172011-03-02 21:32:58 -08006993
6994 // If this is not a secure call, don't let it kill processes that
6995 // are important.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07006996 if (!secure && worstType < ProcessList.SERVICE_ADJ) {
6997 worstType = ProcessList.SERVICE_ADJ;
Dianne Hackborn64825172011-03-02 21:32:58 -08006998 }
6999
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007000 Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007001 for (int i=0; i<pids.length; i++) {
7002 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7003 if (proc == null) {
7004 continue;
7005 }
7006 int adj = proc.setAdj;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007007 if (adj >= worstType && !proc.killedBackground) {
Dianne Hackborn8633e682010-04-22 16:03:41 -07007008 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007009 EventLog.writeEvent(EventLogTags.AM_KILL, proc.pid,
7010 proc.processName, adj, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007011 killed = true;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007012 proc.killedBackground = true;
7013 Process.killProcessQuiet(pids[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007014 }
7015 }
7016 }
7017 return killed;
7018 }
Jeff Sharkeyb9a07012012-03-22 17:00:04 -07007019
7020 @Override
7021 public boolean killProcessesBelowForeground(String reason) {
7022 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7023 throw new SecurityException("killProcessesBelowForeground() only available to system");
7024 }
7025
7026 return killProcessesBelowAdj(ProcessList.FOREGROUND_APP_ADJ, reason);
7027 }
7028
7029 private boolean killProcessesBelowAdj(int belowAdj, String reason) {
7030 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7031 throw new SecurityException("killProcessesBelowAdj() only available to system");
7032 }
7033
7034 boolean killed = false;
7035 synchronized (mPidsSelfLocked) {
7036 final int size = mPidsSelfLocked.size();
7037 for (int i = 0; i < size; i++) {
7038 final int pid = mPidsSelfLocked.keyAt(i);
7039 final ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7040 if (proc == null) continue;
7041
7042 final int adj = proc.setAdj;
7043 if (adj > belowAdj && !proc.killedBackground) {
7044 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
7045 EventLog.writeEvent(
7046 EventLogTags.AM_KILL, proc.pid, proc.processName, adj, reason);
7047 killed = true;
7048 proc.killedBackground = true;
7049 Process.killProcessQuiet(pid);
7050 }
7051 }
7052 }
7053 return killed;
7054 }
7055
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007056 public final void startRunning(String pkg, String cls, String action,
7057 String data) {
7058 synchronized(this) {
7059 if (mStartRunning) {
7060 return;
7061 }
7062 mStartRunning = true;
7063 mTopComponent = pkg != null && cls != null
7064 ? new ComponentName(pkg, cls) : null;
7065 mTopAction = action != null ? action : Intent.ACTION_MAIN;
7066 mTopData = data;
7067 if (!mSystemReady) {
7068 return;
7069 }
7070 }
7071
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007072 systemReady(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007073 }
7074
7075 private void retrieveSettings() {
7076 final ContentResolver resolver = mContext.getContentResolver();
7077 String debugApp = Settings.System.getString(
7078 resolver, Settings.System.DEBUG_APP);
7079 boolean waitForDebugger = Settings.System.getInt(
7080 resolver, Settings.System.WAIT_FOR_DEBUGGER, 0) != 0;
7081 boolean alwaysFinishActivities = Settings.System.getInt(
7082 resolver, Settings.System.ALWAYS_FINISH_ACTIVITIES, 0) != 0;
7083
7084 Configuration configuration = new Configuration();
7085 Settings.System.getConfiguration(resolver, configuration);
7086
7087 synchronized (this) {
7088 mDebugApp = mOrigDebugApp = debugApp;
7089 mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger;
7090 mAlwaysFinishActivities = alwaysFinishActivities;
7091 // This happens before any activities are started, so we can
7092 // change mConfiguration in-place.
Dianne Hackborn813075a62011-11-14 17:45:19 -08007093 updateConfigurationLocked(configuration, null, false, true);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007094 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Initial config: " + mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007095 }
7096 }
7097
7098 public boolean testIsSystemReady() {
7099 // no need to synchronize(this) just to read & return the value
7100 return mSystemReady;
7101 }
7102
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007103 private static File getCalledPreBootReceiversFile() {
7104 File dataDir = Environment.getDataDirectory();
7105 File systemDir = new File(dataDir, "system");
7106 File fname = new File(systemDir, "called_pre_boots.dat");
7107 return fname;
7108 }
Dianne Hackborn661cd522011-08-22 00:26:20 -07007109
7110 static final int LAST_DONE_VERSION = 10000;
7111
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007112 private static ArrayList<ComponentName> readLastDonePreBootReceivers() {
7113 ArrayList<ComponentName> lastDoneReceivers = new ArrayList<ComponentName>();
7114 File file = getCalledPreBootReceiversFile();
7115 FileInputStream fis = null;
7116 try {
7117 fis = new FileInputStream(file);
7118 DataInputStream dis = new DataInputStream(new BufferedInputStream(fis, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007119 int fvers = dis.readInt();
7120 if (fvers == LAST_DONE_VERSION) {
7121 String vers = dis.readUTF();
7122 String codename = dis.readUTF();
7123 String build = dis.readUTF();
7124 if (android.os.Build.VERSION.RELEASE.equals(vers)
7125 && android.os.Build.VERSION.CODENAME.equals(codename)
7126 && android.os.Build.VERSION.INCREMENTAL.equals(build)) {
7127 int num = dis.readInt();
7128 while (num > 0) {
7129 num--;
7130 String pkg = dis.readUTF();
7131 String cls = dis.readUTF();
7132 lastDoneReceivers.add(new ComponentName(pkg, cls));
7133 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007134 }
7135 }
7136 } catch (FileNotFoundException e) {
7137 } catch (IOException e) {
7138 Slog.w(TAG, "Failure reading last done pre-boot receivers", e);
7139 } finally {
7140 if (fis != null) {
7141 try {
7142 fis.close();
7143 } catch (IOException e) {
7144 }
7145 }
7146 }
7147 return lastDoneReceivers;
7148 }
7149
7150 private static void writeLastDonePreBootReceivers(ArrayList<ComponentName> list) {
7151 File file = getCalledPreBootReceiversFile();
7152 FileOutputStream fos = null;
7153 DataOutputStream dos = null;
7154 try {
7155 Slog.i(TAG, "Writing new set of last done pre-boot receivers...");
7156 fos = new FileOutputStream(file);
7157 dos = new DataOutputStream(new BufferedOutputStream(fos, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007158 dos.writeInt(LAST_DONE_VERSION);
7159 dos.writeUTF(android.os.Build.VERSION.RELEASE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007160 dos.writeUTF(android.os.Build.VERSION.CODENAME);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007161 dos.writeUTF(android.os.Build.VERSION.INCREMENTAL);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007162 dos.writeInt(list.size());
7163 for (int i=0; i<list.size(); i++) {
7164 dos.writeUTF(list.get(i).getPackageName());
7165 dos.writeUTF(list.get(i).getClassName());
7166 }
7167 } catch (IOException e) {
7168 Slog.w(TAG, "Failure writing last done pre-boot receivers", e);
7169 file.delete();
7170 } finally {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07007171 FileUtils.sync(fos);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007172 if (dos != null) {
7173 try {
7174 dos.close();
7175 } catch (IOException e) {
7176 // TODO Auto-generated catch block
7177 e.printStackTrace();
7178 }
7179 }
7180 }
7181 }
7182
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007183 public void systemReady(final Runnable goingCallback) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007184 synchronized(this) {
7185 if (mSystemReady) {
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007186 if (goingCallback != null) goingCallback.run();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007187 return;
7188 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007189
7190 // Check to see if there are any update receivers to run.
7191 if (!mDidUpdate) {
7192 if (mWaitingUpdate) {
7193 return;
7194 }
7195 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
7196 List<ResolveInfo> ris = null;
7197 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007198 ris = AppGlobals.getPackageManager().queryIntentReceivers(
Amith Yamasani483f3b02012-03-13 16:08:00 -07007199 intent, null, 0, 0);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007200 } catch (RemoteException e) {
7201 }
7202 if (ris != null) {
7203 for (int i=ris.size()-1; i>=0; i--) {
7204 if ((ris.get(i).activityInfo.applicationInfo.flags
7205 &ApplicationInfo.FLAG_SYSTEM) == 0) {
7206 ris.remove(i);
7207 }
7208 }
7209 intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007210
7211 ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers();
7212
7213 final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007214 for (int i=0; i<ris.size(); i++) {
7215 ActivityInfo ai = ris.get(i).activityInfo;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007216 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7217 if (lastDoneReceivers.contains(comp)) {
7218 ris.remove(i);
7219 i--;
7220 }
7221 }
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07007222
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007223 for (int i=0; i<ris.size(); i++) {
7224 ActivityInfo ai = ris.get(i).activityInfo;
7225 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7226 doneReceivers.add(comp);
7227 intent.setComponent(comp);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007228 IIntentReceiver finisher = null;
Dianne Hackbornd6847842010-01-12 18:14:19 -08007229 if (i == ris.size()-1) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007230 finisher = new IIntentReceiver.Stub() {
7231 public void performReceive(Intent intent, int resultCode,
Dianne Hackborn68d881c2009-10-05 13:58:17 -07007232 String data, Bundle extras, boolean ordered,
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007233 boolean sticky) {
7234 // The raw IIntentReceiver interface is called
7235 // with the AM lock held, so redispatch to
7236 // execute our code without the lock.
7237 mHandler.post(new Runnable() {
7238 public void run() {
7239 synchronized (ActivityManagerService.this) {
7240 mDidUpdate = true;
7241 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007242 writeLastDonePreBootReceivers(doneReceivers);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007243 showBootMessage(mContext.getText(
7244 R.string.android_upgrading_complete),
7245 false);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007246 systemReady(goingCallback);
7247 }
7248 });
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007249 }
7250 };
7251 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08007252 Slog.i(TAG, "Sending system update to: " + intent.getComponent());
Amith Yamasani742a6712011-05-04 14:49:28 -07007253 /* TODO: Send this to all users */
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007254 broadcastIntentLocked(null, null, intent, null, finisher,
Amith Yamasani742a6712011-05-04 14:49:28 -07007255 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID,
Amith Yamasanic600e21f2012-02-14 16:08:07 -08007256 0 /* UserId zero */);
Dianne Hackbornd6847842010-01-12 18:14:19 -08007257 if (finisher != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007258 mWaitingUpdate = true;
7259 }
7260 }
7261 }
7262 if (mWaitingUpdate) {
7263 return;
7264 }
7265 mDidUpdate = true;
7266 }
7267
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007268 mSystemReady = true;
7269 if (!mStartRunning) {
7270 return;
7271 }
7272 }
7273
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007274 ArrayList<ProcessRecord> procsToKill = null;
7275 synchronized(mPidsSelfLocked) {
7276 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
7277 ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7278 if (!isAllowedWhileBooting(proc.info)){
7279 if (procsToKill == null) {
7280 procsToKill = new ArrayList<ProcessRecord>();
7281 }
7282 procsToKill.add(proc);
7283 }
7284 }
7285 }
7286
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007287 synchronized(this) {
7288 if (procsToKill != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007289 for (int i=procsToKill.size()-1; i>=0; i--) {
7290 ProcessRecord proc = procsToKill.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007291 Slog.i(TAG, "Removing system update proc: " + proc);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007292 removeProcessLocked(proc, true, false, "system update done");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007293 }
7294 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007295
7296 // Now that we have cleaned up any update processes, we
7297 // are ready to start launching real processes and know that
7298 // we won't trample on them any more.
7299 mProcessesReady = true;
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007300 }
7301
Joe Onorato8a9b2202010-02-26 18:56:32 -08007302 Slog.i(TAG, "System now ready");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007303 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007304 SystemClock.uptimeMillis());
7305
7306 synchronized(this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007307 // Make sure we have no pre-ready processes sitting around.
7308
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007309 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
7310 ResolveInfo ri = mContext.getPackageManager()
7311 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST),
Dianne Hackborn1655be42009-05-08 14:29:01 -07007312 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007313 CharSequence errorMsg = null;
7314 if (ri != null) {
7315 ActivityInfo ai = ri.activityInfo;
7316 ApplicationInfo app = ai.applicationInfo;
7317 if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7318 mTopAction = Intent.ACTION_FACTORY_TEST;
7319 mTopData = null;
7320 mTopComponent = new ComponentName(app.packageName,
7321 ai.name);
7322 } else {
7323 errorMsg = mContext.getResources().getText(
7324 com.android.internal.R.string.factorytest_not_system);
7325 }
7326 } else {
7327 errorMsg = mContext.getResources().getText(
7328 com.android.internal.R.string.factorytest_no_action);
7329 }
7330 if (errorMsg != null) {
7331 mTopAction = null;
7332 mTopData = null;
7333 mTopComponent = null;
7334 Message msg = Message.obtain();
7335 msg.what = SHOW_FACTORY_ERROR_MSG;
7336 msg.getData().putCharSequence("msg", errorMsg);
7337 mHandler.sendMessage(msg);
7338 }
7339 }
7340 }
7341
7342 retrieveSettings();
7343
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007344 if (goingCallback != null) goingCallback.run();
7345
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007346 synchronized (this) {
7347 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
7348 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007349 List apps = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07007350 getPersistentApplications(STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007351 if (apps != null) {
7352 int N = apps.size();
7353 int i;
7354 for (i=0; i<N; i++) {
7355 ApplicationInfo info
7356 = (ApplicationInfo)apps.get(i);
7357 if (info != null &&
7358 !info.packageName.equals("android")) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007359 addAppLocked(info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007360 }
7361 }
7362 }
7363 } catch (RemoteException ex) {
7364 // pm is in same process, this will never happen.
7365 }
7366 }
7367
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007368 // Start up initial activity.
7369 mBooting = true;
7370
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007371 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007372 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007373 Message msg = Message.obtain();
7374 msg.what = SHOW_UID_ERROR_MSG;
7375 mHandler.sendMessage(msg);
7376 }
7377 } catch (RemoteException e) {
7378 }
7379
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007380 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007381 }
7382 }
7383
Dan Egnorb7f03672009-12-09 16:22:32 -08007384 private boolean makeAppCrashingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007385 String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007386 app.crashing = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007387 app.crashingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007388 ActivityManager.ProcessErrorStateInfo.CRASHED, null, shortMsg, longMsg, stackTrace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007389 startAppProblemLocked(app);
7390 app.stopFreezingAllLocked();
7391 return handleAppCrashLocked(app);
7392 }
7393
Dan Egnorb7f03672009-12-09 16:22:32 -08007394 private void makeAppNotRespondingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007395 String activity, String shortMsg, String longMsg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007396 app.notResponding = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007397 app.notRespondingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007398 ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING,
7399 activity, shortMsg, longMsg, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007400 startAppProblemLocked(app);
7401 app.stopFreezingAllLocked();
7402 }
7403
7404 /**
7405 * Generate a process error record, suitable for attachment to a ProcessRecord.
7406 *
7407 * @param app The ProcessRecord in which the error occurred.
7408 * @param condition Crashing, Application Not Responding, etc. Values are defined in
7409 * ActivityManager.AppErrorStateInfo
Dan Egnor60d87622009-12-16 16:32:58 -08007410 * @param activity The activity associated with the crash, if known.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007411 * @param shortMsg Short message describing the crash.
7412 * @param longMsg Long message describing the crash.
Dan Egnorb7f03672009-12-09 16:22:32 -08007413 * @param stackTrace Full crash stack trace, may be null.
7414 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007415 * @return Returns a fully-formed AppErrorStateInfo record.
7416 */
7417 private ActivityManager.ProcessErrorStateInfo generateProcessError(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007418 int condition, String activity, String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007419 ActivityManager.ProcessErrorStateInfo report = new ActivityManager.ProcessErrorStateInfo();
Dan Egnorb7f03672009-12-09 16:22:32 -08007420
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007421 report.condition = condition;
7422 report.processName = app.processName;
7423 report.pid = app.pid;
7424 report.uid = app.info.uid;
Dan Egnor60d87622009-12-16 16:32:58 -08007425 report.tag = activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007426 report.shortMsg = shortMsg;
7427 report.longMsg = longMsg;
Dan Egnorb7f03672009-12-09 16:22:32 -08007428 report.stackTrace = stackTrace;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007429
7430 return report;
7431 }
7432
Dan Egnor42471dd2010-01-07 17:25:22 -08007433 void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007434 synchronized (this) {
7435 app.crashing = false;
7436 app.crashingReport = null;
7437 app.notResponding = false;
7438 app.notRespondingReport = null;
7439 if (app.anrDialog == fromDialog) {
7440 app.anrDialog = null;
7441 }
7442 if (app.waitDialog == fromDialog) {
7443 app.waitDialog = null;
7444 }
7445 if (app.pid > 0 && app.pid != MY_PID) {
Dan Egnor42471dd2010-01-07 17:25:22 -08007446 handleAppCrashLocked(app);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007447 Slog.i(ActivityManagerService.TAG, "Killing " + app + ": user's request");
Dianne Hackborn8633e682010-04-22 16:03:41 -07007448 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
7449 app.processName, app.setAdj, "user's request after error");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007450 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007451 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007452 }
7453 }
Dan Egnor42471dd2010-01-07 17:25:22 -08007454
Dan Egnorb7f03672009-12-09 16:22:32 -08007455 private boolean handleAppCrashLocked(ProcessRecord app) {
Mike Lockwood86548c42011-09-13 17:21:46 -04007456 if (mHeadless) {
7457 Log.e(TAG, "handleAppCrashLocked: " + app.processName);
7458 return false;
7459 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007460 long now = SystemClock.uptimeMillis();
7461
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007462 Long crashTime;
7463 if (!app.isolated) {
7464 crashTime = mProcessCrashTimes.get(app.info.processName, app.uid);
7465 } else {
7466 crashTime = null;
7467 }
Dianne Hackborn7d608422011-08-07 16:24:18 -07007468 if (crashTime != null && now < crashTime+ProcessList.MIN_CRASH_INTERVAL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007469 // This process loses!
Joe Onorato8a9b2202010-02-26 18:56:32 -08007470 Slog.w(TAG, "Process " + app.info.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007471 + " has crashed too many times: killing!");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007472 EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007473 app.info.processName, app.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007474 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
7475 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007476 if (r.app == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007477 Slog.w(TAG, " Force finishing activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007478 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007479 r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED, null, "crashed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007480 }
7481 }
7482 if (!app.persistent) {
7483 // We don't want to start this process again until the user
7484 // explicitly does so... but for persistent process, we really
7485 // need to keep it running. If a persistent process is actually
7486 // repeatedly crashing, then badness for everyone.
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007487 EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007488 app.info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007489 if (!app.isolated) {
7490 // XXX We don't have a way to mark isolated processes
7491 // as bad, since they don't have a peristent identity.
7492 mBadProcesses.put(app.info.processName, app.uid, now);
7493 mProcessCrashTimes.remove(app.info.processName, app.uid);
7494 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007495 app.bad = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007496 app.removed = true;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07007497 // Don't let services in this process be restarted and potentially
7498 // annoy the user repeatedly. Unless it is persistent, since those
7499 // processes run critical code.
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007500 removeProcessLocked(app, false, false, "crash");
Dianne Hackborncb44d962011-03-10 17:02:27 -08007501 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007502 return false;
7503 }
Dianne Hackborncb44d962011-03-10 17:02:27 -08007504 mMainStack.resumeTopActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007505 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007506 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Kevin Hester-Chowd87a9be2012-03-05 08:01:00 -08007507 if (r != null && r.app == app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007508 // If the top running activity is from this crashing
7509 // process, then terminate it to avoid getting in a loop.
7510 Slog.w(TAG, " Force finishing activity "
7511 + r.intent.getComponent().flattenToShortString());
Dianne Hackbornbe707852011-11-11 14:32:10 -08007512 int index = mMainStack.indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007513 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007514 Activity.RESULT_CANCELED, null, "crashed");
Dianne Hackborn070783f2010-12-29 16:46:28 -08007515 // Also terminate any activities below it that aren't yet
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007516 // stopped, to avoid a situation where one will get
7517 // re-start our crashing activity once it gets resumed again.
7518 index--;
7519 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007520 r = (ActivityRecord)mMainStack.mHistory.get(index);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007521 if (r.state == ActivityState.RESUMED
7522 || r.state == ActivityState.PAUSING
7523 || r.state == ActivityState.PAUSED) {
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08007524 if (!r.isHomeActivity || mHomeProcess != r.app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007525 Slog.w(TAG, " Force finishing activity "
7526 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007527 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007528 Activity.RESULT_CANCELED, null, "crashed");
7529 }
7530 }
7531 }
7532 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007533 }
7534
7535 // Bump up the crash count of any services currently running in the proc.
7536 if (app.services.size() != 0) {
7537 // Any services running in the application need to be placed
7538 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -07007539 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007540 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07007541 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007542 sr.crashCount++;
7543 }
7544 }
Mattias Larssona4fd0072010-06-22 22:37:03 +02007545
7546 // If the crashing process is what we consider to be the "home process" and it has been
7547 // replaced by a third-party app, clear the package preferred activities from packages
7548 // with a home activity running in the process to prevent a repeatedly crashing app
7549 // from blocking the user to manually clear the list.
7550 if (app == mHomeProcess && mHomeProcess.activities.size() > 0
7551 && (mHomeProcess.info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
7552 Iterator it = mHomeProcess.activities.iterator();
7553 while (it.hasNext()) {
Jean-Baptiste Queru5ea89f72010-07-30 09:30:31 -07007554 ActivityRecord r = (ActivityRecord)it.next();
Mattias Larssona4fd0072010-06-22 22:37:03 +02007555 if (r.isHomeActivity) {
7556 Log.i(TAG, "Clearing package preferred activities from " + r.packageName);
7557 try {
7558 ActivityThread.getPackageManager()
7559 .clearPackagePreferredActivities(r.packageName);
7560 } catch (RemoteException c) {
7561 // pm is in same process, this will never happen.
7562 }
7563 }
7564 }
7565 }
7566
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007567 if (!app.isolated) {
7568 // XXX Can't keep track of crash times for isolated processes,
7569 // because they don't have a perisistent identity.
7570 mProcessCrashTimes.put(app.info.processName, app.uid, now);
7571 }
7572
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007573 return true;
7574 }
7575
7576 void startAppProblemLocked(ProcessRecord app) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08007577 app.errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver(
7578 mContext, app.info.packageName, app.info.flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007579 skipCurrentReceiverLocked(app);
7580 }
7581
7582 void skipCurrentReceiverLocked(ProcessRecord app) {
Christopher Tatef46723b2012-01-26 14:19:24 -08007583 for (BroadcastQueue queue : mBroadcastQueues) {
7584 queue.skipCurrentReceiverLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007585 }
7586 }
7587
Dan Egnor60d87622009-12-16 16:32:58 -08007588 /**
7589 * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes.
7590 * The application process will exit immediately after this call returns.
7591 * @param app object of the crashing app, null for the system server
7592 * @param crashInfo describing the exception
7593 */
7594 public void handleApplicationCrash(IBinder app, ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007595 ProcessRecord r = findAppProcess(app, "Crash");
Jeff Sharkeya353d262011-10-28 11:12:06 -07007596 final String processName = app == null ? "system_server"
7597 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08007598
7599 EventLog.writeEvent(EventLogTags.AM_CRASH, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07007600 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08007601 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08007602 crashInfo.exceptionClassName,
7603 crashInfo.exceptionMessage,
7604 crashInfo.throwFileName,
7605 crashInfo.throwLineNumber);
7606
Jeff Sharkeya353d262011-10-28 11:12:06 -07007607 addErrorToDropBox("crash", r, processName, null, null, null, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08007608
7609 crashApplication(r, crashInfo);
7610 }
7611
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007612 public void handleApplicationStrictModeViolation(
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007613 IBinder app,
7614 int violationMask,
7615 StrictMode.ViolationInfo info) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007616 ProcessRecord r = findAppProcess(app, "StrictMode");
7617 if (r == null) {
7618 return;
7619 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007620
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007621 if ((violationMask & StrictMode.PENALTY_DROPBOX) != 0) {
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08007622 Integer stackFingerprint = info.hashCode();
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007623 boolean logIt = true;
7624 synchronized (mAlreadyLoggedViolatedStacks) {
7625 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) {
7626 logIt = false;
7627 // TODO: sub-sample into EventLog for these, with
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007628 // the info.durationMillis? Then we'd get
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007629 // the relative pain numbers, without logging all
7630 // the stack traces repeatedly. We'd want to do
7631 // likewise in the client code, which also does
7632 // dup suppression, before the Binder call.
7633 } else {
7634 if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) {
7635 mAlreadyLoggedViolatedStacks.clear();
7636 }
7637 mAlreadyLoggedViolatedStacks.add(stackFingerprint);
7638 }
7639 }
7640 if (logIt) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007641 logStrictModeViolationToDropBox(r, info);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007642 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007643 }
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007644
7645 if ((violationMask & StrictMode.PENALTY_DIALOG) != 0) {
7646 AppErrorResult result = new AppErrorResult();
7647 synchronized (this) {
7648 final long origId = Binder.clearCallingIdentity();
7649
7650 Message msg = Message.obtain();
7651 msg.what = SHOW_STRICT_MODE_VIOLATION_MSG;
7652 HashMap<String, Object> data = new HashMap<String, Object>();
7653 data.put("result", result);
7654 data.put("app", r);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007655 data.put("violationMask", violationMask);
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007656 data.put("info", info);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007657 msg.obj = data;
7658 mHandler.sendMessage(msg);
7659
7660 Binder.restoreCallingIdentity(origId);
7661 }
7662 int res = result.get();
Dianne Hackbornb424b632010-08-18 15:59:05 -07007663 Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007664 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007665 }
7666
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007667 // Depending on the policy in effect, there could be a bunch of
7668 // these in quick succession so we try to batch these together to
7669 // minimize disk writes, number of dropbox entries, and maximize
7670 // compression, by having more fewer, larger records.
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007671 private void logStrictModeViolationToDropBox(
7672 ProcessRecord process,
7673 StrictMode.ViolationInfo info) {
7674 if (info == null) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007675 return;
7676 }
7677 final boolean isSystemApp = process == null ||
7678 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM |
7679 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07007680 final String processName = process == null ? "unknown" : process.processName;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007681 final String dropboxTag = isSystemApp ? "system_app_strictmode" : "data_app_strictmode";
7682 final DropBoxManager dbox = (DropBoxManager)
7683 mContext.getSystemService(Context.DROPBOX_SERVICE);
7684
7685 // Exit early if the dropbox isn't configured to accept this report type.
7686 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
7687
7688 boolean bufferWasEmpty;
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007689 boolean needsFlush;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007690 final StringBuilder sb = isSystemApp ? mStrictModeBuffer : new StringBuilder(1024);
7691 synchronized (sb) {
7692 bufferWasEmpty = sb.length() == 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07007693 appendDropBoxProcessHeaders(process, processName, sb);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007694 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
7695 sb.append("System-App: ").append(isSystemApp).append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007696 sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n");
7697 if (info.violationNumThisLoop != 0) {
7698 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n");
7699 }
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07007700 if (info.numAnimationsRunning != 0) {
7701 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n");
7702 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07007703 if (info.broadcastIntentAction != null) {
7704 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n");
7705 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08007706 if (info.durationMillis != -1) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007707 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n");
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007708 }
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08007709 if (info.numInstances != -1) {
7710 sb.append("Instance-Count: ").append(info.numInstances).append("\n");
7711 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08007712 if (info.tags != null) {
7713 for (String tag : info.tags) {
7714 sb.append("Span-Tag: ").append(tag).append("\n");
7715 }
7716 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007717 sb.append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007718 if (info.crashInfo != null && info.crashInfo.stackTrace != null) {
7719 sb.append(info.crashInfo.stackTrace);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007720 }
7721 sb.append("\n");
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007722
7723 // Only buffer up to ~64k. Various logging bits truncate
7724 // things at 128k.
7725 needsFlush = (sb.length() > 64 * 1024);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007726 }
7727
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007728 // Flush immediately if the buffer's grown too large, or this
7729 // is a non-system app. Non-system apps are isolated with a
7730 // different tag & policy and not batched.
7731 //
7732 // Batching is useful during internal testing with
7733 // StrictMode settings turned up high. Without batching,
7734 // thousands of separate files could be created on boot.
7735 if (!isSystemApp || needsFlush) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007736 new Thread("Error dump: " + dropboxTag) {
7737 @Override
7738 public void run() {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007739 String report;
7740 synchronized (sb) {
7741 report = sb.toString();
7742 sb.delete(0, sb.length());
7743 sb.trimToSize();
7744 }
7745 if (report.length() != 0) {
7746 dbox.addText(dropboxTag, report);
7747 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007748 }
7749 }.start();
7750 return;
7751 }
7752
7753 // System app batching:
7754 if (!bufferWasEmpty) {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007755 // An existing dropbox-writing thread is outstanding, so
7756 // we don't need to start it up. The existing thread will
7757 // catch the buffer appends we just did.
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007758 return;
7759 }
7760
7761 // Worker thread to both batch writes and to avoid blocking the caller on I/O.
7762 // (After this point, we shouldn't access AMS internal data structures.)
7763 new Thread("Error dump: " + dropboxTag) {
7764 @Override
7765 public void run() {
7766 // 5 second sleep to let stacks arrive and be batched together
7767 try {
7768 Thread.sleep(5000); // 5 seconds
7769 } catch (InterruptedException e) {}
7770
7771 String errorReport;
7772 synchronized (mStrictModeBuffer) {
7773 errorReport = mStrictModeBuffer.toString();
7774 if (errorReport.length() == 0) {
7775 return;
7776 }
7777 mStrictModeBuffer.delete(0, mStrictModeBuffer.length());
7778 mStrictModeBuffer.trimToSize();
7779 }
7780 dbox.addText(dropboxTag, errorReport);
7781 }
7782 }.start();
7783 }
7784
Dan Egnor60d87622009-12-16 16:32:58 -08007785 /**
7786 * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors.
7787 * @param app object of the crashing app, null for the system server
7788 * @param tag reported by the caller
7789 * @param crashInfo describing the context of the error
7790 * @return true if the process should exit immediately (WTF is fatal)
7791 */
7792 public boolean handleApplicationWtf(IBinder app, String tag,
Dan Egnorb7f03672009-12-09 16:22:32 -08007793 ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007794 ProcessRecord r = findAppProcess(app, "WTF");
Jeff Sharkeya353d262011-10-28 11:12:06 -07007795 final String processName = app == null ? "system_server"
7796 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08007797
7798 EventLog.writeEvent(EventLogTags.AM_WTF, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07007799 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08007800 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08007801 tag, crashInfo.exceptionMessage);
7802
Jeff Sharkeya353d262011-10-28 11:12:06 -07007803 addErrorToDropBox("wtf", r, processName, null, null, tag, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08007804
Dianne Hackborn1ab43772011-03-15 14:38:02 -07007805 if (r != null && r.pid != Process.myPid() &&
7806 Settings.Secure.getInt(mContext.getContentResolver(),
7807 Settings.Secure.WTF_IS_FATAL, 0) != 0) {
Dan Egnor60d87622009-12-16 16:32:58 -08007808 crashApplication(r, crashInfo);
7809 return true;
7810 } else {
7811 return false;
7812 }
7813 }
7814
7815 /**
7816 * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit})
7817 * @return the corresponding {@link ProcessRecord} object, or null if none could be found
7818 */
Dianne Hackborncb44d962011-03-10 17:02:27 -08007819 private ProcessRecord findAppProcess(IBinder app, String reason) {
Dan Egnor60d87622009-12-16 16:32:58 -08007820 if (app == null) {
7821 return null;
7822 }
7823
7824 synchronized (this) {
7825 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
7826 final int NA = apps.size();
7827 for (int ia=0; ia<NA; ia++) {
7828 ProcessRecord p = apps.valueAt(ia);
7829 if (p.thread != null && p.thread.asBinder() == app) {
7830 return p;
7831 }
7832 }
7833 }
7834
Dianne Hackborncb44d962011-03-10 17:02:27 -08007835 Slog.w(TAG, "Can't find mystery application for " + reason
7836 + " from pid=" + Binder.getCallingPid()
7837 + " uid=" + Binder.getCallingUid() + ": " + app);
Dan Egnor60d87622009-12-16 16:32:58 -08007838 return null;
7839 }
7840 }
7841
7842 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007843 * Utility function for addErrorToDropBox and handleStrictModeViolation's logging
7844 * to append various headers to the dropbox log text.
Dan Egnor60d87622009-12-16 16:32:58 -08007845 */
Jeff Sharkeya353d262011-10-28 11:12:06 -07007846 private void appendDropBoxProcessHeaders(ProcessRecord process, String processName,
7847 StringBuilder sb) {
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08007848 // Watchdog thread ends up invoking this function (with
7849 // a null ProcessRecord) to add the stack file to dropbox.
7850 // Do not acquire a lock on this (am) in such cases, as it
7851 // could cause a potential deadlock, if and when watchdog
7852 // is invoked due to unavailability of lock on am and it
7853 // would prevent watchdog from killing system_server.
7854 if (process == null) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07007855 sb.append("Process: ").append(processName).append("\n");
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08007856 return;
7857 }
Brad Fitzpatrick1e02d362010-09-10 09:19:50 -07007858 // Note: ProcessRecord 'process' is guarded by the service
7859 // instance. (notably process.pkgList, which could otherwise change
7860 // concurrently during execution of this method)
7861 synchronized (this) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07007862 sb.append("Process: ").append(processName).append("\n");
Dan Egnora455d192010-03-12 08:52:28 -08007863 int flags = process.info.flags;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007864 IPackageManager pm = AppGlobals.getPackageManager();
Dan Egnora455d192010-03-12 08:52:28 -08007865 sb.append("Flags: 0x").append(Integer.toString(flags, 16)).append("\n");
7866 for (String pkg : process.pkgList) {
7867 sb.append("Package: ").append(pkg);
Dan Egnor42471dd2010-01-07 17:25:22 -08007868 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07007869 PackageInfo pi = pm.getPackageInfo(pkg, 0, 0);
Dan Egnora455d192010-03-12 08:52:28 -08007870 if (pi != null) {
7871 sb.append(" v").append(pi.versionCode);
7872 if (pi.versionName != null) {
7873 sb.append(" (").append(pi.versionName).append(")");
7874 }
7875 }
7876 } catch (RemoteException e) {
7877 Slog.e(TAG, "Error getting package info: " + pkg, e);
Dan Egnor60d87622009-12-16 16:32:58 -08007878 }
Dan Egnora455d192010-03-12 08:52:28 -08007879 sb.append("\n");
Dan Egnor60d87622009-12-16 16:32:58 -08007880 }
Dan Egnora455d192010-03-12 08:52:28 -08007881 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007882 }
7883
7884 private static String processClass(ProcessRecord process) {
7885 if (process == null || process.pid == MY_PID) {
7886 return "system_server";
7887 } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
7888 return "system_app";
7889 } else {
7890 return "data_app";
7891 }
7892 }
7893
7894 /**
7895 * Write a description of an error (crash, WTF, ANR) to the drop box.
7896 * @param eventType to include in the drop box tag ("crash", "wtf", etc.)
7897 * @param process which caused the error, null means the system server
7898 * @param activity which triggered the error, null if unknown
7899 * @param parent activity related to the error, null if unknown
7900 * @param subject line related to the error, null if absent
7901 * @param report in long form describing the error, null if absent
7902 * @param logFile to include in the report, null if none
7903 * @param crashInfo giving an application stack trace, null if absent
7904 */
7905 public void addErrorToDropBox(String eventType,
Jeff Sharkeya353d262011-10-28 11:12:06 -07007906 ProcessRecord process, String processName, ActivityRecord activity,
7907 ActivityRecord parent, String subject,
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007908 final String report, final File logFile,
7909 final ApplicationErrorReport.CrashInfo crashInfo) {
7910 // NOTE -- this must never acquire the ActivityManagerService lock,
7911 // otherwise the watchdog may be prevented from resetting the system.
7912
7913 final String dropboxTag = processClass(process) + "_" + eventType;
7914 final DropBoxManager dbox = (DropBoxManager)
7915 mContext.getSystemService(Context.DROPBOX_SERVICE);
7916
7917 // Exit early if the dropbox isn't configured to accept this report type.
7918 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
7919
7920 final StringBuilder sb = new StringBuilder(1024);
Jeff Sharkeya353d262011-10-28 11:12:06 -07007921 appendDropBoxProcessHeaders(process, processName, sb);
Dan Egnora455d192010-03-12 08:52:28 -08007922 if (activity != null) {
7923 sb.append("Activity: ").append(activity.shortComponentName).append("\n");
7924 }
7925 if (parent != null && parent.app != null && parent.app.pid != process.pid) {
7926 sb.append("Parent-Process: ").append(parent.app.processName).append("\n");
7927 }
7928 if (parent != null && parent != activity) {
7929 sb.append("Parent-Activity: ").append(parent.shortComponentName).append("\n");
7930 }
7931 if (subject != null) {
7932 sb.append("Subject: ").append(subject).append("\n");
7933 }
7934 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
Christian Lindeberg03d2ca62010-09-28 14:52:20 +02007935 if (Debug.isDebuggerConnected()) {
7936 sb.append("Debugger: Connected\n");
7937 }
Dan Egnora455d192010-03-12 08:52:28 -08007938 sb.append("\n");
7939
7940 // Do the rest in a worker thread to avoid blocking the caller on I/O
7941 // (After this point, we shouldn't access AMS internal data structures.)
7942 Thread worker = new Thread("Error dump: " + dropboxTag) {
7943 @Override
7944 public void run() {
7945 if (report != null) {
7946 sb.append(report);
7947 }
7948 if (logFile != null) {
7949 try {
7950 sb.append(FileUtils.readTextFile(logFile, 128 * 1024, "\n\n[[TRUNCATED]]"));
7951 } catch (IOException e) {
7952 Slog.e(TAG, "Error reading " + logFile, e);
7953 }
7954 }
7955 if (crashInfo != null && crashInfo.stackTrace != null) {
7956 sb.append(crashInfo.stackTrace);
7957 }
7958
7959 String setting = Settings.Secure.ERROR_LOGCAT_PREFIX + dropboxTag;
7960 int lines = Settings.Secure.getInt(mContext.getContentResolver(), setting, 0);
7961 if (lines > 0) {
7962 sb.append("\n");
7963
7964 // Merge several logcat streams, and take the last N lines
7965 InputStreamReader input = null;
7966 try {
7967 java.lang.Process logcat = new ProcessBuilder("/system/bin/logcat",
7968 "-v", "time", "-b", "events", "-b", "system", "-b", "main",
7969 "-t", String.valueOf(lines)).redirectErrorStream(true).start();
7970
7971 try { logcat.getOutputStream().close(); } catch (IOException e) {}
7972 try { logcat.getErrorStream().close(); } catch (IOException e) {}
7973 input = new InputStreamReader(logcat.getInputStream());
7974
7975 int num;
7976 char[] buf = new char[8192];
7977 while ((num = input.read(buf)) > 0) sb.append(buf, 0, num);
7978 } catch (IOException e) {
7979 Slog.e(TAG, "Error running logcat", e);
7980 } finally {
7981 if (input != null) try { input.close(); } catch (IOException e) {}
7982 }
7983 }
7984
7985 dbox.addText(dropboxTag, sb.toString());
Dan Egnor60d87622009-12-16 16:32:58 -08007986 }
Dan Egnora455d192010-03-12 08:52:28 -08007987 };
7988
7989 if (process == null || process.pid == MY_PID) {
7990 worker.run(); // We may be about to die -- need to run this synchronously
7991 } else {
7992 worker.start();
Dan Egnor60d87622009-12-16 16:32:58 -08007993 }
7994 }
7995
7996 /**
7997 * Bring up the "unexpected error" dialog box for a crashing app.
7998 * Deal with edge cases (intercepts from instrumented applications,
7999 * ActivityController, error intent receivers, that sort of thing).
8000 * @param r the application crashing
8001 * @param crashInfo describing the failure
8002 */
8003 private void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008004 long timeMillis = System.currentTimeMillis();
8005 String shortMsg = crashInfo.exceptionClassName;
8006 String longMsg = crashInfo.exceptionMessage;
8007 String stackTrace = crashInfo.stackTrace;
8008 if (shortMsg != null && longMsg != null) {
8009 longMsg = shortMsg + ": " + longMsg;
8010 } else if (shortMsg != null) {
8011 longMsg = shortMsg;
8012 }
8013
Dan Egnor60d87622009-12-16 16:32:58 -08008014 AppErrorResult result = new AppErrorResult();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008015 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008016 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008017 try {
8018 String name = r != null ? r.processName : null;
8019 int pid = r != null ? r.pid : Binder.getCallingPid();
Dan Egnor60d87622009-12-16 16:32:58 -08008020 if (!mController.appCrashed(name, pid,
Dan Egnorb7f03672009-12-09 16:22:32 -08008021 shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008022 Slog.w(TAG, "Force-killing crashed app " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008023 + " at watcher's request");
8024 Process.killProcess(pid);
Dan Egnorb7f03672009-12-09 16:22:32 -08008025 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008026 }
8027 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008028 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008029 }
8030 }
8031
8032 final long origId = Binder.clearCallingIdentity();
8033
8034 // If this process is running instrumentation, finish it.
8035 if (r != null && r.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008036 Slog.w(TAG, "Error in app " + r.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008037 + " running instrumentation " + r.instrumentationClass + ":");
Joe Onorato8a9b2202010-02-26 18:56:32 -08008038 if (shortMsg != null) Slog.w(TAG, " " + shortMsg);
8039 if (longMsg != null) Slog.w(TAG, " " + longMsg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008040 Bundle info = new Bundle();
8041 info.putString("shortMsg", shortMsg);
8042 info.putString("longMsg", longMsg);
8043 finishInstrumentationLocked(r, Activity.RESULT_CANCELED, info);
8044 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008045 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008046 }
8047
Dan Egnor60d87622009-12-16 16:32:58 -08008048 // If we can't identify the process or it's already exceeded its crash quota,
8049 // quit right away without showing a crash dialog.
8050 if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008051 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008052 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008053 }
8054
8055 Message msg = Message.obtain();
8056 msg.what = SHOW_ERROR_MSG;
8057 HashMap data = new HashMap();
8058 data.put("result", result);
8059 data.put("app", r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008060 msg.obj = data;
8061 mHandler.sendMessage(msg);
8062
8063 Binder.restoreCallingIdentity(origId);
8064 }
8065
8066 int res = result.get();
8067
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008068 Intent appErrorIntent = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008069 synchronized (this) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008070 if (r != null && !r.isolated) {
8071 // XXX Can't keep track of crash time for isolated processes,
8072 // since they don't have a persistent identity.
8073 mProcessCrashTimes.put(r.info.processName, r.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008074 SystemClock.uptimeMillis());
8075 }
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008076 if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008077 appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008078 }
8079 }
8080
8081 if (appErrorIntent != null) {
8082 try {
8083 mContext.startActivity(appErrorIntent);
8084 } catch (ActivityNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008085 Slog.w(TAG, "bug report receiver dissappeared", e);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008086 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008087 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008088 }
Dan Egnorb7f03672009-12-09 16:22:32 -08008089
8090 Intent createAppErrorIntentLocked(ProcessRecord r,
8091 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
8092 ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008093 if (report == null) {
8094 return null;
8095 }
8096 Intent result = new Intent(Intent.ACTION_APP_ERROR);
8097 result.setComponent(r.errorReportReceiver);
8098 result.putExtra(Intent.EXTRA_BUG_REPORT, report);
8099 result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
8100 return result;
8101 }
8102
Dan Egnorb7f03672009-12-09 16:22:32 -08008103 private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r,
8104 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008105 if (r.errorReportReceiver == null) {
8106 return null;
8107 }
8108
8109 if (!r.crashing && !r.notResponding) {
8110 return null;
8111 }
8112
Dan Egnorb7f03672009-12-09 16:22:32 -08008113 ApplicationErrorReport report = new ApplicationErrorReport();
8114 report.packageName = r.info.packageName;
8115 report.installerPackageName = r.errorReportReceiver.getPackageName();
8116 report.processName = r.processName;
8117 report.time = timeMillis;
Jacek Surazskie0ee6ef2010-01-07 16:23:03 +01008118 report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008119
Dan Egnorb7f03672009-12-09 16:22:32 -08008120 if (r.crashing) {
8121 report.type = ApplicationErrorReport.TYPE_CRASH;
8122 report.crashInfo = crashInfo;
8123 } else if (r.notResponding) {
8124 report.type = ApplicationErrorReport.TYPE_ANR;
8125 report.anrInfo = new ApplicationErrorReport.AnrInfo();
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008126
Dan Egnorb7f03672009-12-09 16:22:32 -08008127 report.anrInfo.activity = r.notRespondingReport.tag;
8128 report.anrInfo.cause = r.notRespondingReport.shortMsg;
8129 report.anrInfo.info = r.notRespondingReport.longMsg;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008130 }
8131
Dan Egnorb7f03672009-12-09 16:22:32 -08008132 return report;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008133 }
8134
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008135 public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008136 enforceNotIsolatedCaller("getProcessesInErrorState");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008137 // assume our apps are happy - lazy create the list
8138 List<ActivityManager.ProcessErrorStateInfo> errList = null;
8139
8140 synchronized (this) {
8141
8142 // iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008143 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8144 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008145 if ((app.thread != null) && (app.crashing || app.notResponding)) {
8146 // This one's in trouble, so we'll generate a report for it
8147 // crashes are higher priority (in case there's a crash *and* an anr)
8148 ActivityManager.ProcessErrorStateInfo report = null;
8149 if (app.crashing) {
8150 report = app.crashingReport;
8151 } else if (app.notResponding) {
8152 report = app.notRespondingReport;
8153 }
8154
8155 if (report != null) {
8156 if (errList == null) {
8157 errList = new ArrayList<ActivityManager.ProcessErrorStateInfo>(1);
8158 }
8159 errList.add(report);
8160 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008161 Slog.w(TAG, "Missing app error report, app = " + app.processName +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008162 " crashing = " + app.crashing +
8163 " notResponding = " + app.notResponding);
8164 }
8165 }
8166 }
8167 }
8168
8169 return errList;
8170 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07008171
8172 static int oomAdjToImportance(int adj, ActivityManager.RunningAppProcessInfo currApp) {
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008173 if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008174 if (currApp != null) {
8175 currApp.lru = adj - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
8176 }
8177 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008178 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
8179 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008180 } else if (adj >= ProcessList.HOME_APP_ADJ) {
8181 if (currApp != null) {
8182 currApp.lru = 0;
8183 }
8184 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008185 } else if (adj >= ProcessList.SERVICE_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008186 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
8187 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
8188 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
8189 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
8190 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
8191 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
8192 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
8193 } else {
8194 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
8195 }
8196 }
8197
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008198 private void fillInProcMemInfo(ProcessRecord app,
8199 ActivityManager.RunningAppProcessInfo outInfo) {
8200 outInfo.pid = app.pid;
8201 outInfo.uid = app.info.uid;
8202 if (mHeavyWeightProcess == app) {
8203 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_CANT_SAVE_STATE;
8204 }
8205 if (app.persistent) {
8206 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_PERSISTENT;
8207 }
8208 outInfo.lastTrimLevel = app.trimMemoryLevel;
8209 int adj = app.curAdj;
8210 outInfo.importance = oomAdjToImportance(adj, outInfo);
8211 outInfo.importanceReasonCode = app.adjTypeCode;
8212 }
8213
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008214 public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008215 enforceNotIsolatedCaller("getRunningAppProcesses");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008216 // Lazy instantiation of list
8217 List<ActivityManager.RunningAppProcessInfo> runList = null;
8218 synchronized (this) {
8219 // Iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008220 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8221 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008222 if ((app.thread != null) && (!app.crashing && !app.notResponding)) {
8223 // Generate process state info for running application
8224 ActivityManager.RunningAppProcessInfo currApp =
8225 new ActivityManager.RunningAppProcessInfo(app.processName,
8226 app.pid, app.getPackageList());
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008227 fillInProcMemInfo(app, currApp);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008228 if (app.adjSource instanceof ProcessRecord) {
8229 currApp.importanceReasonPid = ((ProcessRecord)app.adjSource).pid;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008230 currApp.importanceReasonImportance = oomAdjToImportance(
8231 app.adjSourceOom, null);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008232 } else if (app.adjSource instanceof ActivityRecord) {
8233 ActivityRecord r = (ActivityRecord)app.adjSource;
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008234 if (r.app != null) currApp.importanceReasonPid = r.app.pid;
8235 }
8236 if (app.adjTarget instanceof ComponentName) {
8237 currApp.importanceReasonComponent = (ComponentName)app.adjTarget;
8238 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08008239 //Slog.v(TAG, "Proc " + app.processName + ": imp=" + currApp.importance
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008240 // + " lru=" + currApp.lru);
8241 if (runList == null) {
8242 runList = new ArrayList<ActivityManager.RunningAppProcessInfo>();
8243 }
8244 runList.add(currApp);
8245 }
8246 }
8247 }
8248 return runList;
8249 }
8250
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008251 public List<ApplicationInfo> getRunningExternalApplications() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008252 enforceNotIsolatedCaller("getRunningExternalApplications");
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008253 List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses();
8254 List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>();
8255 if (runningApps != null && runningApps.size() > 0) {
8256 Set<String> extList = new HashSet<String>();
8257 for (ActivityManager.RunningAppProcessInfo app : runningApps) {
8258 if (app.pkgList != null) {
8259 for (String pkg : app.pkgList) {
8260 extList.add(pkg);
8261 }
8262 }
8263 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008264 IPackageManager pm = AppGlobals.getPackageManager();
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008265 for (String pkg : extList) {
8266 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07008267 ApplicationInfo info = pm.getApplicationInfo(pkg, 0, UserId.getCallingUserId());
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008268 if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
8269 retList.add(info);
8270 }
8271 } catch (RemoteException e) {
8272 }
8273 }
8274 }
8275 return retList;
8276 }
8277
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008278 @Override
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008279 public void getMyMemoryState(ActivityManager.RunningAppProcessInfo outInfo) {
8280 enforceNotIsolatedCaller("getMyMemoryState");
8281 synchronized (this) {
8282 ProcessRecord proc;
8283 synchronized (mPidsSelfLocked) {
8284 proc = mPidsSelfLocked.get(Binder.getCallingPid());
8285 }
8286 fillInProcMemInfo(proc, outInfo);
8287 }
8288 }
8289
8290 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008291 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008292 if (checkCallingPermission(android.Manifest.permission.DUMP)
8293 != PackageManager.PERMISSION_GRANTED) {
8294 pw.println("Permission Denial: can't dump ActivityManager from from pid="
8295 + Binder.getCallingPid()
8296 + ", uid=" + Binder.getCallingUid()
8297 + " without permission "
8298 + android.Manifest.permission.DUMP);
8299 return;
8300 }
8301
8302 boolean dumpAll = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008303 boolean dumpClient = false;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008304 String dumpPackage = null;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008305
8306 int opti = 0;
8307 while (opti < args.length) {
8308 String opt = args[opti];
8309 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
8310 break;
8311 }
8312 opti++;
8313 if ("-a".equals(opt)) {
8314 dumpAll = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008315 } else if ("-c".equals(opt)) {
8316 dumpClient = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008317 } else if ("-h".equals(opt)) {
8318 pw.println("Activity manager dump options:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008319 pw.println(" [-a] [-c] [-h] [cmd] ...");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008320 pw.println(" cmd may be one of:");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008321 pw.println(" a[ctivities]: activity stack state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008322 pw.println(" b[roadcasts] [PACKAGE_NAME]: broadcast state");
8323 pw.println(" i[ntents] [PACKAGE_NAME]: pending intent state");
8324 pw.println(" p[rocesses] [PACKAGE_NAME]: process state");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008325 pw.println(" o[om]: out of memory management");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008326 pw.println(" prov[iders] [COMP_SPEC ...]: content provider state");
Marco Nelissen18cb2872011-11-15 11:19:53 -08008327 pw.println(" provider [COMP_SPEC]: provider client-side state");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008328 pw.println(" s[ervices] [COMP_SPEC ...]: service state");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008329 pw.println(" service [COMP_SPEC]: service client-side state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008330 pw.println(" package [PACKAGE_NAME]: all state related to given package");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008331 pw.println(" all: dump all activities");
8332 pw.println(" top: dump the top activity");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008333 pw.println(" cmd may also be a COMP_SPEC to dump activities.");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008334 pw.println(" COMP_SPEC may be a component name (com.foo/.myApp),");
8335 pw.println(" a partial substring in a component name, a");
8336 pw.println(" hex object identifier.");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008337 pw.println(" -a: include all available server state.");
8338 pw.println(" -c: include client state.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008339 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008340 } else {
8341 pw.println("Unknown argument: " + opt + "; use -h for help");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008342 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008343 }
8344
8345 // Is the caller requesting to dump a particular piece of data?
8346 if (opti < args.length) {
8347 String cmd = args[opti];
8348 opti++;
8349 if ("activities".equals(cmd) || "a".equals(cmd)) {
8350 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008351 dumpActivitiesLocked(fd, pw, args, opti, true, dumpClient, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008352 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008353 return;
8354 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008355 String[] newArgs;
8356 String name;
8357 if (opti >= args.length) {
8358 name = null;
8359 newArgs = EMPTY_STRING_ARRAY;
8360 } else {
8361 name = args[opti];
8362 opti++;
8363 newArgs = new String[args.length - opti];
8364 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8365 args.length - opti);
8366 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008367 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008368 dumpBroadcastsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008369 }
8370 return;
8371 } else if ("intents".equals(cmd) || "i".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008372 String[] newArgs;
8373 String name;
8374 if (opti >= args.length) {
8375 name = null;
8376 newArgs = EMPTY_STRING_ARRAY;
8377 } else {
8378 name = args[opti];
8379 opti++;
8380 newArgs = new String[args.length - opti];
8381 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8382 args.length - opti);
8383 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008384 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008385 dumpPendingIntentsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008386 }
8387 return;
8388 } else if ("processes".equals(cmd) || "p".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008389 String[] newArgs;
8390 String name;
8391 if (opti >= args.length) {
8392 name = null;
8393 newArgs = EMPTY_STRING_ARRAY;
8394 } else {
8395 name = args[opti];
8396 opti++;
8397 newArgs = new String[args.length - opti];
8398 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8399 args.length - opti);
8400 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008401 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008402 dumpProcessesLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008403 }
8404 return;
Dianne Hackborn287952c2010-09-22 22:34:31 -07008405 } else if ("oom".equals(cmd) || "o".equals(cmd)) {
8406 synchronized (this) {
8407 dumpOomLocked(fd, pw, args, opti, true);
8408 }
8409 return;
Marco Nelissen18cb2872011-11-15 11:19:53 -08008410 } else if ("provider".equals(cmd)) {
8411 String[] newArgs;
8412 String name;
8413 if (opti >= args.length) {
8414 name = null;
8415 newArgs = EMPTY_STRING_ARRAY;
8416 } else {
8417 name = args[opti];
8418 opti++;
8419 newArgs = new String[args.length - opti];
8420 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
8421 }
8422 if (!dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) {
8423 pw.println("No providers match: " + name);
8424 pw.println("Use -h for help.");
8425 }
8426 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008427 } else if ("providers".equals(cmd) || "prov".equals(cmd)) {
8428 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008429 dumpProvidersLocked(fd, pw, args, opti, true, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008430 }
8431 return;
8432 } else if ("service".equals(cmd)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008433 String[] newArgs;
8434 String name;
8435 if (opti >= args.length) {
8436 name = null;
8437 newArgs = EMPTY_STRING_ARRAY;
8438 } else {
8439 name = args[opti];
8440 opti++;
8441 newArgs = new String[args.length - opti];
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008442 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8443 args.length - opti);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008444 }
8445 if (!dumpService(fd, pw, name, newArgs, 0, dumpAll)) {
8446 pw.println("No services match: " + name);
8447 pw.println("Use -h for help.");
8448 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008449 return;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008450 } else if ("package".equals(cmd)) {
8451 String[] newArgs;
8452 if (opti >= args.length) {
8453 pw.println("package: no package name specified");
8454 pw.println("Use -h for help.");
8455 return;
8456 } else {
8457 dumpPackage = args[opti];
8458 opti++;
8459 newArgs = new String[args.length - opti];
8460 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8461 args.length - opti);
8462 args = newArgs;
8463 opti = 0;
8464 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008465 } else if ("services".equals(cmd) || "s".equals(cmd)) {
8466 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008467 dumpServicesLocked(fd, pw, args, opti, true, dumpClient, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008468 }
8469 return;
Dianne Hackborn625ac272010-09-17 18:29:22 -07008470 } else {
8471 // Dumping a single activity?
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008472 if (!dumpActivity(fd, pw, cmd, args, opti, dumpAll)) {
8473 pw.println("Bad activity command, or no activities match: " + cmd);
8474 pw.println("Use -h for help.");
Dianne Hackborn625ac272010-09-17 18:29:22 -07008475 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08008476 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008477 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008478 }
8479
8480 // No piece of data specified, dump everything.
8481 synchronized (this) {
8482 boolean needSep;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008483 needSep = dumpPendingIntentsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008484 if (needSep) {
8485 pw.println(" ");
8486 }
8487 if (dumpAll) {
8488 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008489 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008490 needSep = dumpBroadcastsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008491 if (needSep) {
8492 pw.println(" ");
8493 }
8494 if (dumpAll) {
8495 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008496 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008497 needSep = dumpProvidersLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008498 if (needSep) {
8499 pw.println(" ");
8500 }
8501 if (dumpAll) {
8502 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008503 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008504 needSep = dumpServicesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008505 if (needSep) {
8506 pw.println(" ");
8507 }
8508 if (dumpAll) {
8509 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008510 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008511 needSep = dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008512 if (needSep) {
8513 pw.println(" ");
8514 }
8515 if (dumpAll) {
8516 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008517 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008518 dumpProcessesLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008519 }
8520 }
8521
8522 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008523 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008524 pw.println("ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
8525 pw.println(" Main stack:");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008526 dumpHistoryList(fd, pw, mMainStack.mHistory, " ", "Hist", true, !dumpAll, dumpClient,
8527 dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008528 pw.println(" ");
8529 pw.println(" Running activities (most recent first):");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008530 dumpHistoryList(fd, pw, mMainStack.mLRUActivities, " ", "Run", false, !dumpAll, false,
8531 dumpPackage);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008532 if (mMainStack.mWaitingVisibleActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008533 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008534 pw.println(" Activities waiting for another to become visible:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008535 dumpHistoryList(fd, pw, mMainStack.mWaitingVisibleActivities, " ", "Wait", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008536 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008537 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008538 if (mMainStack.mStoppingActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008539 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008540 pw.println(" Activities waiting to stop:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008541 dumpHistoryList(fd, pw, mMainStack.mStoppingActivities, " ", "Stop", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008542 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008543 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008544 if (mMainStack.mGoingToSleepActivities.size() > 0) {
8545 pw.println(" ");
8546 pw.println(" Activities waiting to sleep:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008547 dumpHistoryList(fd, pw, mMainStack.mGoingToSleepActivities, " ", "Sleep", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008548 !dumpAll, false, dumpPackage);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008549 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008550 if (mMainStack.mFinishingActivities.size() > 0) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008551 pw.println(" ");
8552 pw.println(" Activities waiting to finish:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008553 dumpHistoryList(fd, pw, mMainStack.mFinishingActivities, " ", "Fin", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008554 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008555 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008556
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008557 pw.println(" ");
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08008558 if (mMainStack.mPausingActivity != null) {
8559 pw.println(" mPausingActivity: " + mMainStack.mPausingActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008560 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008561 pw.println(" mResumedActivity: " + mMainStack.mResumedActivity);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008562 pw.println(" mFocusedActivity: " + mFocusedActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008563 if (dumpAll) {
8564 pw.println(" mLastPausedActivity: " + mMainStack.mLastPausedActivity);
8565 pw.println(" mSleepTimeout: " + mMainStack.mSleepTimeout);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07008566 pw.println(" mDismissKeyguardOnNextActivity: "
8567 + mMainStack.mDismissKeyguardOnNextActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008568 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008569
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008570 if (mRecentTasks.size() > 0) {
8571 pw.println();
8572 pw.println(" Recent tasks:");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008573
8574 final int N = mRecentTasks.size();
8575 for (int i=0; i<N; i++) {
8576 TaskRecord tr = mRecentTasks.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008577 if (dumpPackage != null) {
8578 if (tr.realActivity == null ||
8579 !dumpPackage.equals(tr.realActivity)) {
8580 continue;
8581 }
8582 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008583 pw.print(" * Recent #"); pw.print(i); pw.print(": ");
8584 pw.println(tr);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008585 if (dumpAll) {
8586 mRecentTasks.get(i).dump(pw, " ");
8587 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008588 }
8589 }
8590
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008591 if (dumpAll) {
8592 pw.println(" ");
8593 pw.println(" mCurTask: " + mCurTask);
8594 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008595
8596 return true;
8597 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008598
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008599 boolean dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008600 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008601 boolean needSep = false;
8602 int numPers = 0;
8603
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008604 pw.println("ACTIVITY MANAGER RUNNING PROCESSES (dumpsys activity processes)");
8605
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008606 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008607 for (SparseArray<ProcessRecord> procs : mProcessNames.getMap().values()) {
8608 final int NA = procs.size();
8609 for (int ia=0; ia<NA; ia++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008610 ProcessRecord r = procs.valueAt(ia);
8611 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8612 continue;
8613 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008614 if (!needSep) {
8615 pw.println(" All known processes:");
8616 needSep = true;
8617 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008618 pw.print(r.persistent ? " *PERS*" : " *APP*");
8619 pw.print(" UID "); pw.print(procs.keyAt(ia));
8620 pw.print(" "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008621 r.dump(pw, " ");
8622 if (r.persistent) {
8623 numPers++;
8624 }
8625 }
8626 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008627 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008628
8629 if (mIsolatedProcesses.size() > 0) {
8630 if (needSep) pw.println(" ");
8631 needSep = true;
8632 pw.println(" Isolated process list (sorted by uid):");
8633 for (int i=0; i<mIsolatedProcesses.size(); i++) {
8634 ProcessRecord r = mIsolatedProcesses.valueAt(i);
8635 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8636 continue;
8637 }
8638 pw.println(String.format("%sIsolated #%2d: %s",
8639 " ", i, r.toString()));
8640 }
8641 }
8642
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008643 if (mLruProcesses.size() > 0) {
8644 if (needSep) pw.println(" ");
8645 needSep = true;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008646 pw.println(" Process LRU list (sorted by oom_adj):");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008647 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008648 "Proc", "PERS", false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008649 needSep = true;
8650 }
8651
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008652 if (dumpAll) {
8653 synchronized (mPidsSelfLocked) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008654 boolean printed = false;
8655 for (int i=0; i<mPidsSelfLocked.size(); i++) {
8656 ProcessRecord r = mPidsSelfLocked.valueAt(i);
8657 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8658 continue;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008659 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008660 if (!printed) {
8661 if (needSep) pw.println(" ");
8662 needSep = true;
8663 pw.println(" PID mappings:");
8664 printed = true;
8665 }
8666 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i));
8667 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008668 }
8669 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008670 }
8671
8672 if (mForegroundProcesses.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008673 synchronized (mPidsSelfLocked) {
8674 boolean printed = false;
8675 for (int i=0; i<mForegroundProcesses.size(); i++) {
8676 ProcessRecord r = mPidsSelfLocked.get(
8677 mForegroundProcesses.valueAt(i).pid);
8678 if (dumpPackage != null && (r == null
8679 || !dumpPackage.equals(r.info.packageName))) {
8680 continue;
8681 }
8682 if (!printed) {
8683 if (needSep) pw.println(" ");
8684 needSep = true;
8685 pw.println(" Foreground Processes:");
8686 printed = true;
8687 }
8688 pw.print(" PID #"); pw.print(mForegroundProcesses.keyAt(i));
8689 pw.print(": "); pw.println(mForegroundProcesses.valueAt(i));
8690 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008691 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008692 }
8693
8694 if (mPersistentStartingProcesses.size() > 0) {
8695 if (needSep) pw.println(" ");
8696 needSep = true;
8697 pw.println(" Persisent processes that are starting:");
8698 dumpProcessList(pw, this, mPersistentStartingProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008699 "Starting Norm", "Restarting PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008700 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008701
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008702 if (mRemovedProcesses.size() > 0) {
8703 if (needSep) pw.println(" ");
8704 needSep = true;
8705 pw.println(" Processes that are being removed:");
8706 dumpProcessList(pw, this, mRemovedProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008707 "Removed Norm", "Removed PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008708 }
8709
8710 if (mProcessesOnHold.size() > 0) {
8711 if (needSep) pw.println(" ");
8712 needSep = true;
8713 pw.println(" Processes that are on old until the system is ready:");
8714 dumpProcessList(pw, this, mProcessesOnHold, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008715 "OnHold Norm", "OnHold PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008716 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008717
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008718 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008719
8720 if (mProcessCrashTimes.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008721 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008722 long now = SystemClock.uptimeMillis();
8723 for (Map.Entry<String, SparseArray<Long>> procs
8724 : mProcessCrashTimes.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008725 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008726 SparseArray<Long> uids = procs.getValue();
8727 final int N = uids.size();
8728 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008729 int puid = uids.keyAt(i);
8730 ProcessRecord r = mProcessNames.get(pname, puid);
8731 if (dumpPackage != null && (r == null
8732 || !dumpPackage.equals(r.info.packageName))) {
8733 continue;
8734 }
8735 if (!printed) {
8736 if (needSep) pw.println(" ");
8737 needSep = true;
8738 pw.println(" Time since processes crashed:");
8739 printed = true;
8740 }
8741 pw.print(" Process "); pw.print(pname);
8742 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008743 pw.print(": last crashed ");
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008744 TimeUtils.formatDuration(now-uids.valueAt(i), pw);
8745 pw.println(" ago");
Dianne Hackbornfd12af42009-08-27 00:44:33 -07008746 }
8747 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008748 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008749
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008750 if (mBadProcesses.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008751 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008752 for (Map.Entry<String, SparseArray<Long>> procs
8753 : mBadProcesses.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008754 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008755 SparseArray<Long> uids = procs.getValue();
8756 final int N = uids.size();
8757 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008758 int puid = uids.keyAt(i);
8759 ProcessRecord r = mProcessNames.get(pname, puid);
8760 if (dumpPackage != null && (r == null
8761 || !dumpPackage.equals(r.info.packageName))) {
8762 continue;
8763 }
8764 if (!printed) {
8765 if (needSep) pw.println(" ");
8766 needSep = true;
8767 pw.println(" Bad processes:");
8768 }
8769 pw.print(" Bad process "); pw.print(pname);
8770 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008771 pw.print(": crashed at time ");
8772 pw.println(uids.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008773 }
8774 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008775 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008776
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008777 pw.println();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008778 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07008779 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn50685602011-12-01 12:23:37 -08008780 if (dumpAll) {
8781 StringBuilder sb = new StringBuilder(128);
8782 sb.append(" mPreviousProcessVisibleTime: ");
8783 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
8784 pw.println(sb);
8785 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07008786 if (mHeavyWeightProcess != null) {
8787 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
8788 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008789 pw.println(" mConfiguration: " + mConfiguration);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008790 if (dumpAll) {
8791 pw.println(" mConfigWillChange: " + mMainStack.mConfigWillChange);
Dianne Hackborn3d0724d2011-05-12 15:39:41 -07008792 if (mCompatModePackages.getPackages().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008793 boolean printed = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07008794 for (Map.Entry<String, Integer> entry
8795 : mCompatModePackages.getPackages().entrySet()) {
8796 String pkg = entry.getKey();
8797 int mode = entry.getValue();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008798 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
8799 continue;
8800 }
8801 if (!printed) {
8802 pw.println(" mScreenCompatPackages:");
8803 printed = true;
8804 }
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07008805 pw.print(" "); pw.print(pkg); pw.print(": ");
8806 pw.print(mode); pw.println();
8807 }
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07008808 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008809 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008810 pw.println(" mSleeping=" + mSleeping + " mShuttingDown=" + mShuttingDown);
8811 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
8812 || mOrigWaitForDebugger) {
8813 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp
8814 + " mDebugTransient=" + mDebugTransient
8815 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger);
8816 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08008817 if (mOpenGlTraceApp != null) {
8818 pw.println(" mOpenGlTraceApp=" + mOpenGlTraceApp);
8819 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07008820 if (mProfileApp != null || mProfileProc != null || mProfileFile != null
8821 || mProfileFd != null) {
8822 pw.println(" mProfileApp=" + mProfileApp + " mProfileProc=" + mProfileProc);
8823 pw.println(" mProfileFile=" + mProfileFile + " mProfileFd=" + mProfileFd);
8824 pw.println(" mProfileType=" + mProfileType + " mAutoStopProfiler="
8825 + mAutoStopProfiler);
8826 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008827 if (mAlwaysFinishActivities || mController != null) {
8828 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities
8829 + " mController=" + mController);
8830 }
8831 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008832 pw.println(" Total persistent processes: " + numPers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008833 pw.println(" mStartRunning=" + mStartRunning
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07008834 + " mProcessesReady=" + mProcessesReady
8835 + " mSystemReady=" + mSystemReady);
8836 pw.println(" mBooting=" + mBooting
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008837 + " mBooted=" + mBooted
8838 + " mFactoryTest=" + mFactoryTest);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008839 pw.print(" mLastPowerCheckRealtime=");
8840 TimeUtils.formatDuration(mLastPowerCheckRealtime, pw);
8841 pw.println("");
8842 pw.print(" mLastPowerCheckUptime=");
8843 TimeUtils.formatDuration(mLastPowerCheckUptime, pw);
8844 pw.println("");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008845 pw.println(" mGoingToSleep=" + mMainStack.mGoingToSleep);
8846 pw.println(" mLaunchingActivity=" + mMainStack.mLaunchingActivity);
Dianne Hackborn906497c2010-05-10 15:57:38 -07008847 pw.println(" mAdjSeq=" + mAdjSeq + " mLruSeq=" + mLruSeq);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008848 pw.println(" mNumServiceProcs=" + mNumServiceProcs
8849 + " mNewNumServiceProcs=" + mNewNumServiceProcs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008850 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008851
8852 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008853 }
8854
Dianne Hackborn287952c2010-09-22 22:34:31 -07008855 boolean dumpProcessesToGc(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008856 int opti, boolean needSep, boolean dumpAll, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07008857 if (mProcessesToGc.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008858 boolean printed = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -07008859 long now = SystemClock.uptimeMillis();
8860 for (int i=0; i<mProcessesToGc.size(); i++) {
8861 ProcessRecord proc = mProcessesToGc.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008862 if (dumpPackage != null && !dumpPackage.equals(proc.info.packageName)) {
8863 continue;
8864 }
8865 if (!printed) {
8866 if (needSep) pw.println(" ");
8867 needSep = true;
8868 pw.println(" Processes that are waiting to GC:");
8869 printed = true;
8870 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008871 pw.print(" Process "); pw.println(proc);
8872 pw.print(" lowMem="); pw.print(proc.reportLowMemory);
8873 pw.print(", last gced=");
8874 pw.print(now-proc.lastRequestedGc);
8875 pw.print(" ms ago, last lowMem=");
8876 pw.print(now-proc.lastLowMemory);
8877 pw.println(" ms ago");
8878
8879 }
8880 }
8881 return needSep;
8882 }
8883
8884 boolean dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args,
8885 int opti, boolean dumpAll) {
8886 boolean needSep = false;
8887
8888 if (mLruProcesses.size() > 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07008889 if (needSep) pw.println(" ");
8890 needSep = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -07008891 pw.println(" OOM levels:");
Dianne Hackborn7d608422011-08-07 16:24:18 -07008892 pw.print(" SYSTEM_ADJ: "); pw.println(ProcessList.SYSTEM_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008893 pw.print(" PERSISTENT_PROC_ADJ: "); pw.println(ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07008894 pw.print(" FOREGROUND_APP_ADJ: "); pw.println(ProcessList.FOREGROUND_APP_ADJ);
8895 pw.print(" VISIBLE_APP_ADJ: "); pw.println(ProcessList.VISIBLE_APP_ADJ);
8896 pw.print(" PERCEPTIBLE_APP_ADJ: "); pw.println(ProcessList.PERCEPTIBLE_APP_ADJ);
8897 pw.print(" HEAVY_WEIGHT_APP_ADJ: "); pw.println(ProcessList.HEAVY_WEIGHT_APP_ADJ);
8898 pw.print(" BACKUP_APP_ADJ: "); pw.println(ProcessList.BACKUP_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008899 pw.print(" SERVICE_ADJ: "); pw.println(ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07008900 pw.print(" HOME_APP_ADJ: "); pw.println(ProcessList.HOME_APP_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07008901 pw.print(" PREVIOUS_APP_ADJ: "); pw.println(ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008902 pw.print(" SERVICE_B_ADJ: "); pw.println(ProcessList.SERVICE_B_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07008903 pw.print(" HIDDEN_APP_MIN_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008904 pw.print(" HIDDEN_APP_MAX_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MAX_ADJ);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07008905
8906 if (needSep) pw.println(" ");
8907 needSep = true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07008908 pw.println(" Process OOM control:");
Dianne Hackborn905577f2011-09-07 18:31:28 -07008909 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008910 "Proc", "PERS", true, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008911 needSep = true;
8912 }
8913
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008914 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008915
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008916 pw.println();
Dianne Hackborn287952c2010-09-22 22:34:31 -07008917 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07008918 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008919 if (mHeavyWeightProcess != null) {
8920 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
8921 }
8922
8923 return true;
8924 }
8925
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008926 /**
8927 * There are three ways to call this:
8928 * - no service specified: dump all the services
8929 * - a flattened component name that matched an existing service was specified as the
8930 * first arg: dump that one service
8931 * - the first arg isn't the flattened component name of an existing service:
8932 * dump all services whose component contains the first arg as a substring
8933 */
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008934 protected boolean dumpService(FileDescriptor fd, PrintWriter pw, String name, String[] args,
8935 int opti, boolean dumpAll) {
8936 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008937
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008938 if ("all".equals(name)) {
Dianne Hackborn14bfa392010-07-24 19:58:06 -07008939 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07008940 try {
8941 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
8942 for (UserInfo user : users) {
8943 for (ServiceRecord r1 : mServiceMap.getAllServices(user.id)) {
8944 services.add(r1);
8945 }
8946 }
8947 } catch (RemoteException re) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008948 }
8949 }
8950 } else {
8951 ComponentName componentName = name != null
8952 ? ComponentName.unflattenFromString(name) : null;
8953 int objectId = 0;
8954 if (componentName == null) {
8955 // Not a '/' separated full component name; maybe an object ID?
8956 try {
8957 objectId = Integer.parseInt(name, 16);
8958 name = null;
8959 componentName = null;
8960 } catch (RuntimeException e) {
8961 }
8962 }
8963
8964 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07008965 try {
8966 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
8967 for (UserInfo user : users) {
8968 for (ServiceRecord r1 : mServiceMap.getAllServices(user.id)) {
8969 if (componentName != null) {
8970 if (r1.name.equals(componentName)) {
8971 services.add(r1);
8972 }
8973 } else if (name != null) {
8974 if (r1.name.flattenToString().contains(name)) {
8975 services.add(r1);
8976 }
8977 } else if (System.identityHashCode(r1) == objectId) {
8978 services.add(r1);
8979 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008980 }
Dianne Hackborn14bfa392010-07-24 19:58:06 -07008981 }
Amith Yamasani742a6712011-05-04 14:49:28 -07008982 } catch (RemoteException re) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008983 }
8984 }
8985 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008986
8987 if (services.size() <= 0) {
8988 return false;
8989 }
8990
8991 boolean needSep = false;
8992 for (int i=0; i<services.size(); i++) {
8993 if (needSep) {
8994 pw.println();
8995 }
8996 needSep = true;
8997 dumpService("", fd, pw, services.get(i), args, dumpAll);
8998 }
8999 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009000 }
9001
9002 /**
9003 * Invokes IApplicationThread.dumpService() on the thread of the specified service if
9004 * there is a thread associated with the service.
9005 */
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009006 private void dumpService(String prefix, FileDescriptor fd, PrintWriter pw,
9007 final ServiceRecord r, String[] args, boolean dumpAll) {
9008 String innerPrefix = prefix + " ";
9009 synchronized (this) {
9010 pw.print(prefix); pw.print("SERVICE ");
9011 pw.print(r.shortName); pw.print(" ");
9012 pw.print(Integer.toHexString(System.identityHashCode(r)));
9013 pw.print(" pid=");
9014 if (r.app != null) pw.println(r.app.pid);
9015 else pw.println("(not running)");
9016 if (dumpAll) {
9017 r.dump(pw, innerPrefix);
9018 }
9019 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009020 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009021 pw.print(prefix); pw.println(" Client:");
9022 pw.flush();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009023 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009024 TransferPipe tp = new TransferPipe();
9025 try {
9026 r.app.thread.dumpService(tp.getWriteFd().getFileDescriptor(), r, args);
9027 tp.setBufferPrefix(prefix + " ");
9028 tp.go(fd);
9029 } finally {
9030 tp.kill();
9031 }
9032 } catch (IOException e) {
9033 pw.println(prefix + " Failure while dumping the service: " + e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009034 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009035 pw.println(prefix + " Got a RemoteException while dumping the service");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009036 }
9037 }
9038 }
9039
Marco Nelissen18cb2872011-11-15 11:19:53 -08009040 /**
9041 * There are three ways to call this:
9042 * - no provider specified: dump all the providers
9043 * - a flattened component name that matched an existing provider was specified as the
9044 * first arg: dump that one provider
9045 * - the first arg isn't the flattened component name of an existing provider:
9046 * dump all providers whose component contains the first arg as a substring
9047 */
9048 protected boolean dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9049 int opti, boolean dumpAll) {
Marco Nelissende7408c2012-02-08 14:57:38 -08009050 return mProviderMap.dumpProvider(fd, pw, name, args, opti, dumpAll);
Marco Nelissen18cb2872011-11-15 11:19:53 -08009051 }
9052
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009053 static class ItemMatcher {
9054 ArrayList<ComponentName> components;
9055 ArrayList<String> strings;
9056 ArrayList<Integer> objects;
9057 boolean all;
9058
9059 ItemMatcher() {
9060 all = true;
9061 }
9062
9063 void build(String name) {
9064 ComponentName componentName = ComponentName.unflattenFromString(name);
9065 if (componentName != null) {
9066 if (components == null) {
9067 components = new ArrayList<ComponentName>();
9068 }
9069 components.add(componentName);
9070 all = false;
9071 } else {
9072 int objectId = 0;
9073 // Not a '/' separated full component name; maybe an object ID?
9074 try {
9075 objectId = Integer.parseInt(name, 16);
9076 if (objects == null) {
9077 objects = new ArrayList<Integer>();
9078 }
9079 objects.add(objectId);
9080 all = false;
9081 } catch (RuntimeException e) {
9082 // Not an integer; just do string match.
9083 if (strings == null) {
9084 strings = new ArrayList<String>();
9085 }
9086 strings.add(name);
9087 all = false;
9088 }
9089 }
9090 }
9091
9092 int build(String[] args, int opti) {
9093 for (; opti<args.length; opti++) {
9094 String name = args[opti];
9095 if ("--".equals(name)) {
9096 return opti+1;
9097 }
9098 build(name);
9099 }
9100 return opti;
9101 }
9102
9103 boolean match(Object object, ComponentName comp) {
9104 if (all) {
9105 return true;
9106 }
9107 if (components != null) {
9108 for (int i=0; i<components.size(); i++) {
9109 if (components.get(i).equals(comp)) {
9110 return true;
9111 }
9112 }
9113 }
9114 if (objects != null) {
9115 for (int i=0; i<objects.size(); i++) {
9116 if (System.identityHashCode(object) == objects.get(i)) {
9117 return true;
9118 }
9119 }
9120 }
9121 if (strings != null) {
9122 String flat = comp.flattenToString();
9123 for (int i=0; i<strings.size(); i++) {
9124 if (flat.contains(strings.get(i))) {
9125 return true;
9126 }
9127 }
9128 }
9129 return false;
9130 }
9131 }
9132
Dianne Hackborn625ac272010-09-17 18:29:22 -07009133 /**
9134 * There are three things that cmd can be:
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009135 * - a flattened component name that matches an existing activity
Dianne Hackborn625ac272010-09-17 18:29:22 -07009136 * - the cmd arg isn't the flattened component name of an existing activity:
9137 * dump all activity whose component contains the cmd as a substring
9138 * - A hex number of the ActivityRecord object instance.
9139 */
9140 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9141 int opti, boolean dumpAll) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009142 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009143
9144 if ("all".equals(name)) {
9145 synchronized (this) {
9146 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009147 activities.add(r1);
9148 }
9149 }
Dianne Hackbornf9302322011-06-14 18:36:14 -07009150 } else if ("top".equals(name)) {
9151 synchronized (this) {
9152 final int N = mMainStack.mHistory.size();
9153 if (N > 0) {
9154 activities.add((ActivityRecord)mMainStack.mHistory.get(N-1));
9155 }
9156 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009157 } else {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009158 ItemMatcher matcher = new ItemMatcher();
9159 matcher.build(name);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009160
9161 synchronized (this) {
9162 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009163 if (matcher.match(r1, r1.intent.getComponent())) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009164 activities.add(r1);
9165 }
9166 }
9167 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009168 }
9169
9170 if (activities.size() <= 0) {
9171 return false;
9172 }
9173
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009174 String[] newArgs = new String[args.length - opti];
9175 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
9176
Dianne Hackborn30d71892010-12-11 10:37:55 -08009177 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009178 boolean needSep = false;
Dianne Hackborn30d71892010-12-11 10:37:55 -08009179 for (int i=activities.size()-1; i>=0; i--) {
9180 ActivityRecord r = (ActivityRecord)activities.get(i);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009181 if (needSep) {
9182 pw.println();
9183 }
9184 needSep = true;
9185 synchronized (this) {
9186 if (lastTask != r.task) {
9187 lastTask = r.task;
9188 pw.print("TASK "); pw.print(lastTask.affinity);
9189 pw.print(" id="); pw.println(lastTask.taskId);
9190 if (dumpAll) {
9191 lastTask.dump(pw, " ");
9192 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08009193 }
9194 }
9195 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009196 }
9197 return true;
9198 }
9199
9200 /**
9201 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
9202 * there is a thread associated with the activity.
9203 */
Dianne Hackborn30d71892010-12-11 10:37:55 -08009204 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009205 final ActivityRecord r, String[] args, boolean dumpAll) {
9206 String innerPrefix = prefix + " ";
Dianne Hackborn30d71892010-12-11 10:37:55 -08009207 synchronized (this) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009208 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
9209 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
9210 pw.print(" pid=");
Dianne Hackborn30d71892010-12-11 10:37:55 -08009211 if (r.app != null) pw.println(r.app.pid);
9212 else pw.println("(not running)");
9213 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009214 r.dump(pw, innerPrefix);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009215 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009216 }
9217 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009218 // flush anything that is already in the PrintWriter since the thread is going
9219 // to write to the file descriptor directly
9220 pw.flush();
Dianne Hackborn625ac272010-09-17 18:29:22 -07009221 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009222 TransferPipe tp = new TransferPipe();
9223 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009224 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9225 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009226 tp.go(fd);
9227 } finally {
9228 tp.kill();
9229 }
9230 } catch (IOException e) {
9231 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009232 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009233 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
Dianne Hackborn625ac272010-09-17 18:29:22 -07009234 }
9235 }
9236 }
9237
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009238 boolean dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009239 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009240 boolean needSep = false;
9241
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009242 pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009243 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009244 if (mRegisteredReceivers.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009245 boolean printed = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009246 Iterator it = mRegisteredReceivers.values().iterator();
9247 while (it.hasNext()) {
9248 ReceiverList r = (ReceiverList)it.next();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009249 if (dumpPackage != null && (r.app == null ||
9250 !dumpPackage.equals(r.app.info.packageName))) {
9251 continue;
9252 }
9253 if (!printed) {
9254 pw.println(" Registered Receivers:");
9255 needSep = true;
9256 printed = true;
9257 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009258 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009259 r.dump(pw, " ");
9260 }
9261 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009262
9263 if (mReceiverResolver.dump(pw, needSep ?
9264 "\n Receiver Resolver Table:" : " Receiver Resolver Table:",
9265 " ", dumpPackage, false)) {
9266 needSep = true;
9267 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009268 }
Christopher Tatef46723b2012-01-26 14:19:24 -08009269
9270 for (BroadcastQueue q : mBroadcastQueues) {
9271 needSep = q.dumpLocked(fd, pw, args, opti, dumpAll, dumpPackage, needSep);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009272 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009273
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009274 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009275
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009276 if (mStickyBroadcasts != null && dumpPackage == null) {
9277 if (needSep) {
9278 pw.println();
9279 }
9280 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009281 pw.println(" Sticky broadcasts:");
9282 StringBuilder sb = new StringBuilder(128);
9283 for (Map.Entry<String, ArrayList<Intent>> ent
9284 : mStickyBroadcasts.entrySet()) {
9285 pw.print(" * Sticky action "); pw.print(ent.getKey());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009286 if (dumpAll) {
9287 pw.println(":");
9288 ArrayList<Intent> intents = ent.getValue();
9289 final int N = intents.size();
9290 for (int i=0; i<N; i++) {
9291 sb.setLength(0);
9292 sb.append(" Intent: ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009293 intents.get(i).toShortString(sb, false, true, false, false);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009294 pw.println(sb.toString());
9295 Bundle bundle = intents.get(i).getExtras();
9296 if (bundle != null) {
9297 pw.print(" ");
9298 pw.println(bundle.toString());
9299 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009300 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009301 } else {
9302 pw.println("");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009303 }
9304 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009305 needSep = true;
9306 }
9307
9308 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009309 pw.println();
Christopher Tatef46723b2012-01-26 14:19:24 -08009310 for (BroadcastQueue queue : mBroadcastQueues) {
9311 pw.println(" mBroadcastsScheduled [" + queue.mQueueName + "]="
9312 + queue.mBroadcastsScheduled);
9313 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009314 pw.println(" mHandler:");
9315 mHandler.dump(new PrintWriterPrinter(pw), " ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009316 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009317 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009318
9319 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009320 }
9321
Marco Nelissen18cb2872011-11-15 11:19:53 -08009322 /**
9323 * Prints a list of ServiceRecords (dumpsys activity services)
9324 */
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009325 boolean dumpServicesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009326 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009327 boolean needSep = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009328
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009329 ItemMatcher matcher = new ItemMatcher();
9330 matcher.build(args, opti);
9331
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009332 pw.println("ACTIVITY MANAGER SERVICES (dumpsys activity services)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009333 try {
9334 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
9335 for (UserInfo user : users) {
9336 if (mServiceMap.getAllServices(user.id).size() > 0) {
9337 boolean printed = false;
9338 long nowReal = SystemClock.elapsedRealtime();
9339 Iterator<ServiceRecord> it = mServiceMap.getAllServices(
9340 user.id).iterator();
9341 needSep = false;
9342 while (it.hasNext()) {
9343 ServiceRecord r = it.next();
9344 if (!matcher.match(r, r.name)) {
9345 continue;
9346 }
9347 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9348 continue;
9349 }
9350 if (!printed) {
9351 pw.println(" Active services:");
9352 printed = true;
9353 }
9354 if (needSep) {
9355 pw.println();
9356 }
9357 pw.print(" * ");
9358 pw.println(r);
9359 if (dumpAll) {
9360 r.dump(pw, " ");
9361 needSep = true;
9362 } else {
9363 pw.print(" app=");
9364 pw.println(r.app);
9365 pw.print(" created=");
9366 TimeUtils.formatDuration(r.createTime, nowReal, pw);
9367 pw.print(" started=");
9368 pw.print(r.startRequested);
9369 pw.print(" connections=");
9370 pw.println(r.connections.size());
9371 if (r.connections.size() > 0) {
9372 pw.println(" Connections:");
9373 for (ArrayList<ConnectionRecord> clist : r.connections.values()) {
9374 for (int i = 0; i < clist.size(); i++) {
9375 ConnectionRecord conn = clist.get(i);
9376 pw.print(" ");
9377 pw.print(conn.binding.intent.intent.getIntent()
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009378 .toShortString(false, false, false, false));
Amith Yamasani742a6712011-05-04 14:49:28 -07009379 pw.print(" -> ");
9380 ProcessRecord proc = conn.binding.client;
9381 pw.println(proc != null ? proc.toShortString() : "null");
9382 }
9383 }
Dianne Hackborn8ec8d412011-11-14 18:27:24 -08009384 }
9385 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009386 if (dumpClient && r.app != null && r.app.thread != null) {
9387 pw.println(" Client:");
9388 pw.flush();
9389 try {
9390 TransferPipe tp = new TransferPipe();
9391 try {
9392 r.app.thread.dumpService(tp.getWriteFd().getFileDescriptor(),
9393 r, args);
9394 tp.setBufferPrefix(" ");
9395 // Short timeout, since blocking here can
9396 // deadlock with the application.
9397 tp.go(fd, 2000);
9398 } finally {
9399 tp.kill();
9400 }
9401 } catch (IOException e) {
9402 pw.println(" Failure while dumping the service: " + e);
9403 } catch (RemoteException e) {
9404 pw.println(" Got a RemoteException while dumping the service");
9405 }
9406 needSep = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009407 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009408 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009409 needSep = printed;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009410 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009411 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009412 } catch (RemoteException re) {
9413
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009414 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009415
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009416 if (mPendingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009417 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009418 for (int i=0; i<mPendingServices.size(); i++) {
9419 ServiceRecord r = mPendingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009420 if (!matcher.match(r, r.name)) {
9421 continue;
9422 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009423 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9424 continue;
9425 }
9426 if (!printed) {
9427 if (needSep) pw.println(" ");
9428 needSep = true;
9429 pw.println(" Pending services:");
9430 printed = true;
9431 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009432 pw.print(" * Pending "); pw.println(r);
9433 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009434 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009435 needSep = true;
9436 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009437
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009438 if (mRestartingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009439 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009440 for (int i=0; i<mRestartingServices.size(); i++) {
9441 ServiceRecord r = mRestartingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009442 if (!matcher.match(r, r.name)) {
9443 continue;
9444 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009445 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9446 continue;
9447 }
9448 if (!printed) {
9449 if (needSep) pw.println(" ");
9450 needSep = true;
9451 pw.println(" Restarting services:");
9452 printed = true;
9453 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009454 pw.print(" * Restarting "); pw.println(r);
9455 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009456 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009457 needSep = true;
9458 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009459
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009460 if (mStoppingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009461 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009462 for (int i=0; i<mStoppingServices.size(); i++) {
9463 ServiceRecord r = mStoppingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009464 if (!matcher.match(r, r.name)) {
9465 continue;
9466 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009467 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9468 continue;
9469 }
9470 if (!printed) {
9471 if (needSep) pw.println(" ");
9472 needSep = true;
9473 pw.println(" Stopping services:");
9474 printed = true;
9475 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009476 pw.print(" * Stopping "); pw.println(r);
9477 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009478 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009479 needSep = true;
9480 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009481
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009482 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009483 if (mServiceConnections.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009484 boolean printed = false;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009485 Iterator<ArrayList<ConnectionRecord>> it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009486 = mServiceConnections.values().iterator();
9487 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009488 ArrayList<ConnectionRecord> r = it.next();
9489 for (int i=0; i<r.size(); i++) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009490 ConnectionRecord cr = r.get(i);
9491 if (!matcher.match(cr.binding.service, cr.binding.service.name)) {
9492 continue;
9493 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009494 if (dumpPackage != null && (cr.binding.client == null
9495 || !dumpPackage.equals(cr.binding.client.info.packageName))) {
9496 continue;
9497 }
9498 if (!printed) {
9499 if (needSep) pw.println(" ");
9500 needSep = true;
9501 pw.println(" Connection bindings to services:");
9502 printed = true;
9503 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009504 pw.print(" * "); pw.println(cr);
9505 cr.dump(pw, " ");
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009506 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009507 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009508 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009509 }
9510 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009511
9512 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009513 }
9514
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009515 boolean dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009516 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07009517 boolean needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009518
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009519 ItemMatcher matcher = new ItemMatcher();
9520 matcher.build(args, opti);
9521
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009522 pw.println("ACTIVITY MANAGER CONTENT PROVIDERS (dumpsys activity providers)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009523
9524 mProviderMap.dumpProvidersLocked(pw, dumpAll);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009525
9526 if (mLaunchingProviders.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009527 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009528 for (int i=mLaunchingProviders.size()-1; i>=0; i--) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009529 ContentProviderRecord r = mLaunchingProviders.get(i);
9530 if (dumpPackage != null && !dumpPackage.equals(r.name.getPackageName())) {
9531 continue;
9532 }
9533 if (!printed) {
9534 if (needSep) pw.println(" ");
9535 needSep = true;
9536 pw.println(" Launching content providers:");
9537 printed = true;
9538 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009539 pw.print(" Launching #"); pw.print(i); pw.print(": ");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009540 pw.println(r);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009541 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009542 }
9543
9544 if (mGrantedUriPermissions.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009545 if (needSep) pw.println();
9546 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009547 pw.println("Granted Uri Permissions:");
9548 for (int i=0; i<mGrantedUriPermissions.size(); i++) {
9549 int uid = mGrantedUriPermissions.keyAt(i);
9550 HashMap<Uri, UriPermission> perms
9551 = mGrantedUriPermissions.valueAt(i);
9552 pw.print(" * UID "); pw.print(uid);
9553 pw.println(" holds:");
9554 for (UriPermission perm : perms.values()) {
9555 pw.print(" "); pw.println(perm);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009556 if (dumpAll) {
9557 perm.dump(pw, " ");
9558 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009559 }
9560 }
9561 needSep = true;
9562 }
9563
9564 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009565 }
9566
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009567 boolean dumpPendingIntentsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009568 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009569 boolean needSep = false;
9570
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009571 if (mIntentSenderRecords.size() > 0) {
9572 boolean printed = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009573 Iterator<WeakReference<PendingIntentRecord>> it
9574 = mIntentSenderRecords.values().iterator();
9575 while (it.hasNext()) {
9576 WeakReference<PendingIntentRecord> ref = it.next();
9577 PendingIntentRecord rec = ref != null ? ref.get(): null;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009578 if (dumpPackage != null && (rec == null
9579 || !dumpPackage.equals(rec.key.packageName))) {
9580 continue;
9581 }
9582 if (!printed) {
9583 pw.println("ACTIVITY MANAGER PENDING INTENTS (dumpsys activity intents)");
9584 printed = true;
9585 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009586 needSep = true;
9587 if (rec != null) {
9588 pw.print(" * "); pw.println(rec);
9589 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009590 rec.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009591 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009592 } else {
9593 pw.print(" * "); pw.println(ref);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009594 }
9595 }
9596 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009597
9598 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009599 }
9600
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009601 private static final void dumpHistoryList(FileDescriptor fd, PrintWriter pw, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009602 String prefix, String label, boolean complete, boolean brief, boolean client,
9603 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009604 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009605 boolean needNL = false;
9606 final String innerPrefix = prefix + " ";
9607 final String[] args = new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009608 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009609 final ActivityRecord r = (ActivityRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009610 if (dumpPackage != null && !dumpPackage.equals(r.packageName)) {
9611 continue;
9612 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07009613 final boolean full = !brief && (complete || !r.isInHistory());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009614 if (needNL) {
9615 pw.println(" ");
9616 needNL = false;
9617 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009618 if (lastTask != r.task) {
9619 lastTask = r.task;
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009620 pw.print(prefix);
9621 pw.print(full ? "* " : " ");
9622 pw.println(lastTask);
9623 if (full) {
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009624 lastTask.dump(pw, prefix + " ");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009625 } else if (complete) {
9626 // Complete + brief == give a summary. Isn't that obvious?!?
9627 if (lastTask.intent != null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009628 pw.print(prefix); pw.print(" ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009629 pw.println(lastTask.intent.toInsecureStringWithClip());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009630 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009631 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009632 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009633 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label);
9634 pw.print(" #"); pw.print(i); pw.print(": ");
9635 pw.println(r);
9636 if (full) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009637 r.dump(pw, innerPrefix);
9638 } else if (complete) {
9639 // Complete + brief == give a summary. Isn't that obvious?!?
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009640 pw.print(innerPrefix); pw.println(r.intent.toInsecureString());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009641 if (r.app != null) {
9642 pw.print(innerPrefix); pw.println(r.app);
9643 }
9644 }
9645 if (client && r.app != null && r.app.thread != null) {
9646 // flush anything that is already in the PrintWriter since the thread is going
9647 // to write to the file descriptor directly
9648 pw.flush();
9649 try {
9650 TransferPipe tp = new TransferPipe();
9651 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009652 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9653 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009654 // Short timeout, since blocking here can
9655 // deadlock with the application.
9656 tp.go(fd, 2000);
9657 } finally {
9658 tp.kill();
9659 }
9660 } catch (IOException e) {
9661 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
9662 } catch (RemoteException e) {
9663 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
9664 }
9665 needNL = true;
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009666 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009667 }
9668 }
9669
Dianne Hackborn09c916b2009-12-08 14:50:51 -08009670 private static String buildOomTag(String prefix, String space, int val, int base) {
9671 if (val == base) {
9672 if (space == null) return prefix;
9673 return prefix + " ";
9674 }
9675 return prefix + "+" + Integer.toString(val-base);
9676 }
9677
9678 private static final int dumpProcessList(PrintWriter pw,
9679 ActivityManagerService service, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009680 String prefix, String normalLabel, String persistentLabel,
9681 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009682 int numPers = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07009683 final int N = list.size()-1;
9684 for (int i=N; i>=0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009685 ProcessRecord r = (ProcessRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009686 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9687 continue;
9688 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009689 pw.println(String.format("%s%s #%2d: %s",
9690 prefix, (r.persistent ? persistentLabel : normalLabel),
9691 i, r.toString()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009692 if (r.persistent) {
9693 numPers++;
9694 }
9695 }
9696 return numPers;
9697 }
9698
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009699 private static final boolean dumpProcessOomList(PrintWriter pw,
Dianne Hackborn905577f2011-09-07 18:31:28 -07009700 ActivityManagerService service, List<ProcessRecord> origList,
Dianne Hackborn287952c2010-09-22 22:34:31 -07009701 String prefix, String normalLabel, String persistentLabel,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009702 boolean inclDetails, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009703
Dianne Hackborn905577f2011-09-07 18:31:28 -07009704 ArrayList<Pair<ProcessRecord, Integer>> list
9705 = new ArrayList<Pair<ProcessRecord, Integer>>(origList.size());
9706 for (int i=0; i<origList.size(); i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009707 ProcessRecord r = origList.get(i);
9708 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9709 continue;
9710 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07009711 list.add(new Pair<ProcessRecord, Integer>(origList.get(i), i));
9712 }
9713
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009714 if (list.size() <= 0) {
9715 return false;
9716 }
9717
Dianne Hackborn905577f2011-09-07 18:31:28 -07009718 Comparator<Pair<ProcessRecord, Integer>> comparator
9719 = new Comparator<Pair<ProcessRecord, Integer>>() {
9720 @Override
9721 public int compare(Pair<ProcessRecord, Integer> object1,
9722 Pair<ProcessRecord, Integer> object2) {
9723 if (object1.first.setAdj != object2.first.setAdj) {
9724 return object1.first.setAdj > object2.first.setAdj ? -1 : 1;
9725 }
9726 if (object1.second.intValue() != object2.second.intValue()) {
9727 return object1.second.intValue() > object2.second.intValue() ? -1 : 1;
9728 }
9729 return 0;
9730 }
9731 };
9732
9733 Collections.sort(list, comparator);
9734
Dianne Hackborn287952c2010-09-22 22:34:31 -07009735 final long curRealtime = SystemClock.elapsedRealtime();
9736 final long realtimeSince = curRealtime - service.mLastPowerCheckRealtime;
9737 final long curUptime = SystemClock.uptimeMillis();
9738 final long uptimeSince = curUptime - service.mLastPowerCheckUptime;
9739
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009740 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07009741 ProcessRecord r = list.get(i).first;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009742 String oomAdj;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009743 if (r.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07009744 oomAdj = buildOomTag("bak", " ", r.setAdj, ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009745 } else if (r.setAdj >= ProcessList.SERVICE_B_ADJ) {
9746 oomAdj = buildOomTag("svcb ", null, r.setAdj, ProcessList.SERVICE_B_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009747 } else if (r.setAdj >= ProcessList.PREVIOUS_APP_ADJ) {
9748 oomAdj = buildOomTag("prev ", null, r.setAdj, ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009749 } else if (r.setAdj >= ProcessList.HOME_APP_ADJ) {
9750 oomAdj = buildOomTag("home ", null, r.setAdj, ProcessList.HOME_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009751 } else if (r.setAdj >= ProcessList.SERVICE_ADJ) {
9752 oomAdj = buildOomTag("svc ", null, r.setAdj, ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009753 } else if (r.setAdj >= ProcessList.BACKUP_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08009754 oomAdj = buildOomTag("bkup ", null, r.setAdj, ProcessList.BACKUP_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009755 } else if (r.setAdj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
9756 oomAdj = buildOomTag("hvy ", null, r.setAdj, ProcessList.HEAVY_WEIGHT_APP_ADJ);
9757 } else if (r.setAdj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
9758 oomAdj = buildOomTag("prcp ", null, r.setAdj, ProcessList.PERCEPTIBLE_APP_ADJ);
9759 } else if (r.setAdj >= ProcessList.VISIBLE_APP_ADJ) {
9760 oomAdj = buildOomTag("vis ", null, r.setAdj, ProcessList.VISIBLE_APP_ADJ);
9761 } else if (r.setAdj >= ProcessList.FOREGROUND_APP_ADJ) {
9762 oomAdj = buildOomTag("fore ", null, r.setAdj, ProcessList.FOREGROUND_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009763 } else if (r.setAdj >= ProcessList.PERSISTENT_PROC_ADJ) {
9764 oomAdj = buildOomTag("pers ", null, r.setAdj, ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009765 } else if (r.setAdj >= ProcessList.SYSTEM_ADJ) {
9766 oomAdj = buildOomTag("sys ", null, r.setAdj, ProcessList.SYSTEM_ADJ);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009767 } else {
9768 oomAdj = Integer.toString(r.setAdj);
9769 }
9770 String schedGroup;
9771 switch (r.setSchedGroup) {
9772 case Process.THREAD_GROUP_BG_NONINTERACTIVE:
9773 schedGroup = "B";
9774 break;
9775 case Process.THREAD_GROUP_DEFAULT:
9776 schedGroup = "F";
9777 break;
9778 default:
9779 schedGroup = Integer.toString(r.setSchedGroup);
9780 break;
9781 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07009782 String foreground;
9783 if (r.foregroundActivities) {
9784 foreground = "A";
9785 } else if (r.foregroundServices) {
9786 foreground = "S";
9787 } else {
9788 foreground = " ";
9789 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07009790 pw.println(String.format("%s%s #%2d: adj=%s/%s%s trm=%2d %s (%s)",
Dianne Hackborn287952c2010-09-22 22:34:31 -07009791 prefix, (r.persistent ? persistentLabel : normalLabel),
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009792 (origList.size()-1)-list.get(i).second, oomAdj, schedGroup,
9793 foreground, r.trimMemoryLevel, r.toShortString(), r.adjType));
Dianne Hackborn287952c2010-09-22 22:34:31 -07009794 if (r.adjSource != null || r.adjTarget != null) {
9795 pw.print(prefix);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009796 pw.print(" ");
Dianne Hackborn287952c2010-09-22 22:34:31 -07009797 if (r.adjTarget instanceof ComponentName) {
9798 pw.print(((ComponentName)r.adjTarget).flattenToShortString());
9799 } else if (r.adjTarget != null) {
9800 pw.print(r.adjTarget.toString());
9801 } else {
9802 pw.print("{null}");
9803 }
9804 pw.print("<=");
9805 if (r.adjSource instanceof ProcessRecord) {
9806 pw.print("Proc{");
9807 pw.print(((ProcessRecord)r.adjSource).toShortString());
9808 pw.println("}");
9809 } else if (r.adjSource != null) {
9810 pw.println(r.adjSource.toString());
9811 } else {
9812 pw.println("{null}");
9813 }
9814 }
9815 if (inclDetails) {
9816 pw.print(prefix);
9817 pw.print(" ");
9818 pw.print("oom: max="); pw.print(r.maxAdj);
9819 pw.print(" hidden="); pw.print(r.hiddenAdj);
9820 pw.print(" curRaw="); pw.print(r.curRawAdj);
9821 pw.print(" setRaw="); pw.print(r.setRawAdj);
9822 pw.print(" cur="); pw.print(r.curAdj);
9823 pw.print(" set="); pw.println(r.setAdj);
9824 pw.print(prefix);
9825 pw.print(" ");
9826 pw.print("keeping="); pw.print(r.keeping);
9827 pw.print(" hidden="); pw.print(r.hidden);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009828 pw.print(" empty="); pw.print(r.empty);
9829 pw.print(" hasAboveClient="); pw.println(r.hasAboveClient);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009830
9831 if (!r.keeping) {
9832 if (r.lastWakeTime != 0) {
9833 long wtime;
9834 BatteryStatsImpl stats = service.mBatteryStatsService.getActiveStatistics();
9835 synchronized (stats) {
9836 wtime = stats.getProcessWakeTime(r.info.uid,
9837 r.pid, curRealtime);
9838 }
9839 long timeUsed = wtime - r.lastWakeTime;
9840 pw.print(prefix);
9841 pw.print(" ");
9842 pw.print("keep awake over ");
9843 TimeUtils.formatDuration(realtimeSince, pw);
9844 pw.print(" used ");
9845 TimeUtils.formatDuration(timeUsed, pw);
9846 pw.print(" (");
9847 pw.print((timeUsed*100)/realtimeSince);
9848 pw.println("%)");
9849 }
9850 if (r.lastCpuTime != 0) {
9851 long timeUsed = r.curCpuTime - r.lastCpuTime;
9852 pw.print(prefix);
9853 pw.print(" ");
9854 pw.print("run cpu over ");
9855 TimeUtils.formatDuration(uptimeSince, pw);
9856 pw.print(" used ");
9857 TimeUtils.formatDuration(timeUsed, pw);
9858 pw.print(" (");
9859 pw.print((timeUsed*100)/uptimeSince);
9860 pw.println("%)");
9861 }
9862 }
9863 }
9864 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009865 return true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009866 }
9867
Dianne Hackbornb437e092011-08-05 17:50:29 -07009868 ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, String[] args) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009869 ArrayList<ProcessRecord> procs;
9870 synchronized (this) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009871 if (args != null && args.length > start
9872 && args[start].charAt(0) != '-') {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009873 procs = new ArrayList<ProcessRecord>();
9874 int pid = -1;
9875 try {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009876 pid = Integer.parseInt(args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009877 } catch (NumberFormatException e) {
9878
9879 }
9880 for (int i=mLruProcesses.size()-1; i>=0; i--) {
9881 ProcessRecord proc = mLruProcesses.get(i);
9882 if (proc.pid == pid) {
9883 procs.add(proc);
Dianne Hackbornb437e092011-08-05 17:50:29 -07009884 } else if (proc.processName.equals(args[start])) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009885 procs.add(proc);
9886 }
9887 }
9888 if (procs.size() <= 0) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009889 pw.println("No process found for: " + args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009890 return null;
9891 }
9892 } else {
9893 procs = new ArrayList<ProcessRecord>(mLruProcesses);
9894 }
9895 }
9896 return procs;
9897 }
9898
9899 final void dumpGraphicsHardwareUsage(FileDescriptor fd,
9900 PrintWriter pw, String[] args) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009901 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009902 if (procs == null) {
9903 return;
9904 }
9905
9906 long uptime = SystemClock.uptimeMillis();
9907 long realtime = SystemClock.elapsedRealtime();
9908 pw.println("Applications Graphics Acceleration Info:");
9909 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
9910
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009911 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
9912 ProcessRecord r = procs.get(i);
Chet Haase9c1e23b2011-03-24 10:51:31 -07009913 if (r.thread != null) {
9914 pw.println("\n** Graphics info for pid " + r.pid + " [" + r.processName + "] **");
9915 pw.flush();
9916 try {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009917 TransferPipe tp = new TransferPipe();
9918 try {
9919 r.thread.dumpGfxInfo(tp.getWriteFd().getFileDescriptor(), args);
9920 tp.go(fd);
9921 } finally {
9922 tp.kill();
9923 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009924 } catch (IOException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009925 pw.println("Failure while dumping the app: " + r);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009926 pw.flush();
Chet Haase9c1e23b2011-03-24 10:51:31 -07009927 } catch (RemoteException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009928 pw.println("Got a RemoteException while dumping the app " + r);
Chet Haase9c1e23b2011-03-24 10:51:31 -07009929 pw.flush();
9930 }
9931 }
9932 }
Chet Haase9c1e23b2011-03-24 10:51:31 -07009933 }
9934
Jeff Brown6754ba22011-12-14 20:20:01 -08009935 final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) {
9936 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
9937 if (procs == null) {
9938 return;
9939 }
9940
9941 pw.println("Applications Database Info:");
9942
9943 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
9944 ProcessRecord r = procs.get(i);
9945 if (r.thread != null) {
9946 pw.println("\n** Database info for pid " + r.pid + " [" + r.processName + "] **");
9947 pw.flush();
9948 try {
9949 TransferPipe tp = new TransferPipe();
9950 try {
9951 r.thread.dumpDbInfo(tp.getWriteFd().getFileDescriptor(), args);
9952 tp.go(fd);
9953 } finally {
9954 tp.kill();
9955 }
9956 } catch (IOException e) {
9957 pw.println("Failure while dumping the app: " + r);
9958 pw.flush();
9959 } catch (RemoteException e) {
9960 pw.println("Got a RemoteException while dumping the app " + r);
9961 pw.flush();
9962 }
9963 }
9964 }
9965 }
9966
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009967 final static class MemItem {
9968 final String label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009969 final String shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009970 final long pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009971 final int id;
Dianne Hackborna4bacb82011-08-24 15:12:38 -07009972 ArrayList<MemItem> subitems;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009973
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009974 public MemItem(String _label, String _shortLabel, long _pss, int _id) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009975 label = _label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009976 shortLabel = _shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009977 pss = _pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009978 id = _id;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009979 }
9980 }
9981
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009982 static final void dumpMemItems(PrintWriter pw, String prefix, ArrayList<MemItem> items,
Dianne Hackbornb437e092011-08-05 17:50:29 -07009983 boolean sort) {
9984 if (sort) {
9985 Collections.sort(items, new Comparator<MemItem>() {
9986 @Override
9987 public int compare(MemItem lhs, MemItem rhs) {
9988 if (lhs.pss < rhs.pss) {
9989 return 1;
9990 } else if (lhs.pss > rhs.pss) {
9991 return -1;
9992 }
9993 return 0;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009994 }
Dianne Hackbornb437e092011-08-05 17:50:29 -07009995 });
9996 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009997
9998 for (int i=0; i<items.size(); i++) {
9999 MemItem mi = items.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010000 pw.print(prefix); pw.printf("%7d kB: ", mi.pss); pw.println(mi.label);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010001 if (mi.subitems != null) {
10002 dumpMemItems(pw, prefix + " ", mi.subitems, true);
10003 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010004 }
10005 }
10006
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010007 // These are in KB.
10008 static final long[] DUMP_MEM_BUCKETS = new long[] {
10009 5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024,
10010 120*1024, 160*1024, 200*1024,
10011 250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024,
10012 1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024
10013 };
10014
Dianne Hackborn672342c2011-11-29 11:29:02 -080010015 static final void appendMemBucket(StringBuilder out, long memKB, String label,
10016 boolean stackLike) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010017 int start = label.lastIndexOf('.');
10018 if (start >= 0) start++;
10019 else start = 0;
10020 int end = label.length();
10021 for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) {
10022 if (DUMP_MEM_BUCKETS[i] >= memKB) {
10023 long bucket = DUMP_MEM_BUCKETS[i]/1024;
10024 out.append(bucket);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010025 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010026 out.append(label, start, end);
10027 return;
10028 }
10029 }
10030 out.append(memKB/1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010031 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010032 out.append(label, start, end);
10033 }
10034
10035 static final int[] DUMP_MEM_OOM_ADJ = new int[] {
10036 ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ, ProcessList.FOREGROUND_APP_ADJ,
10037 ProcessList.VISIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ,
10038 ProcessList.BACKUP_APP_ADJ, ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ,
10039 ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.HIDDEN_APP_MAX_ADJ
10040 };
10041 static final String[] DUMP_MEM_OOM_LABEL = new String[] {
10042 "System", "Persistent", "Foreground",
10043 "Visible", "Perceptible", "Heavy Weight",
10044 "Backup", "A Services", "Home", "Previous",
10045 "B Services", "Background"
10046 };
10047
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010048 final void dumpApplicationMemoryUsage(FileDescriptor fd,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010049 PrintWriter pw, String prefix, String[] args, boolean brief,
Dianne Hackborn672342c2011-11-29 11:29:02 -080010050 PrintWriter categoryPw, StringBuilder outTag, StringBuilder outStack) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010051 boolean dumpAll = false;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010052 boolean oomOnly = false;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010053
10054 int opti = 0;
10055 while (opti < args.length) {
10056 String opt = args[opti];
10057 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
10058 break;
10059 }
10060 opti++;
10061 if ("-a".equals(opt)) {
10062 dumpAll = true;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010063 } else if ("--oom".equals(opt)) {
10064 oomOnly = true;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010065 } else if ("-h".equals(opt)) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010066 pw.println("meminfo dump options: [-a] [--oom] [process]");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010067 pw.println(" -a: include all available information for each process.");
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010068 pw.println(" --oom: only show processes organized by oom adj.");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010069 pw.println("If [process] is specified it can be the name or ");
10070 pw.println("pid of a specific process to dump.");
10071 return;
10072 } else {
10073 pw.println("Unknown argument: " + opt + "; use -h for help");
10074 }
10075 }
10076
10077 ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010078 if (procs == null) {
10079 return;
10080 }
10081
Dianne Hackborn6447ca32009-04-07 19:50:08 -070010082 final boolean isCheckinRequest = scanArgs(args, "--checkin");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010083 long uptime = SystemClock.uptimeMillis();
10084 long realtime = SystemClock.elapsedRealtime();
Dianne Hackbornb437e092011-08-05 17:50:29 -070010085
10086 if (procs.size() == 1 || isCheckinRequest) {
10087 dumpAll = true;
10088 }
10089
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010090 if (isCheckinRequest) {
10091 // short checkin version
10092 pw.println(uptime + "," + realtime);
10093 pw.flush();
10094 } else {
10095 pw.println("Applications Memory Usage (kB):");
10096 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10097 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010098
Dianne Hackbornb437e092011-08-05 17:50:29 -070010099 String[] innerArgs = new String[args.length-opti];
10100 System.arraycopy(args, opti, innerArgs, 0, args.length-opti);
10101
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010102 ArrayList<MemItem> procMems = new ArrayList<MemItem>();
10103 long nativePss=0, dalvikPss=0, otherPss=0;
10104 long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
10105
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010106 long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length];
10107 ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[])
10108 new ArrayList[DUMP_MEM_OOM_LABEL.length];
Dianne Hackbornb437e092011-08-05 17:50:29 -070010109
10110 long totalPss = 0;
10111
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010112 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10113 ProcessRecord r = procs.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010114 if (r.thread != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010115 if (!isCheckinRequest && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010116 pw.println("\n** MEMINFO in pid " + r.pid + " [" + r.processName + "] **");
10117 pw.flush();
10118 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010119 Debug.MemoryInfo mi = null;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010120 if (dumpAll) {
10121 try {
10122 mi = r.thread.dumpMemInfo(fd, isCheckinRequest, dumpAll, innerArgs);
10123 } catch (RemoteException e) {
10124 if (!isCheckinRequest) {
10125 pw.println("Got RemoteException!");
10126 pw.flush();
10127 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010128 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010129 } else {
10130 mi = new Debug.MemoryInfo();
10131 Debug.getMemoryInfo(r.pid, mi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010132 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010133
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010134 if (!isCheckinRequest && mi != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010135 long myTotalPss = mi.getTotalPss();
10136 totalPss += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010137 MemItem pssItem = new MemItem(r.processName + " (pid " + r.pid + ")",
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010138 r.processName, myTotalPss, 0);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010139 procMems.add(pssItem);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010140
10141 nativePss += mi.nativePss;
10142 dalvikPss += mi.dalvikPss;
10143 otherPss += mi.otherPss;
10144 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
10145 long mem = mi.getOtherPss(j);
10146 miscPss[j] += mem;
10147 otherPss -= mem;
10148 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010149
10150 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010151 if (r.setAdj <= DUMP_MEM_OOM_ADJ[oomIndex]
10152 || oomIndex == (oomPss.length-1)) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010153 oomPss[oomIndex] += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010154 if (oomProcs[oomIndex] == null) {
10155 oomProcs[oomIndex] = new ArrayList<MemItem>();
10156 }
10157 oomProcs[oomIndex].add(pssItem);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010158 break;
10159 }
10160 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010161 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010162 }
10163 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010164
10165 if (!isCheckinRequest && procs.size() > 1) {
10166 ArrayList<MemItem> catMems = new ArrayList<MemItem>();
10167
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010168 catMems.add(new MemItem("Native", "Native", nativePss, -1));
10169 catMems.add(new MemItem("Dalvik", "Dalvik", dalvikPss, -2));
10170 catMems.add(new MemItem("Unknown", "Unknown", otherPss, -3));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010171 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010172 String label = Debug.MemoryInfo.getOtherLabel(j);
10173 catMems.add(new MemItem(label, label, miscPss[j], j));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010174 }
10175
Dianne Hackbornb437e092011-08-05 17:50:29 -070010176 ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
10177 for (int j=0; j<oomPss.length; j++) {
10178 if (oomPss[j] != 0) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010179 String label = DUMP_MEM_OOM_LABEL[j];
10180 MemItem item = new MemItem(label, label, oomPss[j],
10181 DUMP_MEM_OOM_ADJ[j]);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010182 item.subitems = oomProcs[j];
10183 oomMems.add(item);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010184 }
10185 }
10186
Dianne Hackborn672342c2011-11-29 11:29:02 -080010187 if (outTag != null || outStack != null) {
10188 if (outTag != null) {
10189 appendMemBucket(outTag, totalPss, "total", false);
10190 }
10191 if (outStack != null) {
10192 appendMemBucket(outStack, totalPss, "total", true);
10193 }
10194 boolean firstLine = true;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010195 for (int i=0; i<oomMems.size(); i++) {
10196 MemItem miCat = oomMems.get(i);
10197 if (miCat.subitems == null || miCat.subitems.size() < 1) {
10198 continue;
10199 }
10200 if (miCat.id < ProcessList.SERVICE_ADJ
10201 || miCat.id == ProcessList.HOME_APP_ADJ
10202 || miCat.id == ProcessList.PREVIOUS_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010203 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10204 outTag.append(" / ");
10205 }
10206 if (outStack != null) {
10207 if (miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10208 if (firstLine) {
10209 outStack.append(":");
10210 firstLine = false;
10211 }
10212 outStack.append("\n\t at ");
10213 } else {
10214 outStack.append("$");
10215 }
10216 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010217 for (int j=0; j<miCat.subitems.size(); j++) {
10218 MemItem mi = miCat.subitems.get(j);
10219 if (j > 0) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010220 if (outTag != null) {
10221 outTag.append(" ");
10222 }
10223 if (outStack != null) {
10224 outStack.append("$");
10225 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010226 }
Dianne Hackborn672342c2011-11-29 11:29:02 -080010227 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10228 appendMemBucket(outTag, mi.pss, mi.shortLabel, false);
10229 }
10230 if (outStack != null) {
10231 appendMemBucket(outStack, mi.pss, mi.shortLabel, true);
10232 }
10233 }
10234 if (outStack != null && miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10235 outStack.append("(");
10236 for (int k=0; k<DUMP_MEM_OOM_ADJ.length; k++) {
10237 if (DUMP_MEM_OOM_ADJ[k] == miCat.id) {
10238 outStack.append(DUMP_MEM_OOM_LABEL[k]);
10239 outStack.append(":");
10240 outStack.append(DUMP_MEM_OOM_ADJ[k]);
10241 }
10242 }
10243 outStack.append(")");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010244 }
10245 }
10246 }
10247 }
10248
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010249 if (!brief && !oomOnly) {
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010250 pw.println();
10251 pw.println("Total PSS by process:");
10252 dumpMemItems(pw, " ", procMems, true);
10253 pw.println();
10254 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010255 pw.println("Total PSS by OOM adjustment:");
10256 dumpMemItems(pw, " ", oomMems, false);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010257 if (!oomOnly) {
10258 PrintWriter out = categoryPw != null ? categoryPw : pw;
10259 out.println();
10260 out.println("Total PSS by category:");
10261 dumpMemItems(out, " ", catMems, true);
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010262 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010263 pw.println();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010264 pw.print("Total PSS: "); pw.print(totalPss); pw.println(" kB");
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010265 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010266 }
10267
10268 /**
10269 * Searches array of arguments for the specified string
10270 * @param args array of argument strings
10271 * @param value value to search for
10272 * @return true if the value is contained in the array
10273 */
10274 private static boolean scanArgs(String[] args, String value) {
10275 if (args != null) {
10276 for (String arg : args) {
10277 if (value.equals(arg)) {
10278 return true;
10279 }
10280 }
10281 }
10282 return false;
10283 }
10284
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010285 private final void killServicesLocked(ProcessRecord app,
10286 boolean allowRestart) {
10287 // Report disconnected services.
10288 if (false) {
10289 // XXX we are letting the client link to the service for
10290 // death notifications.
10291 if (app.services.size() > 0) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010292 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010293 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010294 ServiceRecord r = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010295 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010296 Iterator<ArrayList<ConnectionRecord>> jt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010297 = r.connections.values().iterator();
10298 while (jt.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010299 ArrayList<ConnectionRecord> cl = jt.next();
10300 for (int i=0; i<cl.size(); i++) {
10301 ConnectionRecord c = cl.get(i);
10302 if (c.binding.client != app) {
10303 try {
10304 //c.conn.connected(r.className, null);
10305 } catch (Exception e) {
10306 // todo: this should be asynchronous!
10307 Slog.w(TAG, "Exception thrown disconnected servce "
10308 + r.shortName
10309 + " from app " + app.processName, e);
10310 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010311 }
10312 }
10313 }
10314 }
10315 }
10316 }
10317 }
10318
10319 // Clean up any connections this application has to other services.
10320 if (app.connections.size() > 0) {
10321 Iterator<ConnectionRecord> it = app.connections.iterator();
10322 while (it.hasNext()) {
10323 ConnectionRecord r = it.next();
10324 removeConnectionLocked(r, app, null);
10325 }
10326 }
10327 app.connections.clear();
10328
10329 if (app.services.size() != 0) {
10330 // Any services running in the application need to be placed
10331 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -070010332 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010333 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010334 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010335 synchronized (sr.stats.getBatteryStats()) {
10336 sr.stats.stopLaunchedLocked();
10337 }
10338 sr.app = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010339 sr.isolatedProc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010340 sr.executeNesting = 0;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010341 if (mStoppingServices.remove(sr)) {
10342 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
10343 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010344
10345 boolean hasClients = sr.bindings.size() > 0;
10346 if (hasClients) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010347 Iterator<IntentBindRecord> bindings
10348 = sr.bindings.values().iterator();
10349 while (bindings.hasNext()) {
10350 IntentBindRecord b = bindings.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -080010351 if (DEBUG_SERVICE) Slog.v(TAG, "Killing binding " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010352 + ": shouldUnbind=" + b.hasBound);
10353 b.binder = null;
10354 b.requested = b.received = b.hasBound = false;
10355 }
10356 }
10357
Dianne Hackborn070783f2010-12-29 16:46:28 -080010358 if (sr.crashCount >= 2 && (sr.serviceInfo.applicationInfo.flags
10359 &ApplicationInfo.FLAG_PERSISTENT) == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010360 Slog.w(TAG, "Service crashed " + sr.crashCount
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010361 + " times, stopping: " + sr);
Doug Zongker2bec3d42009-12-04 12:52:44 -080010362 EventLog.writeEvent(EventLogTags.AM_SERVICE_CRASHED_TOO_MUCH,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010363 sr.crashCount, sr.shortName, app.pid);
10364 bringDownServiceLocked(sr, true);
10365 } else if (!allowRestart) {
10366 bringDownServiceLocked(sr, true);
10367 } else {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010368 boolean canceled = scheduleServiceRestartLocked(sr, true);
10369
10370 // Should the service remain running? Note that in the
10371 // extreme case of so many attempts to deliver a command
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010372 // that it failed we also will stop it here.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010373 if (sr.startRequested && (sr.stopIfKilled || canceled)) {
10374 if (sr.pendingStarts.size() == 0) {
10375 sr.startRequested = false;
10376 if (!hasClients) {
10377 // Whoops, no reason to restart!
10378 bringDownServiceLocked(sr, true);
10379 }
10380 }
10381 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010382 }
10383 }
10384
10385 if (!allowRestart) {
10386 app.services.clear();
10387 }
10388 }
10389
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010390 // Make sure we have no more records on the stopping list.
10391 int i = mStoppingServices.size();
10392 while (i > 0) {
10393 i--;
10394 ServiceRecord sr = mStoppingServices.get(i);
10395 if (sr.app == app) {
10396 mStoppingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010397 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010398 }
10399 }
10400
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010401 app.executingServices.clear();
10402 }
10403
10404 private final void removeDyingProviderLocked(ProcessRecord proc,
10405 ContentProviderRecord cpr) {
10406 synchronized (cpr) {
10407 cpr.launchingApp = null;
10408 cpr.notifyAll();
10409 }
10410
Amith Yamasani742a6712011-05-04 14:49:28 -070010411 mProviderMap.removeProviderByClass(cpr.name, UserId.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010412 String names[] = cpr.info.authority.split(";");
10413 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010414 mProviderMap.removeProviderByName(names[j], UserId.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010415 }
10416
10417 Iterator<ProcessRecord> cit = cpr.clients.iterator();
10418 while (cit.hasNext()) {
10419 ProcessRecord capp = cit.next();
10420 if (!capp.persistent && capp.thread != null
10421 && capp.pid != 0
10422 && capp.pid != MY_PID) {
Dianne Hackborn8633e682010-04-22 16:03:41 -070010423 Slog.i(TAG, "Kill " + capp.processName
10424 + " (pid " + capp.pid + "): provider " + cpr.info.name
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010425 + " in dying process " + (proc != null ? proc.processName : "??"));
Dianne Hackborn8633e682010-04-22 16:03:41 -070010426 EventLog.writeEvent(EventLogTags.AM_KILL, capp.pid,
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010427 capp.processName, capp.setAdj, "dying provider "
10428 + cpr.name.toShortString());
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070010429 Process.killProcessQuiet(capp.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010430 }
10431 }
10432
10433 mLaunchingProviders.remove(cpr);
10434 }
10435
10436 /**
10437 * Main code for cleaning up a process when it has gone away. This is
10438 * called both as a result of the process dying, or directly when stopping
10439 * a process when running in single process mode.
10440 */
10441 private final void cleanUpApplicationRecordLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010442 boolean restarting, boolean allowRestart, int index) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010443 if (index >= 0) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010444 mLruProcesses.remove(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010445 }
10446
Dianne Hackborn36124872009-10-08 16:22:03 -070010447 mProcessesToGc.remove(app);
10448
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010449 // Dismiss any open dialogs.
10450 if (app.crashDialog != null) {
10451 app.crashDialog.dismiss();
10452 app.crashDialog = null;
10453 }
10454 if (app.anrDialog != null) {
10455 app.anrDialog.dismiss();
10456 app.anrDialog = null;
10457 }
10458 if (app.waitDialog != null) {
10459 app.waitDialog.dismiss();
10460 app.waitDialog = null;
10461 }
10462
10463 app.crashing = false;
10464 app.notResponding = false;
10465
10466 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -070010467 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010468 app.thread = null;
10469 app.forcingToForeground = null;
10470 app.foregroundServices = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010471 app.foregroundActivities = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070010472 app.hasShownUi = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010473 app.hasAboveClient = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010474
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010475 killServicesLocked(app, allowRestart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010476
10477 boolean restart = false;
10478
10479 int NL = mLaunchingProviders.size();
10480
10481 // Remove published content providers.
10482 if (!app.pubProviders.isEmpty()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010483 Iterator<ContentProviderRecord> it = app.pubProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010484 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010485 ContentProviderRecord cpr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010486 cpr.provider = null;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010487 cpr.proc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010488
10489 // See if someone is waiting for this provider... in which
10490 // case we don't remove it, but just let it restart.
10491 int i = 0;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010492 if (!app.bad && allowRestart) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010493 for (; i<NL; i++) {
10494 if (mLaunchingProviders.get(i) == cpr) {
10495 restart = true;
10496 break;
10497 }
10498 }
10499 } else {
10500 i = NL;
10501 }
10502
10503 if (i >= NL) {
10504 removeDyingProviderLocked(app, cpr);
10505 NL = mLaunchingProviders.size();
10506 }
10507 }
10508 app.pubProviders.clear();
10509 }
10510
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010511 // Take care of any launching providers waiting for this process.
10512 if (checkAppInLaunchingProvidersLocked(app, false)) {
10513 restart = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010514 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010515
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010516 // Unregister from connected content providers.
10517 if (!app.conProviders.isEmpty()) {
Dianne Hackborn0c3154d2009-10-06 17:18:05 -070010518 Iterator it = app.conProviders.keySet().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010519 while (it.hasNext()) {
10520 ContentProviderRecord cpr = (ContentProviderRecord)it.next();
10521 cpr.clients.remove(app);
10522 }
10523 app.conProviders.clear();
10524 }
10525
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010526 // At this point there may be remaining entries in mLaunchingProviders
10527 // where we were the only one waiting, so they are no longer of use.
10528 // Look for these and clean up if found.
10529 // XXX Commented out for now. Trying to figure out a way to reproduce
10530 // the actual situation to identify what is actually going on.
10531 if (false) {
10532 for (int i=0; i<NL; i++) {
10533 ContentProviderRecord cpr = (ContentProviderRecord)
10534 mLaunchingProviders.get(i);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080010535 if (cpr.clients.size() <= 0 && !cpr.hasExternalProcessHandles()) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010536 synchronized (cpr) {
10537 cpr.launchingApp = null;
10538 cpr.notifyAll();
10539 }
10540 }
10541 }
10542 }
10543
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010544 skipCurrentReceiverLocked(app);
10545
10546 // Unregister any receivers.
10547 if (app.receivers.size() > 0) {
10548 Iterator<ReceiverList> it = app.receivers.iterator();
10549 while (it.hasNext()) {
10550 removeReceiverLocked(it.next());
10551 }
10552 app.receivers.clear();
10553 }
10554
Christopher Tate181fafa2009-05-14 11:12:14 -070010555 // If the app is undergoing backup, tell the backup manager about it
10556 if (mBackupTarget != null && app.pid == mBackupTarget.app.pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010557 if (DEBUG_BACKUP) Slog.d(TAG, "App " + mBackupTarget.appInfo + " died during backup");
Christopher Tate181fafa2009-05-14 11:12:14 -070010558 try {
10559 IBackupManager bm = IBackupManager.Stub.asInterface(
10560 ServiceManager.getService(Context.BACKUP_SERVICE));
10561 bm.agentDisconnected(app.info.packageName);
10562 } catch (RemoteException e) {
10563 // can't happen; backup manager is local
10564 }
10565 }
10566
Jeff Sharkey287bd832011-05-28 19:36:26 -070010567 mHandler.obtainMessage(DISPATCH_PROCESS_DIED, app.pid, app.info.uid, null).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010568
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010569 // If the caller is restarting this app, then leave it in its
10570 // current lists and let the caller take care of it.
10571 if (restarting) {
10572 return;
10573 }
10574
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010575 if (!app.persistent || app.isolated) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010576 if (DEBUG_PROCESSES) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010577 "Removing non-persistent process during cleanup: " + app);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010578 mProcessNames.remove(app.processName, app.uid);
10579 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -070010580 if (mHeavyWeightProcess == app) {
10581 mHeavyWeightProcess = null;
10582 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
10583 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010584 } else if (!app.removed) {
10585 // This app is persistent, so we need to keep its record around.
10586 // If it is not already on the pending app list, add it there
10587 // and start a new process for it.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010588 if (mPersistentStartingProcesses.indexOf(app) < 0) {
10589 mPersistentStartingProcesses.add(app);
10590 restart = true;
10591 }
10592 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070010593 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
10594 "Clean-up removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010595 mProcessesOnHold.remove(app);
10596
The Android Open Source Project4df24232009-03-05 14:34:35 -080010597 if (app == mHomeProcess) {
10598 mHomeProcess = null;
10599 }
Dianne Hackbornf35fe232011-11-01 19:25:20 -070010600 if (app == mPreviousProcess) {
10601 mPreviousProcess = null;
10602 }
10603
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010604 if (restart && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010605 // We have components that still need to be running in the
10606 // process, so re-launch it.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010607 mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010608 startProcessLocked(app, "restart", app.processName);
10609 } else if (app.pid > 0 && app.pid != MY_PID) {
10610 // Goodbye!
10611 synchronized (mPidsSelfLocked) {
10612 mPidsSelfLocked.remove(app.pid);
10613 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
10614 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010615 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010616 }
10617 }
10618
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010619 boolean checkAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) {
10620 // Look through the content providers we are waiting to have launched,
10621 // and if any run in this process then either schedule a restart of
10622 // the process or kill the client waiting for it if this process has
10623 // gone bad.
10624 int NL = mLaunchingProviders.size();
10625 boolean restart = false;
10626 for (int i=0; i<NL; i++) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010627 ContentProviderRecord cpr = mLaunchingProviders.get(i);
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010628 if (cpr.launchingApp == app) {
10629 if (!alwaysBad && !app.bad) {
10630 restart = true;
10631 } else {
10632 removeDyingProviderLocked(app, cpr);
10633 NL = mLaunchingProviders.size();
10634 }
10635 }
10636 }
10637 return restart;
10638 }
10639
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010640 // =========================================================
10641 // SERVICES
10642 // =========================================================
10643
10644 ActivityManager.RunningServiceInfo makeRunningServiceInfoLocked(ServiceRecord r) {
10645 ActivityManager.RunningServiceInfo info =
10646 new ActivityManager.RunningServiceInfo();
10647 info.service = r.name;
10648 if (r.app != null) {
10649 info.pid = r.app.pid;
10650 }
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010651 info.uid = r.appInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010652 info.process = r.processName;
10653 info.foreground = r.isForeground;
10654 info.activeSince = r.createTime;
10655 info.started = r.startRequested;
10656 info.clientCount = r.connections.size();
10657 info.crashCount = r.crashCount;
10658 info.lastActivityTime = r.lastActivity;
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010659 if (r.isForeground) {
10660 info.flags |= ActivityManager.RunningServiceInfo.FLAG_FOREGROUND;
10661 }
10662 if (r.startRequested) {
10663 info.flags |= ActivityManager.RunningServiceInfo.FLAG_STARTED;
10664 }
Dan Egnor42471dd2010-01-07 17:25:22 -080010665 if (r.app != null && r.app.pid == MY_PID) {
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010666 info.flags |= ActivityManager.RunningServiceInfo.FLAG_SYSTEM_PROCESS;
10667 }
10668 if (r.app != null && r.app.persistent) {
10669 info.flags |= ActivityManager.RunningServiceInfo.FLAG_PERSISTENT_PROCESS;
10670 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010671
10672 for (ArrayList<ConnectionRecord> connl : r.connections.values()) {
10673 for (int i=0; i<connl.size(); i++) {
10674 ConnectionRecord conn = connl.get(i);
10675 if (conn.clientLabel != 0) {
10676 info.clientPackage = conn.binding.client.info.packageName;
10677 info.clientLabel = conn.clientLabel;
10678 return info;
10679 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010680 }
10681 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010682 return info;
10683 }
10684
10685 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum,
10686 int flags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010687 enforceNotIsolatedCaller("getServices");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010688 synchronized (this) {
10689 ArrayList<ActivityManager.RunningServiceInfo> res
10690 = new ArrayList<ActivityManager.RunningServiceInfo>();
10691
Amith Yamasani742a6712011-05-04 14:49:28 -070010692 int userId = UserId.getUserId(Binder.getCallingUid());
10693 if (mServiceMap.getAllServices(userId).size() > 0) {
10694 Iterator<ServiceRecord> it
10695 = mServiceMap.getAllServices(userId).iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010696 while (it.hasNext() && res.size() < maxNum) {
10697 res.add(makeRunningServiceInfoLocked(it.next()));
10698 }
10699 }
10700
10701 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
10702 ServiceRecord r = mRestartingServices.get(i);
10703 ActivityManager.RunningServiceInfo info =
10704 makeRunningServiceInfoLocked(r);
10705 info.restarting = r.nextRestartTime;
10706 res.add(info);
10707 }
10708
10709 return res;
10710 }
10711 }
10712
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010713 public PendingIntent getRunningServiceControlPanel(ComponentName name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010714 enforceNotIsolatedCaller("getRunningServiceControlPanel");
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010715 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010716 int userId = UserId.getUserId(Binder.getCallingUid());
10717 ServiceRecord r = mServiceMap.getServiceByName(name, userId);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010718 if (r != null) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010719 for (ArrayList<ConnectionRecord> conn : r.connections.values()) {
10720 for (int i=0; i<conn.size(); i++) {
10721 if (conn.get(i).clientIntent != null) {
10722 return conn.get(i).clientIntent;
10723 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010724 }
10725 }
10726 }
10727 }
10728 return null;
10729 }
10730
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010731 private final ServiceRecord findServiceLocked(ComponentName name,
10732 IBinder token) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010733 ServiceRecord r = mServiceMap.getServiceByName(name, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010734 return r == token ? r : null;
10735 }
10736
10737 private final class ServiceLookupResult {
10738 final ServiceRecord record;
10739 final String permission;
10740
10741 ServiceLookupResult(ServiceRecord _record, String _permission) {
10742 record = _record;
10743 permission = _permission;
10744 }
10745 };
10746
10747 private ServiceLookupResult findServiceLocked(Intent service,
Amith Yamasani483f3b02012-03-13 16:08:00 -070010748 String resolvedType, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010749 ServiceRecord r = null;
10750 if (service.getComponent() != null) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070010751 r = mServiceMap.getServiceByName(service.getComponent(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010752 }
10753 if (r == null) {
10754 Intent.FilterComparison filter = new Intent.FilterComparison(service);
Amith Yamasani483f3b02012-03-13 16:08:00 -070010755 r = mServiceMap.getServiceByIntent(filter, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010756 }
10757
10758 if (r == null) {
10759 try {
10760 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070010761 AppGlobals.getPackageManager().resolveService(
Amith Yamasani483f3b02012-03-13 16:08:00 -070010762 service, resolvedType, 0, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010763 ServiceInfo sInfo =
10764 rInfo != null ? rInfo.serviceInfo : null;
10765 if (sInfo == null) {
10766 return null;
10767 }
10768
10769 ComponentName name = new ComponentName(
10770 sInfo.applicationInfo.packageName, sInfo.name);
Amith Yamasani742a6712011-05-04 14:49:28 -070010771 r = mServiceMap.getServiceByName(name, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010772 } catch (RemoteException ex) {
10773 // pm is in same process, this will never happen.
10774 }
10775 }
10776 if (r != null) {
10777 int callingPid = Binder.getCallingPid();
10778 int callingUid = Binder.getCallingUid();
10779 if (checkComponentPermission(r.permission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010780 callingPid, callingUid, r.appInfo.uid, r.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010781 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010782 if (!r.exported) {
10783 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
10784 + " from pid=" + callingPid
10785 + ", uid=" + callingUid
10786 + " that is not exported from uid " + r.appInfo.uid);
10787 return new ServiceLookupResult(null, "not exported from uid "
10788 + r.appInfo.uid);
10789 }
Joe Onorato8a9b2202010-02-26 18:56:32 -080010790 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010791 + " from pid=" + callingPid
10792 + ", uid=" + callingUid
10793 + " requires " + r.permission);
10794 return new ServiceLookupResult(null, r.permission);
10795 }
10796 return new ServiceLookupResult(r, null);
10797 }
10798 return null;
10799 }
10800
10801 private class ServiceRestarter implements Runnable {
10802 private ServiceRecord mService;
10803
10804 void setService(ServiceRecord service) {
10805 mService = service;
10806 }
10807
10808 public void run() {
10809 synchronized(ActivityManagerService.this) {
10810 performServiceRestartLocked(mService);
10811 }
10812 }
10813 }
10814
10815 private ServiceLookupResult retrieveServiceLocked(Intent service,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010816 String resolvedType, int callingPid, int callingUid, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010817 ServiceRecord r = null;
Amith Yamasani742a6712011-05-04 14:49:28 -070010818 if (DEBUG_SERVICE)
10819 Slog.v(TAG, "retrieveServiceLocked: " + service + " type=" + resolvedType
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010820 + " callingUid=" + callingUid);
Amith Yamasani742a6712011-05-04 14:49:28 -070010821
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010822 if (service.getComponent() != null) {
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010823 r = mServiceMap.getServiceByName(service.getComponent(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010824 }
Amith Yamasani742a6712011-05-04 14:49:28 -070010825 if (r == null) {
10826 Intent.FilterComparison filter = new Intent.FilterComparison(service);
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010827 r = mServiceMap.getServiceByIntent(filter, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -070010828 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010829 if (r == null) {
10830 try {
10831 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070010832 AppGlobals.getPackageManager().resolveService(
Amith Yamasani483f3b02012-03-13 16:08:00 -070010833 service, resolvedType, STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010834 ServiceInfo sInfo =
10835 rInfo != null ? rInfo.serviceInfo : null;
10836 if (sInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010837 Slog.w(TAG, "Unable to start service " + service +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010838 ": not found");
10839 return null;
10840 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010841 if (userId > 0) {
10842 sInfo.applicationInfo = getAppInfoForUser(sInfo.applicationInfo, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -070010843 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010844 ComponentName name = new ComponentName(
10845 sInfo.applicationInfo.packageName, sInfo.name);
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010846 r = mServiceMap.getServiceByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010847 if (r == null) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010848 Intent.FilterComparison filter = new Intent.FilterComparison(
10849 service.cloneFilter());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010850 ServiceRestarter res = new ServiceRestarter();
10851 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
10852 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
10853 synchronized (stats) {
10854 ss = stats.getServiceStatsLocked(
10855 sInfo.applicationInfo.uid, sInfo.packageName,
10856 sInfo.name);
10857 }
Dianne Hackbornb1c4a2a2010-01-19 15:36:42 -080010858 r = new ServiceRecord(this, ss, name, filter, sInfo, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010859 res.setService(r);
Amith Yamasani742a6712011-05-04 14:49:28 -070010860 mServiceMap.putServiceByName(name, UserId.getUserId(r.appInfo.uid), r);
10861 mServiceMap.putServiceByIntent(filter, UserId.getUserId(r.appInfo.uid), r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010862
10863 // Make sure this component isn't in the pending list.
10864 int N = mPendingServices.size();
10865 for (int i=0; i<N; i++) {
10866 ServiceRecord pr = mPendingServices.get(i);
10867 if (pr.name.equals(name)) {
10868 mPendingServices.remove(i);
10869 i--;
10870 N--;
10871 }
10872 }
10873 }
10874 } catch (RemoteException ex) {
10875 // pm is in same process, this will never happen.
10876 }
10877 }
10878 if (r != null) {
10879 if (checkComponentPermission(r.permission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010880 callingPid, callingUid, r.appInfo.uid, r.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010881 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010882 if (!r.exported) {
10883 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
10884 + " from pid=" + callingPid
10885 + ", uid=" + callingUid
10886 + " that is not exported from uid " + r.appInfo.uid);
10887 return new ServiceLookupResult(null, "not exported from uid "
10888 + r.appInfo.uid);
10889 }
Joe Onorato8a9b2202010-02-26 18:56:32 -080010890 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010891 + " from pid=" + callingPid
10892 + ", uid=" + callingUid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010893 + " requires " + r.permission);
10894 return new ServiceLookupResult(null, r.permission);
10895 }
10896 return new ServiceLookupResult(r, null);
10897 }
10898 return null;
10899 }
10900
Dianne Hackborn287952c2010-09-22 22:34:31 -070010901 private final void bumpServiceExecutingLocked(ServiceRecord r, String why) {
10902 if (DEBUG_SERVICE) Log.v(TAG, ">>> EXECUTING "
10903 + why + " of " + r + " in app " + r.app);
10904 else if (DEBUG_SERVICE_EXECUTING) Log.v(TAG, ">>> EXECUTING "
10905 + why + " of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010906 long now = SystemClock.uptimeMillis();
10907 if (r.executeNesting == 0 && r.app != null) {
10908 if (r.app.executingServices.size() == 0) {
10909 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
10910 msg.obj = r.app;
10911 mHandler.sendMessageAtTime(msg, now+SERVICE_TIMEOUT);
10912 }
10913 r.app.executingServices.add(r);
10914 }
10915 r.executeNesting++;
10916 r.executingStart = now;
10917 }
10918
10919 private final void sendServiceArgsLocked(ServiceRecord r,
10920 boolean oomAdjusted) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010921 final int N = r.pendingStarts.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010922 if (N == 0) {
10923 return;
10924 }
10925
Dianne Hackborn39792d22010-08-19 18:01:52 -070010926 while (r.pendingStarts.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010927 try {
Dianne Hackborn39792d22010-08-19 18:01:52 -070010928 ServiceRecord.StartItem si = r.pendingStarts.remove(0);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010929 if (DEBUG_SERVICE) Slog.v(TAG, "Sending arguments to: "
10930 + r + " " + r.intent + " args=" + si.intent);
Dianne Hackborn3a28f222011-03-01 12:25:54 -080010931 if (si.intent == null && N > 1) {
10932 // If somehow we got a dummy null intent in the middle,
10933 // then skip it. DO NOT skip a null intent when it is
10934 // the only one in the list -- this is to support the
10935 // onStartCommand(null) case.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010936 continue;
10937 }
Dianne Hackborn39792d22010-08-19 18:01:52 -070010938 si.deliveredTime = SystemClock.uptimeMillis();
10939 r.deliveredStarts.add(si);
10940 si.deliveryCount++;
Dianne Hackborn21c241e2012-03-08 13:57:23 -080010941 if (si.neededGrants != null) {
10942 grantUriPermissionUncheckedFromIntentLocked(si.neededGrants,
10943 si.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -070010944 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070010945 bumpServiceExecutingLocked(r, "start");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010946 if (!oomAdjusted) {
10947 oomAdjusted = true;
10948 updateOomAdjLocked(r.app);
10949 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010950 int flags = 0;
10951 if (si.deliveryCount > 0) {
10952 flags |= Service.START_FLAG_RETRY;
10953 }
10954 if (si.doneExecutingCount > 0) {
10955 flags |= Service.START_FLAG_REDELIVERY;
10956 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070010957 r.app.thread.scheduleServiceArgs(r, si.taskRemoved, si.id, flags, si.intent);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010958 } catch (RemoteException e) {
10959 // Remote process gone... we'll let the normal cleanup take
10960 // care of this.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010961 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while scheduling start: " + r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010962 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010963 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010964 Slog.w(TAG, "Unexpected exception", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010965 break;
10966 }
10967 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010968 }
10969
10970 private final boolean requestServiceBindingLocked(ServiceRecord r,
10971 IntentBindRecord i, boolean rebind) {
10972 if (r.app == null || r.app.thread == null) {
10973 // If service is not currently running, can't yet bind.
10974 return false;
10975 }
10976 if ((!i.requested || rebind) && i.apps.size() > 0) {
10977 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070010978 bumpServiceExecutingLocked(r, "bind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010979 r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind);
10980 if (!rebind) {
10981 i.requested = true;
10982 }
10983 i.hasBound = true;
10984 i.doRebind = false;
10985 } catch (RemoteException e) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010986 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while binding " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010987 return false;
10988 }
10989 }
10990 return true;
10991 }
10992
10993 private final void requestServiceBindingsLocked(ServiceRecord r) {
10994 Iterator<IntentBindRecord> bindings = r.bindings.values().iterator();
10995 while (bindings.hasNext()) {
10996 IntentBindRecord i = bindings.next();
10997 if (!requestServiceBindingLocked(r, i, false)) {
10998 break;
10999 }
11000 }
11001 }
11002
11003 private final void realStartServiceLocked(ServiceRecord r,
11004 ProcessRecord app) throws RemoteException {
11005 if (app.thread == null) {
11006 throw new RemoteException();
11007 }
Amith Yamasani742a6712011-05-04 14:49:28 -070011008 if (DEBUG_MU)
11009 Slog.v(TAG_MU, "realStartServiceLocked, ServiceRecord.uid = " + r.appInfo.uid
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011010 + ", ProcessRecord.uid = " + app.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011011 r.app = app;
The Android Open Source Project10592532009-03-18 17:39:46 -070011012 r.restartTime = r.lastActivity = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011013
11014 app.services.add(r);
Dianne Hackborn287952c2010-09-22 22:34:31 -070011015 bumpServiceExecutingLocked(r, "create");
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011016 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011017
11018 boolean created = false;
11019 try {
Dianne Hackborna33e3f72009-09-29 17:28:24 -070011020 mStringBuilder.setLength(0);
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011021 r.intent.getIntent().toShortString(mStringBuilder, true, false, true, false);
Doug Zongker2bec3d42009-12-04 12:52:44 -080011022 EventLog.writeEvent(EventLogTags.AM_CREATE_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011023 System.identityHashCode(r), r.shortName,
Dianne Hackborna33e3f72009-09-29 17:28:24 -070011024 mStringBuilder.toString(), r.app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011025 synchronized (r.stats.getBatteryStats()) {
11026 r.stats.startLaunchedLocked();
11027 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -070011028 ensurePackageDexOpt(r.serviceInfo.packageName);
Dianne Hackborne2515ee2011-04-27 18:52:56 -040011029 app.thread.scheduleCreateService(r, r.serviceInfo,
11030 compatibilityInfoForPackageLocked(r.serviceInfo.applicationInfo));
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011031 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011032 created = true;
11033 } finally {
11034 if (!created) {
11035 app.services.remove(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011036 scheduleServiceRestartLocked(r, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011037 }
11038 }
11039
11040 requestServiceBindingsLocked(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011041
11042 // If the service is in the started state, and there are no
11043 // pending arguments, then fake up one so its onStartCommand() will
11044 // be called.
11045 if (r.startRequested && r.callStart && r.pendingStarts.size() == 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011046 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011047 null, null));
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011048 }
11049
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011050 sendServiceArgsLocked(r, true);
11051 }
11052
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011053 private final boolean scheduleServiceRestartLocked(ServiceRecord r,
11054 boolean allowCancel) {
11055 boolean canceled = false;
11056
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011057 final long now = SystemClock.uptimeMillis();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011058 long minDuration = SERVICE_RESTART_DURATION;
Dianne Hackborn6ccd2af2009-08-27 12:26:44 -070011059 long resetTime = SERVICE_RESET_RUN_DURATION;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011060
Dianne Hackborn070783f2010-12-29 16:46:28 -080011061 if ((r.serviceInfo.applicationInfo.flags
11062 &ApplicationInfo.FLAG_PERSISTENT) != 0) {
11063 minDuration /= 4;
11064 }
11065
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011066 // Any delivered but not yet finished starts should be put back
11067 // on the pending list.
11068 final int N = r.deliveredStarts.size();
11069 if (N > 0) {
11070 for (int i=N-1; i>=0; i--) {
11071 ServiceRecord.StartItem si = r.deliveredStarts.get(i);
Dianne Hackborn39792d22010-08-19 18:01:52 -070011072 si.removeUriPermissionsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011073 if (si.intent == null) {
11074 // We'll generate this again if needed.
11075 } else if (!allowCancel || (si.deliveryCount < ServiceRecord.MAX_DELIVERY_COUNT
11076 && si.doneExecutingCount < ServiceRecord.MAX_DONE_EXECUTING_COUNT)) {
11077 r.pendingStarts.add(0, si);
11078 long dur = SystemClock.uptimeMillis() - si.deliveredTime;
11079 dur *= 2;
11080 if (minDuration < dur) minDuration = dur;
11081 if (resetTime < dur) resetTime = dur;
11082 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011083 Slog.w(TAG, "Canceling start item " + si.intent + " in service "
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011084 + r.name);
11085 canceled = true;
11086 }
11087 }
11088 r.deliveredStarts.clear();
11089 }
11090
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011091 r.totalRestartCount++;
11092 if (r.restartDelay == 0) {
11093 r.restartCount++;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011094 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011095 } else {
11096 // If it has been a "reasonably long time" since the service
11097 // was started, then reset our restart duration back to
11098 // the beginning, so we don't infinitely increase the duration
11099 // on a service that just occasionally gets killed (which is
11100 // a normal case, due to process being killed to reclaim memory).
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011101 if (now > (r.restartTime+resetTime)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011102 r.restartCount = 1;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011103 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011104 } else {
Dianne Hackborn070783f2010-12-29 16:46:28 -080011105 if ((r.serviceInfo.applicationInfo.flags
11106 &ApplicationInfo.FLAG_PERSISTENT) != 0) {
11107 // Services in peristent processes will restart much more
11108 // quickly, since they are pretty important. (Think SystemUI).
11109 r.restartDelay += minDuration/2;
11110 } else {
11111 r.restartDelay *= SERVICE_RESTART_DURATION_FACTOR;
11112 if (r.restartDelay < minDuration) {
11113 r.restartDelay = minDuration;
11114 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011115 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011116 }
11117 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011118
11119 r.nextRestartTime = now + r.restartDelay;
11120
11121 // Make sure that we don't end up restarting a bunch of services
11122 // all at the same time.
11123 boolean repeat;
11124 do {
11125 repeat = false;
11126 for (int i=mRestartingServices.size()-1; i>=0; i--) {
11127 ServiceRecord r2 = mRestartingServices.get(i);
11128 if (r2 != r && r.nextRestartTime
11129 >= (r2.nextRestartTime-SERVICE_MIN_RESTART_TIME_BETWEEN)
11130 && r.nextRestartTime
11131 < (r2.nextRestartTime+SERVICE_MIN_RESTART_TIME_BETWEEN)) {
11132 r.nextRestartTime = r2.nextRestartTime + SERVICE_MIN_RESTART_TIME_BETWEEN;
11133 r.restartDelay = r.nextRestartTime - now;
11134 repeat = true;
11135 break;
11136 }
11137 }
11138 } while (repeat);
11139
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011140 if (!mRestartingServices.contains(r)) {
11141 mRestartingServices.add(r);
11142 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011143
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011144 r.cancelNotification();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011145
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011146 mHandler.removeCallbacks(r.restarter);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011147 mHandler.postAtTime(r.restarter, r.nextRestartTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011148 r.nextRestartTime = SystemClock.uptimeMillis() + r.restartDelay;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011149 Slog.w(TAG, "Scheduling restart of crashed service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011150 + r.shortName + " in " + r.restartDelay + "ms");
Doug Zongker2bec3d42009-12-04 12:52:44 -080011151 EventLog.writeEvent(EventLogTags.AM_SCHEDULE_SERVICE_RESTART,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011152 r.shortName, r.restartDelay);
11153
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011154 return canceled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011155 }
11156
11157 final void performServiceRestartLocked(ServiceRecord r) {
11158 if (!mRestartingServices.contains(r)) {
11159 return;
11160 }
11161 bringUpServiceLocked(r, r.intent.getIntent().getFlags(), true);
11162 }
11163
11164 private final boolean unscheduleServiceRestartLocked(ServiceRecord r) {
11165 if (r.restartDelay == 0) {
11166 return false;
11167 }
11168 r.resetRestartCounter();
11169 mRestartingServices.remove(r);
11170 mHandler.removeCallbacks(r.restarter);
11171 return true;
11172 }
11173
11174 private final boolean bringUpServiceLocked(ServiceRecord r,
11175 int intentFlags, boolean whileRestarting) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011176 //Slog.i(TAG, "Bring up service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011177 //r.dump(" ");
11178
Dianne Hackborn36124872009-10-08 16:22:03 -070011179 if (r.app != null && r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011180 sendServiceArgsLocked(r, false);
11181 return true;
11182 }
11183
11184 if (!whileRestarting && r.restartDelay > 0) {
11185 // If waiting for a restart, then do nothing.
11186 return true;
11187 }
11188
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011189 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing up " + r + " " + r.intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011190
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011191 // We are now bringing the service up, so no longer in the
11192 // restarting state.
11193 mRestartingServices.remove(r);
11194
Dianne Hackborne7f97212011-02-24 14:40:20 -080011195 // Service is now being launched, its package can't be stopped.
11196 try {
11197 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -070011198 r.packageName, false, r.userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -080011199 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080011200 } catch (IllegalArgumentException e) {
11201 Slog.w(TAG, "Failed trying to unstop package "
11202 + r.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080011203 }
11204
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011205 final boolean isolated = (r.serviceInfo.flags&ServiceInfo.FLAG_ISOLATED_PROCESS) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011206 final String appName = r.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011207 ProcessRecord app;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011208
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011209 if (!isolated) {
11210 app = getProcessRecordLocked(appName, r.appInfo.uid);
11211 if (DEBUG_MU)
11212 Slog.v(TAG_MU, "bringUpServiceLocked: appInfo.uid=" + r.appInfo.uid + " app=" + app);
11213 if (app != null && app.thread != null) {
11214 try {
11215 app.addPackage(r.appInfo.packageName);
11216 realStartServiceLocked(r, app);
11217 return true;
11218 } catch (RemoteException e) {
11219 Slog.w(TAG, "Exception when starting service " + r.shortName, e);
11220 }
11221
11222 // If a dead object exception was thrown -- fall through to
11223 // restart the application.
11224 }
11225 } else {
11226 // If this service runs in an isolated process, then each time
11227 // we call startProcessLocked() we will get a new isolated
11228 // process, starting another process if we are currently waiting
11229 // for a previous process to come up. To deal with this, we store
11230 // in the service any current isolated process it is running in or
11231 // waiting to have come up.
11232 app = r.isolatedProc;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011233 }
11234
Dianne Hackborn36124872009-10-08 16:22:03 -070011235 // Not running -- get it started, and enqueue this service record
11236 // to be executed when the app comes up.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011237 if (app == null) {
11238 if ((app=startProcessLocked(appName, r.appInfo, true, intentFlags,
11239 "service", r.name, false, isolated)) == null) {
11240 Slog.w(TAG, "Unable to launch app "
11241 + r.appInfo.packageName + "/"
11242 + r.appInfo.uid + " for service "
11243 + r.intent.getIntent() + ": process is bad");
11244 bringDownServiceLocked(r, true);
11245 return false;
11246 }
11247 if (isolated) {
11248 r.isolatedProc = app;
11249 }
Dianne Hackborn36124872009-10-08 16:22:03 -070011250 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011251
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011252 if (!mPendingServices.contains(r)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011253 mPendingServices.add(r);
11254 }
Dianne Hackborn36124872009-10-08 16:22:03 -070011255
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011256 return true;
11257 }
11258
11259 private final void bringDownServiceLocked(ServiceRecord r, boolean force) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011260 //Slog.i(TAG, "Bring down service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011261 //r.dump(" ");
11262
11263 // Does it still need to run?
11264 if (!force && r.startRequested) {
11265 return;
11266 }
11267 if (r.connections.size() > 0) {
11268 if (!force) {
11269 // XXX should probably keep a count of the number of auto-create
11270 // connections directly in the service.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011271 Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011272 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011273 ArrayList<ConnectionRecord> cr = it.next();
11274 for (int i=0; i<cr.size(); i++) {
11275 if ((cr.get(i).flags&Context.BIND_AUTO_CREATE) != 0) {
11276 return;
11277 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011278 }
11279 }
11280 }
11281
11282 // Report to all of the connections that the service is no longer
11283 // available.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011284 Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011285 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011286 ArrayList<ConnectionRecord> c = it.next();
11287 for (int i=0; i<c.size(); i++) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011288 ConnectionRecord cr = c.get(i);
11289 // There is still a connection to the service that is
11290 // being brought down. Mark it as dead.
11291 cr.serviceDead = true;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011292 try {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011293 cr.conn.connected(r.name, null);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011294 } catch (Exception e) {
11295 Slog.w(TAG, "Failure disconnecting service " + r.name +
11296 " to connection " + c.get(i).conn.asBinder() +
11297 " (in " + c.get(i).binding.client.processName + ")", e);
11298 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011299 }
11300 }
11301 }
11302
11303 // Tell the service that it has been unbound.
11304 if (r.bindings.size() > 0 && r.app != null && r.app.thread != null) {
11305 Iterator<IntentBindRecord> it = r.bindings.values().iterator();
11306 while (it.hasNext()) {
11307 IntentBindRecord ibr = it.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -080011308 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down binding " + ibr
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011309 + ": hasBound=" + ibr.hasBound);
11310 if (r.app != null && r.app.thread != null && ibr.hasBound) {
11311 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011312 bumpServiceExecutingLocked(r, "bring down unbind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011313 updateOomAdjLocked(r.app);
11314 ibr.hasBound = false;
11315 r.app.thread.scheduleUnbindService(r,
11316 ibr.intent.getIntent());
11317 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011318 Slog.w(TAG, "Exception when unbinding service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011319 + r.shortName, e);
11320 serviceDoneExecutingLocked(r, true);
11321 }
11322 }
11323 }
11324 }
11325
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011326 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down " + r + " " + r.intent);
Doug Zongker2bec3d42009-12-04 12:52:44 -080011327 EventLog.writeEvent(EventLogTags.AM_DESTROY_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011328 System.identityHashCode(r), r.shortName,
11329 (r.app != null) ? r.app.pid : -1);
11330
Amith Yamasani742a6712011-05-04 14:49:28 -070011331 mServiceMap.removeServiceByName(r.name, r.userId);
11332 mServiceMap.removeServiceByIntent(r.intent, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011333 r.totalRestartCount = 0;
11334 unscheduleServiceRestartLocked(r);
11335
11336 // Also make sure it is not on the pending list.
11337 int N = mPendingServices.size();
11338 for (int i=0; i<N; i++) {
11339 if (mPendingServices.get(i) == r) {
11340 mPendingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011341 if (DEBUG_SERVICE) Slog.v(TAG, "Removed pending: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011342 i--;
11343 N--;
11344 }
11345 }
11346
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011347 r.cancelNotification();
11348 r.isForeground = false;
11349 r.foregroundId = 0;
11350 r.foregroundNoti = null;
11351
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011352 // Clear start entries.
Dianne Hackborn39792d22010-08-19 18:01:52 -070011353 r.clearDeliveredStartsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011354 r.pendingStarts.clear();
11355
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011356 if (r.app != null) {
11357 synchronized (r.stats.getBatteryStats()) {
11358 r.stats.stopLaunchedLocked();
11359 }
11360 r.app.services.remove(r);
11361 if (r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011362 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011363 bumpServiceExecutingLocked(r, "stop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011364 mStoppingServices.add(r);
11365 updateOomAdjLocked(r.app);
11366 r.app.thread.scheduleStopService(r);
11367 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011368 Slog.w(TAG, "Exception when stopping service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011369 + r.shortName, e);
11370 serviceDoneExecutingLocked(r, true);
11371 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011372 updateServiceForegroundLocked(r.app, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011373 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011374 if (DEBUG_SERVICE) Slog.v(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011375 TAG, "Removed service that has no process: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011376 }
11377 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011378 if (DEBUG_SERVICE) Slog.v(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011379 TAG, "Removed service that is not running: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011380 }
Vairavan Srinivasana207ce22010-12-23 13:51:48 -080011381
11382 if (r.bindings.size() > 0) {
11383 r.bindings.clear();
11384 }
11385
11386 if (r.restarter instanceof ServiceRestarter) {
11387 ((ServiceRestarter)r.restarter).setService(null);
11388 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011389 }
11390
11391 ComponentName startServiceLocked(IApplicationThread caller,
11392 Intent service, String resolvedType,
11393 int callingPid, int callingUid) {
11394 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011395 if (DEBUG_SERVICE) Slog.v(TAG, "startService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011396 + " type=" + resolvedType + " args=" + service.getExtras());
11397
11398 if (caller != null) {
11399 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11400 if (callerApp == null) {
11401 throw new SecurityException(
11402 "Unable to find app for caller " + caller
11403 + " (pid=" + Binder.getCallingPid()
11404 + ") when starting service " + service);
11405 }
11406 }
11407
11408 ServiceLookupResult res =
11409 retrieveServiceLocked(service, resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011410 callingPid, callingUid, UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011411 if (res == null) {
11412 return null;
11413 }
11414 if (res.record == null) {
11415 return new ComponentName("!", res.permission != null
11416 ? res.permission : "private to package");
11417 }
11418 ServiceRecord r = res.record;
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011419 NeededUriGrants neededGrants = checkGrantUriPermissionFromIntentLocked(
11420 callingUid, r.packageName, service, service.getFlags(), null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011421 if (unscheduleServiceRestartLocked(r)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011422 if (DEBUG_SERVICE) Slog.v(TAG, "START SERVICE WHILE RESTART PENDING: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011423 }
11424 r.startRequested = true;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011425 r.callStart = false;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011426 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011427 service, neededGrants));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011428 r.lastActivity = SystemClock.uptimeMillis();
11429 synchronized (r.stats.getBatteryStats()) {
11430 r.stats.startRunningLocked();
11431 }
11432 if (!bringUpServiceLocked(r, service.getFlags(), false)) {
11433 return new ComponentName("!", "Service process is bad");
11434 }
11435 return r.name;
11436 }
11437 }
11438
11439 public ComponentName startService(IApplicationThread caller, Intent service,
11440 String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011441 enforceNotIsolatedCaller("startService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011442 // Refuse possible leaked file descriptors
11443 if (service != null && service.hasFileDescriptors() == true) {
11444 throw new IllegalArgumentException("File descriptors passed in Intent");
11445 }
11446
Amith Yamasani742a6712011-05-04 14:49:28 -070011447 if (DEBUG_SERVICE)
11448 Slog.v(TAG, "startService: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011449 synchronized(this) {
11450 final int callingPid = Binder.getCallingPid();
11451 final int callingUid = Binder.getCallingUid();
11452 final long origId = Binder.clearCallingIdentity();
11453 ComponentName res = startServiceLocked(caller, service,
11454 resolvedType, callingPid, callingUid);
11455 Binder.restoreCallingIdentity(origId);
11456 return res;
11457 }
11458 }
11459
11460 ComponentName startServiceInPackage(int uid,
11461 Intent service, String resolvedType) {
11462 synchronized(this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070011463 if (DEBUG_SERVICE)
11464 Slog.v(TAG, "startServiceInPackage: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011465 final long origId = Binder.clearCallingIdentity();
11466 ComponentName res = startServiceLocked(null, service,
11467 resolvedType, -1, uid);
11468 Binder.restoreCallingIdentity(origId);
11469 return res;
11470 }
11471 }
11472
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011473 private void stopServiceLocked(ServiceRecord service) {
11474 synchronized (service.stats.getBatteryStats()) {
11475 service.stats.stopRunningLocked();
11476 }
11477 service.startRequested = false;
11478 service.callStart = false;
11479 bringDownServiceLocked(service, false);
11480 }
11481
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011482 public int stopService(IApplicationThread caller, Intent service,
11483 String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011484 enforceNotIsolatedCaller("stopService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011485 // Refuse possible leaked file descriptors
11486 if (service != null && service.hasFileDescriptors() == true) {
11487 throw new IllegalArgumentException("File descriptors passed in Intent");
11488 }
11489
11490 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011491 if (DEBUG_SERVICE) Slog.v(TAG, "stopService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011492 + " type=" + resolvedType);
11493
11494 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11495 if (caller != null && callerApp == null) {
11496 throw new SecurityException(
11497 "Unable to find app for caller " + caller
11498 + " (pid=" + Binder.getCallingPid()
11499 + ") when stopping service " + service);
11500 }
11501
11502 // If this service is active, make sure it is stopped.
Amith Yamasani483f3b02012-03-13 16:08:00 -070011503 ServiceLookupResult r = findServiceLocked(service, resolvedType,
11504 callerApp == null ? UserId.getCallingUserId() : callerApp.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011505 if (r != null) {
11506 if (r.record != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011507 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011508 try {
11509 stopServiceLocked(r.record);
11510 } finally {
11511 Binder.restoreCallingIdentity(origId);
11512 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011513 return 1;
11514 }
11515 return -1;
11516 }
11517 }
11518
11519 return 0;
11520 }
11521
11522 public IBinder peekService(Intent service, String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011523 enforceNotIsolatedCaller("peekService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011524 // Refuse possible leaked file descriptors
11525 if (service != null && service.hasFileDescriptors() == true) {
11526 throw new IllegalArgumentException("File descriptors passed in Intent");
11527 }
11528
11529 IBinder ret = null;
11530
11531 synchronized(this) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070011532 ServiceLookupResult r = findServiceLocked(service, resolvedType,
11533 UserId.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011534
11535 if (r != null) {
11536 // r.record is null if findServiceLocked() failed the caller permission check
11537 if (r.record == null) {
11538 throw new SecurityException(
11539 "Permission Denial: Accessing service " + r.record.name
11540 + " from pid=" + Binder.getCallingPid()
11541 + ", uid=" + Binder.getCallingUid()
11542 + " requires " + r.permission);
11543 }
11544 IntentBindRecord ib = r.record.bindings.get(r.record.intent);
11545 if (ib != null) {
11546 ret = ib.binder;
11547 }
11548 }
11549 }
11550
11551 return ret;
11552 }
11553
11554 public boolean stopServiceToken(ComponentName className, IBinder token,
11555 int startId) {
11556 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011557 if (DEBUG_SERVICE) Slog.v(TAG, "stopServiceToken: " + className
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011558 + " " + token + " startId=" + startId);
11559 ServiceRecord r = findServiceLocked(className, token);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011560 if (r != null) {
11561 if (startId >= 0) {
11562 // Asked to only stop if done with all work. Note that
11563 // to avoid leaks, we will take this as dropping all
11564 // start items up to and including this one.
11565 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
11566 if (si != null) {
11567 while (r.deliveredStarts.size() > 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -070011568 ServiceRecord.StartItem cur = r.deliveredStarts.remove(0);
11569 cur.removeUriPermissionsLocked();
11570 if (cur == si) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011571 break;
11572 }
11573 }
11574 }
11575
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011576 if (r.getLastStartId() != startId) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011577 return false;
11578 }
11579
11580 if (r.deliveredStarts.size() > 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011581 Slog.w(TAG, "stopServiceToken startId " + startId
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011582 + " is last, but have " + r.deliveredStarts.size()
11583 + " remaining args");
11584 }
11585 }
11586
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011587 synchronized (r.stats.getBatteryStats()) {
11588 r.stats.stopRunningLocked();
11589 r.startRequested = false;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011590 r.callStart = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011591 }
11592 final long origId = Binder.clearCallingIdentity();
11593 bringDownServiceLocked(r, false);
11594 Binder.restoreCallingIdentity(origId);
11595 return true;
11596 }
11597 }
11598 return false;
11599 }
11600
11601 public void setServiceForeground(ComponentName className, IBinder token,
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011602 int id, Notification notification, boolean removeNotification) {
11603 final long origId = Binder.clearCallingIdentity();
11604 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011605 synchronized(this) {
11606 ServiceRecord r = findServiceLocked(className, token);
11607 if (r != null) {
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011608 if (id != 0) {
11609 if (notification == null) {
11610 throw new IllegalArgumentException("null notification");
11611 }
11612 if (r.foregroundId != id) {
11613 r.cancelNotification();
11614 r.foregroundId = id;
11615 }
11616 notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
11617 r.foregroundNoti = notification;
11618 r.isForeground = true;
11619 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011620 if (r.app != null) {
11621 updateServiceForegroundLocked(r.app, true);
11622 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011623 } else {
11624 if (r.isForeground) {
11625 r.isForeground = false;
11626 if (r.app != null) {
Dianne Hackborn8633e682010-04-22 16:03:41 -070011627 updateLruProcessLocked(r.app, false, true);
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011628 updateServiceForegroundLocked(r.app, true);
11629 }
11630 }
11631 if (removeNotification) {
11632 r.cancelNotification();
11633 r.foregroundId = 0;
11634 r.foregroundNoti = null;
11635 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011636 }
11637 }
11638 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011639 } finally {
11640 Binder.restoreCallingIdentity(origId);
11641 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011642 }
11643
11644 public void updateServiceForegroundLocked(ProcessRecord proc, boolean oomAdj) {
11645 boolean anyForeground = false;
Dianne Hackborn860755f2010-06-03 18:47:52 -070011646 for (ServiceRecord sr : proc.services) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011647 if (sr.isForeground) {
11648 anyForeground = true;
11649 break;
11650 }
11651 }
11652 if (anyForeground != proc.foregroundServices) {
11653 proc.foregroundServices = anyForeground;
11654 if (oomAdj) {
11655 updateOomAdjLocked();
11656 }
11657 }
11658 }
11659
11660 public int bindService(IApplicationThread caller, IBinder token,
11661 Intent service, String resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011662 IServiceConnection connection, int flags, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011663 enforceNotIsolatedCaller("bindService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011664 // Refuse possible leaked file descriptors
11665 if (service != null && service.hasFileDescriptors() == true) {
11666 throw new IllegalArgumentException("File descriptors passed in Intent");
11667 }
11668
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011669 checkValidCaller(Binder.getCallingUid(), userId);
11670
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011671 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011672 if (DEBUG_SERVICE) Slog.v(TAG, "bindService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011673 + " type=" + resolvedType + " conn=" + connection.asBinder()
11674 + " flags=0x" + Integer.toHexString(flags));
Amith Yamasani742a6712011-05-04 14:49:28 -070011675 if (DEBUG_MU)
11676 Slog.i(TAG_MU, "bindService uid=" + Binder.getCallingUid() + " origUid="
11677 + Binder.getOrigCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011678 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11679 if (callerApp == null) {
11680 throw new SecurityException(
11681 "Unable to find app for caller " + caller
11682 + " (pid=" + Binder.getCallingPid()
11683 + ") when binding service " + service);
11684 }
11685
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011686 ActivityRecord activity = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011687 if (token != null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070011688 activity = mMainStack.isInStackLocked(token);
11689 if (activity == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011690 Slog.w(TAG, "Binding with unknown activity: " + token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011691 return 0;
11692 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011693 }
11694
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011695 int clientLabel = 0;
11696 PendingIntent clientIntent = null;
11697
11698 if (callerApp.info.uid == Process.SYSTEM_UID) {
11699 // Hacky kind of thing -- allow system stuff to tell us
11700 // what they are, so we can report this elsewhere for
11701 // others to know why certain services are running.
11702 try {
11703 clientIntent = (PendingIntent)service.getParcelableExtra(
11704 Intent.EXTRA_CLIENT_INTENT);
11705 } catch (RuntimeException e) {
11706 }
11707 if (clientIntent != null) {
11708 clientLabel = service.getIntExtra(Intent.EXTRA_CLIENT_LABEL, 0);
11709 if (clientLabel != 0) {
11710 // There are no useful extras in the intent, trash them.
11711 // System code calling with this stuff just needs to know
11712 // this will happen.
11713 service = service.cloneFilter();
11714 }
11715 }
11716 }
11717
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011718 ServiceLookupResult res =
11719 retrieveServiceLocked(service, resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011720 Binder.getCallingPid(), Binder.getCallingUid(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011721 if (res == null) {
11722 return 0;
11723 }
11724 if (res.record == null) {
11725 return -1;
11726 }
11727 ServiceRecord s = res.record;
11728
11729 final long origId = Binder.clearCallingIdentity();
11730
11731 if (unscheduleServiceRestartLocked(s)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011732 if (DEBUG_SERVICE) Slog.v(TAG, "BIND SERVICE WHILE RESTART PENDING: "
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011733 + s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011734 }
11735
11736 AppBindRecord b = s.retrieveAppBindingLocked(service, callerApp);
11737 ConnectionRecord c = new ConnectionRecord(b, activity,
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011738 connection, flags, clientLabel, clientIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011739
11740 IBinder binder = connection.asBinder();
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011741 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
11742 if (clist == null) {
11743 clist = new ArrayList<ConnectionRecord>();
11744 s.connections.put(binder, clist);
11745 }
11746 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011747 b.connections.add(c);
11748 if (activity != null) {
11749 if (activity.connections == null) {
11750 activity.connections = new HashSet<ConnectionRecord>();
11751 }
11752 activity.connections.add(c);
11753 }
11754 b.client.connections.add(c);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070011755 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
11756 b.client.hasAboveClient = true;
11757 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011758 clist = mServiceConnections.get(binder);
11759 if (clist == null) {
11760 clist = new ArrayList<ConnectionRecord>();
11761 mServiceConnections.put(binder, clist);
11762 }
11763 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011764
11765 if ((flags&Context.BIND_AUTO_CREATE) != 0) {
11766 s.lastActivity = SystemClock.uptimeMillis();
11767 if (!bringUpServiceLocked(s, service.getFlags(), false)) {
11768 return 0;
11769 }
11770 }
11771
11772 if (s.app != null) {
11773 // This could have made the service more important.
11774 updateOomAdjLocked(s.app);
11775 }
11776
Joe Onorato8a9b2202010-02-26 18:56:32 -080011777 if (DEBUG_SERVICE) Slog.v(TAG, "Bind " + s + " with " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011778 + ": received=" + b.intent.received
11779 + " apps=" + b.intent.apps.size()
11780 + " doRebind=" + b.intent.doRebind);
11781
11782 if (s.app != null && b.intent.received) {
11783 // Service is already running, so we can immediately
11784 // publish the connection.
11785 try {
11786 c.conn.connected(s.name, b.intent.binder);
11787 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011788 Slog.w(TAG, "Failure sending service " + s.shortName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011789 + " to connection " + c.conn.asBinder()
11790 + " (in " + c.binding.client.processName + ")", e);
11791 }
11792
11793 // If this is the first app connected back to this binding,
11794 // and the service had previously asked to be told when
11795 // rebound, then do so.
11796 if (b.intent.apps.size() == 1 && b.intent.doRebind) {
11797 requestServiceBindingLocked(s, b.intent, true);
11798 }
11799 } else if (!b.intent.requested) {
11800 requestServiceBindingLocked(s, b.intent, false);
11801 }
11802
11803 Binder.restoreCallingIdentity(origId);
11804 }
11805
11806 return 1;
11807 }
11808
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070011809 void removeConnectionLocked(
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011810 ConnectionRecord c, ProcessRecord skipApp, ActivityRecord skipAct) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011811 IBinder binder = c.conn.asBinder();
11812 AppBindRecord b = c.binding;
11813 ServiceRecord s = b.service;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011814 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
11815 if (clist != null) {
11816 clist.remove(c);
11817 if (clist.size() == 0) {
11818 s.connections.remove(binder);
11819 }
11820 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011821 b.connections.remove(c);
11822 if (c.activity != null && c.activity != skipAct) {
11823 if (c.activity.connections != null) {
11824 c.activity.connections.remove(c);
11825 }
11826 }
11827 if (b.client != skipApp) {
11828 b.client.connections.remove(c);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070011829 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
11830 b.client.updateHasAboveClientLocked();
11831 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011832 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011833 clist = mServiceConnections.get(binder);
11834 if (clist != null) {
11835 clist.remove(c);
11836 if (clist.size() == 0) {
11837 mServiceConnections.remove(binder);
11838 }
11839 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011840
11841 if (b.connections.size() == 0) {
11842 b.intent.apps.remove(b.client);
11843 }
11844
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011845 if (!c.serviceDead) {
11846 if (DEBUG_SERVICE) Slog.v(TAG, "Disconnecting binding " + b.intent
11847 + ": shouldUnbind=" + b.intent.hasBound);
11848 if (s.app != null && s.app.thread != null && b.intent.apps.size() == 0
11849 && b.intent.hasBound) {
11850 try {
11851 bumpServiceExecutingLocked(s, "unbind");
11852 updateOomAdjLocked(s.app);
11853 b.intent.hasBound = false;
11854 // Assume the client doesn't want to know about a rebind;
11855 // we will deal with that later if it asks for one.
11856 b.intent.doRebind = false;
11857 s.app.thread.scheduleUnbindService(s, b.intent.intent.getIntent());
11858 } catch (Exception e) {
11859 Slog.w(TAG, "Exception when unbinding service " + s.shortName, e);
11860 serviceDoneExecutingLocked(s, true);
11861 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011862 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011863
11864 if ((c.flags&Context.BIND_AUTO_CREATE) != 0) {
11865 bringDownServiceLocked(s, false);
11866 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011867 }
11868 }
11869
11870 public boolean unbindService(IServiceConnection connection) {
11871 synchronized (this) {
11872 IBinder binder = connection.asBinder();
Joe Onorato8a9b2202010-02-26 18:56:32 -080011873 if (DEBUG_SERVICE) Slog.v(TAG, "unbindService: conn=" + binder);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011874 ArrayList<ConnectionRecord> clist = mServiceConnections.get(binder);
11875 if (clist == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011876 Slog.w(TAG, "Unbind failed: could not find connection for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011877 + connection.asBinder());
11878 return false;
11879 }
11880
11881 final long origId = Binder.clearCallingIdentity();
11882
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011883 while (clist.size() > 0) {
11884 ConnectionRecord r = clist.get(0);
11885 removeConnectionLocked(r, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011886
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011887 if (r.binding.service.app != null) {
11888 // This could have made the service less important.
11889 updateOomAdjLocked(r.binding.service.app);
11890 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011891 }
11892
11893 Binder.restoreCallingIdentity(origId);
11894 }
11895
11896 return true;
11897 }
11898
11899 public void publishService(IBinder token, Intent intent, IBinder service) {
11900 // Refuse possible leaked file descriptors
11901 if (intent != null && intent.hasFileDescriptors() == true) {
11902 throw new IllegalArgumentException("File descriptors passed in Intent");
11903 }
11904
11905 synchronized(this) {
11906 if (!(token instanceof ServiceRecord)) {
11907 throw new IllegalArgumentException("Invalid service token");
11908 }
11909 ServiceRecord r = (ServiceRecord)token;
11910
11911 final long origId = Binder.clearCallingIdentity();
11912
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011913 if (DEBUG_SERVICE) Slog.v(TAG, "PUBLISHING " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011914 + " " + intent + ": " + service);
11915 if (r != null) {
11916 Intent.FilterComparison filter
11917 = new Intent.FilterComparison(intent);
11918 IntentBindRecord b = r.bindings.get(filter);
11919 if (b != null && !b.received) {
11920 b.binder = service;
11921 b.requested = true;
11922 b.received = true;
11923 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011924 Iterator<ArrayList<ConnectionRecord>> it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011925 = r.connections.values().iterator();
11926 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011927 ArrayList<ConnectionRecord> clist = it.next();
11928 for (int i=0; i<clist.size(); i++) {
11929 ConnectionRecord c = clist.get(i);
11930 if (!filter.equals(c.binding.intent.intent)) {
11931 if (DEBUG_SERVICE) Slog.v(
11932 TAG, "Not publishing to: " + c);
11933 if (DEBUG_SERVICE) Slog.v(
11934 TAG, "Bound intent: " + c.binding.intent.intent);
11935 if (DEBUG_SERVICE) Slog.v(
11936 TAG, "Published intent: " + intent);
11937 continue;
11938 }
11939 if (DEBUG_SERVICE) Slog.v(TAG, "Publishing to: " + c);
11940 try {
11941 c.conn.connected(r.name, service);
11942 } catch (Exception e) {
11943 Slog.w(TAG, "Failure sending service " + r.name +
11944 " to connection " + c.conn.asBinder() +
11945 " (in " + c.binding.client.processName + ")", e);
11946 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011947 }
11948 }
11949 }
11950 }
11951
11952 serviceDoneExecutingLocked(r, mStoppingServices.contains(r));
11953
11954 Binder.restoreCallingIdentity(origId);
11955 }
11956 }
11957 }
11958
11959 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
11960 // Refuse possible leaked file descriptors
11961 if (intent != null && intent.hasFileDescriptors() == true) {
11962 throw new IllegalArgumentException("File descriptors passed in Intent");
11963 }
11964
11965 synchronized(this) {
11966 if (!(token instanceof ServiceRecord)) {
11967 throw new IllegalArgumentException("Invalid service token");
11968 }
11969 ServiceRecord r = (ServiceRecord)token;
11970
11971 final long origId = Binder.clearCallingIdentity();
11972
11973 if (r != null) {
11974 Intent.FilterComparison filter
11975 = new Intent.FilterComparison(intent);
11976 IntentBindRecord b = r.bindings.get(filter);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011977 if (DEBUG_SERVICE) Slog.v(TAG, "unbindFinished in " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011978 + " at " + b + ": apps="
11979 + (b != null ? b.apps.size() : 0));
Per Edelberg78f9fff2010-08-30 20:01:35 +020011980
11981 boolean inStopping = mStoppingServices.contains(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011982 if (b != null) {
Per Edelberg78f9fff2010-08-30 20:01:35 +020011983 if (b.apps.size() > 0 && !inStopping) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011984 // Applications have already bound since the last
11985 // unbind, so just rebind right here.
11986 requestServiceBindingLocked(r, b, true);
11987 } else {
11988 // Note to tell the service the next time there is
11989 // a new client.
11990 b.doRebind = true;
11991 }
11992 }
11993
Per Edelberg78f9fff2010-08-30 20:01:35 +020011994 serviceDoneExecutingLocked(r, inStopping);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011995
11996 Binder.restoreCallingIdentity(origId);
11997 }
11998 }
11999 }
12000
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012001 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012002 synchronized(this) {
12003 if (!(token instanceof ServiceRecord)) {
12004 throw new IllegalArgumentException("Invalid service token");
12005 }
12006 ServiceRecord r = (ServiceRecord)token;
12007 boolean inStopping = mStoppingServices.contains(token);
12008 if (r != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012009 if (r != token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012010 Slog.w(TAG, "Done executing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012011 + " with incorrect token: given " + token
12012 + ", expected " + r);
12013 return;
12014 }
12015
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012016 if (type == 1) {
12017 // This is a call from a service start... take care of
12018 // book-keeping.
12019 r.callStart = true;
12020 switch (res) {
12021 case Service.START_STICKY_COMPATIBILITY:
12022 case Service.START_STICKY: {
12023 // We are done with the associated start arguments.
12024 r.findDeliveredStart(startId, true);
12025 // Don't stop if killed.
12026 r.stopIfKilled = false;
12027 break;
12028 }
12029 case Service.START_NOT_STICKY: {
12030 // We are done with the associated start arguments.
12031 r.findDeliveredStart(startId, true);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070012032 if (r.getLastStartId() == startId) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012033 // There is no more work, and this service
12034 // doesn't want to hang around if killed.
12035 r.stopIfKilled = true;
12036 }
12037 break;
12038 }
12039 case Service.START_REDELIVER_INTENT: {
12040 // We'll keep this item until they explicitly
12041 // call stop for it, but keep track of the fact
12042 // that it was delivered.
12043 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
12044 if (si != null) {
12045 si.deliveryCount = 0;
12046 si.doneExecutingCount++;
12047 // Don't stop if killed.
12048 r.stopIfKilled = true;
12049 }
12050 break;
12051 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070012052 case Service.START_TASK_REMOVED_COMPLETE: {
12053 // Special processing for onTaskRemoved(). Don't
12054 // impact normal onStartCommand() processing.
12055 r.findDeliveredStart(startId, true);
12056 break;
12057 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012058 default:
12059 throw new IllegalArgumentException(
12060 "Unknown service start result: " + res);
12061 }
12062 if (res == Service.START_STICKY_COMPATIBILITY) {
12063 r.callStart = false;
12064 }
12065 }
Amith Yamasani742a6712011-05-04 14:49:28 -070012066 if (DEBUG_MU)
12067 Slog.v(TAG_MU, "before serviceDontExecutingLocked, uid="
12068 + Binder.getOrigCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012069 final long origId = Binder.clearCallingIdentity();
12070 serviceDoneExecutingLocked(r, inStopping);
12071 Binder.restoreCallingIdentity(origId);
12072 } else {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012073 Slog.w(TAG, "Done executing unknown service from pid "
12074 + Binder.getCallingPid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012075 }
12076 }
12077 }
12078
12079 public void serviceDoneExecutingLocked(ServiceRecord r, boolean inStopping) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012080 if (DEBUG_SERVICE) Slog.v(TAG, "<<< DONE EXECUTING " + r
12081 + ": nesting=" + r.executeNesting
12082 + ", inStopping=" + inStopping + ", app=" + r.app);
Dianne Hackborn287952c2010-09-22 22:34:31 -070012083 else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG, "<<< DONE EXECUTING " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012084 r.executeNesting--;
12085 if (r.executeNesting <= 0 && r.app != null) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012086 if (DEBUG_SERVICE) Slog.v(TAG,
12087 "Nesting at 0 of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012088 r.app.executingServices.remove(r);
12089 if (r.app.executingServices.size() == 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012090 if (DEBUG_SERVICE || DEBUG_SERVICE_EXECUTING) Slog.v(TAG,
12091 "No more executingServices of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012092 mHandler.removeMessages(SERVICE_TIMEOUT_MSG, r.app);
12093 }
12094 if (inStopping) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012095 if (DEBUG_SERVICE) Slog.v(TAG,
12096 "doneExecuting remove stopping " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012097 mStoppingServices.remove(r);
Mattias Petersson3996b412010-10-27 09:32:51 +020012098 r.bindings.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012099 }
12100 updateOomAdjLocked(r.app);
12101 }
12102 }
12103
12104 void serviceTimeout(ProcessRecord proc) {
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012105 String anrMessage = null;
12106
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012107 synchronized(this) {
12108 if (proc.executingServices.size() == 0 || proc.thread == null) {
12109 return;
12110 }
12111 long maxTime = SystemClock.uptimeMillis() - SERVICE_TIMEOUT;
12112 Iterator<ServiceRecord> it = proc.executingServices.iterator();
12113 ServiceRecord timeout = null;
12114 long nextTime = 0;
12115 while (it.hasNext()) {
12116 ServiceRecord sr = it.next();
12117 if (sr.executingStart < maxTime) {
12118 timeout = sr;
12119 break;
12120 }
12121 if (sr.executingStart > nextTime) {
12122 nextTime = sr.executingStart;
12123 }
12124 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012125 if (timeout != null && mLruProcesses.contains(proc)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012126 Slog.w(TAG, "Timeout executing service: " + timeout);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012127 anrMessage = "Executing service " + timeout.shortName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012128 } else {
12129 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
12130 msg.obj = proc;
12131 mHandler.sendMessageAtTime(msg, nextTime+SERVICE_TIMEOUT);
12132 }
12133 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012134
12135 if (anrMessage != null) {
12136 appNotResponding(proc, null, null, anrMessage);
12137 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012138 }
12139
12140 // =========================================================
Christopher Tate181fafa2009-05-14 11:12:14 -070012141 // BACKUP AND RESTORE
12142 // =========================================================
12143
12144 // Cause the target app to be launched if necessary and its backup agent
12145 // instantiated. The backup agent will invoke backupAgentCreated() on the
12146 // activity manager to announce its creation.
12147 public boolean bindBackupAgent(ApplicationInfo app, int backupMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012148 if (DEBUG_BACKUP) Slog.v(TAG, "startBackupAgent: app=" + app + " mode=" + backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070012149 enforceCallingPermission("android.permission.BACKUP", "startBackupAgent");
12150
12151 synchronized(this) {
12152 // !!! TODO: currently no check here that we're already bound
12153 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
12154 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
12155 synchronized (stats) {
12156 ss = stats.getServiceStatsLocked(app.uid, app.packageName, app.name);
12157 }
12158
Dianne Hackborne7f97212011-02-24 14:40:20 -080012159 // Backup agent is now in use, its package can't be stopped.
12160 try {
12161 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -070012162 app.packageName, false, UserId.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -080012163 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080012164 } catch (IllegalArgumentException e) {
12165 Slog.w(TAG, "Failed trying to unstop package "
12166 + app.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080012167 }
12168
Christopher Tate181fafa2009-05-14 11:12:14 -070012169 BackupRecord r = new BackupRecord(ss, app, backupMode);
Christopher Tate4a627c72011-04-01 14:43:32 -070012170 ComponentName hostingName = (backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL)
12171 ? new ComponentName(app.packageName, app.backupAgentName)
12172 : new ComponentName("android", "FullBackupAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -070012173 // startProcessLocked() returns existing proc's record if it's already running
12174 ProcessRecord proc = startProcessLocked(app.processName, app,
Dianne Hackborna0c283e2012-02-09 10:47:01 -080012175 false, 0, "backup", hostingName, false, false);
Christopher Tate181fafa2009-05-14 11:12:14 -070012176 if (proc == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012177 Slog.e(TAG, "Unable to start backup agent process " + r);
Christopher Tate181fafa2009-05-14 11:12:14 -070012178 return false;
12179 }
12180
12181 r.app = proc;
12182 mBackupTarget = r;
12183 mBackupAppName = app.packageName;
12184
Christopher Tate6fa95972009-06-05 18:43:55 -070012185 // Try not to kill the process during backup
12186 updateOomAdjLocked(proc);
12187
Christopher Tate181fafa2009-05-14 11:12:14 -070012188 // If the process is already attached, schedule the creation of the backup agent now.
12189 // If it is not yet live, this will be done when it attaches to the framework.
12190 if (proc.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012191 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc already running: " + proc);
Christopher Tate181fafa2009-05-14 11:12:14 -070012192 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040012193 proc.thread.scheduleCreateBackupAgent(app,
12194 compatibilityInfoForPackageLocked(app), backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070012195 } catch (RemoteException e) {
Christopher Tate436344a2009-09-30 16:17:37 -070012196 // Will time out on the backup manager side
Christopher Tate181fafa2009-05-14 11:12:14 -070012197 }
12198 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012199 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc not running, waiting for attach");
Christopher Tate181fafa2009-05-14 11:12:14 -070012200 }
12201 // Invariants: at this point, the target app process exists and the application
12202 // is either already running or in the process of coming up. mBackupTarget and
12203 // mBackupAppName describe the app, so that when it binds back to the AM we
12204 // know that it's scheduled for a backup-agent operation.
12205 }
12206
12207 return true;
12208 }
12209
12210 // A backup agent has just come up
12211 public void backupAgentCreated(String agentPackageName, IBinder agent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012212 if (DEBUG_BACKUP) Slog.v(TAG, "backupAgentCreated: " + agentPackageName
Christopher Tate181fafa2009-05-14 11:12:14 -070012213 + " = " + agent);
12214
12215 synchronized(this) {
12216 if (!agentPackageName.equals(mBackupAppName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012217 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
Christopher Tate181fafa2009-05-14 11:12:14 -070012218 return;
12219 }
Dianne Hackborn06740692010-09-22 22:46:21 -070012220 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012221
Dianne Hackborn06740692010-09-22 22:46:21 -070012222 long oldIdent = Binder.clearCallingIdentity();
12223 try {
12224 IBackupManager bm = IBackupManager.Stub.asInterface(
12225 ServiceManager.getService(Context.BACKUP_SERVICE));
12226 bm.agentConnected(agentPackageName, agent);
12227 } catch (RemoteException e) {
12228 // can't happen; the backup manager service is local
12229 } catch (Exception e) {
12230 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: ");
12231 e.printStackTrace();
12232 } finally {
12233 Binder.restoreCallingIdentity(oldIdent);
Christopher Tate181fafa2009-05-14 11:12:14 -070012234 }
12235 }
12236
12237 // done with this agent
12238 public void unbindBackupAgent(ApplicationInfo appInfo) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012239 if (DEBUG_BACKUP) Slog.v(TAG, "unbindBackupAgent: " + appInfo);
Christopher Tate8a27f922009-06-26 11:49:18 -070012240 if (appInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012241 Slog.w(TAG, "unbind backup agent for null app");
Christopher Tate8a27f922009-06-26 11:49:18 -070012242 return;
12243 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012244
12245 synchronized(this) {
Christopher Tate8a27f922009-06-26 11:49:18 -070012246 if (mBackupAppName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012247 Slog.w(TAG, "Unbinding backup agent with no active backup");
Christopher Tate8a27f922009-06-26 11:49:18 -070012248 return;
12249 }
12250
Christopher Tate181fafa2009-05-14 11:12:14 -070012251 if (!mBackupAppName.equals(appInfo.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012252 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
Christopher Tate181fafa2009-05-14 11:12:14 -070012253 return;
12254 }
12255
Christopher Tate6fa95972009-06-05 18:43:55 -070012256 ProcessRecord proc = mBackupTarget.app;
12257 mBackupTarget = null;
12258 mBackupAppName = null;
12259
12260 // Not backing this app up any more; reset its OOM adjustment
12261 updateOomAdjLocked(proc);
12262
Christopher Tatec7b31e32009-06-10 15:49:30 -070012263 // If the app crashed during backup, 'thread' will be null here
12264 if (proc.thread != null) {
12265 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040012266 proc.thread.scheduleDestroyBackupAgent(appInfo,
12267 compatibilityInfoForPackageLocked(appInfo));
Christopher Tatec7b31e32009-06-10 15:49:30 -070012268 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012269 Slog.e(TAG, "Exception when unbinding backup agent:");
Christopher Tatec7b31e32009-06-10 15:49:30 -070012270 e.printStackTrace();
12271 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012272 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012273 }
12274 }
12275 // =========================================================
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012276 // BROADCASTS
12277 // =========================================================
12278
Josh Bartel7f208742010-02-25 11:01:44 -060012279 private final List getStickiesLocked(String action, IntentFilter filter,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012280 List cur) {
12281 final ContentResolver resolver = mContext.getContentResolver();
12282 final ArrayList<Intent> list = mStickyBroadcasts.get(action);
12283 if (list == null) {
12284 return cur;
12285 }
12286 int N = list.size();
12287 for (int i=0; i<N; i++) {
12288 Intent intent = list.get(i);
12289 if (filter.match(resolver, intent, true, TAG) >= 0) {
12290 if (cur == null) {
12291 cur = new ArrayList<Intent>();
12292 }
12293 cur.add(intent);
12294 }
12295 }
12296 return cur;
12297 }
12298
Christopher Tatef46723b2012-01-26 14:19:24 -080012299 boolean isPendingBroadcastProcessLocked(int pid) {
12300 return mFgBroadcastQueue.isPendingBroadcastProcessLocked(pid)
12301 || mBgBroadcastQueue.isPendingBroadcastProcessLocked(pid);
12302 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012303
Christopher Tatef46723b2012-01-26 14:19:24 -080012304 void skipPendingBroadcastLocked(int pid) {
12305 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
12306 for (BroadcastQueue queue : mBroadcastQueues) {
12307 queue.skipPendingBroadcastLocked(pid);
12308 }
12309 }
12310
12311 // The app just attached; send any pending broadcasts that it should receive
12312 boolean sendPendingBroadcastsLocked(ProcessRecord app) {
12313 boolean didSomething = false;
12314 for (BroadcastQueue queue : mBroadcastQueues) {
12315 didSomething |= queue.sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012316 }
Christopher Tatef46723b2012-01-26 14:19:24 -080012317 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012318 }
12319
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012320 public Intent registerReceiver(IApplicationThread caller, String callerPackage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012321 IIntentReceiver receiver, IntentFilter filter, String permission) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012322 enforceNotIsolatedCaller("registerReceiver");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012323 synchronized(this) {
12324 ProcessRecord callerApp = null;
12325 if (caller != null) {
12326 callerApp = getRecordForAppLocked(caller);
12327 if (callerApp == null) {
12328 throw new SecurityException(
12329 "Unable to find app for caller " + caller
12330 + " (pid=" + Binder.getCallingPid()
12331 + ") when registering receiver " + receiver);
12332 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012333 if (callerApp.info.uid != Process.SYSTEM_UID &&
12334 !callerApp.pkgList.contains(callerPackage)) {
12335 throw new SecurityException("Given caller package " + callerPackage
12336 + " is not running in process " + callerApp);
12337 }
12338 } else {
12339 callerPackage = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012340 }
12341
12342 List allSticky = null;
12343
12344 // Look for any matching sticky broadcasts...
12345 Iterator actions = filter.actionsIterator();
12346 if (actions != null) {
12347 while (actions.hasNext()) {
12348 String action = (String)actions.next();
Josh Bartel7f208742010-02-25 11:01:44 -060012349 allSticky = getStickiesLocked(action, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012350 }
12351 } else {
Josh Bartel7f208742010-02-25 11:01:44 -060012352 allSticky = getStickiesLocked(null, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012353 }
12354
12355 // The first sticky in the list is returned directly back to
12356 // the client.
12357 Intent sticky = allSticky != null ? (Intent)allSticky.get(0) : null;
12358
Joe Onorato8a9b2202010-02-26 18:56:32 -080012359 if (DEBUG_BROADCAST) Slog.v(TAG, "Register receiver " + filter
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012360 + ": " + sticky);
12361
12362 if (receiver == null) {
12363 return sticky;
12364 }
12365
12366 ReceiverList rl
12367 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
12368 if (rl == null) {
12369 rl = new ReceiverList(this, callerApp,
12370 Binder.getCallingPid(),
12371 Binder.getCallingUid(), receiver);
12372 if (rl.app != null) {
12373 rl.app.receivers.add(rl);
12374 } else {
12375 try {
12376 receiver.asBinder().linkToDeath(rl, 0);
12377 } catch (RemoteException e) {
12378 return sticky;
12379 }
12380 rl.linkedToDeath = true;
12381 }
12382 mRegisteredReceivers.put(receiver.asBinder(), rl);
12383 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012384 BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage, permission);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012385 rl.add(bf);
12386 if (!bf.debugCheck()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012387 Slog.w(TAG, "==> For Dynamic broadast");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012388 }
12389 mReceiverResolver.addFilter(bf);
12390
12391 // Enqueue broadcasts for all existing stickies that match
12392 // this filter.
12393 if (allSticky != null) {
12394 ArrayList receivers = new ArrayList();
12395 receivers.add(bf);
12396
12397 int N = allSticky.size();
12398 for (int i=0; i<N; i++) {
12399 Intent intent = (Intent)allSticky.get(i);
Christopher Tatef46723b2012-01-26 14:19:24 -080012400 BroadcastQueue queue = broadcastQueueForIntent(intent);
12401 BroadcastRecord r = new BroadcastRecord(queue, intent, null,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012402 null, -1, -1, null, receivers, null, 0, null, null,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012403 false, true, true);
Christopher Tatef46723b2012-01-26 14:19:24 -080012404 queue.enqueueParallelBroadcastLocked(r);
12405 queue.scheduleBroadcastsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012406 }
12407 }
12408
12409 return sticky;
12410 }
12411 }
12412
12413 public void unregisterReceiver(IIntentReceiver receiver) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012414 if (DEBUG_BROADCAST) Slog.v(TAG, "Unregister receiver: " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012415
Christopher Tatef46723b2012-01-26 14:19:24 -080012416 final long origId = Binder.clearCallingIdentity();
12417 try {
12418 boolean doTrim = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012419
Christopher Tatef46723b2012-01-26 14:19:24 -080012420 synchronized(this) {
12421 ReceiverList rl
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012422 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
Christopher Tatef46723b2012-01-26 14:19:24 -080012423 if (rl != null) {
12424 if (rl.curBroadcast != null) {
12425 BroadcastRecord r = rl.curBroadcast;
12426 final boolean doNext = finishReceiverLocked(
12427 receiver.asBinder(), r.resultCode, r.resultData,
12428 r.resultExtras, r.resultAbort, true);
12429 if (doNext) {
12430 doTrim = true;
12431 r.queue.processNextBroadcast(false);
12432 }
12433 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012434
Christopher Tatef46723b2012-01-26 14:19:24 -080012435 if (rl.app != null) {
12436 rl.app.receivers.remove(rl);
12437 }
12438 removeReceiverLocked(rl);
12439 if (rl.linkedToDeath) {
12440 rl.linkedToDeath = false;
12441 rl.receiver.asBinder().unlinkToDeath(rl, 0);
12442 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012443 }
12444 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012445
Christopher Tatef46723b2012-01-26 14:19:24 -080012446 // If we actually concluded any broadcasts, we might now be able
12447 // to trim the recipients' apps from our working set
12448 if (doTrim) {
12449 trimApplications();
12450 return;
12451 }
12452
12453 } finally {
12454 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012455 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012456 }
12457
12458 void removeReceiverLocked(ReceiverList rl) {
12459 mRegisteredReceivers.remove(rl.receiver.asBinder());
12460 int N = rl.size();
12461 for (int i=0; i<N; i++) {
12462 mReceiverResolver.removeFilter(rl.get(i));
12463 }
12464 }
12465
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012466 private final void sendPackageBroadcastLocked(int cmd, String[] packages) {
12467 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
12468 ProcessRecord r = mLruProcesses.get(i);
12469 if (r.thread != null) {
12470 try {
12471 r.thread.dispatchPackageBroadcast(cmd, packages);
12472 } catch (RemoteException ex) {
12473 }
12474 }
12475 }
12476 }
12477
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012478 private final int broadcastIntentLocked(ProcessRecord callerApp,
12479 String callerPackage, Intent intent, String resolvedType,
12480 IIntentReceiver resultTo, int resultCode, String resultData,
12481 Bundle map, String requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070012482 boolean ordered, boolean sticky, int callingPid, int callingUid,
12483 int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012484 intent = new Intent(intent);
12485
Dianne Hackborne7f97212011-02-24 14:40:20 -080012486 // By default broadcasts do not go to stopped apps.
12487 intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
12488
Joe Onorato8a9b2202010-02-26 18:56:32 -080012489 if (DEBUG_BROADCAST_LIGHT) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012490 TAG, (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
Amith Yamasani13593602012-03-22 16:16:17 -070012491 + " ordered=" + ordered + " userid=" + userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012492 if ((resultTo != null) && !ordered) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012493 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012494 }
12495
12496 // Handle special intents: if this broadcast is from the package
12497 // manager about a package being removed, we need to remove all of
12498 // its activities from the history stack.
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012499 final boolean uidRemoved = Intent.ACTION_UID_REMOVED.equals(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012500 intent.getAction());
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012501 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())
12502 || Intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction())
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080012503 || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012504 || uidRemoved) {
12505 if (checkComponentPermission(
12506 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080012507 callingPid, callingUid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012508 == PackageManager.PERMISSION_GRANTED) {
12509 if (uidRemoved) {
12510 final Bundle intentExtras = intent.getExtras();
12511 final int uid = intentExtras != null
12512 ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
12513 if (uid >= 0) {
12514 BatteryStatsImpl bs = mBatteryStatsService.getActiveStatistics();
12515 synchronized (bs) {
12516 bs.removeUidStatsLocked(uid);
12517 }
12518 }
12519 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012520 // If resources are unvailble just force stop all
12521 // those packages and flush the attribute cache as well.
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080012522 if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012523 String list[] = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
12524 if (list != null && (list.length > 0)) {
12525 for (String pkg : list) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070012526 forceStopPackageLocked(pkg, -1, false, true, true, false, userId);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012527 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012528 sendPackageBroadcastLocked(
12529 IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE, list);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012530 }
12531 } else {
12532 Uri data = intent.getData();
12533 String ssp;
12534 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
12535 if (!intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false)) {
12536 forceStopPackageLocked(ssp,
Amith Yamasani483f3b02012-03-13 16:08:00 -070012537 intent.getIntExtra(Intent.EXTRA_UID, -1), false, true, true,
12538 false, userId);
Dianne Hackbornde7faf62009-06-30 13:27:30 -070012539 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012540 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012541 sendPackageBroadcastLocked(IApplicationThread.PACKAGE_REMOVED,
12542 new String[] {ssp});
12543 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012544 }
12545 }
12546 }
12547 } else {
12548 String msg = "Permission Denial: " + intent.getAction()
12549 + " broadcast from " + callerPackage + " (pid=" + callingPid
12550 + ", uid=" + callingUid + ")"
12551 + " requires "
12552 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012553 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012554 throw new SecurityException(msg);
12555 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012556
12557 // Special case for adding a package: by default turn on compatibility
12558 // mode.
12559 } else if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -070012560 Uri data = intent.getData();
12561 String ssp;
12562 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
12563 mCompatModePackages.handlePackageAddedLocked(ssp,
12564 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false));
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012565 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012566 }
12567
12568 /*
12569 * If this is the time zone changed action, queue up a message that will reset the timezone
12570 * of all currently running processes. This message will get queued up before the broadcast
12571 * happens.
12572 */
12573 if (intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) {
12574 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
12575 }
12576
Robert Greenwalt03595d02010-11-02 14:08:23 -070012577 if (intent.ACTION_CLEAR_DNS_CACHE.equals(intent.getAction())) {
12578 mHandler.sendEmptyMessage(CLEAR_DNS_CACHE);
12579 }
12580
Robert Greenwalt434203a2010-10-11 16:00:27 -070012581 if (Proxy.PROXY_CHANGE_ACTION.equals(intent.getAction())) {
12582 ProxyProperties proxy = intent.getParcelableExtra("proxy");
12583 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY, proxy));
12584 }
12585
Dianne Hackborn854060af2009-07-09 18:14:31 -070012586 /*
12587 * Prevent non-system code (defined here to be non-persistent
12588 * processes) from sending protected broadcasts.
12589 */
12590 if (callingUid == Process.SYSTEM_UID || callingUid == Process.PHONE_UID
12591 || callingUid == Process.SHELL_UID || callingUid == 0) {
12592 // Always okay.
12593 } else if (callerApp == null || !callerApp.persistent) {
12594 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012595 if (AppGlobals.getPackageManager().isProtectedBroadcast(
Dianne Hackborn854060af2009-07-09 18:14:31 -070012596 intent.getAction())) {
12597 String msg = "Permission Denial: not allowed to send broadcast "
12598 + intent.getAction() + " from pid="
12599 + callingPid + ", uid=" + callingUid;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012600 Slog.w(TAG, msg);
Dianne Hackborn854060af2009-07-09 18:14:31 -070012601 throw new SecurityException(msg);
12602 }
12603 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012604 Slog.w(TAG, "Remote exception", e);
Dianne Hackborna4972e92012-03-14 10:38:05 -070012605 return ActivityManager.BROADCAST_SUCCESS;
Dianne Hackborn854060af2009-07-09 18:14:31 -070012606 }
12607 }
12608
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012609 // Add to the sticky list if requested.
12610 if (sticky) {
12611 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
12612 callingPid, callingUid)
12613 != PackageManager.PERMISSION_GRANTED) {
12614 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
12615 + callingPid + ", uid=" + callingUid
12616 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012617 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012618 throw new SecurityException(msg);
12619 }
12620 if (requiredPermission != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012621 Slog.w(TAG, "Can't broadcast sticky intent " + intent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012622 + " and enforce permission " + requiredPermission);
Dianne Hackborna4972e92012-03-14 10:38:05 -070012623 return ActivityManager.BROADCAST_STICKY_CANT_HAVE_PERMISSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012624 }
12625 if (intent.getComponent() != null) {
12626 throw new SecurityException(
12627 "Sticky broadcasts can't target a specific component");
12628 }
12629 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
12630 if (list == null) {
12631 list = new ArrayList<Intent>();
12632 mStickyBroadcasts.put(intent.getAction(), list);
12633 }
12634 int N = list.size();
12635 int i;
12636 for (i=0; i<N; i++) {
12637 if (intent.filterEquals(list.get(i))) {
12638 // This sticky already exists, replace it.
12639 list.set(i, new Intent(intent));
12640 break;
12641 }
12642 }
12643 if (i >= N) {
12644 list.add(new Intent(intent));
12645 }
12646 }
12647
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012648 // Figure out who all will receive this broadcast.
12649 List receivers = null;
12650 List<BroadcastFilter> registeredReceivers = null;
12651 try {
12652 if (intent.getComponent() != null) {
12653 // Broadcast is going to one specific receiver class...
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012654 ActivityInfo ai = AppGlobals.getPackageManager().
Amith Yamasani483f3b02012-03-13 16:08:00 -070012655 getReceiverInfo(intent.getComponent(), STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012656 if (ai != null) {
12657 receivers = new ArrayList();
12658 ResolveInfo ri = new ResolveInfo();
Amith Yamasani742a6712011-05-04 14:49:28 -070012659 ri.activityInfo = getActivityInfoForUser(ai, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012660 receivers.add(ri);
12661 }
12662 } else {
12663 // Need to resolve the intent to interested receivers...
12664 if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
12665 == 0) {
12666 receivers =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012667 AppGlobals.getPackageManager().queryIntentReceivers(
Amith Yamasani483f3b02012-03-13 16:08:00 -070012668 intent, resolvedType, STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012669 }
Amith Yamasani483f3b02012-03-13 16:08:00 -070012670 registeredReceivers = mReceiverResolver.queryIntent(intent, resolvedType, false,
12671 userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012672 }
12673 } catch (RemoteException ex) {
12674 // pm is in same process, this will never happen.
12675 }
12676
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012677 final boolean replacePending =
12678 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
12679
Joe Onorato8a9b2202010-02-26 18:56:32 -080012680 if (DEBUG_BROADCAST) Slog.v(TAG, "Enqueing broadcast: " + intent.getAction()
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012681 + " replacePending=" + replacePending);
12682
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012683 int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
12684 if (!ordered && NR > 0) {
12685 // If we are not serializing this broadcast, then send the
12686 // registered receivers separately so they don't wait for the
12687 // components to be launched.
Christopher Tatef46723b2012-01-26 14:19:24 -080012688 final BroadcastQueue queue = broadcastQueueForIntent(intent);
12689 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012690 callerPackage, callingPid, callingUid, requiredPermission,
12691 registeredReceivers, resultTo, resultCode, resultData, map,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012692 ordered, sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012693 if (DEBUG_BROADCAST) Slog.v(
Christopher Tatef46723b2012-01-26 14:19:24 -080012694 TAG, "Enqueueing parallel broadcast " + r);
12695 final boolean replaced = replacePending && queue.replaceParallelBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012696 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012697 queue.enqueueParallelBroadcastLocked(r);
12698 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012699 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012700 registeredReceivers = null;
12701 NR = 0;
12702 }
12703
12704 // Merge into one list.
12705 int ir = 0;
12706 if (receivers != null) {
12707 // A special case for PACKAGE_ADDED: do not allow the package
12708 // being added to see this broadcast. This prevents them from
12709 // using this as a back door to get run as soon as they are
12710 // installed. Maybe in the future we want to have a special install
12711 // broadcast or such for apps, but we'd like to deliberately make
12712 // this decision.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012713 String skipPackages[] = null;
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012714 if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
12715 || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
12716 || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012717 Uri data = intent.getData();
12718 if (data != null) {
12719 String pkgName = data.getSchemeSpecificPart();
12720 if (pkgName != null) {
12721 skipPackages = new String[] { pkgName };
12722 }
12723 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012724 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012725 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
The Android Open Source Project10592532009-03-18 17:39:46 -070012726 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012727 if (skipPackages != null && (skipPackages.length > 0)) {
12728 for (String skipPackage : skipPackages) {
12729 if (skipPackage != null) {
12730 int NT = receivers.size();
12731 for (int it=0; it<NT; it++) {
12732 ResolveInfo curt = (ResolveInfo)receivers.get(it);
12733 if (curt.activityInfo.packageName.equals(skipPackage)) {
12734 receivers.remove(it);
12735 it--;
12736 NT--;
12737 }
12738 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012739 }
12740 }
12741 }
12742
12743 int NT = receivers != null ? receivers.size() : 0;
12744 int it = 0;
12745 ResolveInfo curt = null;
12746 BroadcastFilter curr = null;
12747 while (it < NT && ir < NR) {
12748 if (curt == null) {
12749 curt = (ResolveInfo)receivers.get(it);
12750 }
12751 if (curr == null) {
12752 curr = registeredReceivers.get(ir);
12753 }
12754 if (curr.getPriority() >= curt.priority) {
12755 // Insert this broadcast record into the final list.
12756 receivers.add(it, curr);
12757 ir++;
12758 curr = null;
12759 it++;
12760 NT++;
12761 } else {
12762 // Skip to the next ResolveInfo in the final list.
12763 it++;
12764 curt = null;
12765 }
12766 }
12767 }
12768 while (ir < NR) {
12769 if (receivers == null) {
12770 receivers = new ArrayList();
12771 }
12772 receivers.add(registeredReceivers.get(ir));
12773 ir++;
12774 }
12775
12776 if ((receivers != null && receivers.size() > 0)
12777 || resultTo != null) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012778 BroadcastQueue queue = broadcastQueueForIntent(intent);
12779 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012780 callerPackage, callingPid, callingUid, requiredPermission,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012781 receivers, resultTo, resultCode, resultData, map, ordered,
12782 sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012783 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012784 TAG, "Enqueueing ordered broadcast " + r
Christopher Tatef46723b2012-01-26 14:19:24 -080012785 + ": prev had " + queue.mOrderedBroadcasts.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012786 if (DEBUG_BROADCAST) {
12787 int seq = r.intent.getIntExtra("seq", -1);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012788 Slog.i(TAG, "Enqueueing broadcast " + r.intent.getAction() + " seq=" + seq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012789 }
Christopher Tatef46723b2012-01-26 14:19:24 -080012790 boolean replaced = replacePending && queue.replaceOrderedBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012791 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012792 queue.enqueueOrderedBroadcastLocked(r);
12793 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012794 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012795 }
12796
Dianne Hackborna4972e92012-03-14 10:38:05 -070012797 return ActivityManager.BROADCAST_SUCCESS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012798 }
12799
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012800 final Intent verifyBroadcastLocked(Intent intent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012801 // Refuse possible leaked file descriptors
12802 if (intent != null && intent.hasFileDescriptors() == true) {
12803 throw new IllegalArgumentException("File descriptors passed in Intent");
12804 }
12805
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012806 int flags = intent.getFlags();
12807
12808 if (!mProcessesReady) {
12809 // if the caller really truly claims to know what they're doing, go
12810 // ahead and allow the broadcast without launching any receivers
12811 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
12812 intent = new Intent(intent);
12813 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
12814 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
12815 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
12816 + " before boot completion");
12817 throw new IllegalStateException("Cannot broadcast before boot completed");
12818 }
12819 }
12820
12821 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
12822 throw new IllegalArgumentException(
12823 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
12824 }
12825
12826 return intent;
12827 }
12828
12829 public final int broadcastIntent(IApplicationThread caller,
12830 Intent intent, String resolvedType, IIntentReceiver resultTo,
12831 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070012832 String requiredPermission, boolean serialized, boolean sticky, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012833 enforceNotIsolatedCaller("broadcastIntent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012834 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012835 intent = verifyBroadcastLocked(intent);
Dianne Hackborn9acc0302009-08-25 00:27:12 -070012836
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012837 final ProcessRecord callerApp = getRecordForAppLocked(caller);
12838 final int callingPid = Binder.getCallingPid();
12839 final int callingUid = Binder.getCallingUid();
12840 final long origId = Binder.clearCallingIdentity();
12841 int res = broadcastIntentLocked(callerApp,
12842 callerApp != null ? callerApp.info.packageName : null,
12843 intent, resolvedType, resultTo,
Amith Yamasani742a6712011-05-04 14:49:28 -070012844 resultCode, resultData, map, requiredPermission, serialized, sticky,
12845 callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012846 Binder.restoreCallingIdentity(origId);
12847 return res;
12848 }
12849 }
12850
12851 int broadcastIntentInPackage(String packageName, int uid,
12852 Intent intent, String resolvedType, IIntentReceiver resultTo,
12853 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070012854 String requiredPermission, boolean serialized, boolean sticky, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012855 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012856 intent = verifyBroadcastLocked(intent);
12857
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012858 final long origId = Binder.clearCallingIdentity();
12859 int res = broadcastIntentLocked(null, packageName, intent, resolvedType,
12860 resultTo, resultCode, resultData, map, requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070012861 serialized, sticky, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012862 Binder.restoreCallingIdentity(origId);
12863 return res;
12864 }
12865 }
12866
Amith Yamasani742a6712011-05-04 14:49:28 -070012867 // TODO: Use the userId; maybe mStickyBroadcasts need to be tied to the user.
12868 public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012869 // Refuse possible leaked file descriptors
12870 if (intent != null && intent.hasFileDescriptors() == true) {
12871 throw new IllegalArgumentException("File descriptors passed in Intent");
12872 }
12873
12874 synchronized(this) {
12875 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
12876 != PackageManager.PERMISSION_GRANTED) {
12877 String msg = "Permission Denial: unbroadcastIntent() from pid="
12878 + Binder.getCallingPid()
12879 + ", uid=" + Binder.getCallingUid()
12880 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012881 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012882 throw new SecurityException(msg);
12883 }
12884 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
12885 if (list != null) {
12886 int N = list.size();
12887 int i;
12888 for (i=0; i<N; i++) {
12889 if (intent.filterEquals(list.get(i))) {
12890 list.remove(i);
12891 break;
12892 }
12893 }
12894 }
12895 }
12896 }
12897
12898 private final boolean finishReceiverLocked(IBinder receiver, int resultCode,
12899 String resultData, Bundle resultExtras, boolean resultAbort,
12900 boolean explicit) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012901 final BroadcastRecord r = broadcastRecordForReceiverLocked(receiver);
12902 if (r == null) {
12903 Slog.w(TAG, "finishReceiver called but not found on queue");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012904 return false;
12905 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012906
Christopher Tatef46723b2012-01-26 14:19:24 -080012907 return r.queue.finishReceiverLocked(r, resultCode, resultData, resultExtras, resultAbort,
12908 explicit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012909 }
12910
12911 public void finishReceiver(IBinder who, int resultCode, String resultData,
12912 Bundle resultExtras, boolean resultAbort) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012913 if (DEBUG_BROADCAST) Slog.v(TAG, "Finish receiver: " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012914
12915 // Refuse possible leaked file descriptors
12916 if (resultExtras != null && resultExtras.hasFileDescriptors()) {
12917 throw new IllegalArgumentException("File descriptors passed in Bundle");
12918 }
12919
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012920 final long origId = Binder.clearCallingIdentity();
Christopher Tatef46723b2012-01-26 14:19:24 -080012921 try {
12922 boolean doNext = false;
12923 BroadcastRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012924
Christopher Tatef46723b2012-01-26 14:19:24 -080012925 synchronized(this) {
12926 r = broadcastRecordForReceiverLocked(who);
12927 if (r != null) {
12928 doNext = r.queue.finishReceiverLocked(r, resultCode,
12929 resultData, resultExtras, resultAbort, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012930 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012931 }
Jeff Brown4d94a762010-09-23 11:33:28 -070012932
Christopher Tatef46723b2012-01-26 14:19:24 -080012933 if (doNext) {
12934 r.queue.processNextBroadcast(false);
12935 }
12936 trimApplications();
12937 } finally {
12938 Binder.restoreCallingIdentity(origId);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012939 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012940 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012941
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012942 // =========================================================
12943 // INSTRUMENTATION
12944 // =========================================================
12945
12946 public boolean startInstrumentation(ComponentName className,
12947 String profileFile, int flags, Bundle arguments,
12948 IInstrumentationWatcher watcher) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012949 enforceNotIsolatedCaller("startInstrumentation");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012950 // Refuse possible leaked file descriptors
12951 if (arguments != null && arguments.hasFileDescriptors()) {
12952 throw new IllegalArgumentException("File descriptors passed in Bundle");
12953 }
12954
12955 synchronized(this) {
12956 InstrumentationInfo ii = null;
12957 ApplicationInfo ai = null;
12958 try {
12959 ii = mContext.getPackageManager().getInstrumentationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070012960 className, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012961 ai = mContext.getPackageManager().getApplicationInfo(
Amith Yamasani483f3b02012-03-13 16:08:00 -070012962 ii.targetPackage, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012963 } catch (PackageManager.NameNotFoundException e) {
12964 }
12965 if (ii == null) {
12966 reportStartInstrumentationFailure(watcher, className,
12967 "Unable to find instrumentation info for: " + className);
12968 return false;
12969 }
12970 if (ai == null) {
12971 reportStartInstrumentationFailure(watcher, className,
12972 "Unable to find instrumentation target package: " + ii.targetPackage);
12973 return false;
12974 }
12975
12976 int match = mContext.getPackageManager().checkSignatures(
12977 ii.targetPackage, ii.packageName);
12978 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
12979 String msg = "Permission Denial: starting instrumentation "
12980 + className + " from pid="
12981 + Binder.getCallingPid()
12982 + ", uid=" + Binder.getCallingPid()
12983 + " not allowed because package " + ii.packageName
12984 + " does not have a signature matching the target "
12985 + ii.targetPackage;
12986 reportStartInstrumentationFailure(watcher, className, msg);
12987 throw new SecurityException(msg);
12988 }
12989
Amith Yamasani483f3b02012-03-13 16:08:00 -070012990 int userId = UserId.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012991 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -070012992 // Instrumentation can kill and relaunch even persistent processes
Amith Yamasani483f3b02012-03-13 16:08:00 -070012993 forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true, userId);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080012994 ProcessRecord app = addAppLocked(ai, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012995 app.instrumentationClass = className;
Dianne Hackborn1655be42009-05-08 14:29:01 -070012996 app.instrumentationInfo = ai;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012997 app.instrumentationProfileFile = profileFile;
12998 app.instrumentationArguments = arguments;
12999 app.instrumentationWatcher = watcher;
13000 app.instrumentationResultClass = className;
13001 Binder.restoreCallingIdentity(origId);
13002 }
13003
13004 return true;
13005 }
13006
13007 /**
13008 * Report errors that occur while attempting to start Instrumentation. Always writes the
13009 * error to the logs, but if somebody is watching, send the report there too. This enables
13010 * the "am" command to report errors with more information.
13011 *
13012 * @param watcher The IInstrumentationWatcher. Null if there isn't one.
13013 * @param cn The component name of the instrumentation.
13014 * @param report The error report.
13015 */
13016 private void reportStartInstrumentationFailure(IInstrumentationWatcher watcher,
13017 ComponentName cn, String report) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013018 Slog.w(TAG, report);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013019 try {
13020 if (watcher != null) {
13021 Bundle results = new Bundle();
13022 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
13023 results.putString("Error", report);
13024 watcher.instrumentationStatus(cn, -1, results);
13025 }
13026 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013027 Slog.w(TAG, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013028 }
13029 }
13030
13031 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
13032 if (app.instrumentationWatcher != null) {
13033 try {
13034 // NOTE: IInstrumentationWatcher *must* be oneway here
13035 app.instrumentationWatcher.instrumentationFinished(
13036 app.instrumentationClass,
13037 resultCode,
13038 results);
13039 } catch (RemoteException e) {
13040 }
13041 }
13042 app.instrumentationWatcher = null;
13043 app.instrumentationClass = null;
Dianne Hackborn1655be42009-05-08 14:29:01 -070013044 app.instrumentationInfo = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013045 app.instrumentationProfileFile = null;
13046 app.instrumentationArguments = null;
13047
Amith Yamasani483f3b02012-03-13 16:08:00 -070013048 forceStopPackageLocked(app.processName, -1, false, false, true, true, app.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013049 }
13050
13051 public void finishInstrumentation(IApplicationThread target,
13052 int resultCode, Bundle results) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070013053 int userId = UserId.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013054 // Refuse possible leaked file descriptors
13055 if (results != null && results.hasFileDescriptors()) {
13056 throw new IllegalArgumentException("File descriptors passed in Intent");
13057 }
13058
13059 synchronized(this) {
13060 ProcessRecord app = getRecordForAppLocked(target);
13061 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013062 Slog.w(TAG, "finishInstrumentation: no app for " + target);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013063 return;
13064 }
13065 final long origId = Binder.clearCallingIdentity();
13066 finishInstrumentationLocked(app, resultCode, results);
13067 Binder.restoreCallingIdentity(origId);
13068 }
13069 }
13070
13071 // =========================================================
13072 // CONFIGURATION
13073 // =========================================================
13074
13075 public ConfigurationInfo getDeviceConfigurationInfo() {
13076 ConfigurationInfo config = new ConfigurationInfo();
13077 synchronized (this) {
13078 config.reqTouchScreen = mConfiguration.touchscreen;
13079 config.reqKeyboardType = mConfiguration.keyboard;
13080 config.reqNavigation = mConfiguration.navigation;
Dianne Hackbornfae76f52009-07-16 13:41:23 -070013081 if (mConfiguration.navigation == Configuration.NAVIGATION_DPAD
13082 || mConfiguration.navigation == Configuration.NAVIGATION_TRACKBALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013083 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
13084 }
Dianne Hackbornfae76f52009-07-16 13:41:23 -070013085 if (mConfiguration.keyboard != Configuration.KEYBOARD_UNDEFINED
13086 && mConfiguration.keyboard != Configuration.KEYBOARD_NOKEYS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013087 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
13088 }
Jack Palevichb90d28c2009-07-22 15:35:24 -070013089 config.reqGlEsVersion = GL_ES_VERSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013090 }
13091 return config;
13092 }
13093
13094 public Configuration getConfiguration() {
13095 Configuration ci;
13096 synchronized(this) {
13097 ci = new Configuration(mConfiguration);
13098 }
13099 return ci;
13100 }
13101
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013102 public void updatePersistentConfiguration(Configuration values) {
13103 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
13104 "updateConfiguration()");
13105 enforceCallingPermission(android.Manifest.permission.WRITE_SETTINGS,
13106 "updateConfiguration()");
13107 if (values == null) {
13108 throw new NullPointerException("Configuration must not be null");
13109 }
13110
13111 synchronized(this) {
13112 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn813075a62011-11-14 17:45:19 -080013113 updateConfigurationLocked(values, null, true, false);
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013114 Binder.restoreCallingIdentity(origId);
13115 }
13116 }
13117
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013118 public void updateConfiguration(Configuration values) {
13119 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
13120 "updateConfiguration()");
13121
13122 synchronized(this) {
13123 if (values == null && mWindowManager != null) {
13124 // sentinel: fetch the current configuration from the window manager
13125 values = mWindowManager.computeNewConfiguration();
13126 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013127
13128 if (mWindowManager != null) {
13129 mProcessList.applyDisplaySize(mWindowManager);
13130 }
13131
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013132 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013133 if (values != null) {
13134 Settings.System.clearConfiguration(values);
13135 }
Dianne Hackborn813075a62011-11-14 17:45:19 -080013136 updateConfigurationLocked(values, null, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013137 Binder.restoreCallingIdentity(origId);
13138 }
13139 }
13140
13141 /**
13142 * Do either or both things: (1) change the current configuration, and (2)
13143 * make sure the given activity is running with the (now) current
13144 * configuration. Returns true if the activity has been left running, or
13145 * false if <var>starting</var> is being destroyed to match the new
13146 * configuration.
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013147 * @param persistent TODO
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013148 */
Dianne Hackborna573f6a2012-02-09 16:12:18 -080013149 boolean updateConfigurationLocked(Configuration values,
Dianne Hackborn813075a62011-11-14 17:45:19 -080013150 ActivityRecord starting, boolean persistent, boolean initLocale) {
Mike Lockwood3a74bd32011-08-12 13:55:22 -070013151 // do nothing if we are headless
13152 if (mHeadless) return true;
13153
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013154 int changes = 0;
13155
13156 boolean kept = true;
13157
13158 if (values != null) {
13159 Configuration newConfig = new Configuration(mConfiguration);
13160 changes = newConfig.updateFrom(values);
13161 if (changes != 0) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013162 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013163 Slog.i(TAG, "Updating configuration to: " + values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013164 }
13165
Doug Zongker2bec3d42009-12-04 12:52:44 -080013166 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013167
Dianne Hackborn813075a62011-11-14 17:45:19 -080013168 if (values.locale != null && !initLocale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013169 saveLocaleLocked(values.locale,
13170 !values.locale.equals(mConfiguration.locale),
13171 values.userSetLocale);
13172 }
13173
Dianne Hackborne36d6e22010-02-17 19:46:25 -080013174 mConfigurationSeq++;
13175 if (mConfigurationSeq <= 0) {
13176 mConfigurationSeq = 1;
13177 }
13178 newConfig.seq = mConfigurationSeq;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013179 mConfiguration = newConfig;
Joe Onorato8a9b2202010-02-26 18:56:32 -080013180 Slog.i(TAG, "Config changed: " + newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013181
13182 final Configuration configCopy = new Configuration(mConfiguration);
Joe Onorato54a4a412011-11-02 20:50:08 -070013183
13184 // TODO: If our config changes, should we auto dismiss any currently
13185 // showing dialogs?
13186 mShowDialogs = shouldShowDialogs(newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013187
Dianne Hackborn826d17c2009-11-12 12:55:51 -080013188 AttributeCache ac = AttributeCache.instance();
13189 if (ac != null) {
Dianne Hackborn813075a62011-11-14 17:45:19 -080013190 ac.updateConfiguration(configCopy);
Dianne Hackborn826d17c2009-11-12 12:55:51 -080013191 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013192
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070013193 // Make sure all resources in our process are updated
13194 // right now, so that anyone who is going to retrieve
13195 // resource values after we return will be sure to get
13196 // the new ones. This is especially important during
13197 // boot, where the first config change needs to guarantee
13198 // all resources have that config before following boot
13199 // code is executed.
Dianne Hackborn813075a62011-11-14 17:45:19 -080013200 mSystemThread.applyConfigurationToResources(configCopy);
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070013201
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013202 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080013203 Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013204 msg.obj = new Configuration(configCopy);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080013205 mHandler.sendMessage(msg);
13206 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013207
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013208 for (int i=mLruProcesses.size()-1; i>=0; i--) {
13209 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013210 try {
13211 if (app.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013212 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending to proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013213 + app.processName + " new config " + mConfiguration);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013214 app.thread.scheduleConfigurationChanged(configCopy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013215 }
13216 } catch (Exception e) {
13217 }
13218 }
13219 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080013220 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
13221 | Intent.FLAG_RECEIVER_REPLACE_PENDING);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013222 broadcastIntentLocked(null, null, intent, null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070013223 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080013224 if ((changes&ActivityInfo.CONFIG_LOCALE) != 0) {
13225 broadcastIntentLocked(null, null,
13226 new Intent(Intent.ACTION_LOCALE_CHANGED),
13227 null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070013228 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080013229 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013230 }
13231 }
13232
13233 if (changes != 0 && starting == null) {
13234 // If the configuration changed, and the caller is not already
13235 // in the process of starting an activity, then find the top
13236 // activity to check if its configuration needs to change.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013237 starting = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013238 }
13239
13240 if (starting != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013241 kept = mMainStack.ensureActivityConfigurationLocked(starting, changes);
Dianne Hackborn5f4d6432010-12-21 20:40:11 -080013242 // And we need to make sure at this point that all other activities
13243 // are made visible with the correct configuration.
13244 mMainStack.ensureActivitiesVisibleLocked(starting, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013245 }
13246
Dianne Hackborne36d6e22010-02-17 19:46:25 -080013247 if (values != null && mWindowManager != null) {
13248 mWindowManager.setNewConfiguration(mConfiguration);
13249 }
13250
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013251 return kept;
13252 }
Joe Onorato54a4a412011-11-02 20:50:08 -070013253
13254 /**
13255 * Decide based on the configuration whether we should shouw the ANR,
13256 * crash, etc dialogs. The idea is that if there is no affordnace to
13257 * press the on-screen buttons, we shouldn't show the dialog.
13258 *
13259 * A thought: SystemUI might also want to get told about this, the Power
13260 * dialog / global actions also might want different behaviors.
13261 */
13262 private static final boolean shouldShowDialogs(Configuration config) {
13263 return !(config.keyboard == Configuration.KEYBOARD_NOKEYS
13264 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH);
13265 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013266
13267 /**
13268 * Save the locale. You must be inside a synchronized (this) block.
13269 */
13270 private void saveLocaleLocked(Locale l, boolean isDiff, boolean isPersist) {
13271 if(isDiff) {
13272 SystemProperties.set("user.language", l.getLanguage());
13273 SystemProperties.set("user.region", l.getCountry());
13274 }
13275
13276 if(isPersist) {
13277 SystemProperties.set("persist.sys.language", l.getLanguage());
13278 SystemProperties.set("persist.sys.country", l.getCountry());
13279 SystemProperties.set("persist.sys.localevar", l.getVariant());
13280 }
13281 }
13282
13283 // =========================================================
13284 // LIFETIME MANAGEMENT
13285 // =========================================================
13286
Christopher Tatef46723b2012-01-26 14:19:24 -080013287 // Returns which broadcast queue the app is the current [or imminent] receiver
13288 // on, or 'null' if the app is not an active broadcast recipient.
13289 private BroadcastQueue isReceivingBroadcast(ProcessRecord app) {
13290 BroadcastRecord r = app.curReceiver;
13291 if (r != null) {
13292 return r.queue;
13293 }
13294
13295 // It's not the current receiver, but it might be starting up to become one
13296 synchronized (this) {
13297 for (BroadcastQueue queue : mBroadcastQueues) {
13298 r = queue.mPendingBroadcast;
13299 if (r != null && r.curApp == app) {
13300 // found it; report which queue it's in
13301 return queue;
13302 }
13303 }
13304 }
13305
13306 return null;
13307 }
13308
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013309 private final int computeOomAdjLocked(ProcessRecord app, int hiddenAdj,
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013310 ProcessRecord TOP_APP, boolean recursed, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013311 if (mAdjSeq == app.adjSeq) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013312 // This adjustment has already been computed. If we are calling
13313 // from the top, we may have already computed our adjustment with
13314 // an earlier hidden adjustment that isn't really for us... if
13315 // so, use the new hidden adjustment.
13316 if (!recursed && app.hidden) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013317 app.curAdj = app.curRawAdj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013318 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013319 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013320 }
13321
13322 if (app.thread == null) {
13323 app.adjSeq = mAdjSeq;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013324 app.curSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013325 return (app.curAdj=ProcessList.HIDDEN_APP_MAX_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013326 }
13327
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013328 app.adjTypeCode = ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN;
13329 app.adjSource = null;
13330 app.adjTarget = null;
13331 app.empty = false;
13332 app.hidden = false;
13333
13334 final int activitiesSize = app.activities.size();
13335
Dianne Hackborn7d608422011-08-07 16:24:18 -070013336 if (app.maxAdj <= ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013337 // The max adjustment doesn't allow this app to be anything
13338 // below foreground, so it is not worth doing work for it.
13339 app.adjType = "fixed";
13340 app.adjSeq = mAdjSeq;
13341 app.curRawAdj = app.maxAdj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013342 app.foregroundActivities = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013343 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013344 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013345 // System process can do UI, and when they do we want to have
13346 // them trim their memory after the user leaves the UI. To
13347 // facilitate this, here we need to determine whether or not it
13348 // is currently showing UI.
13349 app.systemNoUi = true;
13350 if (app == TOP_APP) {
13351 app.systemNoUi = false;
13352 } else if (activitiesSize > 0) {
13353 for (int j = 0; j < activitiesSize; j++) {
13354 final ActivityRecord r = app.activities.get(j);
13355 if (r.visible) {
13356 app.systemNoUi = false;
13357 break;
13358 }
13359 }
13360 }
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013361 return (app.curAdj=app.maxAdj);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013362 }
13363
13364 final boolean hadForegroundActivities = app.foregroundActivities;
13365
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013366 app.foregroundActivities = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013367 app.keeping = false;
13368 app.systemNoUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013369
The Android Open Source Project4df24232009-03-05 14:34:35 -080013370 // Determine the importance of the process, starting with most
13371 // important to least, and assign an appropriate OOM adjustment.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013372 int adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013373 int schedGroup;
Christopher Tatef46723b2012-01-26 14:19:24 -080013374 BroadcastQueue queue;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013375 if (app == TOP_APP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013376 // The last app on the list is the foreground app.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013377 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013378 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013379 app.adjType = "top-activity";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013380 app.foregroundActivities = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013381 } else if (app.instrumentationClass != null) {
13382 // Don't want to kill running instrumentation.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013383 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013384 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013385 app.adjType = "instrumentation";
Christopher Tatef46723b2012-01-26 14:19:24 -080013386 } else if ((queue = isReceivingBroadcast(app)) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013387 // An app that is currently receiving a broadcast also
Christopher Tatef46723b2012-01-26 14:19:24 -080013388 // counts as being in the foreground for OOM killer purposes.
13389 // It's placed in a sched group based on the nature of the
13390 // broadcast as reflected by which queue it's active in.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013391 adj = ProcessList.FOREGROUND_APP_ADJ;
Christopher Tatef46723b2012-01-26 14:19:24 -080013392 schedGroup = (queue == mFgBroadcastQueue)
13393 ? Process.THREAD_GROUP_DEFAULT : Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013394 app.adjType = "broadcast";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013395 } else if (app.executingServices.size() > 0) {
13396 // An app that is currently executing a service callback also
13397 // counts as being in the foreground.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013398 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013399 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013400 app.adjType = "exec-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013401 } else if (activitiesSize > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013402 // This app is in the background with paused activities.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013403 // We inspect activities to potentially upgrade adjustment further below.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013404 adj = hiddenAdj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013405 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013406 app.hidden = true;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013407 app.adjType = "bg-activities";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013408 } else {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013409 // A very not-needed process. If this is lower in the lru list,
13410 // we will push it in to the empty bucket.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013411 adj = hiddenAdj;
13412 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013413 app.hidden = true;
13414 app.empty = true;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013415 app.adjType = "bg-empty";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013416 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013417
13418 // Examine all activities if not already foreground.
13419 if (!app.foregroundActivities && activitiesSize > 0) {
13420 for (int j = 0; j < activitiesSize; j++) {
13421 final ActivityRecord r = app.activities.get(j);
13422 if (r.visible) {
13423 // App has a visible activity; only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013424 if (adj > ProcessList.VISIBLE_APP_ADJ) {
13425 adj = ProcessList.VISIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013426 app.adjType = "visible";
13427 }
13428 schedGroup = Process.THREAD_GROUP_DEFAULT;
13429 app.hidden = false;
13430 app.foregroundActivities = true;
13431 break;
13432 } else if (r.state == ActivityState.PAUSING || r.state == ActivityState.PAUSED
13433 || r.state == ActivityState.STOPPING) {
13434 // Only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013435 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13436 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013437 app.adjType = "stopping";
13438 }
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -080013439 app.hidden = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013440 app.foregroundActivities = true;
13441 }
13442 }
13443 }
13444
Dianne Hackborn7d608422011-08-07 16:24:18 -070013445 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013446 if (app.foregroundServices) {
13447 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013448 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013449 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013450 app.adjType = "foreground-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013451 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013452 } else if (app.forcingToForeground != null) {
13453 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013454 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013455 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013456 app.adjType = "force-foreground";
13457 app.adjSource = app.forcingToForeground;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013458 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013459 }
13460 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013461
Dianne Hackborn7d608422011-08-07 16:24:18 -070013462 if (adj > ProcessList.HEAVY_WEIGHT_APP_ADJ && app == mHeavyWeightProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013463 // We don't want to kill the current heavy-weight process.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013464 adj = ProcessList.HEAVY_WEIGHT_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013465 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013466 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013467 app.adjType = "heavy";
13468 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013469
Dianne Hackborn7d608422011-08-07 16:24:18 -070013470 if (adj > ProcessList.HOME_APP_ADJ && app == mHomeProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013471 // This process is hosting what we currently consider to be the
13472 // home app, so we don't want to let it go into the background.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013473 adj = ProcessList.HOME_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013474 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013475 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013476 app.adjType = "home";
13477 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013478
Dianne Hackbornf35fe232011-11-01 19:25:20 -070013479 if (adj > ProcessList.PREVIOUS_APP_ADJ && app == mPreviousProcess
13480 && app.activities.size() > 0) {
13481 // This was the previous process that showed UI to the user.
13482 // We want to try to keep it around more aggressively, to give
13483 // a good experience around switching between two apps.
13484 adj = ProcessList.PREVIOUS_APP_ADJ;
13485 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
13486 app.hidden = false;
13487 app.adjType = "previous";
13488 }
13489
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013490 if (false) Slog.i(TAG, "OOM " + app + ": initial adj=" + adj
13491 + " reason=" + app.adjType);
13492
The Android Open Source Project4df24232009-03-05 14:34:35 -080013493 // By default, we use the computed adjustment. It may be changed if
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013494 // there are applications dependent on our services or providers, but
13495 // this gives us a baseline and makes sure we don't get into an
13496 // infinite recursion.
13497 app.adjSeq = mAdjSeq;
13498 app.curRawAdj = adj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013499
Christopher Tate6fa95972009-06-05 18:43:55 -070013500 if (mBackupTarget != null && app == mBackupTarget.app) {
13501 // If possible we want to avoid killing apps while they're being backed up
Dianne Hackborn7d608422011-08-07 16:24:18 -070013502 if (adj > ProcessList.BACKUP_APP_ADJ) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013503 if (DEBUG_BACKUP) Slog.v(TAG, "oom BACKUP_APP_ADJ for " + app);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013504 adj = ProcessList.BACKUP_APP_ADJ;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013505 app.adjType = "backup";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013506 app.hidden = false;
Christopher Tate6fa95972009-06-05 18:43:55 -070013507 }
13508 }
13509
Dianne Hackborn7d608422011-08-07 16:24:18 -070013510 if (app.services.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013511 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013512 final long now = SystemClock.uptimeMillis();
13513 // This process is more important if the top activity is
13514 // bound to the service.
Dianne Hackborn860755f2010-06-03 18:47:52 -070013515 Iterator<ServiceRecord> jt = app.services.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013516 while (jt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013517 ServiceRecord s = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013518 if (s.startRequested) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013519 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013520 // If this process has shown some UI, let it immediately
13521 // go to the LRU list because it may be pretty heavy with
13522 // UI stuff. We'll tag it with a label just to help
13523 // debug and understand what is going on.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013524 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013525 app.adjType = "started-bg-ui-services";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013526 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013527 } else {
13528 if (now < (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
13529 // This service has seen some activity within
13530 // recent memory, so we will keep its process ahead
13531 // of the background processes.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013532 if (adj > ProcessList.SERVICE_ADJ) {
13533 adj = ProcessList.SERVICE_ADJ;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013534 app.adjType = "started-services";
13535 app.hidden = false;
13536 }
13537 }
13538 // If we have let the service slide into the background
13539 // state, still have some text describing what it is doing
13540 // even though the service no longer has an impact.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013541 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013542 app.adjType = "started-bg-services";
13543 }
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080013544 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013545 // Don't kill this process because it is doing work; it
13546 // has said it is doing work.
13547 app.keeping = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013548 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013549 if (s.connections.size() > 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013550 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013551 Iterator<ArrayList<ConnectionRecord>> kt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013552 = s.connections.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013553 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013554 ArrayList<ConnectionRecord> clist = kt.next();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013555 for (int i=0; i<clist.size() && adj > ProcessList.FOREGROUND_APP_ADJ; i++) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013556 // XXX should compute this based on the max of
13557 // all connected clients.
13558 ConnectionRecord cr = clist.get(i);
13559 if (cr.binding.client == app) {
13560 // Binding to ourself is not interesting.
13561 continue;
13562 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013563 if ((cr.flags&Context.BIND_WAIVE_PRIORITY) == 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013564 ProcessRecord client = cr.binding.client;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013565 int clientAdj = adj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013566 int myHiddenAdj = hiddenAdj;
13567 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013568 if (client.hiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013569 myHiddenAdj = client.hiddenAdj;
13570 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013571 myHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013572 }
13573 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013574 clientAdj = computeOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013575 client, myHiddenAdj, TOP_APP, true, doingAll);
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013576 String adjType = null;
13577 if ((cr.flags&Context.BIND_ALLOW_OOM_MANAGEMENT) != 0) {
13578 // Not doing bind OOM management, so treat
13579 // this guy more like a started service.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013580 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013581 // If this process has shown some UI, let it immediately
13582 // go to the LRU list because it may be pretty heavy with
13583 // UI stuff. We'll tag it with a label just to help
13584 // debug and understand what is going on.
13585 if (adj > clientAdj) {
13586 adjType = "bound-bg-ui-services";
13587 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013588 app.hidden = false;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013589 clientAdj = adj;
13590 } else {
13591 if (now >= (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
13592 // This service has not seen activity within
13593 // recent memory, so allow it to drop to the
13594 // LRU list if there is no other reason to keep
13595 // it around. We'll also tag it with a label just
13596 // to help debug and undertand what is going on.
13597 if (adj > clientAdj) {
13598 adjType = "bound-bg-services";
13599 }
13600 clientAdj = adj;
13601 }
13602 }
13603 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013604 if (adj > clientAdj) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013605 // If this process has recently shown UI, and
13606 // the process that is binding to it is less
13607 // important than being visible, then we don't
13608 // care about the binding as much as we care
13609 // about letting this process get into the LRU
13610 // list to be killed and restarted if needed for
13611 // memory.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013612 if (app.hasShownUi && app != mHomeProcess
13613 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013614 adjType = "bound-bg-ui-services";
13615 } else {
13616 if ((cr.flags&(Context.BIND_ABOVE_CLIENT
13617 |Context.BIND_IMPORTANT)) != 0) {
13618 adj = clientAdj;
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070013619 } else if ((cr.flags&Context.BIND_NOT_VISIBLE) != 0
13620 && clientAdj < ProcessList.PERCEPTIBLE_APP_ADJ
13621 && adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13622 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13623 } else if (clientAdj > ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013624 adj = clientAdj;
13625 } else {
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070013626 app.pendingUiClean = true;
13627 if (adj > ProcessList.VISIBLE_APP_ADJ) {
13628 adj = ProcessList.VISIBLE_APP_ADJ;
13629 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013630 }
13631 if (!client.hidden) {
13632 app.hidden = false;
13633 }
13634 if (client.keeping) {
13635 app.keeping = true;
13636 }
13637 adjType = "service";
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013638 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013639 }
13640 if (adjType != null) {
13641 app.adjType = adjType;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013642 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13643 .REASON_SERVICE_IN_USE;
13644 app.adjSource = cr.binding.client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013645 app.adjSourceOom = clientAdj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013646 app.adjTarget = s.name;
13647 }
13648 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
13649 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
13650 schedGroup = Process.THREAD_GROUP_DEFAULT;
13651 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013652 }
13653 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013654 if ((cr.flags&Context.BIND_ADJUST_WITH_ACTIVITY) != 0) {
13655 ActivityRecord a = cr.activity;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013656 if (a != null && adj > ProcessList.FOREGROUND_APP_ADJ &&
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013657 (a.visible || a.state == ActivityState.RESUMED
13658 || a.state == ActivityState.PAUSING)) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013659 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013660 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
13661 schedGroup = Process.THREAD_GROUP_DEFAULT;
13662 }
13663 app.hidden = false;
13664 app.adjType = "service";
13665 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13666 .REASON_SERVICE_IN_USE;
13667 app.adjSource = a;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013668 app.adjSourceOom = adj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013669 app.adjTarget = s.name;
13670 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013671 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013672 }
13673 }
13674 }
13675 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013676
Dianne Hackborn287952c2010-09-22 22:34:31 -070013677 // Finally, if this process has active services running in it, we
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013678 // would like to avoid killing it unless it would prevent the current
13679 // application from running. By default we put the process in
13680 // with the rest of the background processes; as we scan through
13681 // its services we may bump it up from there.
13682 if (adj > hiddenAdj) {
13683 adj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013684 app.hidden = false;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013685 app.adjType = "bg-services";
13686 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013687 }
13688
Dianne Hackborn7d608422011-08-07 16:24:18 -070013689 if (app.pubProviders.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013690 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013691 Iterator<ContentProviderRecord> jt = app.pubProviders.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013692 while (jt.hasNext() && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013693 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013694 ContentProviderRecord cpr = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013695 if (cpr.clients.size() != 0) {
13696 Iterator<ProcessRecord> kt = cpr.clients.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013697 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013698 ProcessRecord client = kt.next();
The Android Open Source Project10592532009-03-18 17:39:46 -070013699 if (client == app) {
13700 // Being our own client is not interesting.
13701 continue;
13702 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013703 int myHiddenAdj = hiddenAdj;
13704 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013705 if (client.hiddenAdj > ProcessList.FOREGROUND_APP_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013706 myHiddenAdj = client.hiddenAdj;
13707 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013708 myHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013709 }
13710 }
13711 int clientAdj = computeOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013712 client, myHiddenAdj, TOP_APP, true, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013713 if (adj > clientAdj) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013714 if (app.hasShownUi && app != mHomeProcess
13715 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013716 app.adjType = "bg-ui-provider";
13717 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013718 adj = clientAdj > ProcessList.FOREGROUND_APP_ADJ
13719 ? clientAdj : ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013720 app.adjType = "provider";
13721 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013722 if (!client.hidden) {
13723 app.hidden = false;
13724 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013725 if (client.keeping) {
13726 app.keeping = true;
13727 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070013728 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13729 .REASON_PROVIDER_IN_USE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013730 app.adjSource = client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013731 app.adjSourceOom = clientAdj;
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070013732 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013733 }
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013734 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
13735 schedGroup = Process.THREAD_GROUP_DEFAULT;
13736 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013737 }
13738 }
13739 // If the provider has external (non-framework) process
13740 // dependencies, ensure that its adjustment is at least
13741 // FOREGROUND_APP_ADJ.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080013742 if (cpr.hasExternalProcessHandles()) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013743 if (adj > ProcessList.FOREGROUND_APP_ADJ) {
13744 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013745 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013746 app.hidden = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013747 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013748 app.adjType = "provider";
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070013749 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013750 }
13751 }
13752 }
13753 }
13754
13755 app.curRawAdj = adj;
13756
Joe Onorato8a9b2202010-02-26 18:56:32 -080013757 //Slog.i(TAG, "OOM ADJ " + app + ": pid=" + app.pid +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013758 // " adj=" + adj + " curAdj=" + app.curAdj + " maxAdj=" + app.maxAdj);
13759 if (adj > app.maxAdj) {
13760 adj = app.maxAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013761 if (app.maxAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013762 schedGroup = Process.THREAD_GROUP_DEFAULT;
13763 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013764 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013765 if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070013766 app.keeping = true;
13767 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013768
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013769 if (app.hasAboveClient) {
13770 // If this process has bound to any services with BIND_ABOVE_CLIENT,
13771 // then we need to drop its adjustment to be lower than the service's
13772 // in order to honor the request. We want to drop it by one adjustment
13773 // level... but there is special meaning applied to various levels so
13774 // we will skip some of them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013775 if (adj < ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013776 // System process will not get dropped, ever
Dianne Hackborn7d608422011-08-07 16:24:18 -070013777 } else if (adj < ProcessList.VISIBLE_APP_ADJ) {
13778 adj = ProcessList.VISIBLE_APP_ADJ;
13779 } else if (adj < ProcessList.PERCEPTIBLE_APP_ADJ) {
13780 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13781 } else if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
13782 adj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013783 } else if (adj < ProcessList.HIDDEN_APP_MAX_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013784 adj++;
13785 }
13786 }
13787
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013788 if (adj == ProcessList.SERVICE_ADJ) {
13789 if (doingAll) {
13790 app.serviceb = mNewNumServiceProcs > (mNumServiceProcs/3);
13791 mNewNumServiceProcs++;
13792 }
13793 if (app.serviceb) {
13794 adj = ProcessList.SERVICE_B_ADJ;
13795 }
13796 } else {
13797 app.serviceb = false;
13798 }
13799
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013800 app.curAdj = adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013801 app.curSchedGroup = schedGroup;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013802
13803 if (hadForegroundActivities != app.foregroundActivities) {
Jeff Sharkey287bd832011-05-28 19:36:26 -070013804 mHandler.obtainMessage(DISPATCH_FOREGROUND_ACTIVITIES_CHANGED, app.pid, app.info.uid,
13805 app.foregroundActivities).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013806 }
13807
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013808 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013809 }
13810
13811 /**
13812 * Ask a given process to GC right now.
13813 */
13814 final void performAppGcLocked(ProcessRecord app) {
13815 try {
13816 app.lastRequestedGc = SystemClock.uptimeMillis();
13817 if (app.thread != null) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013818 if (app.reportLowMemory) {
13819 app.reportLowMemory = false;
13820 app.thread.scheduleLowMemory();
13821 } else {
13822 app.thread.processInBackground();
13823 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013824 }
13825 } catch (Exception e) {
13826 // whatever.
13827 }
13828 }
13829
13830 /**
13831 * Returns true if things are idle enough to perform GCs.
13832 */
Josh Bartel7f208742010-02-25 11:01:44 -060013833 private final boolean canGcNowLocked() {
Christopher Tatef46723b2012-01-26 14:19:24 -080013834 boolean processingBroadcasts = false;
13835 for (BroadcastQueue q : mBroadcastQueues) {
13836 if (q.mParallelBroadcasts.size() != 0 || q.mOrderedBroadcasts.size() != 0) {
13837 processingBroadcasts = true;
13838 }
13839 }
13840 return !processingBroadcasts
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013841 && (mSleeping || (mMainStack.mResumedActivity != null &&
13842 mMainStack.mResumedActivity.idle));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013843 }
13844
13845 /**
13846 * Perform GCs on all processes that are waiting for it, but only
13847 * if things are idle.
13848 */
13849 final void performAppGcsLocked() {
13850 final int N = mProcessesToGc.size();
13851 if (N <= 0) {
13852 return;
13853 }
Josh Bartel7f208742010-02-25 11:01:44 -060013854 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013855 while (mProcessesToGc.size() > 0) {
13856 ProcessRecord proc = mProcessesToGc.remove(0);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013857 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013858 if ((proc.lastRequestedGc+GC_MIN_INTERVAL)
13859 <= SystemClock.uptimeMillis()) {
13860 // To avoid spamming the system, we will GC processes one
13861 // at a time, waiting a few seconds between each.
13862 performAppGcLocked(proc);
13863 scheduleAppGcsLocked();
13864 return;
13865 } else {
13866 // It hasn't been long enough since we last GCed this
13867 // process... put it in the list to wait for its time.
13868 addProcessToGcListLocked(proc);
13869 break;
13870 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013871 }
13872 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013873
13874 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013875 }
13876 }
13877
13878 /**
13879 * If all looks good, perform GCs on all processes waiting for them.
13880 */
13881 final void performAppGcsIfAppropriateLocked() {
Josh Bartel7f208742010-02-25 11:01:44 -060013882 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013883 performAppGcsLocked();
13884 return;
13885 }
13886 // Still not idle, wait some more.
13887 scheduleAppGcsLocked();
13888 }
13889
13890 /**
13891 * Schedule the execution of all pending app GCs.
13892 */
13893 final void scheduleAppGcsLocked() {
13894 mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013895
13896 if (mProcessesToGc.size() > 0) {
13897 // Schedule a GC for the time to the next process.
13898 ProcessRecord proc = mProcessesToGc.get(0);
13899 Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG);
13900
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013901 long when = proc.lastRequestedGc + GC_MIN_INTERVAL;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013902 long now = SystemClock.uptimeMillis();
13903 if (when < (now+GC_TIMEOUT)) {
13904 when = now + GC_TIMEOUT;
13905 }
13906 mHandler.sendMessageAtTime(msg, when);
13907 }
13908 }
13909
13910 /**
13911 * Add a process to the array of processes waiting to be GCed. Keeps the
13912 * list in sorted order by the last GC time. The process can't already be
13913 * on the list.
13914 */
13915 final void addProcessToGcListLocked(ProcessRecord proc) {
13916 boolean added = false;
13917 for (int i=mProcessesToGc.size()-1; i>=0; i--) {
13918 if (mProcessesToGc.get(i).lastRequestedGc <
13919 proc.lastRequestedGc) {
13920 added = true;
13921 mProcessesToGc.add(i+1, proc);
13922 break;
13923 }
13924 }
13925 if (!added) {
13926 mProcessesToGc.add(0, proc);
13927 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013928 }
13929
13930 /**
13931 * Set up to ask a process to GC itself. This will either do it
13932 * immediately, or put it on the list of processes to gc the next
13933 * time things are idle.
13934 */
13935 final void scheduleAppGcLocked(ProcessRecord app) {
13936 long now = SystemClock.uptimeMillis();
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013937 if ((app.lastRequestedGc+GC_MIN_INTERVAL) > now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013938 return;
13939 }
13940 if (!mProcessesToGc.contains(app)) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013941 addProcessToGcListLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013942 scheduleAppGcsLocked();
13943 }
13944 }
13945
Dianne Hackborn287952c2010-09-22 22:34:31 -070013946 final void checkExcessivePowerUsageLocked(boolean doKills) {
13947 updateCpuStatsNow();
13948
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013949 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013950 boolean doWakeKills = doKills;
13951 boolean doCpuKills = doKills;
13952 if (mLastPowerCheckRealtime == 0) {
13953 doWakeKills = false;
13954 }
13955 if (mLastPowerCheckUptime == 0) {
13956 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013957 }
13958 if (stats.isScreenOn()) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070013959 doWakeKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013960 }
13961 final long curRealtime = SystemClock.elapsedRealtime();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013962 final long realtimeSince = curRealtime - mLastPowerCheckRealtime;
13963 final long curUptime = SystemClock.uptimeMillis();
13964 final long uptimeSince = curUptime - mLastPowerCheckUptime;
13965 mLastPowerCheckRealtime = curRealtime;
13966 mLastPowerCheckUptime = curUptime;
13967 if (realtimeSince < WAKE_LOCK_MIN_CHECK_DURATION) {
13968 doWakeKills = false;
13969 }
13970 if (uptimeSince < CPU_MIN_CHECK_DURATION) {
13971 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013972 }
13973 int i = mLruProcesses.size();
13974 while (i > 0) {
13975 i--;
13976 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013977 if (!app.keeping) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013978 long wtime;
13979 synchronized (stats) {
13980 wtime = stats.getProcessWakeTime(app.info.uid,
13981 app.pid, curRealtime);
13982 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013983 long wtimeUsed = wtime - app.lastWakeTime;
13984 long cputimeUsed = app.curCpuTime - app.lastCpuTime;
13985 if (DEBUG_POWER) {
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013986 StringBuilder sb = new StringBuilder(128);
13987 sb.append("Wake for ");
13988 app.toShortString(sb);
13989 sb.append(": over ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013990 TimeUtils.formatDuration(realtimeSince, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013991 sb.append(" used ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013992 TimeUtils.formatDuration(wtimeUsed, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013993 sb.append(" (");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013994 sb.append((wtimeUsed*100)/realtimeSince);
13995 sb.append("%)");
13996 Slog.i(TAG, sb.toString());
13997 sb.setLength(0);
13998 sb.append("CPU for ");
13999 app.toShortString(sb);
14000 sb.append(": over ");
14001 TimeUtils.formatDuration(uptimeSince, sb);
14002 sb.append(" used ");
14003 TimeUtils.formatDuration(cputimeUsed, sb);
14004 sb.append(" (");
14005 sb.append((cputimeUsed*100)/uptimeSince);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014006 sb.append("%)");
14007 Slog.i(TAG, sb.toString());
14008 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014009 // If a process has held a wake lock for more
14010 // than 50% of the time during this period,
14011 // that sounds pad. Kill!
Dianne Hackborn287952c2010-09-22 22:34:31 -070014012 if (doWakeKills && realtimeSince > 0
14013 && ((wtimeUsed*100)/realtimeSince) >= 50) {
14014 synchronized (stats) {
14015 stats.reportExcessiveWakeLocked(app.info.uid, app.processName,
14016 realtimeSince, wtimeUsed);
14017 }
14018 Slog.w(TAG, "Excessive wake lock in " + app.processName
14019 + " (pid " + app.pid + "): held " + wtimeUsed
14020 + " during " + realtimeSince);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014021 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14022 app.processName, app.setAdj, "excessive wake lock");
14023 Process.killProcessQuiet(app.pid);
Dianne Hackborn287952c2010-09-22 22:34:31 -070014024 } else if (doCpuKills && uptimeSince > 0
14025 && ((cputimeUsed*100)/uptimeSince) >= 50) {
14026 synchronized (stats) {
14027 stats.reportExcessiveCpuLocked(app.info.uid, app.processName,
14028 uptimeSince, cputimeUsed);
14029 }
14030 Slog.w(TAG, "Excessive CPU in " + app.processName
14031 + " (pid " + app.pid + "): used " + cputimeUsed
14032 + " during " + uptimeSince);
14033 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14034 app.processName, app.setAdj, "excessive cpu");
14035 Process.killProcessQuiet(app.pid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014036 } else {
14037 app.lastWakeTime = wtime;
Dianne Hackborn287952c2010-09-22 22:34:31 -070014038 app.lastCpuTime = app.curCpuTime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014039 }
14040 }
14041 }
14042 }
14043
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014044 private final boolean updateOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014045 ProcessRecord app, int hiddenAdj, ProcessRecord TOP_APP, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014046 app.hiddenAdj = hiddenAdj;
14047
14048 if (app.thread == null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014049 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014050 }
14051
Dianne Hackborn287952c2010-09-22 22:34:31 -070014052 final boolean wasKeeping = app.keeping;
14053
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014054 boolean success = true;
14055
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014056 computeOomAdjLocked(app, hiddenAdj, TOP_APP, false, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014057
Jeff Brown10e89712011-07-08 18:52:57 -070014058 if (app.curRawAdj != app.setRawAdj) {
Dianne Hackborn905577f2011-09-07 18:31:28 -070014059 if (false) {
14060 // Removing for now. Forcing GCs is not so useful anymore
14061 // with Dalvik, and the new memory level hint facility is
14062 // better for what we need to do these days.
14063 if (app.curRawAdj > ProcessList.FOREGROUND_APP_ADJ
14064 && app.setRawAdj <= ProcessList.FOREGROUND_APP_ADJ) {
14065 // If this app is transitioning from foreground to
14066 // non-foreground, have it do a gc.
14067 scheduleAppGcLocked(app);
14068 } else if (app.curRawAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
14069 && app.setRawAdj < ProcessList.HIDDEN_APP_MIN_ADJ) {
14070 // Likewise do a gc when an app is moving in to the
14071 // background (such as a service stopping).
14072 scheduleAppGcLocked(app);
14073 }
Jeff Brown10e89712011-07-08 18:52:57 -070014074 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070014075
Jeff Brown10e89712011-07-08 18:52:57 -070014076 if (wasKeeping && !app.keeping) {
14077 // This app is no longer something we want to keep. Note
14078 // its current wake lock time to later know to kill it if
14079 // it is not behaving well.
14080 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
14081 synchronized (stats) {
14082 app.lastWakeTime = stats.getProcessWakeTime(app.info.uid,
14083 app.pid, SystemClock.elapsedRealtime());
14084 }
14085 app.lastCpuTime = app.curCpuTime;
14086 }
14087
14088 app.setRawAdj = app.curRawAdj;
14089 }
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014090
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014091 if (app.curAdj != app.setAdj) {
14092 if (Process.setOomAdj(app.pid, app.curAdj)) {
Dianne Hackbornbbb09ac2011-11-30 11:31:29 -080014093 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014094 TAG, "Set " + app.pid + " " + app.processName +
14095 " adj " + app.curAdj + ": " + app.adjType);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014096 app.setAdj = app.curAdj;
Jeff Brown10e89712011-07-08 18:52:57 -070014097 } else {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014098 success = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014099 Slog.w(TAG, "Failed setting oom adj of " + app + " to " + app.curAdj);
Jeff Brown10e89712011-07-08 18:52:57 -070014100 }
14101 }
14102 if (app.setSchedGroup != app.curSchedGroup) {
14103 app.setSchedGroup = app.curSchedGroup;
14104 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
14105 "Setting process group of " + app.processName
14106 + " to " + app.curSchedGroup);
14107 if (app.waitingToKill != null &&
14108 app.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
14109 Slog.i(TAG, "Killing " + app.toShortString() + ": " + app.waitingToKill);
14110 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14111 app.processName, app.setAdj, app.waitingToKill);
14112 Process.killProcessQuiet(app.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014113 success = false;
Jeff Brown10e89712011-07-08 18:52:57 -070014114 } else {
14115 if (true) {
14116 long oldId = Binder.clearCallingIdentity();
14117 try {
14118 Process.setProcessGroup(app.pid, app.curSchedGroup);
14119 } catch (Exception e) {
14120 Slog.w(TAG, "Failed setting process group of " + app.pid
14121 + " to " + app.curSchedGroup);
14122 e.printStackTrace();
14123 } finally {
14124 Binder.restoreCallingIdentity(oldId);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014125 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014126 } else {
Jeff Brown10e89712011-07-08 18:52:57 -070014127 if (app.thread != null) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070014128 try {
Jeff Brown10e89712011-07-08 18:52:57 -070014129 app.thread.setSchedulingGroup(app.curSchedGroup);
14130 } catch (RemoteException e) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070014131 }
14132 }
14133 }
14134 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014135 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014136 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014137 }
14138
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014139 private final ActivityRecord resumedAppLocked() {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014140 ActivityRecord resumedActivity = mMainStack.mResumedActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014141 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -080014142 resumedActivity = mMainStack.mPausingActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014143 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014144 resumedActivity = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014145 }
14146 }
14147 return resumedActivity;
14148 }
14149
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014150 private final boolean updateOomAdjLocked(ProcessRecord app) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014151 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014152 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
14153 int curAdj = app.curAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070014154 final boolean wasHidden = curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
14155 && curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014156
14157 mAdjSeq++;
14158
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014159 boolean success = updateOomAdjLocked(app, app.hiddenAdj, TOP_APP, false);
Dianne Hackborn7d608422011-08-07 16:24:18 -070014160 final boolean nowHidden = app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
14161 && app.curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014162 if (nowHidden != wasHidden) {
14163 // Changed to/from hidden state, so apps after it in the LRU
14164 // list may also be changed.
14165 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014166 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014167 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014168 }
14169
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014170 final void updateOomAdjLocked() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014171 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014172 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
14173
14174 if (false) {
14175 RuntimeException e = new RuntimeException();
14176 e.fillInStackTrace();
Joe Onorato8a9b2202010-02-26 18:56:32 -080014177 Slog.i(TAG, "updateOomAdj: top=" + TOP_ACT, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014178 }
14179
14180 mAdjSeq++;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014181 mNewNumServiceProcs = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014182
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014183 // Let's determine how many processes we have running vs.
14184 // how many slots we have for background processes; we may want
14185 // to put multiple processes in a slot of there are enough of
14186 // them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014187 int numSlots = ProcessList.HIDDEN_APP_MAX_ADJ - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014188 int factor = (mLruProcesses.size()-4)/numSlots;
14189 if (factor < 1) factor = 1;
14190 int step = 0;
Dianne Hackborn8633e682010-04-22 16:03:41 -070014191 int numHidden = 0;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014192
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014193 // First update the OOM adjustment for each of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014194 // application processes based on their current state.
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014195 int i = mLruProcesses.size();
Dianne Hackborn7d608422011-08-07 16:24:18 -070014196 int curHiddenAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014197 while (i > 0) {
14198 i--;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014199 ProcessRecord app = mLruProcesses.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080014200 //Slog.i(TAG, "OOM " + app + ": cur hidden=" + curHiddenAdj);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014201 updateOomAdjLocked(app, curHiddenAdj, TOP_APP, true);
14202 if (curHiddenAdj < ProcessList.HIDDEN_APP_MAX_ADJ
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014203 && app.curAdj == curHiddenAdj) {
14204 step++;
14205 if (step >= factor) {
14206 step = 0;
14207 curHiddenAdj++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014208 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014209 }
14210 if (!app.killedBackground) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070014211 if (app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014212 numHidden++;
14213 if (numHidden > mProcessLimit) {
14214 Slog.i(TAG, "No longer want " + app.processName
14215 + " (pid " + app.pid + "): hidden #" + numHidden);
14216 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14217 app.processName, app.setAdj, "too many background");
14218 app.killedBackground = true;
14219 Process.killProcessQuiet(app.pid);
Dianne Hackborn8633e682010-04-22 16:03:41 -070014220 }
14221 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -080014222 if (!app.killedBackground && app.isolated && app.services.size() <= 0) {
14223 // If this is an isolated process, and there are no
14224 // services running in it, then the process is no longer
14225 // needed. We agressively kill these because we can by
14226 // definition not re-use the same process again, and it is
14227 // good to avoid having whatever code was running in them
14228 // left sitting around after no longer needed.
14229 Slog.i(TAG, "Isolated process " + app.processName
14230 + " (pid " + app.pid + ") no longer needed");
14231 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14232 app.processName, app.setAdj, "isolated not needed");
14233 app.killedBackground = true;
14234 Process.killProcessQuiet(app.pid);
14235 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014236 }
14237 }
14238
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014239 mNumServiceProcs = mNewNumServiceProcs;
14240
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014241 // Now determine the memory trimming level of background processes.
14242 // Unfortunately we need to start at the back of the list to do this
14243 // properly. We only do this if the number of background apps we
14244 // are managing to keep around is less than half the maximum we desire;
14245 // if we are keeping a good number around, we'll let them use whatever
14246 // memory they want.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014247 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/2)) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014248 final int N = mLruProcesses.size();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080014249 factor = numHidden/3;
14250 int minFactor = 2;
14251 if (mHomeProcess != null) minFactor++;
14252 if (mPreviousProcess != null) minFactor++;
14253 if (factor < minFactor) factor = minFactor;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014254 step = 0;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014255 int fgTrimLevel;
14256 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/5)) {
14257 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL;
14258 } else if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/3)) {
14259 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW;
14260 } else {
14261 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE;
14262 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014263 int curLevel = ComponentCallbacks2.TRIM_MEMORY_COMPLETE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014264 for (i=0; i<N; i++) {
14265 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080014266 if (app.curAdj >= ProcessList.HOME_APP_ADJ
14267 && app.curAdj != ProcessList.SERVICE_B_ADJ
14268 && !app.killedBackground) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014269 if (app.trimMemoryLevel < curLevel && app.thread != null) {
14270 try {
14271 app.thread.scheduleTrimMemory(curLevel);
14272 } catch (RemoteException e) {
14273 }
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080014274 if (false) {
14275 // For now we won't do this; our memory trimming seems
14276 // to be good enough at this point that destroying
14277 // activities causes more harm than good.
14278 if (curLevel >= ComponentCallbacks2.TRIM_MEMORY_COMPLETE
14279 && app != mHomeProcess && app != mPreviousProcess) {
14280 // For these apps we will also finish their activities
14281 // to help them free memory.
14282 mMainStack.destroyActivitiesLocked(app, false, "trim");
14283 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014284 }
14285 }
14286 app.trimMemoryLevel = curLevel;
14287 step++;
14288 if (step >= factor) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014289 step = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014290 switch (curLevel) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014291 case ComponentCallbacks2.TRIM_MEMORY_COMPLETE:
14292 curLevel = ComponentCallbacks2.TRIM_MEMORY_MODERATE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014293 break;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014294 case ComponentCallbacks2.TRIM_MEMORY_MODERATE:
14295 curLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014296 break;
14297 }
14298 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070014299 } else if (app.curAdj == ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014300 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014301 && app.thread != null) {
14302 try {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014303 app.thread.scheduleTrimMemory(
14304 ComponentCallbacks2.TRIM_MEMORY_BACKGROUND);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014305 } catch (RemoteException e) {
14306 }
14307 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014308 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014309 } else {
14310 if ((app.curAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
14311 && app.pendingUiClean) {
14312 // If this application is now in the background and it
14313 // had done UI, then give it the special trim level to
14314 // have it free UI resources.
14315 final int level = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
14316 if (app.trimMemoryLevel < level && app.thread != null) {
14317 try {
14318 app.thread.scheduleTrimMemory(level);
14319 } catch (RemoteException e) {
14320 }
14321 }
14322 app.pendingUiClean = false;
14323 }
14324 if (app.trimMemoryLevel < fgTrimLevel && app.thread != null) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014325 try {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014326 app.thread.scheduleTrimMemory(fgTrimLevel);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014327 } catch (RemoteException e) {
14328 }
14329 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014330 app.trimMemoryLevel = fgTrimLevel;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014331 }
14332 }
14333 } else {
14334 final int N = mLruProcesses.size();
14335 for (i=0; i<N; i++) {
14336 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -070014337 if ((app.curAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014338 && app.pendingUiClean) {
14339 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
14340 && app.thread != null) {
14341 try {
14342 app.thread.scheduleTrimMemory(
14343 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
14344 } catch (RemoteException e) {
14345 }
14346 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014347 app.pendingUiClean = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014348 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014349 app.trimMemoryLevel = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014350 }
14351 }
14352
14353 if (mAlwaysFinishActivities) {
Dianne Hackborn28695e02011-11-02 21:59:51 -070014354 mMainStack.destroyActivitiesLocked(null, false, "always-finish");
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014355 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014356 }
14357
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014358 final void trimApplications() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014359 synchronized (this) {
14360 int i;
14361
14362 // First remove any unused application processes whose package
14363 // has been removed.
14364 for (i=mRemovedProcesses.size()-1; i>=0; i--) {
14365 final ProcessRecord app = mRemovedProcesses.get(i);
14366 if (app.activities.size() == 0
14367 && app.curReceiver == null && app.services.size() == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080014368 Slog.i(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014369 TAG, "Exiting empty application process "
14370 + app.processName + " ("
14371 + (app.thread != null ? app.thread.asBinder() : null)
14372 + ")\n");
14373 if (app.pid > 0 && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070014374 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14375 app.processName, app.setAdj, "empty");
14376 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014377 } else {
14378 try {
14379 app.thread.scheduleExit();
14380 } catch (Exception e) {
14381 // Ignore exceptions.
14382 }
14383 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070014384 cleanUpApplicationRecordLocked(app, false, true, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014385 mRemovedProcesses.remove(i);
14386
14387 if (app.persistent) {
14388 if (app.persistent) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080014389 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014390 }
14391 }
14392 }
14393 }
14394
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014395 // Now update the oom adj for all processes.
14396 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014397 }
14398 }
14399
14400 /** This method sends the specified signal to each of the persistent apps */
14401 public void signalPersistentProcesses(int sig) throws RemoteException {
14402 if (sig != Process.SIGNAL_USR1) {
14403 throw new SecurityException("Only SIGNAL_USR1 is allowed");
14404 }
14405
14406 synchronized (this) {
14407 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
14408 != PackageManager.PERMISSION_GRANTED) {
14409 throw new SecurityException("Requires permission "
14410 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
14411 }
14412
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014413 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
14414 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014415 if (r.thread != null && r.persistent) {
14416 Process.sendSignal(r.pid, sig);
14417 }
14418 }
14419 }
14420 }
14421
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014422 private void stopProfilerLocked(ProcessRecord proc, String path, int profileType) {
14423 if (proc == null || proc == mProfileProc) {
14424 proc = mProfileProc;
14425 path = mProfileFile;
14426 profileType = mProfileType;
14427 clearProfilerLocked();
14428 }
14429 if (proc == null) {
14430 return;
14431 }
14432 try {
14433 proc.thread.profilerControl(false, path, null, profileType);
14434 } catch (RemoteException e) {
14435 throw new IllegalStateException("Process disappeared");
14436 }
14437 }
14438
14439 private void clearProfilerLocked() {
14440 if (mProfileFd != null) {
14441 try {
14442 mProfileFd.close();
14443 } catch (IOException e) {
14444 }
14445 }
14446 mProfileApp = null;
14447 mProfileProc = null;
14448 mProfileFile = null;
14449 mProfileType = 0;
14450 mAutoStopProfiler = false;
14451 }
14452
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014453 public boolean profileControl(String process, boolean start,
Romain Guy7eabe552011-07-21 14:56:34 -070014454 String path, ParcelFileDescriptor fd, int profileType) throws RemoteException {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014455
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014456 try {
14457 synchronized (this) {
14458 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14459 // its own permission.
14460 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14461 != PackageManager.PERMISSION_GRANTED) {
14462 throw new SecurityException("Requires permission "
14463 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014464 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014465
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014466 if (start && fd == null) {
14467 throw new IllegalArgumentException("null fd");
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014468 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014469
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014470 ProcessRecord proc = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014471 if (process != null) {
14472 try {
14473 int pid = Integer.parseInt(process);
14474 synchronized (mPidsSelfLocked) {
14475 proc = mPidsSelfLocked.get(pid);
14476 }
14477 } catch (NumberFormatException e) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014478 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014479
14480 if (proc == null) {
14481 HashMap<String, SparseArray<ProcessRecord>> all
14482 = mProcessNames.getMap();
14483 SparseArray<ProcessRecord> procs = all.get(process);
14484 if (procs != null && procs.size() > 0) {
14485 proc = procs.valueAt(0);
14486 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014487 }
14488 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014489
14490 if (start && (proc == null || proc.thread == null)) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014491 throw new IllegalArgumentException("Unknown process: " + process);
14492 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014493
14494 if (start) {
14495 stopProfilerLocked(null, null, 0);
14496 setProfileApp(proc.info, proc.processName, path, fd, false);
14497 mProfileProc = proc;
14498 mProfileType = profileType;
14499 try {
14500 fd = fd.dup();
14501 } catch (IOException e) {
14502 fd = null;
14503 }
14504 proc.thread.profilerControl(start, path, fd, profileType);
14505 fd = null;
14506 mProfileFd = null;
14507 } else {
14508 stopProfilerLocked(proc, path, profileType);
14509 if (fd != null) {
14510 try {
14511 fd.close();
14512 } catch (IOException e) {
14513 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014514 }
14515 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014516
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014517 return true;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014518 }
14519 } catch (RemoteException e) {
14520 throw new IllegalStateException("Process disappeared");
14521 } finally {
14522 if (fd != null) {
14523 try {
14524 fd.close();
14525 } catch (IOException e) {
14526 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014527 }
14528 }
14529 }
Andy McFadden824c5102010-07-09 16:26:57 -070014530
14531 public boolean dumpHeap(String process, boolean managed,
14532 String path, ParcelFileDescriptor fd) throws RemoteException {
14533
14534 try {
14535 synchronized (this) {
14536 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14537 // its own permission (same as profileControl).
14538 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14539 != PackageManager.PERMISSION_GRANTED) {
14540 throw new SecurityException("Requires permission "
14541 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
14542 }
14543
14544 if (fd == null) {
14545 throw new IllegalArgumentException("null fd");
14546 }
14547
14548 ProcessRecord proc = null;
14549 try {
14550 int pid = Integer.parseInt(process);
14551 synchronized (mPidsSelfLocked) {
14552 proc = mPidsSelfLocked.get(pid);
14553 }
14554 } catch (NumberFormatException e) {
14555 }
14556
14557 if (proc == null) {
14558 HashMap<String, SparseArray<ProcessRecord>> all
14559 = mProcessNames.getMap();
14560 SparseArray<ProcessRecord> procs = all.get(process);
14561 if (procs != null && procs.size() > 0) {
14562 proc = procs.valueAt(0);
14563 }
14564 }
14565
14566 if (proc == null || proc.thread == null) {
14567 throw new IllegalArgumentException("Unknown process: " + process);
14568 }
14569
Dianne Hackbornf02e57b2011-03-01 22:21:04 -080014570 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
14571 if (!isDebuggable) {
Andy McFadden824c5102010-07-09 16:26:57 -070014572 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
14573 throw new SecurityException("Process not debuggable: " + proc);
14574 }
14575 }
14576
14577 proc.thread.dumpHeap(managed, path, fd);
14578 fd = null;
14579 return true;
14580 }
14581 } catch (RemoteException e) {
14582 throw new IllegalStateException("Process disappeared");
14583 } finally {
14584 if (fd != null) {
14585 try {
14586 fd.close();
14587 } catch (IOException e) {
14588 }
14589 }
14590 }
14591 }
14592
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014593 /** In this method we try to acquire our lock to make sure that we have not deadlocked */
14594 public void monitor() {
14595 synchronized (this) { }
14596 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014597
Dianne Hackborna573f6a2012-02-09 16:12:18 -080014598 void onCoreSettingsChange(Bundle settings) {
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014599 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
14600 ProcessRecord processRecord = mLruProcesses.get(i);
14601 try {
14602 if (processRecord.thread != null) {
14603 processRecord.thread.setCoreSettings(settings);
14604 }
14605 } catch (RemoteException re) {
14606 /* ignore */
14607 }
14608 }
14609 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014610
14611 // Multi-user methods
14612
Amith Yamasani742a6712011-05-04 14:49:28 -070014613 private int mCurrentUserId;
14614 private SparseIntArray mLoggedInUsers = new SparseIntArray(5);
14615
14616 public boolean switchUser(int userId) {
14617 final int callingUid = Binder.getCallingUid();
14618 if (callingUid != 0 && callingUid != Process.myUid()) {
14619 Slog.e(TAG, "Trying to switch user from unauthorized app");
14620 return false;
14621 }
14622 if (mCurrentUserId == userId)
14623 return true;
14624
14625 synchronized (this) {
14626 // Check if user is already logged in, otherwise check if user exists first before
14627 // adding to the list of logged in users.
14628 if (mLoggedInUsers.indexOfKey(userId) < 0) {
14629 if (!userExists(userId)) {
14630 return false;
14631 }
14632 mLoggedInUsers.append(userId, userId);
14633 }
14634
14635 mCurrentUserId = userId;
14636 boolean haveActivities = mMainStack.switchUser(userId);
14637 if (!haveActivities) {
14638 startHomeActivityLocked(userId);
14639 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014640
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014641 }
Amith Yamasani13593602012-03-22 16:16:17 -070014642
14643 // Inform of user switch
14644 Intent addedIntent = new Intent(Intent.ACTION_USER_SWITCHED);
14645 addedIntent.putExtra(Intent.EXTRA_USERID, userId);
14646 mContext.sendBroadcast(addedIntent, android.Manifest.permission.MANAGE_ACCOUNTS);
14647
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014648 return true;
14649 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014650
Amith Yamasani52f1d752012-03-28 18:19:29 -070014651 @Override
14652 public UserInfo getCurrentUser() throws RemoteException {
14653 final int callingUid = Binder.getCallingUid();
14654 if (callingUid != 0 && callingUid != Process.myUid()) {
14655 Slog.e(TAG, "Trying to get user from unauthorized app");
14656 return null;
14657 }
14658 return AppGlobals.getPackageManager().getUser(mCurrentUserId);
14659 }
14660
Amith Yamasani13593602012-03-22 16:16:17 -070014661 private void onUserRemoved(Intent intent) {
14662 int extraUserId = intent.getIntExtra(Intent.EXTRA_USERID, -1);
14663 if (extraUserId < 1) return;
14664
14665 // Kill all the processes for the user
14666 ArrayList<Pair<String, Integer>> pkgAndUids = new ArrayList<Pair<String,Integer>>();
14667 synchronized (this) {
14668 HashMap<String,SparseArray<ProcessRecord>> map = mProcessNames.getMap();
14669 for (Entry<String, SparseArray<ProcessRecord>> uidMap : map.entrySet()) {
14670 SparseArray<ProcessRecord> uids = uidMap.getValue();
14671 for (int i = 0; i < uids.size(); i++) {
14672 if (UserId.getUserId(uids.keyAt(i)) == extraUserId) {
14673 pkgAndUids.add(new Pair<String,Integer>(uidMap.getKey(), uids.keyAt(i)));
14674 }
14675 }
14676 }
14677
14678 for (Pair<String,Integer> pkgAndUid : pkgAndUids) {
14679 forceStopPackageLocked(pkgAndUid.first, pkgAndUid.second,
14680 false, false, true, true, extraUserId);
14681 }
14682 }
14683 }
14684
Amith Yamasani742a6712011-05-04 14:49:28 -070014685 private boolean userExists(int userId) {
14686 try {
Amith Yamasani13593602012-03-22 16:16:17 -070014687 UserInfo user = AppGlobals.getPackageManager().getUser(userId);
14688 return user != null;
Amith Yamasani742a6712011-05-04 14:49:28 -070014689 } catch (RemoteException re) {
14690 // Won't happen, in same process
14691 }
14692
14693 return false;
14694 }
14695
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014696 private void checkValidCaller(int uid, int userId) {
14697 if (UserId.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) return;
14698
14699 throw new SecurityException("Caller uid=" + uid
14700 + " is not privileged to communicate with user=" + userId);
14701 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014702
14703 private int applyUserId(int uid, int userId) {
14704 return UserId.getUid(userId, uid);
14705 }
14706
14707 private ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080014708 if (info == null) return null;
Amith Yamasani742a6712011-05-04 14:49:28 -070014709 ApplicationInfo newInfo = new ApplicationInfo(info);
14710 newInfo.uid = applyUserId(info.uid, userId);
14711 if (newInfo.uid >= Process.FIRST_APPLICATION_UID) {
14712 newInfo.dataDir = USER_DATA_DIR + userId + "/"
14713 + info.packageName;
14714 }
14715 return newInfo;
14716 }
14717
14718 ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080014719 if (aInfo == null || aInfo.applicationInfo.uid < Process.FIRST_APPLICATION_UID
Amith Yamasani742a6712011-05-04 14:49:28 -070014720 || userId < 1) {
14721 return aInfo;
14722 }
14723
14724 ActivityInfo info = new ActivityInfo(aInfo);
14725 info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId);
14726 return info;
14727 }
14728
14729 static class ServiceMap {
14730
14731 private final SparseArray<HashMap<ComponentName, ServiceRecord>> mServicesByNamePerUser
14732 = new SparseArray<HashMap<ComponentName, ServiceRecord>>();
14733 private final SparseArray<HashMap<Intent.FilterComparison, ServiceRecord>>
14734 mServicesByIntentPerUser = new SparseArray<
14735 HashMap<Intent.FilterComparison, ServiceRecord>>();
14736
14737 ServiceRecord getServiceByName(ComponentName name, int callingUser) {
14738 // TODO: Deal with global services
14739 if (DEBUG_MU)
14740 Slog.v(TAG_MU, "getServiceByName(" + name + "), callingUser = " + callingUser);
14741 return getServices(callingUser).get(name);
14742 }
14743
14744 ServiceRecord getServiceByName(ComponentName name) {
14745 return getServiceByName(name, -1);
14746 }
14747
14748 ServiceRecord getServiceByIntent(Intent.FilterComparison filter, int callingUser) {
14749 // TODO: Deal with global services
14750 if (DEBUG_MU)
14751 Slog.v(TAG_MU, "getServiceByIntent(" + filter + "), callingUser = " + callingUser);
14752 return getServicesByIntent(callingUser).get(filter);
14753 }
14754
14755 ServiceRecord getServiceByIntent(Intent.FilterComparison filter) {
14756 return getServiceByIntent(filter, -1);
14757 }
14758
14759 void putServiceByName(ComponentName name, int callingUser, ServiceRecord value) {
14760 // TODO: Deal with global services
14761 getServices(callingUser).put(name, value);
14762 }
14763
14764 void putServiceByIntent(Intent.FilterComparison filter, int callingUser,
14765 ServiceRecord value) {
14766 // TODO: Deal with global services
14767 getServicesByIntent(callingUser).put(filter, value);
14768 }
14769
14770 void removeServiceByName(ComponentName name, int callingUser) {
14771 // TODO: Deal with global services
14772 ServiceRecord removed = getServices(callingUser).remove(name);
14773 if (DEBUG_MU)
14774 Slog.v(TAG, "removeServiceByName user=" + callingUser + " name=" + name
14775 + " removed=" + removed);
14776 }
14777
14778 void removeServiceByIntent(Intent.FilterComparison filter, int callingUser) {
14779 // TODO: Deal with global services
14780 ServiceRecord removed = getServicesByIntent(callingUser).remove(filter);
14781 if (DEBUG_MU)
14782 Slog.v(TAG_MU, "removeServiceByIntent user=" + callingUser + " intent=" + filter
14783 + " removed=" + removed);
14784 }
14785
14786 Collection<ServiceRecord> getAllServices(int callingUser) {
14787 // TODO: Deal with global services
14788 return getServices(callingUser).values();
14789 }
14790
14791 private HashMap<ComponentName, ServiceRecord> getServices(int callingUser) {
14792 HashMap map = mServicesByNamePerUser.get(callingUser);
14793 if (map == null) {
14794 map = new HashMap<ComponentName, ServiceRecord>();
14795 mServicesByNamePerUser.put(callingUser, map);
14796 }
14797 return map;
14798 }
14799
14800 private HashMap<Intent.FilterComparison, ServiceRecord> getServicesByIntent(
14801 int callingUser) {
14802 HashMap map = mServicesByIntentPerUser.get(callingUser);
14803 if (map == null) {
14804 map = new HashMap<Intent.FilterComparison, ServiceRecord>();
14805 mServicesByIntentPerUser.put(callingUser, map);
14806 }
14807 return map;
14808 }
14809 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014810}