blob: 467297ba995ccf83d5e8b9bb3719a5d96bf22239 [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) {
1798 // The system gets to run in any process. If there are multiple
1799 // processes with the same uid, just pick the first (this
1800 // should never happen).
1801 SparseArray<ProcessRecord> procs = mProcessNames.getMap().get(
1802 processName);
1803 return procs != null ? procs.valueAt(0) : null;
1804 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001805 // uid = applyUserId(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001806 ProcessRecord proc = mProcessNames.get(processName, uid);
1807 return proc;
1808 }
1809
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001810 void ensurePackageDexOpt(String packageName) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001811 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001812 try {
1813 if (pm.performDexOpt(packageName)) {
1814 mDidDexOpt = true;
1815 }
1816 } catch (RemoteException e) {
1817 }
1818 }
1819
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001820 boolean isNextTransitionForward() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001821 int transit = mWindowManager.getPendingAppTransition();
1822 return transit == WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
1823 || transit == WindowManagerPolicy.TRANSIT_TASK_OPEN
1824 || transit == WindowManagerPolicy.TRANSIT_TASK_TO_FRONT;
1825 }
1826
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001827 final ProcessRecord startProcessLocked(String processName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001828 ApplicationInfo info, boolean knownToBeDead, int intentFlags,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001829 String hostingType, ComponentName hostingName, boolean allowWhileBooting,
1830 boolean isolated) {
1831 ProcessRecord app;
1832 if (!isolated) {
1833 app = getProcessRecordLocked(processName, info.uid);
1834 } else {
1835 // If this is an isolated process, it can't re-use an existing process.
1836 app = null;
1837 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001838 // We don't have to do anything more if:
1839 // (1) There is an existing application record; and
1840 // (2) The caller doesn't think it is dead, OR there is no thread
1841 // object attached to it so we know it couldn't have crashed; and
1842 // (3) There is a pid assigned to it, so it is either starting or
1843 // already running.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001844 if (DEBUG_PROCESSES) Slog.v(TAG, "startProcess: name=" + processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001845 + " app=" + app + " knownToBeDead=" + knownToBeDead
1846 + " thread=" + (app != null ? app.thread : null)
1847 + " pid=" + (app != null ? app.pid : -1));
Magnus Edlund7bb25812010-02-24 15:45:06 +01001848 if (app != null && app.pid > 0) {
1849 if (!knownToBeDead || app.thread == null) {
Dianne Hackborn20cb56e2010-03-04 00:58:29 -08001850 // We already have the app running, or are waiting for it to
1851 // come up (we have a pid but not yet its thread), so keep it.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001852 if (DEBUG_PROCESSES) Slog.v(TAG, "App already running: " + app);
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001853 // If this is a new package in the process, add the package to the list
1854 app.addPackage(info.packageName);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001855 return app;
1856 } else {
1857 // An application record is attached to a previous process,
1858 // clean it up now.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001859 if (DEBUG_PROCESSES) Slog.v(TAG, "App died: " + app);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07001860 handleAppDiedLocked(app, true, true);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001861 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001862 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01001863
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001864 String hostingNameStr = hostingName != null
1865 ? hostingName.flattenToShortString() : null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001866
1867 if (!isolated) {
1868 if ((intentFlags&Intent.FLAG_FROM_BACKGROUND) != 0) {
1869 // If we are in the background, then check to see if this process
1870 // is bad. If so, we will just silently fail.
1871 if (mBadProcesses.get(info.processName, info.uid) != null) {
1872 if (DEBUG_PROCESSES) Slog.v(TAG, "Bad process: " + info.uid
1873 + "/" + info.processName);
1874 return null;
1875 }
1876 } else {
1877 // When the user is explicitly starting a process, then clear its
1878 // crash count so that we won't make it bad until they see at
1879 // least one crash dialog again, and make the process good again
1880 // if it had been bad.
1881 if (DEBUG_PROCESSES) Slog.v(TAG, "Clearing bad process: " + info.uid
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001882 + "/" + info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001883 mProcessCrashTimes.remove(info.processName, info.uid);
1884 if (mBadProcesses.get(info.processName, info.uid) != null) {
1885 EventLog.writeEvent(EventLogTags.AM_PROC_GOOD, info.uid,
1886 info.processName);
1887 mBadProcesses.remove(info.processName, info.uid);
1888 if (app != null) {
1889 app.bad = false;
1890 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001891 }
1892 }
1893 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001894
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001895 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001896 app = newProcessRecordLocked(null, info, processName, isolated);
1897 if (app == null) {
1898 Slog.w(TAG, "Failed making new process record for "
1899 + processName + "/" + info.uid + " isolated=" + isolated);
1900 return null;
1901 }
1902 mProcessNames.put(processName, app.uid, app);
1903 if (isolated) {
1904 mIsolatedProcesses.put(app.uid, app);
1905 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001906 } else {
1907 // If this is a new package in the process, add the package to the list
1908 app.addPackage(info.packageName);
1909 }
1910
1911 // If the system is not ready yet, then hold off on starting this
1912 // process until it is.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001913 if (!mProcessesReady
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001914 && !isAllowedWhileBooting(info)
1915 && !allowWhileBooting) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001916 if (!mProcessesOnHold.contains(app)) {
1917 mProcessesOnHold.add(app);
1918 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001919 if (DEBUG_PROCESSES) Slog.v(TAG, "System not ready, putting on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001920 return app;
1921 }
1922
1923 startProcessLocked(app, hostingType, hostingNameStr);
1924 return (app.pid != 0) ? app : null;
1925 }
1926
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001927 boolean isAllowedWhileBooting(ApplicationInfo ai) {
1928 return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0;
1929 }
1930
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001931 private final void startProcessLocked(ProcessRecord app,
1932 String hostingType, String hostingNameStr) {
1933 if (app.pid > 0 && app.pid != MY_PID) {
1934 synchronized (mPidsSelfLocked) {
1935 mPidsSelfLocked.remove(app.pid);
1936 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
1937 }
1938 app.pid = 0;
1939 }
1940
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001941 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
1942 "startProcessLocked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001943 mProcessesOnHold.remove(app);
1944
1945 updateCpuStats();
1946
1947 System.arraycopy(mProcDeaths, 0, mProcDeaths, 1, mProcDeaths.length-1);
1948 mProcDeaths[0] = 0;
1949
1950 try {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001951 int uid = app.uid;
Amith Yamasani742a6712011-05-04 14:49:28 -07001952
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001953 int[] gids = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001954 if (!app.isolated) {
1955 try {
1956 gids = mContext.getPackageManager().getPackageGids(
1957 app.info.packageName);
1958 } catch (PackageManager.NameNotFoundException e) {
1959 Slog.w(TAG, "Unable to retrieve gids", e);
1960 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001961 }
1962 if (mFactoryTest != SystemServer.FACTORY_TEST_OFF) {
1963 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
1964 && mTopComponent != null
1965 && app.processName.equals(mTopComponent.getPackageName())) {
1966 uid = 0;
1967 }
1968 if (mFactoryTest == SystemServer.FACTORY_TEST_HIGH_LEVEL
1969 && (app.info.flags&ApplicationInfo.FLAG_FACTORY_TEST) != 0) {
1970 uid = 0;
1971 }
1972 }
1973 int debugFlags = 0;
1974 if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
1975 debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;
Elliott Hughesfa36aee2011-06-17 14:39:41 -07001976 // Also turn on CheckJNI for debuggable apps. It's quite
1977 // awkward to turn on otherwise.
1978 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001979 }
Ben Cheng6c0afff2010-02-14 16:18:56 -08001980 // Run the app in safe mode if its manifest requests so or the
1981 // system is booted in safe mode.
1982 if ((app.info.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0 ||
1983 Zygote.systemInSafeMode == true) {
Ben Cheng23085b72010-02-08 16:06:32 -08001984 debugFlags |= Zygote.DEBUG_ENABLE_SAFEMODE;
1985 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001986 if ("1".equals(SystemProperties.get("debug.checkjni"))) {
1987 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
1988 }
Elliott Hughesae07ecf2011-07-06 17:33:27 -07001989 if ("1".equals(SystemProperties.get("debug.jni.logging"))) {
1990 debugFlags |= Zygote.DEBUG_ENABLE_JNI_LOGGING;
1991 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001992 if ("1".equals(SystemProperties.get("debug.assert"))) {
1993 debugFlags |= Zygote.DEBUG_ENABLE_ASSERT;
1994 }
Jeff Brown3f9dd282011-07-08 20:02:19 -07001995
1996 // Start the process. It will either succeed and return a result containing
1997 // the PID of the new process, or else throw a RuntimeException.
1998 Process.ProcessStartResult startResult = Process.start("android.app.ActivityThread",
Elliott Hughese1dfcb72011-07-08 11:08:07 -07001999 app.processName, uid, uid, gids, debugFlags,
2000 app.info.targetSdkVersion, null);
Jeff Brown3f9dd282011-07-08 20:02:19 -07002001
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002002 BatteryStatsImpl bs = app.batteryStats.getBatteryStats();
2003 synchronized (bs) {
2004 if (bs.isOnBattery()) {
2005 app.batteryStats.incStartsLocked();
2006 }
2007 }
2008
Jeff Brown3f9dd282011-07-08 20:02:19 -07002009 EventLog.writeEvent(EventLogTags.AM_PROC_START, startResult.pid, uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002010 app.processName, hostingType,
2011 hostingNameStr != null ? hostingNameStr : "");
2012
2013 if (app.persistent) {
Jeff Brown3f9dd282011-07-08 20:02:19 -07002014 Watchdog.getInstance().processStarted(app.processName, startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002015 }
2016
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07002017 StringBuilder buf = mStringBuilder;
2018 buf.setLength(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002019 buf.append("Start proc ");
2020 buf.append(app.processName);
2021 buf.append(" for ");
2022 buf.append(hostingType);
2023 if (hostingNameStr != null) {
2024 buf.append(" ");
2025 buf.append(hostingNameStr);
2026 }
2027 buf.append(": pid=");
Jeff Brown3f9dd282011-07-08 20:02:19 -07002028 buf.append(startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002029 buf.append(" uid=");
2030 buf.append(uid);
2031 buf.append(" gids={");
2032 if (gids != null) {
2033 for (int gi=0; gi<gids.length; gi++) {
2034 if (gi != 0) buf.append(", ");
2035 buf.append(gids[gi]);
2036
2037 }
2038 }
2039 buf.append("}");
Joe Onorato8a9b2202010-02-26 18:56:32 -08002040 Slog.i(TAG, buf.toString());
Jeff Brown3f9dd282011-07-08 20:02:19 -07002041 app.pid = startResult.pid;
2042 app.usingWrapper = startResult.usingWrapper;
2043 app.removed = false;
2044 synchronized (mPidsSelfLocked) {
2045 this.mPidsSelfLocked.put(startResult.pid, app);
2046 Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
2047 msg.obj = app;
2048 mHandler.sendMessageDelayed(msg, startResult.usingWrapper
2049 ? PROC_START_TIMEOUT_WITH_WRAPPER : PROC_START_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002050 }
2051 } catch (RuntimeException e) {
2052 // XXX do better error recovery.
2053 app.pid = 0;
Joe Onorato8a9b2202010-02-26 18:56:32 -08002054 Slog.e(TAG, "Failure starting process " + app.processName, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002055 }
2056 }
2057
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002058 void updateUsageStats(ActivityRecord resumedComponent, boolean resumed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002059 if (resumed) {
2060 mUsageStatsService.noteResumeComponent(resumedComponent.realActivity);
2061 } else {
2062 mUsageStatsService.notePauseComponent(resumedComponent.realActivity);
2063 }
2064 }
2065
Amith Yamasani742a6712011-05-04 14:49:28 -07002066 boolean startHomeActivityLocked(int userId) {
Mike Lockwooda8f767a2011-08-31 14:32:37 -04002067 if (mHeadless) {
2068 // Added because none of the other calls to ensureBootCompleted seem to fire
2069 // when running headless.
2070 ensureBootCompleted();
2071 return false;
2072 }
2073
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002074 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2075 && mTopAction == null) {
2076 // We are running in factory test mode, but unable to find
2077 // the factory test app, so just sit around displaying the
2078 // error message and don't try to start anything.
2079 return false;
2080 }
2081 Intent intent = new Intent(
2082 mTopAction,
2083 mTopData != null ? Uri.parse(mTopData) : null);
2084 intent.setComponent(mTopComponent);
2085 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
2086 intent.addCategory(Intent.CATEGORY_HOME);
2087 }
2088 ActivityInfo aInfo =
2089 intent.resolveActivityInfo(mContext.getPackageManager(),
2090 STOCK_PM_FLAGS);
2091 if (aInfo != null) {
2092 intent.setComponent(new ComponentName(
2093 aInfo.applicationInfo.packageName, aInfo.name));
2094 // Don't do this if the home app is currently being
2095 // instrumented.
Amith Yamasani742a6712011-05-04 14:49:28 -07002096 aInfo = new ActivityInfo(aInfo);
2097 aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002098 ProcessRecord app = getProcessRecordLocked(aInfo.processName,
2099 aInfo.applicationInfo.uid);
2100 if (app == null || app.instrumentationClass == null) {
2101 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002102 mMainStack.startActivityLocked(null, intent, null, aInfo,
2103 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002104 }
2105 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002106
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002107 return true;
2108 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002109
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002110 /**
2111 * Starts the "new version setup screen" if appropriate.
2112 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002113 void startSetupActivityLocked() {
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002114 // Only do this once per boot.
2115 if (mCheckedForSetup) {
2116 return;
2117 }
2118
2119 // We will show this screen if the current one is a different
2120 // version than the last one shown, and we are not running in
2121 // low-level factory test mode.
2122 final ContentResolver resolver = mContext.getContentResolver();
2123 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL &&
2124 Settings.Secure.getInt(resolver,
2125 Settings.Secure.DEVICE_PROVISIONED, 0) != 0) {
2126 mCheckedForSetup = true;
2127
2128 // See if we should be showing the platform update setup UI.
2129 Intent intent = new Intent(Intent.ACTION_UPGRADE_SETUP);
2130 List<ResolveInfo> ris = mSelf.mContext.getPackageManager()
2131 .queryIntentActivities(intent, PackageManager.GET_META_DATA);
2132
2133 // We don't allow third party apps to replace this.
2134 ResolveInfo ri = null;
2135 for (int i=0; ris != null && i<ris.size(); i++) {
2136 if ((ris.get(i).activityInfo.applicationInfo.flags
2137 & ApplicationInfo.FLAG_SYSTEM) != 0) {
2138 ri = ris.get(i);
2139 break;
2140 }
2141 }
2142
2143 if (ri != null) {
2144 String vers = ri.activityInfo.metaData != null
2145 ? ri.activityInfo.metaData.getString(Intent.METADATA_SETUP_VERSION)
2146 : null;
2147 if (vers == null && ri.activityInfo.applicationInfo.metaData != null) {
2148 vers = ri.activityInfo.applicationInfo.metaData.getString(
2149 Intent.METADATA_SETUP_VERSION);
2150 }
2151 String lastVers = Settings.Secure.getString(
2152 resolver, Settings.Secure.LAST_SETUP_SHOWN);
2153 if (vers != null && !vers.equals(lastVers)) {
2154 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2155 intent.setComponent(new ComponentName(
2156 ri.activityInfo.packageName, ri.activityInfo.name));
Dianne Hackborna4972e92012-03-14 10:38:05 -07002157 mMainStack.startActivityLocked(null, intent, null, ri.activityInfo,
2158 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002159 }
2160 }
2161 }
2162 }
2163
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002164 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002165 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002166 }
2167
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002168 void enforceNotIsolatedCaller(String caller) {
2169 if (UserId.isIsolated(Binder.getCallingUid())) {
2170 throw new SecurityException("Isolated process not allowed to call " + caller);
2171 }
2172 }
2173
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002174 public int getFrontActivityScreenCompatMode() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002175 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002176 synchronized (this) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002177 return mCompatModePackages.getFrontActivityScreenCompatModeLocked();
2178 }
2179 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002180
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002181 public void setFrontActivityScreenCompatMode(int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002182 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2183 "setFrontActivityScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002184 synchronized (this) {
2185 mCompatModePackages.setFrontActivityScreenCompatModeLocked(mode);
2186 }
2187 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002188
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002189 public int getPackageScreenCompatMode(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002190 enforceNotIsolatedCaller("getPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002191 synchronized (this) {
2192 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
2193 }
2194 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002195
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002196 public void setPackageScreenCompatMode(String packageName, int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002197 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2198 "setPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002199 synchronized (this) {
2200 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002201 }
2202 }
2203
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002204 public boolean getPackageAskScreenCompat(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002205 enforceNotIsolatedCaller("getPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002206 synchronized (this) {
2207 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
2208 }
2209 }
2210
2211 public void setPackageAskScreenCompat(String packageName, boolean ask) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002212 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2213 "setPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002214 synchronized (this) {
2215 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
2216 }
2217 }
2218
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002219 void reportResumedActivityLocked(ActivityRecord r) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002220 //Slog.i(TAG, "**** REPORT RESUME: " + r);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002221
2222 final int identHash = System.identityHashCode(r);
2223 updateUsageStats(r, true);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002224 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002225
Jeff Sharkeya4620792011-05-20 15:29:23 -07002226 private void dispatchForegroundActivitiesChanged(int pid, int uid, boolean foregroundActivities) {
2227 int i = mProcessObservers.beginBroadcast();
2228 while (i > 0) {
2229 i--;
2230 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2231 if (observer != null) {
2232 try {
2233 observer.onForegroundActivitiesChanged(pid, uid, foregroundActivities);
2234 } catch (RemoteException e) {
2235 }
2236 }
2237 }
2238 mProcessObservers.finishBroadcast();
2239 }
2240
2241 private void dispatchProcessDied(int pid, int uid) {
2242 int i = mProcessObservers.beginBroadcast();
2243 while (i > 0) {
2244 i--;
2245 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2246 if (observer != null) {
2247 try {
2248 observer.onProcessDied(pid, uid);
2249 } catch (RemoteException e) {
2250 }
2251 }
2252 }
2253 mProcessObservers.finishBroadcast();
2254 }
2255
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002256 final void doPendingActivityLaunchesLocked(boolean doResume) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002257 final int N = mPendingActivityLaunches.size();
2258 if (N <= 0) {
2259 return;
2260 }
2261 for (int i=0; i<N; i++) {
2262 PendingActivityLaunch pal = mPendingActivityLaunches.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002263 mMainStack.startActivityUncheckedLocked(pal.r, pal.sourceRecord,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002264 pal.startFlags, doResume && i == (N-1), null);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002265 }
2266 mPendingActivityLaunches.clear();
2267 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002268
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002269 public final int startActivity(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002270 Intent intent, String resolvedType, IBinder resultTo,
2271 String resultWho, int requestCode, int startFlags,
2272 String profileFile, ParcelFileDescriptor profileFd, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002273 enforceNotIsolatedCaller("startActivity");
Amith Yamasani742a6712011-05-04 14:49:28 -07002274 int userId = 0;
2275 if (intent.getCategories() != null && intent.getCategories().contains(Intent.CATEGORY_HOME)) {
2276 // Requesting home, set the identity to the current user
2277 // HACK!
2278 userId = mCurrentUserId;
2279 } else {
2280 // TODO: Fix this in a better way - calls coming from SystemUI should probably carry
2281 // the current user's userId
2282 if (Binder.getCallingUid() < Process.FIRST_APPLICATION_UID) {
2283 userId = 0;
2284 } else {
2285 userId = Binder.getOrigCallingUser();
2286 }
2287 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002288 return mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002289 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
2290 null, null, options, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002291 }
2292
2293 public final WaitResult startActivityAndWait(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002294 Intent intent, String resolvedType, IBinder resultTo,
2295 String resultWho, int requestCode, int startFlags, String profileFile,
2296 ParcelFileDescriptor profileFd, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002297 enforceNotIsolatedCaller("startActivityAndWait");
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002298 WaitResult res = new WaitResult();
Amith Yamasani742a6712011-05-04 14:49:28 -07002299 int userId = Binder.getOrigCallingUser();
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002300 mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002301 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
2302 res, null, options, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002303 return res;
2304 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08002305
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002306 public final int startActivityWithConfig(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002307 Intent intent, String resolvedType, IBinder resultTo,
2308 String resultWho, int requestCode, int startFlags, Configuration config,
2309 Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002310 enforceNotIsolatedCaller("startActivityWithConfig");
Amith Yamasani742a6712011-05-04 14:49:28 -07002311 int ret = mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002312 resultTo, resultWho, requestCode, startFlags,
2313 null, null, null, config, options, Binder.getOrigCallingUser());
Amith Yamasani742a6712011-05-04 14:49:28 -07002314 return ret;
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002315 }
2316
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002317 public int startActivityIntentSender(IApplicationThread caller,
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002318 IntentSender intent, Intent fillInIntent, String resolvedType,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002319 IBinder resultTo, String resultWho, int requestCode,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002320 int flagsMask, int flagsValues, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002321 enforceNotIsolatedCaller("startActivityIntentSender");
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002322 // Refuse possible leaked file descriptors
2323 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
2324 throw new IllegalArgumentException("File descriptors passed in Intent");
2325 }
2326
2327 IIntentSender sender = intent.getTarget();
2328 if (!(sender instanceof PendingIntentRecord)) {
2329 throw new IllegalArgumentException("Bad PendingIntent object");
2330 }
2331
2332 PendingIntentRecord pir = (PendingIntentRecord)sender;
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002333
2334 synchronized (this) {
2335 // If this is coming from the currently resumed activity, it is
2336 // effectively saying that app switches are allowed at this point.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002337 if (mMainStack.mResumedActivity != null
2338 && mMainStack.mResumedActivity.info.applicationInfo.uid ==
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002339 Binder.getCallingUid()) {
2340 mAppSwitchesAllowedTime = 0;
2341 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002342 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002343 int ret = pir.sendInner(0, fillInIntent, resolvedType, null, null,
2344 resultTo, resultWho, requestCode, flagsMask, flagsValues, options);
Amith Yamasani742a6712011-05-04 14:49:28 -07002345 return ret;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002346 }
2347
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002348 public boolean startNextMatchingActivity(IBinder callingActivity,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002349 Intent intent, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002350 // Refuse possible leaked file descriptors
2351 if (intent != null && intent.hasFileDescriptors() == true) {
2352 throw new IllegalArgumentException("File descriptors passed in Intent");
2353 }
2354
2355 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002356 ActivityRecord r = mMainStack.isInStackLocked(callingActivity);
2357 if (r == null) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002358 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002359 return false;
2360 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002361 if (r.app == null || r.app.thread == null) {
2362 // The caller is not running... d'oh!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002363 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002364 return false;
2365 }
2366 intent = new Intent(intent);
2367 // The caller is not allowed to change the data.
2368 intent.setDataAndType(r.intent.getData(), r.intent.getType());
2369 // And we are resetting to find the next component...
2370 intent.setComponent(null);
2371
2372 ActivityInfo aInfo = null;
2373 try {
2374 List<ResolveInfo> resolves =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002375 AppGlobals.getPackageManager().queryIntentActivities(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002376 intent, r.resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002377 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
2378 UserId.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002379
2380 // Look for the original activity in the list...
2381 final int N = resolves != null ? resolves.size() : 0;
2382 for (int i=0; i<N; i++) {
2383 ResolveInfo rInfo = resolves.get(i);
2384 if (rInfo.activityInfo.packageName.equals(r.packageName)
2385 && rInfo.activityInfo.name.equals(r.info.name)) {
2386 // We found the current one... the next matching is
2387 // after it.
2388 i++;
2389 if (i<N) {
2390 aInfo = resolves.get(i).activityInfo;
2391 }
2392 break;
2393 }
2394 }
2395 } catch (RemoteException e) {
2396 }
2397
2398 if (aInfo == null) {
2399 // Nobody who is next!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002400 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002401 return false;
2402 }
2403
2404 intent.setComponent(new ComponentName(
2405 aInfo.applicationInfo.packageName, aInfo.name));
2406 intent.setFlags(intent.getFlags()&~(
2407 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
2408 Intent.FLAG_ACTIVITY_CLEAR_TOP|
2409 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
2410 Intent.FLAG_ACTIVITY_NEW_TASK));
2411
2412 // Okay now we need to start the new activity, replacing the
2413 // currently running activity. This is a little tricky because
2414 // we want to start the new one as if the current one is finished,
2415 // but not finish the current one first so that there is no flicker.
2416 // And thus...
2417 final boolean wasFinishing = r.finishing;
2418 r.finishing = true;
2419
2420 // Propagate reply information over to the new activity.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002421 final ActivityRecord resultTo = r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002422 final String resultWho = r.resultWho;
2423 final int requestCode = r.requestCode;
2424 r.resultTo = null;
2425 if (resultTo != null) {
2426 resultTo.removeResultsLocked(r, resultWho, requestCode);
2427 }
2428
2429 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002430 int res = mMainStack.startActivityLocked(r.app.thread, intent,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002431 r.resolvedType, aInfo, resultTo != null ? resultTo.appToken : null,
2432 resultWho, requestCode, -1, r.launchedFromUid, 0,
2433 options, false, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002434 Binder.restoreCallingIdentity(origId);
2435
2436 r.finishing = wasFinishing;
Dianne Hackborna4972e92012-03-14 10:38:05 -07002437 if (res != ActivityManager.START_SUCCESS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002438 return false;
2439 }
2440 return true;
2441 }
2442 }
2443
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002444 public final int startActivityInPackage(int uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002445 Intent intent, String resolvedType, IBinder resultTo,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002446 String resultWho, int requestCode, int startFlags, Bundle options) {
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002447
2448 // This is so super not safe, that only the system (or okay root)
2449 // can do it.
Amith Yamasani742a6712011-05-04 14:49:28 -07002450 int userId = Binder.getOrigCallingUser();
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002451 final int callingUid = Binder.getCallingUid();
2452 if (callingUid != 0 && callingUid != Process.myUid()) {
2453 throw new SecurityException(
2454 "startActivityInPackage only available to the system");
2455 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002456
Amith Yamasani742a6712011-05-04 14:49:28 -07002457 int ret = mMainStack.startActivityMayWait(null, uid, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002458 resultTo, resultWho, requestCode, startFlags,
2459 null, null, null, null, options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002460 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002461 }
2462
2463 public final int startActivities(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002464 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002465 enforceNotIsolatedCaller("startActivities");
Amith Yamasani742a6712011-05-04 14:49:28 -07002466 int ret = mMainStack.startActivities(caller, -1, intents, resolvedTypes, resultTo,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002467 options, Binder.getOrigCallingUser());
Amith Yamasani742a6712011-05-04 14:49:28 -07002468 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002469 }
2470
2471 public final int startActivitiesInPackage(int uid,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002472 Intent[] intents, String[] resolvedTypes, IBinder resultTo,
2473 Bundle options) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002474
2475 // This is so super not safe, that only the system (or okay root)
2476 // can do it.
2477 final int callingUid = Binder.getCallingUid();
2478 if (callingUid != 0 && callingUid != Process.myUid()) {
2479 throw new SecurityException(
2480 "startActivityInPackage only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002481 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002482 int ret = mMainStack.startActivities(null, uid, intents, resolvedTypes, resultTo,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002483 options, UserId.getUserId(uid));
Amith Yamasani742a6712011-05-04 14:49:28 -07002484 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002485 }
2486
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002487 final void addRecentTaskLocked(TaskRecord task) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002488 int N = mRecentTasks.size();
Dianne Hackborn7c0e75e2010-12-21 19:15:40 -08002489 // Quick case: check if the top-most recent task is the same.
2490 if (N > 0 && mRecentTasks.get(0) == task) {
2491 return;
2492 }
2493 // Remove any existing entries that are the same kind of task.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002494 for (int i=0; i<N; i++) {
2495 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07002496 if (task.userId == tr.userId
2497 && ((task.affinity != null && task.affinity.equals(tr.affinity))
2498 || (task.intent != null && task.intent.filterEquals(tr.intent)))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002499 mRecentTasks.remove(i);
2500 i--;
2501 N--;
2502 if (task.intent == null) {
2503 // If the new recent task we are adding is not fully
2504 // specified, then replace it with the existing recent task.
2505 task = tr;
2506 }
2507 }
2508 }
2509 if (N >= MAX_RECENT_TASKS) {
2510 mRecentTasks.remove(N-1);
2511 }
2512 mRecentTasks.add(0, task);
2513 }
2514
2515 public void setRequestedOrientation(IBinder token,
2516 int requestedOrientation) {
2517 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002518 ActivityRecord r = mMainStack.isInStackLocked(token);
2519 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002520 return;
2521 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002522 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornbe707852011-11-11 14:32:10 -08002523 mWindowManager.setAppOrientation(r.appToken, requestedOrientation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002524 Configuration config = mWindowManager.updateOrientationFromAppTokens(
The Android Open Source Project10592532009-03-18 17:39:46 -07002525 mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -08002526 r.mayFreezeScreenLocked(r.app) ? r.appToken : null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002527 if (config != null) {
2528 r.frozenBeforeDestroy = true;
Dianne Hackborn813075a62011-11-14 17:45:19 -08002529 if (!updateConfigurationLocked(config, r, false, false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002530 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002531 }
2532 }
2533 Binder.restoreCallingIdentity(origId);
2534 }
2535 }
2536
2537 public int getRequestedOrientation(IBinder token) {
2538 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002539 ActivityRecord r = mMainStack.isInStackLocked(token);
2540 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002541 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
2542 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08002543 return mWindowManager.getAppOrientation(r.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002544 }
2545 }
2546
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002547 /**
2548 * This is the internal entry point for handling Activity.finish().
2549 *
2550 * @param token The Binder token referencing the Activity we want to finish.
2551 * @param resultCode Result code, if any, from this Activity.
2552 * @param resultData Result data (Intent), if any, from this Activity.
2553 *
Alexey Tarasov83bad3d2009-08-12 15:05:43 +11002554 * @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 -08002555 */
2556 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData) {
2557 // Refuse possible leaked file descriptors
2558 if (resultData != null && resultData.hasFileDescriptors() == true) {
2559 throw new IllegalArgumentException("File descriptors passed in Intent");
2560 }
2561
2562 synchronized(this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002563 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002564 // Find the first activity that is not finishing.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002565 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002566 if (next != null) {
2567 // ask watcher if this is allowed
2568 boolean resumeOK = true;
2569 try {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002570 resumeOK = mController.activityResuming(next.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002571 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002572 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002573 }
2574
2575 if (!resumeOK) {
2576 return false;
2577 }
2578 }
2579 }
2580 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002581 boolean res = mMainStack.requestFinishActivityLocked(token, resultCode,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002582 resultData, "app-request");
2583 Binder.restoreCallingIdentity(origId);
2584 return res;
2585 }
2586 }
2587
Dianne Hackborn860755f2010-06-03 18:47:52 -07002588 public final void finishHeavyWeightApp() {
2589 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2590 != PackageManager.PERMISSION_GRANTED) {
2591 String msg = "Permission Denial: finishHeavyWeightApp() from pid="
2592 + Binder.getCallingPid()
2593 + ", uid=" + Binder.getCallingUid()
2594 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2595 Slog.w(TAG, msg);
2596 throw new SecurityException(msg);
2597 }
2598
2599 synchronized(this) {
2600 if (mHeavyWeightProcess == null) {
2601 return;
2602 }
2603
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002604 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>(
Dianne Hackborn860755f2010-06-03 18:47:52 -07002605 mHeavyWeightProcess.activities);
2606 for (int i=0; i<activities.size(); i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002607 ActivityRecord r = activities.get(i);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002608 if (!r.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002609 int index = mMainStack.indexOfTokenLocked(r.appToken);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002610 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002611 mMainStack.finishActivityLocked(r, index, Activity.RESULT_CANCELED,
Dianne Hackborn860755f2010-06-03 18:47:52 -07002612 null, "finish-heavy");
2613 }
2614 }
2615 }
2616
2617 mHeavyWeightProcess = null;
2618 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
2619 }
2620 }
2621
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002622 public void crashApplication(int uid, int initialPid, String packageName,
2623 String message) {
2624 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2625 != PackageManager.PERMISSION_GRANTED) {
2626 String msg = "Permission Denial: crashApplication() from pid="
2627 + Binder.getCallingPid()
2628 + ", uid=" + Binder.getCallingUid()
2629 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2630 Slog.w(TAG, msg);
2631 throw new SecurityException(msg);
2632 }
2633
2634 synchronized(this) {
2635 ProcessRecord proc = null;
2636
2637 // Figure out which process to kill. We don't trust that initialPid
2638 // still has any relation to current pids, so must scan through the
2639 // list.
2640 synchronized (mPidsSelfLocked) {
2641 for (int i=0; i<mPidsSelfLocked.size(); i++) {
2642 ProcessRecord p = mPidsSelfLocked.valueAt(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002643 if (p.uid != uid) {
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002644 continue;
2645 }
2646 if (p.pid == initialPid) {
2647 proc = p;
2648 break;
2649 }
2650 for (String str : p.pkgList) {
2651 if (str.equals(packageName)) {
2652 proc = p;
2653 }
2654 }
2655 }
2656 }
2657
2658 if (proc == null) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07002659 Slog.w(TAG, "crashApplication: nothing for uid=" + uid
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002660 + " initialPid=" + initialPid
2661 + " packageName=" + packageName);
2662 return;
2663 }
2664
2665 if (proc.thread != null) {
Dianne Hackborn9f531192010-08-04 17:48:03 -07002666 if (proc.pid == Process.myPid()) {
2667 Log.w(TAG, "crashApplication: trying to crash self!");
2668 return;
2669 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002670 long ident = Binder.clearCallingIdentity();
2671 try {
2672 proc.thread.scheduleCrash(message);
2673 } catch (RemoteException e) {
2674 }
2675 Binder.restoreCallingIdentity(ident);
2676 }
2677 }
2678 }
2679
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002680 public final void finishSubActivity(IBinder token, String resultWho,
2681 int requestCode) {
2682 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002683 ActivityRecord self = mMainStack.isInStackLocked(token);
2684 if (self == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002685 return;
2686 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002687
2688 final long origId = Binder.clearCallingIdentity();
2689
2690 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002691 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2692 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002693 if (r.resultTo == self && r.requestCode == requestCode) {
2694 if ((r.resultWho == null && resultWho == null) ||
2695 (r.resultWho != null && r.resultWho.equals(resultWho))) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002696 mMainStack.finishActivityLocked(r, i,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002697 Activity.RESULT_CANCELED, null, "request-sub");
2698 }
2699 }
2700 }
2701
2702 Binder.restoreCallingIdentity(origId);
2703 }
2704 }
2705
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002706 public boolean willActivityBeVisible(IBinder token) {
2707 synchronized(this) {
2708 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002709 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2710 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08002711 if (r.appToken == token) {
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002712 return true;
2713 }
2714 if (r.fullscreen && !r.finishing) {
2715 return false;
2716 }
2717 }
2718 return true;
2719 }
2720 }
2721
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002722 public void overridePendingTransition(IBinder token, String packageName,
2723 int enterAnim, int exitAnim) {
2724 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002725 ActivityRecord self = mMainStack.isInStackLocked(token);
2726 if (self == null) {
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002727 return;
2728 }
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002729
2730 final long origId = Binder.clearCallingIdentity();
2731
2732 if (self.state == ActivityState.RESUMED
2733 || self.state == ActivityState.PAUSING) {
2734 mWindowManager.overridePendingAppTransition(packageName,
2735 enterAnim, exitAnim);
2736 }
2737
2738 Binder.restoreCallingIdentity(origId);
2739 }
2740 }
2741
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002742 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002743 * Main function for removing an existing process from the activity manager
2744 * as a result of that process going away. Clears out all connections
2745 * to the process.
2746 */
2747 private final void handleAppDiedLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002748 boolean restarting, boolean allowRestart) {
2749 cleanUpApplicationRecordLocked(app, restarting, allowRestart, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002750 if (!restarting) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002751 mLruProcesses.remove(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002752 }
2753
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002754 if (mProfileProc == app) {
2755 clearProfilerLocked();
2756 }
2757
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002758 // Just in case...
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002759 if (mMainStack.mPausingActivity != null && mMainStack.mPausingActivity.app == app) {
2760 if (DEBUG_PAUSE) Slog.v(TAG, "App died while pausing: " +mMainStack.mPausingActivity);
2761 mMainStack.mPausingActivity = null;
2762 }
2763 if (mMainStack.mLastPausedActivity != null && mMainStack.mLastPausedActivity.app == app) {
2764 mMainStack.mLastPausedActivity = null;
2765 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002766
2767 // Remove this application's activities from active lists.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002768 mMainStack.removeHistoryRecordsForAppLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002769
2770 boolean atTop = true;
2771 boolean hasVisibleActivities = false;
2772
2773 // Clean out the history list.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002774 int i = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08002775 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002776 TAG, "Removing app " + app + " from history with " + i + " entries");
2777 while (i > 0) {
2778 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002779 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002780 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002781 TAG, "Record #" + i + " " + r + ": app=" + r.app);
2782 if (r.app == app) {
2783 if ((!r.haveState && !r.stateNotNeeded) || r.finishing) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002784 if (ActivityStack.DEBUG_ADD_REMOVE) {
2785 RuntimeException here = new RuntimeException("here");
2786 here.fillInStackTrace();
2787 Slog.i(TAG, "Removing activity " + r + " from stack at " + i
2788 + ": haveState=" + r.haveState
2789 + " stateNotNeeded=" + r.stateNotNeeded
2790 + " finishing=" + r.finishing
2791 + " state=" + r.state, here);
2792 }
2793 if (!r.finishing) {
2794 Slog.w(TAG, "Force removing " + r + ": app died, no saved state");
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -08002795 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
2796 System.identityHashCode(r),
2797 r.task.taskId, r.shortComponentName,
2798 "proc died without state saved");
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002799 }
Dianne Hackborn5c607432012-02-28 14:44:19 -08002800 mMainStack.removeActivityFromHistoryLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002801
2802 } else {
2803 // We have the current state for this activity, so
2804 // it can be restarted later when needed.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002805 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002806 TAG, "Keeping entry, setting app to null");
2807 if (r.visible) {
2808 hasVisibleActivities = true;
2809 }
2810 r.app = null;
2811 r.nowVisible = false;
2812 if (!r.haveState) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002813 if (ActivityStack.DEBUG_SAVED_STATE) Slog.i(TAG,
2814 "App died, clearing saved state of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002815 r.icicle = null;
2816 }
2817 }
2818
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002819 r.stack.cleanUpActivityLocked(r, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002820 }
2821 atTop = false;
2822 }
2823
2824 app.activities.clear();
2825
2826 if (app.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002827 Slog.w(TAG, "Crash of app " + app.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002828 + " running instrumentation " + app.instrumentationClass);
2829 Bundle info = new Bundle();
2830 info.putString("shortMsg", "Process crashed.");
2831 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
2832 }
2833
2834 if (!restarting) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002835 if (!mMainStack.resumeTopActivityLocked(null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002836 // If there was nothing to resume, and we are not already
2837 // restarting this process, but there is a visible activity that
2838 // is hosted by the process... then make sure all visible
2839 // activities are running, taking care of restarting this
2840 // process.
2841 if (hasVisibleActivities) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002842 mMainStack.ensureActivitiesVisibleLocked(null, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002843 }
2844 }
2845 }
2846 }
2847
2848 private final int getLRURecordIndexForAppLocked(IApplicationThread thread) {
2849 IBinder threadBinder = thread.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002850 // Find the application record.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002851 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2852 ProcessRecord rec = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002853 if (rec.thread != null && rec.thread.asBinder() == threadBinder) {
2854 return i;
2855 }
2856 }
2857 return -1;
2858 }
2859
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002860 final ProcessRecord getRecordForAppLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002861 IApplicationThread thread) {
2862 if (thread == null) {
2863 return null;
2864 }
2865
2866 int appIndex = getLRURecordIndexForAppLocked(thread);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002867 return appIndex >= 0 ? mLruProcesses.get(appIndex) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002868 }
2869
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002870 final void appDiedLocked(ProcessRecord app, int pid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002871 IApplicationThread thread) {
2872
2873 mProcDeaths[0]++;
2874
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002875 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
2876 synchronized (stats) {
2877 stats.noteProcessDiedLocked(app.info.uid, pid);
2878 }
2879
Magnus Edlund7bb25812010-02-24 15:45:06 +01002880 // Clean up already done if the process has been re-started.
2881 if (app.pid == pid && app.thread != null &&
2882 app.thread.asBinder() == thread.asBinder()) {
Dianne Hackborn906497c2010-05-10 15:57:38 -07002883 if (!app.killedBackground) {
2884 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
2885 + ") has died.");
2886 }
Doug Zongker2bec3d42009-12-04 12:52:44 -08002887 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002888 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002889 TAG, "Dying app: " + app + ", pid: " + pid
2890 + ", thread: " + thread.asBinder());
2891 boolean doLowMem = app.instrumentationClass == null;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002892 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002893
2894 if (doLowMem) {
2895 // If there are no longer any background processes running,
2896 // and the app that died was not running instrumentation,
2897 // then tell everyone we are now low on memory.
2898 boolean haveBg = false;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002899 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2900 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -07002901 if (rec.thread != null && rec.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002902 haveBg = true;
2903 break;
2904 }
2905 }
2906
2907 if (!haveBg) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002908 EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mLruProcesses.size());
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002909 long now = SystemClock.uptimeMillis();
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002910 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2911 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn36124872009-10-08 16:22:03 -07002912 if (rec != app && rec.thread != null &&
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002913 (rec.lastLowMemory+GC_MIN_INTERVAL) <= now) {
2914 // The low memory report is overriding any current
2915 // state for a GC request. Make sure to do
Dianne Hackborn32907cf2010-06-10 17:50:20 -07002916 // heavy/important/visible/foreground processes first.
Dianne Hackborn7d608422011-08-07 16:24:18 -07002917 if (rec.setAdj <= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002918 rec.lastRequestedGc = 0;
2919 } else {
2920 rec.lastRequestedGc = rec.lastLowMemory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002921 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002922 rec.reportLowMemory = true;
2923 rec.lastLowMemory = now;
2924 mProcessesToGc.remove(rec);
2925 addProcessToGcListLocked(rec);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002926 }
2927 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07002928 mHandler.sendEmptyMessage(REPORT_MEM_USAGE);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002929 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002930 }
2931 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01002932 } else if (app.pid != pid) {
2933 // A new process has already been started.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002934 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
Magnus Edlund7bb25812010-02-24 15:45:06 +01002935 + ") has died and restarted (pid " + app.pid + ").");
Dianne Hackborn28a8c2b2010-03-01 11:30:02 -08002936 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08002937 } else if (DEBUG_PROCESSES) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002938 Slog.d(TAG, "Received spurious death notification for thread "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002939 + thread.asBinder());
2940 }
2941 }
2942
Dan Egnor42471dd2010-01-07 17:25:22 -08002943 /**
2944 * If a stack trace dump file is configured, dump process stack traces.
Christopher Tate6ee412d2010-05-28 12:01:56 -07002945 * @param clearTraces causes the dump file to be erased prior to the new
2946 * traces being written, if true; when false, the new traces will be
2947 * appended to any existing file content.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002948 * @param firstPids of dalvik VM processes to dump stack traces for first
2949 * @param lastPids of dalvik VM processes to dump stack traces for last
Dan Egnor42471dd2010-01-07 17:25:22 -08002950 * @return file containing stack traces, or null if no dump file is configured
2951 */
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002952 public static File dumpStackTraces(boolean clearTraces, ArrayList<Integer> firstPids,
2953 ProcessStats processStats, SparseArray<Boolean> lastPids) {
Dan Egnor42471dd2010-01-07 17:25:22 -08002954 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
2955 if (tracesPath == null || tracesPath.length() == 0) {
2956 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002957 }
Dan Egnor42471dd2010-01-07 17:25:22 -08002958
2959 File tracesFile = new File(tracesPath);
2960 try {
2961 File tracesDir = tracesFile.getParentFile();
2962 if (!tracesDir.exists()) tracesFile.mkdirs();
2963 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
2964
Christopher Tate6ee412d2010-05-28 12:01:56 -07002965 if (clearTraces && tracesFile.exists()) tracesFile.delete();
Dan Egnor42471dd2010-01-07 17:25:22 -08002966 tracesFile.createNewFile();
2967 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
2968 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002969 Slog.w(TAG, "Unable to prepare ANR traces file: " + tracesPath, e);
Dan Egnor42471dd2010-01-07 17:25:22 -08002970 return null;
2971 }
2972
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07002973 dumpStackTraces(tracesPath, firstPids, processStats, lastPids);
2974 return tracesFile;
2975 }
2976
2977 private static void dumpStackTraces(String tracesPath, ArrayList<Integer> firstPids,
2978 ProcessStats processStats, SparseArray<Boolean> lastPids) {
Dan Egnor42471dd2010-01-07 17:25:22 -08002979 // Use a FileObserver to detect when traces finish writing.
2980 // The order of traces is considered important to maintain for legibility.
2981 FileObserver observer = new FileObserver(tracesPath, FileObserver.CLOSE_WRITE) {
2982 public synchronized void onEvent(int event, String path) { notify(); }
2983 };
2984
2985 try {
2986 observer.startWatching();
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002987
2988 // First collect all of the stacks of the most important pids.
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07002989 if (firstPids != null) {
2990 try {
2991 int num = firstPids.size();
2992 for (int i = 0; i < num; i++) {
2993 synchronized (observer) {
2994 Process.sendSignal(firstPids.get(i), Process.SIGNAL_QUIT);
2995 observer.wait(200); // Wait for write-close, give up after 200msec
2996 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002997 }
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07002998 } catch (InterruptedException e) {
2999 Log.wtf(TAG, e);
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003000 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003001 }
3002
3003 // Next measure CPU usage.
3004 if (processStats != null) {
3005 processStats.init();
3006 System.gc();
3007 processStats.update();
3008 try {
3009 synchronized (processStats) {
3010 processStats.wait(500); // measure over 1/2 second.
3011 }
3012 } catch (InterruptedException e) {
3013 }
3014 processStats.update();
3015
3016 // We'll take the stack crawls of just the top apps using CPU.
3017 final int N = processStats.countWorkingStats();
3018 int numProcs = 0;
3019 for (int i=0; i<N && numProcs<5; i++) {
3020 ProcessStats.Stats stats = processStats.getWorkingStats(i);
3021 if (lastPids.indexOfKey(stats.pid) >= 0) {
3022 numProcs++;
3023 try {
3024 synchronized (observer) {
3025 Process.sendSignal(stats.pid, Process.SIGNAL_QUIT);
3026 observer.wait(200); // Wait for write-close, give up after 200msec
3027 }
3028 } catch (InterruptedException e) {
3029 Log.wtf(TAG, e);
3030 }
3031
3032 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003033 }
3034 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003035
Dan Egnor42471dd2010-01-07 17:25:22 -08003036 } finally {
3037 observer.stopWatching();
3038 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003039 }
3040
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003041 final void logAppTooSlow(ProcessRecord app, long startTime, String msg) {
3042 if (IS_USER_BUILD) {
3043 return;
3044 }
3045 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
3046 if (tracesPath == null || tracesPath.length() == 0) {
3047 return;
3048 }
3049
3050 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
3051 StrictMode.allowThreadDiskWrites();
3052 try {
3053 final File tracesFile = new File(tracesPath);
3054 final File tracesDir = tracesFile.getParentFile();
3055 final File tracesTmp = new File(tracesDir, "__tmp__");
3056 try {
3057 if (!tracesDir.exists()) tracesFile.mkdirs();
3058 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
3059
3060 if (tracesFile.exists()) {
3061 tracesTmp.delete();
3062 tracesFile.renameTo(tracesTmp);
3063 }
3064 StringBuilder sb = new StringBuilder();
3065 Time tobj = new Time();
3066 tobj.set(System.currentTimeMillis());
3067 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
3068 sb.append(": ");
3069 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
3070 sb.append(" since ");
3071 sb.append(msg);
3072 FileOutputStream fos = new FileOutputStream(tracesFile);
3073 fos.write(sb.toString().getBytes());
3074 if (app == null) {
3075 fos.write("\n*** No application process!".getBytes());
3076 }
3077 fos.close();
3078 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
3079 } catch (IOException e) {
3080 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesPath, e);
3081 return;
3082 }
3083
3084 if (app != null) {
3085 ArrayList<Integer> firstPids = new ArrayList<Integer>();
3086 firstPids.add(app.pid);
3087 dumpStackTraces(tracesPath, firstPids, null, null);
3088 }
3089
3090 File lastTracesFile = null;
3091 File curTracesFile = null;
3092 for (int i=9; i>=0; i--) {
3093 String name = String.format("slow%02d.txt", i);
3094 curTracesFile = new File(tracesDir, name);
3095 if (curTracesFile.exists()) {
3096 if (lastTracesFile != null) {
3097 curTracesFile.renameTo(lastTracesFile);
3098 } else {
3099 curTracesFile.delete();
3100 }
3101 }
3102 lastTracesFile = curTracesFile;
3103 }
3104 tracesFile.renameTo(curTracesFile);
3105 if (tracesTmp.exists()) {
3106 tracesTmp.renameTo(tracesFile);
3107 }
3108 } finally {
3109 StrictMode.setThreadPolicy(oldPolicy);
3110 }
3111 }
3112
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003113 final void appNotResponding(ProcessRecord app, ActivityRecord activity,
3114 ActivityRecord parent, final String annotation) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003115 ArrayList<Integer> firstPids = new ArrayList<Integer>(5);
3116 SparseArray<Boolean> lastPids = new SparseArray<Boolean>(20);
3117
Dianne Hackborn287952c2010-09-22 22:34:31 -07003118 if (mController != null) {
3119 try {
3120 // 0 == continue, -1 = kill process immediately
3121 int res = mController.appEarlyNotResponding(app.processName, app.pid, annotation);
3122 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3123 } catch (RemoteException e) {
3124 mController = null;
3125 }
3126 }
3127
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003128 long anrTime = SystemClock.uptimeMillis();
3129 if (MONITOR_CPU_USAGE) {
3130 updateCpuStatsNow();
3131 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003132
3133 synchronized (this) {
3134 // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down.
3135 if (mShuttingDown) {
3136 Slog.i(TAG, "During shutdown skipping ANR: " + app + " " + annotation);
3137 return;
3138 } else if (app.notResponding) {
3139 Slog.i(TAG, "Skipping duplicate ANR: " + app + " " + annotation);
3140 return;
3141 } else if (app.crashing) {
3142 Slog.i(TAG, "Crashing app skipping ANR: " + app + " " + annotation);
3143 return;
3144 }
3145
3146 // In case we come through here for the same app before completing
3147 // this one, mark as anring now so we will bail out.
3148 app.notResponding = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08003149
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003150 // Log the ANR to the event log.
3151 EventLog.writeEvent(EventLogTags.AM_ANR, app.pid, app.processName, app.info.flags,
3152 annotation);
Dan Egnor42471dd2010-01-07 17:25:22 -08003153
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003154 // Dump thread traces as quickly as we can, starting with "interesting" processes.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003155 firstPids.add(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003156
3157 int parentPid = app.pid;
3158 if (parent != null && parent.app != null && parent.app.pid > 0) parentPid = parent.app.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003159 if (parentPid != app.pid) firstPids.add(parentPid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003160
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003161 if (MY_PID != app.pid && MY_PID != parentPid) firstPids.add(MY_PID);
Dan Egnor42471dd2010-01-07 17:25:22 -08003162
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003163 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
3164 ProcessRecord r = mLruProcesses.get(i);
3165 if (r != null && r.thread != null) {
3166 int pid = r.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003167 if (pid > 0 && pid != app.pid && pid != parentPid && pid != MY_PID) {
3168 if (r.persistent) {
3169 firstPids.add(pid);
3170 } else {
3171 lastPids.put(pid, Boolean.TRUE);
3172 }
3173 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003174 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003175 }
3176 }
3177
Dan Egnor42471dd2010-01-07 17:25:22 -08003178 // Log the ANR to the main log.
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07003179 StringBuilder info = mStringBuilder;
3180 info.setLength(0);
Dan Egnor42471dd2010-01-07 17:25:22 -08003181 info.append("ANR in ").append(app.processName);
3182 if (activity != null && activity.shortComponentName != null) {
3183 info.append(" (").append(activity.shortComponentName).append(")");
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07003184 }
Eric Rowe6f4f6192010-02-17 18:29:04 -08003185 info.append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003186 if (annotation != null) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003187 info.append("Reason: ").append(annotation).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003188 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003189 if (parent != null && parent != activity) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003190 info.append("Parent: ").append(parent.shortComponentName).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003191 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003192
Dianne Hackborn287952c2010-09-22 22:34:31 -07003193 final ProcessStats processStats = new ProcessStats(true);
3194
3195 File tracesFile = dumpStackTraces(true, firstPids, processStats, lastPids);
3196
Dan Egnor42471dd2010-01-07 17:25:22 -08003197 String cpuInfo = null;
3198 if (MONITOR_CPU_USAGE) {
3199 updateCpuStatsNow();
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003200 synchronized (mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003201 cpuInfo = mProcessStats.printCurrentState(anrTime);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003202 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003203 info.append(processStats.printCurrentLoad());
Dan Egnor42471dd2010-01-07 17:25:22 -08003204 info.append(cpuInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003205 }
3206
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003207 info.append(processStats.printCurrentState(anrTime));
3208
Joe Onorato8a9b2202010-02-26 18:56:32 -08003209 Slog.e(TAG, info.toString());
Dan Egnor42471dd2010-01-07 17:25:22 -08003210 if (tracesFile == null) {
3211 // There is no trace file, so dump (only) the alleged culprit's threads to the log
3212 Process.sendSignal(app.pid, Process.SIGNAL_QUIT);
3213 }
3214
Jeff Sharkeya353d262011-10-28 11:12:06 -07003215 addErrorToDropBox("anr", app, app.processName, activity, parent, annotation,
3216 cpuInfo, tracesFile, null);
Dan Egnor42471dd2010-01-07 17:25:22 -08003217
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003218 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003219 try {
Dan Egnor42471dd2010-01-07 17:25:22 -08003220 // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately
3221 int res = mController.appNotResponding(app.processName, app.pid, info.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003222 if (res != 0) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003223 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3224 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003225 }
3226 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003227 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003228 }
3229 }
3230
Dan Egnor42471dd2010-01-07 17:25:22 -08003231 // Unless configured otherwise, swallow ANRs in background processes & kill the process.
3232 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
3233 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003234
3235 synchronized (this) {
3236 if (!showBackground && !app.isInterestingToUserLocked() && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003237 Slog.w(TAG, "Killing " + app + ": background ANR");
3238 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
3239 app.processName, app.setAdj, "background ANR");
3240 Process.killProcessQuiet(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003241 return;
3242 }
3243
3244 // Set the app's notResponding state, and look up the errorReportReceiver
3245 makeAppNotRespondingLocked(app,
3246 activity != null ? activity.shortComponentName : null,
3247 annotation != null ? "ANR " + annotation : "ANR",
3248 info.toString());
3249
3250 // Bring up the infamous App Not Responding dialog
3251 Message msg = Message.obtain();
3252 HashMap map = new HashMap();
3253 msg.what = SHOW_NOT_RESPONDING_MSG;
3254 msg.obj = map;
3255 map.put("app", app);
3256 if (activity != null) {
3257 map.put("activity", activity);
3258 }
3259
3260 mHandler.sendMessage(msg);
Dan Egnor42471dd2010-01-07 17:25:22 -08003261 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003262 }
3263
Dianne Hackborn0dad3642010-09-09 21:25:35 -07003264 final void showLaunchWarningLocked(final ActivityRecord cur, final ActivityRecord next) {
3265 if (!mLaunchWarningShown) {
3266 mLaunchWarningShown = true;
3267 mHandler.post(new Runnable() {
3268 @Override
3269 public void run() {
3270 synchronized (ActivityManagerService.this) {
3271 final Dialog d = new LaunchWarningWindow(mContext, cur, next);
3272 d.show();
3273 mHandler.postDelayed(new Runnable() {
3274 @Override
3275 public void run() {
3276 synchronized (ActivityManagerService.this) {
3277 d.dismiss();
3278 mLaunchWarningShown = false;
3279 }
3280 }
3281 }, 4000);
3282 }
3283 }
3284 });
3285 }
3286 }
3287
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003288 public boolean clearApplicationUserData(final String packageName,
Amith Yamasani742a6712011-05-04 14:49:28 -07003289 final IPackageDataObserver observer, final int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003290 enforceNotIsolatedCaller("clearApplicationUserData");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003291 int uid = Binder.getCallingUid();
3292 int pid = Binder.getCallingPid();
3293 long callingId = Binder.clearCallingIdentity();
3294 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003295 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003296 int pkgUid = -1;
3297 synchronized(this) {
3298 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003299 pkgUid = pm.getPackageUid(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003300 } catch (RemoteException e) {
3301 }
3302 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003303 Slog.w(TAG, "Invalid packageName:" + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003304 return false;
3305 }
3306 if (uid == pkgUid || checkComponentPermission(
3307 android.Manifest.permission.CLEAR_APP_USER_DATA,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08003308 pid, uid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003309 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003310 forceStopPackageLocked(packageName, pkgUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003311 } else {
3312 throw new SecurityException(pid+" does not have permission:"+
3313 android.Manifest.permission.CLEAR_APP_USER_DATA+" to clear data" +
3314 "for process:"+packageName);
3315 }
3316 }
3317
3318 try {
3319 //clear application user data
Amith Yamasani483f3b02012-03-13 16:08:00 -07003320 pm.clearApplicationUserData(packageName, observer, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003321 Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED,
3322 Uri.fromParts("package", packageName, null));
3323 intent.putExtra(Intent.EXTRA_UID, pkgUid);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003324 broadcastIntentInPackage("android", Process.SYSTEM_UID, intent,
Amith Yamasani742a6712011-05-04 14:49:28 -07003325 null, null, 0, null, null, null, false, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003326 } catch (RemoteException e) {
3327 }
3328 } finally {
3329 Binder.restoreCallingIdentity(callingId);
3330 }
3331 return true;
3332 }
3333
Dianne Hackborn03abb812010-01-04 18:43:19 -08003334 public void killBackgroundProcesses(final String packageName) {
3335 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3336 != PackageManager.PERMISSION_GRANTED &&
3337 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES)
3338 != PackageManager.PERMISSION_GRANTED) {
3339 String msg = "Permission Denial: killBackgroundProcesses() from pid="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003340 + Binder.getCallingPid()
3341 + ", uid=" + Binder.getCallingUid()
Dianne Hackborn03abb812010-01-04 18:43:19 -08003342 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003343 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003344 throw new SecurityException(msg);
3345 }
3346
Amith Yamasani483f3b02012-03-13 16:08:00 -07003347 int userId = UserId.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003348 long callingId = Binder.clearCallingIdentity();
3349 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003350 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003351 int pkgUid = -1;
3352 synchronized(this) {
3353 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003354 pkgUid = pm.getPackageUid(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003355 } catch (RemoteException e) {
3356 }
3357 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003358 Slog.w(TAG, "Invalid packageName: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003359 return;
3360 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003361 killPackageProcessesLocked(packageName, pkgUid,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003362 ProcessList.SERVICE_ADJ, false, true, true, false, "kill background");
3363 }
3364 } finally {
3365 Binder.restoreCallingIdentity(callingId);
3366 }
3367 }
3368
3369 public void killAllBackgroundProcesses() {
3370 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3371 != PackageManager.PERMISSION_GRANTED) {
3372 String msg = "Permission Denial: killAllBackgroundProcesses() from pid="
3373 + Binder.getCallingPid()
3374 + ", uid=" + Binder.getCallingUid()
3375 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
3376 Slog.w(TAG, msg);
3377 throw new SecurityException(msg);
3378 }
3379
3380 long callingId = Binder.clearCallingIdentity();
3381 try {
3382 synchronized(this) {
3383 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
3384 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3385 final int NA = apps.size();
3386 for (int ia=0; ia<NA; ia++) {
3387 ProcessRecord app = apps.valueAt(ia);
3388 if (app.persistent) {
3389 // we don't kill persistent processes
3390 continue;
3391 }
3392 if (app.removed) {
3393 procs.add(app);
3394 } else if (app.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
3395 app.removed = true;
3396 procs.add(app);
3397 }
3398 }
3399 }
3400
3401 int N = procs.size();
3402 for (int i=0; i<N; i++) {
3403 removeProcessLocked(procs.get(i), false, true, "kill all background");
3404 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003405 }
3406 } finally {
3407 Binder.restoreCallingIdentity(callingId);
3408 }
3409 }
3410
3411 public void forceStopPackage(final String packageName) {
3412 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3413 != PackageManager.PERMISSION_GRANTED) {
3414 String msg = "Permission Denial: forceStopPackage() from pid="
3415 + Binder.getCallingPid()
3416 + ", uid=" + Binder.getCallingUid()
3417 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003418 Slog.w(TAG, msg);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003419 throw new SecurityException(msg);
3420 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07003421 final int userId = UserId.getCallingUserId();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003422 long callingId = Binder.clearCallingIdentity();
3423 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003424 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003425 int pkgUid = -1;
3426 synchronized(this) {
3427 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003428 pkgUid = pm.getPackageUid(packageName, userId);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003429 } catch (RemoteException e) {
3430 }
3431 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003432 Slog.w(TAG, "Invalid packageName: " + packageName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003433 return;
3434 }
3435 forceStopPackageLocked(packageName, pkgUid);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003436 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003437 pm.setPackageStoppedState(packageName, true, userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003438 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08003439 } catch (IllegalArgumentException e) {
3440 Slog.w(TAG, "Failed trying to unstop package "
3441 + packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003442 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003443 }
3444 } finally {
3445 Binder.restoreCallingIdentity(callingId);
3446 }
3447 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003448
3449 /*
3450 * The pkg name and uid have to be specified.
3451 * @see android.app.IActivityManager#killApplicationWithUid(java.lang.String, int)
3452 */
3453 public void killApplicationWithUid(String pkg, int uid) {
3454 if (pkg == null) {
3455 return;
3456 }
3457 // Make sure the uid is valid.
3458 if (uid < 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003459 Slog.w(TAG, "Invalid uid specified for pkg : " + pkg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003460 return;
3461 }
3462 int callerUid = Binder.getCallingUid();
3463 // Only the system server can kill an application
3464 if (callerUid == Process.SYSTEM_UID) {
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07003465 // Post an aysnc message to kill the application
3466 Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG);
3467 msg.arg1 = uid;
3468 msg.arg2 = 0;
3469 msg.obj = pkg;
Suchi Amalapurapud50066f2009-08-18 16:57:41 -07003470 mHandler.sendMessage(msg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003471 } else {
3472 throw new SecurityException(callerUid + " cannot kill pkg: " +
3473 pkg);
3474 }
3475 }
3476
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003477 public void closeSystemDialogs(String reason) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003478 enforceNotIsolatedCaller("closeSystemDialogs");
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003479 Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003480 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003481 if (reason != null) {
3482 intent.putExtra("reason", reason);
3483 }
3484
3485 final int uid = Binder.getCallingUid();
3486 final long origId = Binder.clearCallingIdentity();
3487 synchronized (this) {
Dianne Hackbornffa42482009-09-23 22:20:11 -07003488 mWindowManager.closeSystemDialogs(reason);
3489
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08003490 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003491 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornffa42482009-09-23 22:20:11 -07003492 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003493 r.stack.finishActivityLocked(r, i,
Dianne Hackbornffa42482009-09-23 22:20:11 -07003494 Activity.RESULT_CANCELED, null, "close-sys");
3495 }
3496 }
3497
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003498 broadcastIntentLocked(null, null, intent, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07003499 null, 0, null, null, null, false, false, -1, uid, 0 /* TODO: Verify */);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003500 }
3501 Binder.restoreCallingIdentity(origId);
3502 }
3503
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003504 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids)
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003505 throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003506 enforceNotIsolatedCaller("getProcessMemoryInfo");
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003507 Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length];
3508 for (int i=pids.length-1; i>=0; i--) {
3509 infos[i] = new Debug.MemoryInfo();
3510 Debug.getMemoryInfo(pids[i], infos[i]);
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003511 }
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003512 return infos;
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003513 }
Christopher Tate5e1ab332009-09-01 20:32:49 -07003514
Dianne Hackbornb437e092011-08-05 17:50:29 -07003515 public long[] getProcessPss(int[] pids) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003516 enforceNotIsolatedCaller("getProcessPss");
Dianne Hackbornb437e092011-08-05 17:50:29 -07003517 long[] pss = new long[pids.length];
3518 for (int i=pids.length-1; i>=0; i--) {
3519 pss[i] = Debug.getPss(pids[i]);
3520 }
3521 return pss;
3522 }
3523
Christopher Tate5e1ab332009-09-01 20:32:49 -07003524 public void killApplicationProcess(String processName, int uid) {
3525 if (processName == null) {
3526 return;
3527 }
3528
3529 int callerUid = Binder.getCallingUid();
3530 // Only the system server can kill an application
3531 if (callerUid == Process.SYSTEM_UID) {
3532 synchronized (this) {
3533 ProcessRecord app = getProcessRecordLocked(processName, uid);
Christopher Tate4a627c72011-04-01 14:43:32 -07003534 if (app != null && app.thread != null) {
Christopher Tate5e1ab332009-09-01 20:32:49 -07003535 try {
3536 app.thread.scheduleSuicide();
3537 } catch (RemoteException e) {
3538 // If the other end already died, then our work here is done.
3539 }
3540 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003541 Slog.w(TAG, "Process/uid not found attempting kill of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07003542 + processName + " / " + uid);
3543 }
3544 }
3545 } else {
3546 throw new SecurityException(callerUid + " cannot kill app process: " +
3547 processName);
3548 }
3549 }
3550
Dianne Hackborn03abb812010-01-04 18:43:19 -08003551 private void forceStopPackageLocked(final String packageName, int uid) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003552 forceStopPackageLocked(packageName, uid, false, false, true, false, UserId.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003553 Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED,
3554 Uri.fromParts("package", packageName, null));
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003555 if (!mProcessesReady) {
3556 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3557 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003558 intent.putExtra(Intent.EXTRA_UID, uid);
3559 broadcastIntentLocked(null, null, intent,
3560 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07003561 false, false,
3562 MY_PID, Process.SYSTEM_UID, UserId.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003563 }
3564
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003565 private final boolean killPackageProcessesLocked(String packageName, int uid,
Christopher Tate3dacd842011-08-19 14:56:15 -07003566 int minOomAdj, boolean callerWillRestart, boolean allowRestart, boolean doit,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003567 boolean evenPersistent, String reason) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003568 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003569
Dianne Hackborn03abb812010-01-04 18:43:19 -08003570 // Remove all processes this package may have touched: all with the
3571 // same UID (except for the system or root user), and all whose name
3572 // matches the package name.
3573 final String procNamePrefix = packageName + ":";
3574 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3575 final int NA = apps.size();
3576 for (int ia=0; ia<NA; ia++) {
3577 ProcessRecord app = apps.valueAt(ia);
Christopher Tate3dacd842011-08-19 14:56:15 -07003578 if (app.persistent && !evenPersistent) {
Christopher Tate064d8422011-07-26 15:38:07 -07003579 // we don't kill persistent processes
3580 continue;
3581 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003582 if (app.removed) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003583 if (doit) {
3584 procs.add(app);
3585 }
Amith Yamasani13593602012-03-22 16:16:17 -07003586 // If uid is specified and the uid and process name match
3587 // Or, the uid is not specified and the process name matches
3588 } else if (((uid > 0 && uid != Process.SYSTEM_UID && app.info.uid == uid)
3589 && (app.processName.equals(packageName)
3590 || app.processName.startsWith(procNamePrefix)))
3591 || (uid < 0
3592 && (app.processName.equals(packageName)
3593 || app.processName.startsWith(procNamePrefix)))) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003594 if (app.setAdj >= minOomAdj) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003595 if (!doit) {
3596 return true;
3597 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003598 app.removed = true;
3599 procs.add(app);
3600 }
3601 }
3602 }
3603 }
3604
3605 int N = procs.size();
3606 for (int i=0; i<N; i++) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003607 removeProcessLocked(procs.get(i), callerWillRestart, allowRestart, reason);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003608 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003609 return N > 0;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003610 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003611
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003612 private final boolean forceStopPackageLocked(String name, int uid,
Christopher Tate3dacd842011-08-19 14:56:15 -07003613 boolean callerWillRestart, boolean purgeCache, boolean doit,
Amith Yamasani483f3b02012-03-13 16:08:00 -07003614 boolean evenPersistent, int userId) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003615 int i;
3616 int N;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003617
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003618 if (uid < 0) {
3619 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003620 uid = AppGlobals.getPackageManager().getPackageUid(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003621 } catch (RemoteException e) {
3622 }
3623 }
3624
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003625 if (doit) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003626 Slog.i(TAG, "Force stopping package " + name + " uid=" + uid);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003627
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003628 Iterator<SparseArray<Long>> badApps = mProcessCrashTimes.getMap().values().iterator();
3629 while (badApps.hasNext()) {
3630 SparseArray<Long> ba = badApps.next();
3631 if (ba.get(uid) != null) {
3632 badApps.remove();
3633 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003634 }
3635 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003636
3637 boolean didSomething = killPackageProcessesLocked(name, uid, -100,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003638 callerWillRestart, false, doit, evenPersistent, "force stop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003639
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003640 TaskRecord lastTask = null;
3641 for (i=0; i<mMainStack.mHistory.size(); i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003642 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003643 final boolean samePackage = r.packageName.equals(name);
Amith Yamasani13593602012-03-22 16:16:17 -07003644 if (r.userId == userId
3645 && (samePackage || r.task == lastTask)
Christopher Tate3dacd842011-08-19 14:56:15 -07003646 && (r.app == null || evenPersistent || !r.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003647 if (!doit) {
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003648 if (r.finishing) {
3649 // If this activity is just finishing, then it is not
3650 // interesting as far as something to stop.
3651 continue;
3652 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003653 return true;
3654 }
3655 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003656 Slog.i(TAG, " Force finishing activity " + r);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003657 if (samePackage) {
3658 if (r.app != null) {
3659 r.app.removed = true;
3660 }
3661 r.app = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003662 }
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003663 lastTask = r.task;
3664 if (r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003665 null, "force-stop", true)) {
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003666 i--;
3667 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003668 }
3669 }
3670
3671 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
Amith Yamasani742a6712011-05-04 14:49:28 -07003672 for (ServiceRecord service : mServiceMap.getAllServices(userId)) {
Christopher Tate064d8422011-07-26 15:38:07 -07003673 if (service.packageName.equals(name)
Christopher Tate3dacd842011-08-19 14:56:15 -07003674 && (service.app == null || evenPersistent || !service.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003675 if (!doit) {
3676 return true;
3677 }
3678 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003679 Slog.i(TAG, " Force stopping service " + service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003680 if (service.app != null) {
3681 service.app.removed = true;
3682 }
3683 service.app = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003684 service.isolatedProc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003685 services.add(service);
3686 }
3687 }
3688
3689 N = services.size();
3690 for (i=0; i<N; i++) {
3691 bringDownServiceLocked(services.get(i), true);
3692 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003693
3694 ArrayList<ContentProviderRecord> providers = new ArrayList<ContentProviderRecord>();
Amith Yamasani13593602012-03-22 16:16:17 -07003695 for (ContentProviderRecord provider : mProviderMap.getProvidersByClass(userId).values()) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003696 if (provider.info.packageName.equals(name)
3697 && (provider.proc == null || evenPersistent || !provider.proc.persistent)) {
3698 if (!doit) {
3699 return true;
3700 }
3701 didSomething = true;
3702 providers.add(provider);
3703 }
3704 }
3705
3706 N = providers.size();
3707 for (i=0; i<N; i++) {
3708 removeDyingProviderLocked(null, providers.get(i));
3709 }
3710
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003711 if (doit) {
3712 if (purgeCache) {
3713 AttributeCache ac = AttributeCache.instance();
3714 if (ac != null) {
3715 ac.removePackage(name);
3716 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003717 }
Dianne Hackborn38cc8962011-10-13 11:33:55 -07003718 if (mBooted) {
3719 mMainStack.resumeTopActivityLocked(null);
3720 mMainStack.scheduleIdleLocked();
3721 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003722 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003723
3724 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003725 }
3726
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003727 private final boolean removeProcessLocked(ProcessRecord app,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003728 boolean callerWillRestart, boolean allowRestart, String reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003729 final String name = app.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003730 final int uid = app.uid;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003731 if (DEBUG_PROCESSES) Slog.d(
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003732 TAG, "Force removing proc " + app.toShortString() + " (" + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003733 + "/" + uid + ")");
3734
3735 mProcessNames.remove(name, uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003736 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003737 if (mHeavyWeightProcess == app) {
3738 mHeavyWeightProcess = null;
3739 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3740 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003741 boolean needRestart = false;
3742 if (app.pid > 0 && app.pid != MY_PID) {
3743 int pid = app.pid;
3744 synchronized (mPidsSelfLocked) {
3745 mPidsSelfLocked.remove(pid);
3746 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3747 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003748 Slog.i(TAG, "Killing proc " + app.toShortString() + ": " + reason);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003749 handleAppDiedLocked(app, true, allowRestart);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003750 mLruProcesses.remove(app);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003751 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003752
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003753 if (app.persistent && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003754 if (!callerWillRestart) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003755 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003756 } else {
3757 needRestart = true;
3758 }
3759 }
3760 } else {
3761 mRemovedProcesses.add(app);
3762 }
3763
3764 return needRestart;
3765 }
3766
3767 private final void processStartTimedOutLocked(ProcessRecord app) {
3768 final int pid = app.pid;
3769 boolean gone = false;
3770 synchronized (mPidsSelfLocked) {
3771 ProcessRecord knownApp = mPidsSelfLocked.get(pid);
3772 if (knownApp != null && knownApp.thread == null) {
3773 mPidsSelfLocked.remove(pid);
3774 gone = true;
3775 }
3776 }
3777
3778 if (gone) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003779 Slog.w(TAG, "Process " + app + " failed to attach");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003780 EventLog.writeEvent(EventLogTags.AM_PROCESS_START_TIMEOUT, pid, app.uid,
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003781 app.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003782 mProcessNames.remove(app.processName, app.uid);
3783 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003784 if (mHeavyWeightProcess == app) {
3785 mHeavyWeightProcess = null;
3786 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3787 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003788 // Take care of any launching providers waiting for this process.
3789 checkAppInLaunchingProvidersLocked(app, true);
3790 // Take care of any services that are waiting for the process.
3791 for (int i=0; i<mPendingServices.size(); i++) {
3792 ServiceRecord sr = mPendingServices.get(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003793 if ((app.uid == sr.appInfo.uid
3794 && app.processName.equals(sr.processName))
3795 || sr.isolatedProc == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003796 Slog.w(TAG, "Forcing bringing down service: " + sr);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003797 sr.isolatedProc = null;
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003798 mPendingServices.remove(i);
3799 i--;
3800 bringDownServiceLocked(sr, true);
3801 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003802 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003803 EventLog.writeEvent(EventLogTags.AM_KILL, pid,
3804 app.processName, app.setAdj, "start timeout");
3805 Process.killProcessQuiet(pid);
Christopher Tate181fafa2009-05-14 11:12:14 -07003806 if (mBackupTarget != null && mBackupTarget.app.pid == pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003807 Slog.w(TAG, "Unattached app died before backup, skipping");
Christopher Tate181fafa2009-05-14 11:12:14 -07003808 try {
3809 IBackupManager bm = IBackupManager.Stub.asInterface(
3810 ServiceManager.getService(Context.BACKUP_SERVICE));
3811 bm.agentDisconnected(app.info.packageName);
3812 } catch (RemoteException e) {
3813 // Can't happen; the backup manager is local
3814 }
3815 }
Christopher Tatef46723b2012-01-26 14:19:24 -08003816 if (isPendingBroadcastProcessLocked(pid)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003817 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
Christopher Tatef46723b2012-01-26 14:19:24 -08003818 skipPendingBroadcastLocked(pid);
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003819 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003820 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003821 Slog.w(TAG, "Spurious process start timeout - pid not known for " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003822 }
3823 }
3824
3825 private final boolean attachApplicationLocked(IApplicationThread thread,
3826 int pid) {
3827
3828 // Find the application record that is being attached... either via
3829 // the pid if we are running in multiple processes, or just pull the
3830 // next app record if we are emulating process with anonymous threads.
3831 ProcessRecord app;
3832 if (pid != MY_PID && pid >= 0) {
3833 synchronized (mPidsSelfLocked) {
3834 app = mPidsSelfLocked.get(pid);
3835 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003836 } else {
3837 app = null;
3838 }
3839
3840 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003841 Slog.w(TAG, "No pending application record for pid " + pid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003842 + " (IApplicationThread " + thread + "); dropping process");
Doug Zongker2bec3d42009-12-04 12:52:44 -08003843 EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003844 if (pid > 0 && pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003845 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003846 } else {
3847 try {
3848 thread.scheduleExit();
3849 } catch (Exception e) {
3850 // Ignore exceptions.
3851 }
3852 }
3853 return false;
3854 }
3855
3856 // If this application record is still attached to a previous
3857 // process, clean it up now.
3858 if (app.thread != null) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003859 handleAppDiedLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003860 }
3861
3862 // Tell the process all about itself.
3863
Joe Onorato8a9b2202010-02-26 18:56:32 -08003864 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003865 TAG, "Binding process pid " + pid + " to record " + app);
3866
3867 String processName = app.processName;
3868 try {
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07003869 AppDeathRecipient adr = new AppDeathRecipient(
3870 app, pid, thread);
3871 thread.asBinder().linkToDeath(adr, 0);
3872 app.deathRecipient = adr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003873 } catch (RemoteException e) {
3874 app.resetPackageList();
3875 startProcessLocked(app, "link fail", processName);
3876 return false;
3877 }
3878
Doug Zongker2bec3d42009-12-04 12:52:44 -08003879 EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.pid, app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003880
3881 app.thread = thread;
3882 app.curAdj = app.setAdj = -100;
Dianne Hackborn09c916b2009-12-08 14:50:51 -08003883 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
3884 app.setSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003885 app.forcingToForeground = null;
3886 app.foregroundServices = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07003887 app.hasShownUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003888 app.debugging = false;
3889
3890 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3891
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003892 boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003893 List providers = normalMode ? generateApplicationProvidersLocked(app) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003894
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003895 if (!normalMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003896 Slog.i(TAG, "Launching preboot mode app: " + app);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003897 }
3898
Joe Onorato8a9b2202010-02-26 18:56:32 -08003899 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003900 TAG, "New app record " + app
3901 + " thread=" + thread.asBinder() + " pid=" + pid);
3902 try {
3903 int testMode = IApplicationThread.DEBUG_OFF;
3904 if (mDebugApp != null && mDebugApp.equals(processName)) {
3905 testMode = mWaitForDebugger
3906 ? IApplicationThread.DEBUG_WAIT
3907 : IApplicationThread.DEBUG_ON;
3908 app.debugging = true;
3909 if (mDebugTransient) {
3910 mDebugApp = mOrigDebugApp;
3911 mWaitForDebugger = mOrigWaitForDebugger;
3912 }
3913 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003914 String profileFile = app.instrumentationProfileFile;
3915 ParcelFileDescriptor profileFd = null;
3916 boolean profileAutoStop = false;
3917 if (mProfileApp != null && mProfileApp.equals(processName)) {
3918 mProfileProc = app;
3919 profileFile = mProfileFile;
3920 profileFd = mProfileFd;
3921 profileAutoStop = mAutoStopProfiler;
3922 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08003923 boolean enableOpenGlTrace = false;
3924 if (mOpenGlTraceApp != null && mOpenGlTraceApp.equals(processName)) {
3925 enableOpenGlTrace = true;
3926 mOpenGlTraceApp = null;
3927 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003928
Christopher Tate181fafa2009-05-14 11:12:14 -07003929 // If the app is being launched for restore or full backup, set it up specially
3930 boolean isRestrictedBackupMode = false;
3931 if (mBackupTarget != null && mBackupAppName.equals(processName)) {
3932 isRestrictedBackupMode = (mBackupTarget.backupMode == BackupRecord.RESTORE)
Christopher Tate75a99702011-05-18 16:28:19 -07003933 || (mBackupTarget.backupMode == BackupRecord.RESTORE_FULL)
Christopher Tate181fafa2009-05-14 11:12:14 -07003934 || (mBackupTarget.backupMode == BackupRecord.BACKUP_FULL);
3935 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003936
Dianne Hackbornd7f6daa2009-06-22 17:06:35 -07003937 ensurePackageDexOpt(app.instrumentationInfo != null
3938 ? app.instrumentationInfo.packageName
3939 : app.info.packageName);
3940 if (app.instrumentationClass != null) {
3941 ensurePackageDexOpt(app.instrumentationClass.getPackageName());
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003942 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08003943 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Binding proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003944 + processName + " with config " + mConfiguration);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003945 ApplicationInfo appInfo = app.instrumentationInfo != null
3946 ? app.instrumentationInfo : app.info;
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -07003947 app.compat = compatibilityInfoForPackageLocked(appInfo);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003948 if (profileFd != null) {
3949 profileFd = profileFd.dup();
3950 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003951 thread.bindApplication(processName, appInfo, providers,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003952 app.instrumentationClass, profileFile, profileFd, profileAutoStop,
Siva Velusamy92a8b222012-03-09 16:24:04 -08003953 app.instrumentationArguments, app.instrumentationWatcher, testMode,
3954 enableOpenGlTrace, isRestrictedBackupMode || !normalMode, app.persistent,
Dianne Hackborn813075a62011-11-14 17:45:19 -08003955 new Configuration(mConfiguration), app.compat, getCommonServicesLocked(),
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08003956 mCoreSettingsObserver.getCoreSettingsLocked());
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003957 updateLruProcessLocked(app, false, true);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003958 app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003959 } catch (Exception e) {
3960 // todo: Yikes! What should we do? For now we will try to
3961 // start another process, but that could easily get us in
3962 // an infinite loop of restarting processes...
Joe Onorato8a9b2202010-02-26 18:56:32 -08003963 Slog.w(TAG, "Exception thrown during bind!", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003964
3965 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07003966 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003967 startProcessLocked(app, "bind fail", processName);
3968 return false;
3969 }
3970
3971 // Remove this record from the list of starting applications.
3972 mPersistentStartingProcesses.remove(app);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003973 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
3974 "Attach application locked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003975 mProcessesOnHold.remove(app);
3976
3977 boolean badApp = false;
3978 boolean didSomething = false;
3979
3980 // See if the top visible activity is waiting to run in this process...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003981 ActivityRecord hr = mMainStack.topRunningActivityLocked(null);
Christopher Tate04c0af82010-06-07 18:35:20 -07003982 if (hr != null && normalMode) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003983 if (hr.app == null && app.uid == hr.info.applicationInfo.uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003984 && processName.equals(hr.processName)) {
3985 try {
Mike Lockwood3a74bd32011-08-12 13:55:22 -07003986 if (mHeadless) {
3987 Slog.e(TAG, "Starting activities not supported on headless device: " + hr);
3988 } else if (mMainStack.realStartActivityLocked(hr, app, true, true)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003989 didSomething = true;
3990 }
3991 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003992 Slog.w(TAG, "Exception in new application when starting activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003993 + hr.intent.getComponent().flattenToShortString(), e);
3994 badApp = true;
3995 }
3996 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003997 mMainStack.ensureActivitiesVisibleLocked(hr, null, processName, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003998 }
3999 }
4000
4001 // Find any services that should be running in this process...
4002 if (!badApp && mPendingServices.size() > 0) {
4003 ServiceRecord sr = null;
4004 try {
4005 for (int i=0; i<mPendingServices.size(); i++) {
4006 sr = mPendingServices.get(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004007 if (app != sr.isolatedProc && (app.uid != sr.appInfo.uid
4008 || !processName.equals(sr.processName))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004009 continue;
4010 }
4011
4012 mPendingServices.remove(i);
4013 i--;
4014 realStartServiceLocked(sr, app);
4015 didSomething = true;
4016 }
4017 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004018 Slog.w(TAG, "Exception in new application when starting service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004019 + sr.shortName, e);
4020 badApp = true;
4021 }
4022 }
4023
Christopher Tatef46723b2012-01-26 14:19:24 -08004024 // Check if a next-broadcast receiver is in this process...
4025 if (!badApp && isPendingBroadcastProcessLocked(pid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004026 try {
Christopher Tatef46723b2012-01-26 14:19:24 -08004027 didSomething = sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004028 } catch (Exception e) {
Christopher Tatef46723b2012-01-26 14:19:24 -08004029 // If the app died trying to launch the receiver we declare it 'bad'
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004030 badApp = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004031 }
4032 }
4033
Christopher Tate181fafa2009-05-14 11:12:14 -07004034 // Check whether the next backup agent is in this process...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004035 if (!badApp && mBackupTarget != null && mBackupTarget.appInfo.uid == app.uid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004036 if (DEBUG_BACKUP) Slog.v(TAG, "New app is backup target, launching agent for " + app);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004037 ensurePackageDexOpt(mBackupTarget.appInfo.packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07004038 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004039 thread.scheduleCreateBackupAgent(mBackupTarget.appInfo,
4040 compatibilityInfoForPackageLocked(mBackupTarget.appInfo),
4041 mBackupTarget.backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -07004042 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004043 Slog.w(TAG, "Exception scheduling backup agent creation: ");
Christopher Tate181fafa2009-05-14 11:12:14 -07004044 e.printStackTrace();
4045 }
4046 }
4047
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004048 if (badApp) {
4049 // todo: Also need to kill application to deal with all
4050 // kinds of exceptions.
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004051 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004052 return false;
4053 }
4054
4055 if (!didSomething) {
4056 updateOomAdjLocked();
4057 }
4058
4059 return true;
4060 }
4061
4062 public final void attachApplication(IApplicationThread thread) {
4063 synchronized (this) {
4064 int callingPid = Binder.getCallingPid();
4065 final long origId = Binder.clearCallingIdentity();
4066 attachApplicationLocked(thread, callingPid);
4067 Binder.restoreCallingIdentity(origId);
4068 }
4069 }
4070
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004071 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004072 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004073 ActivityRecord r = mMainStack.activityIdleInternal(token, false, config);
4074 if (stopProfiling) {
4075 synchronized (this) {
4076 if (mProfileProc == r.app) {
4077 if (mProfileFd != null) {
4078 try {
4079 mProfileFd.close();
4080 } catch (IOException e) {
4081 }
4082 clearProfilerLocked();
4083 }
4084 }
4085 }
4086 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004087 Binder.restoreCallingIdentity(origId);
4088 }
4089
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004090 void enableScreenAfterBoot() {
Doug Zongker2bec3d42009-12-04 12:52:44 -08004091 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004092 SystemClock.uptimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004093 mWindowManager.enableScreenAfterBoot();
4094 }
4095
Dianne Hackborn661cd522011-08-22 00:26:20 -07004096 public void showBootMessage(final CharSequence msg, final boolean always) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004097 enforceNotIsolatedCaller("showBootMessage");
Dianne Hackborn661cd522011-08-22 00:26:20 -07004098 mWindowManager.showBootMessage(msg, always);
4099 }
4100
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004101 public void dismissKeyguardOnNextActivity() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004102 enforceNotIsolatedCaller("dismissKeyguardOnNextActivity");
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004103 synchronized (this) {
4104 mMainStack.dismissKeyguardOnNextActivityLocked();
4105 }
4106 }
4107
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004108 final void finishBooting() {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004109 IntentFilter pkgFilter = new IntentFilter();
4110 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
4111 pkgFilter.addDataScheme("package");
4112 mContext.registerReceiver(new BroadcastReceiver() {
4113 @Override
4114 public void onReceive(Context context, Intent intent) {
4115 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
4116 if (pkgs != null) {
4117 for (String pkg : pkgs) {
Vairavan Srinivasan61f07652010-07-22 13:36:40 -07004118 synchronized (ActivityManagerService.this) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07004119 if (forceStopPackageLocked(pkg, -1, false, false, false, false, 0)) {
4120 setResultCode(Activity.RESULT_OK);
4121 return;
4122 }
4123 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004124 }
4125 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004126 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004127 }, pkgFilter);
Amith Yamasani13593602012-03-22 16:16:17 -07004128
4129 IntentFilter userFilter = new IntentFilter();
4130 userFilter.addAction(Intent.ACTION_USER_REMOVED);
4131 mContext.registerReceiver(new BroadcastReceiver() {
4132 @Override
4133 public void onReceive(Context context, Intent intent) {
4134 onUserRemoved(intent);
4135 }
4136 }, userFilter);
4137
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004138 synchronized (this) {
4139 // Ensure that any processes we had put on hold are now started
4140 // up.
4141 final int NP = mProcessesOnHold.size();
4142 if (NP > 0) {
4143 ArrayList<ProcessRecord> procs =
4144 new ArrayList<ProcessRecord>(mProcessesOnHold);
4145 for (int ip=0; ip<NP; ip++) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004146 if (DEBUG_PROCESSES) Slog.v(TAG, "Starting process on hold: "
4147 + procs.get(ip));
4148 startProcessLocked(procs.get(ip), "on-hold", null);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004149 }
4150 }
4151
4152 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004153 // Start looking for apps that are abusing wake locks.
4154 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07004155 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004156 // Tell anyone interested that we are done booting!
Dianne Hackbornf4c454b2010-08-11 12:47:41 -07004157 SystemProperties.set("sys.boot_completed", "1");
Guang Zhu191713a2012-01-12 12:02:22 -08004158 SystemProperties.set("dev.bootcomplete", "1");
Amith Yamasani742a6712011-05-04 14:49:28 -07004159 /* TODO: Send this to all users that are to be logged in on startup */
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004160 broadcastIntentLocked(null, null,
4161 new Intent(Intent.ACTION_BOOT_COMPLETED, null),
4162 null, null, 0, null, null,
4163 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
Amith Yamasani742a6712011-05-04 14:49:28 -07004164 false, false, MY_PID, Process.SYSTEM_UID, Binder.getOrigCallingUser());
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004165 }
4166 }
4167 }
4168
4169 final void ensureBootCompleted() {
4170 boolean booting;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004171 boolean enableScreen;
4172 synchronized (this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004173 booting = mBooting;
4174 mBooting = false;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004175 enableScreen = !mBooted;
4176 mBooted = true;
4177 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004178
4179 if (booting) {
4180 finishBooting();
4181 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004182
4183 if (enableScreen) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004184 enableScreenAfterBoot();
4185 }
4186 }
4187
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004188 public final void activityPaused(IBinder token) {
4189 final long origId = Binder.clearCallingIdentity();
4190 mMainStack.activityPaused(token, false);
4191 Binder.restoreCallingIdentity(origId);
4192 }
4193
4194 public final void activityStopped(IBinder token, Bundle icicle, Bitmap thumbnail,
4195 CharSequence description) {
4196 if (localLOGV) Slog.v(
4197 TAG, "Activity stopped: token=" + token);
4198
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004199 // Refuse possible leaked file descriptors
4200 if (icicle != null && icicle.hasFileDescriptors()) {
4201 throw new IllegalArgumentException("File descriptors passed in Bundle");
4202 }
4203
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004204 ActivityRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004205
4206 final long origId = Binder.clearCallingIdentity();
4207
4208 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004209 r = mMainStack.isInStackLocked(token);
4210 if (r != null) {
4211 r.stack.activityStoppedLocked(r, icicle, thumbnail, description);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004212 }
4213 }
4214
4215 if (r != null) {
4216 sendPendingThumbnail(r, null, null, null, false);
4217 }
4218
4219 trimApplications();
4220
4221 Binder.restoreCallingIdentity(origId);
4222 }
4223
4224 public final void activityDestroyed(IBinder token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004225 if (DEBUG_SWITCH) Slog.v(TAG, "ACTIVITY DESTROYED: " + token);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004226 mMainStack.activityDestroyed(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004227 }
4228
4229 public String getCallingPackage(IBinder token) {
4230 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004231 ActivityRecord r = getCallingRecordLocked(token);
Dianne Hackborn9bbcb912009-10-20 15:42:38 -07004232 return r != null && r.app != null ? r.info.packageName : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004233 }
4234 }
4235
4236 public ComponentName getCallingActivity(IBinder token) {
4237 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004238 ActivityRecord r = getCallingRecordLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004239 return r != null ? r.intent.getComponent() : null;
4240 }
4241 }
4242
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004243 private ActivityRecord getCallingRecordLocked(IBinder token) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004244 ActivityRecord r = mMainStack.isInStackLocked(token);
4245 if (r == null) {
4246 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004247 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004248 return r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004249 }
4250
4251 public ComponentName getActivityClassForToken(IBinder token) {
4252 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004253 ActivityRecord r = mMainStack.isInStackLocked(token);
4254 if (r == null) {
4255 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004256 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004257 return r.intent.getComponent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004258 }
4259 }
4260
4261 public String getPackageForToken(IBinder token) {
4262 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004263 ActivityRecord r = mMainStack.isInStackLocked(token);
4264 if (r == null) {
4265 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004266 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004267 return r.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004268 }
4269 }
4270
4271 public IIntentSender getIntentSender(int type,
4272 String packageName, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004273 int requestCode, Intent[] intents, String[] resolvedTypes,
4274 int flags, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004275 enforceNotIsolatedCaller("getIntentSender");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004276 // Refuse possible leaked file descriptors
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004277 if (intents != null) {
4278 if (intents.length < 1) {
4279 throw new IllegalArgumentException("Intents array length must be >= 1");
4280 }
4281 for (int i=0; i<intents.length; i++) {
4282 Intent intent = intents[i];
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004283 if (intent != null) {
4284 if (intent.hasFileDescriptors()) {
4285 throw new IllegalArgumentException("File descriptors passed in Intent");
4286 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07004287 if (type == ActivityManager.INTENT_SENDER_BROADCAST &&
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004288 (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
4289 throw new IllegalArgumentException(
4290 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
4291 }
4292 intents[i] = new Intent(intent);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004293 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004294 }
4295 if (resolvedTypes != null && resolvedTypes.length != intents.length) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004296 throw new IllegalArgumentException(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004297 "Intent array length does not match resolvedTypes length");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004298 }
4299 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004300 if (options != null) {
4301 if (options.hasFileDescriptors()) {
4302 throw new IllegalArgumentException("File descriptors passed in options");
4303 }
4304 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004305
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004306 synchronized(this) {
4307 int callingUid = Binder.getCallingUid();
4308 try {
Jeff Brown10e89712011-07-08 18:52:57 -07004309 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004310 int uid = AppGlobals.getPackageManager()
Amith Yamasani483f3b02012-03-13 16:08:00 -07004311 .getPackageUid(packageName, UserId.getUserId(callingUid));
4312 if (!UserId.isSameApp(callingUid, uid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004313 String msg = "Permission Denial: getIntentSender() from pid="
4314 + Binder.getCallingPid()
4315 + ", uid=" + Binder.getCallingUid()
4316 + ", (need uid=" + uid + ")"
4317 + " is not allowed to send as package " + packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004318 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004319 throw new SecurityException(msg);
4320 }
4321 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004322
Amith Yamasani742a6712011-05-04 14:49:28 -07004323 if (DEBUG_MU)
4324 Slog.i(TAG_MU, "Getting intent sender for origCallingUid="
4325 + Binder.getOrigCallingUid());
4326 return getIntentSenderLocked(type, packageName, Binder.getOrigCallingUid(),
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004327 token, resultWho, requestCode, intents, resolvedTypes, flags, options);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004328
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004329 } catch (RemoteException e) {
4330 throw new SecurityException(e);
4331 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004332 }
4333 }
4334
4335 IIntentSender getIntentSenderLocked(int type,
4336 String packageName, int callingUid, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004337 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
4338 Bundle options) {
Amith Yamasani742a6712011-05-04 14:49:28 -07004339 if (DEBUG_MU)
4340 Slog.v(TAG_MU, "getIntentSenderLocked(): uid=" + callingUid);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004341 ActivityRecord activity = null;
Dianne Hackborna4972e92012-03-14 10:38:05 -07004342 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004343 activity = mMainStack.isInStackLocked(token);
4344 if (activity == null) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004345 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004346 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004347 if (activity.finishing) {
4348 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004349 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004350 }
4351
4352 final boolean noCreate = (flags&PendingIntent.FLAG_NO_CREATE) != 0;
4353 final boolean cancelCurrent = (flags&PendingIntent.FLAG_CANCEL_CURRENT) != 0;
4354 final boolean updateCurrent = (flags&PendingIntent.FLAG_UPDATE_CURRENT) != 0;
4355 flags &= ~(PendingIntent.FLAG_NO_CREATE|PendingIntent.FLAG_CANCEL_CURRENT
4356 |PendingIntent.FLAG_UPDATE_CURRENT);
4357
4358 PendingIntentRecord.Key key = new PendingIntentRecord.Key(
4359 type, packageName, activity, resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004360 requestCode, intents, resolvedTypes, flags, options);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004361 WeakReference<PendingIntentRecord> ref;
4362 ref = mIntentSenderRecords.get(key);
4363 PendingIntentRecord rec = ref != null ? ref.get() : null;
4364 if (rec != null) {
4365 if (!cancelCurrent) {
4366 if (updateCurrent) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004367 if (rec.key.requestIntent != null) {
4368 rec.key.requestIntent.replaceExtras(intents != null ? intents[0] : null);
4369 }
4370 if (intents != null) {
4371 intents[intents.length-1] = rec.key.requestIntent;
4372 rec.key.allIntents = intents;
4373 rec.key.allResolvedTypes = resolvedTypes;
4374 } else {
4375 rec.key.allIntents = null;
4376 rec.key.allResolvedTypes = null;
4377 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004378 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004379 return rec;
4380 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004381 rec.canceled = true;
4382 mIntentSenderRecords.remove(key);
4383 }
4384 if (noCreate) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004385 return rec;
4386 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004387 rec = new PendingIntentRecord(this, key, callingUid);
4388 mIntentSenderRecords.put(key, rec.ref);
Dianne Hackborna4972e92012-03-14 10:38:05 -07004389 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004390 if (activity.pendingResults == null) {
4391 activity.pendingResults
4392 = new HashSet<WeakReference<PendingIntentRecord>>();
4393 }
4394 activity.pendingResults.add(rec.ref);
4395 }
4396 return rec;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004397 }
4398
4399 public void cancelIntentSender(IIntentSender sender) {
4400 if (!(sender instanceof PendingIntentRecord)) {
4401 return;
4402 }
4403 synchronized(this) {
4404 PendingIntentRecord rec = (PendingIntentRecord)sender;
4405 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004406 int uid = AppGlobals.getPackageManager()
Amith Yamasani483f3b02012-03-13 16:08:00 -07004407 .getPackageUid(rec.key.packageName, UserId.getCallingUserId());
Amith Yamasani04e0d262012-02-14 11:50:53 -08004408 if (!UserId.isSameApp(uid, Binder.getCallingUid())) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004409 String msg = "Permission Denial: cancelIntentSender() from pid="
4410 + Binder.getCallingPid()
4411 + ", uid=" + Binder.getCallingUid()
4412 + " is not allowed to cancel packges "
4413 + rec.key.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004414 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004415 throw new SecurityException(msg);
4416 }
4417 } catch (RemoteException e) {
4418 throw new SecurityException(e);
4419 }
4420 cancelIntentSenderLocked(rec, true);
4421 }
4422 }
4423
4424 void cancelIntentSenderLocked(PendingIntentRecord rec, boolean cleanActivity) {
4425 rec.canceled = true;
4426 mIntentSenderRecords.remove(rec.key);
4427 if (cleanActivity && rec.key.activity != null) {
4428 rec.key.activity.pendingResults.remove(rec.ref);
4429 }
4430 }
4431
4432 public String getPackageForIntentSender(IIntentSender pendingResult) {
4433 if (!(pendingResult instanceof PendingIntentRecord)) {
4434 return null;
4435 }
Brad Fitzpatrickb213d102010-04-19 11:58:52 -07004436 try {
4437 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4438 return res.key.packageName;
4439 } catch (ClassCastException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004440 }
4441 return null;
4442 }
4443
Dianne Hackborn6c418d52011-06-29 14:05:33 -07004444 public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) {
4445 if (!(pendingResult instanceof PendingIntentRecord)) {
4446 return false;
4447 }
4448 try {
4449 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4450 if (res.key.allIntents == null) {
4451 return false;
4452 }
4453 for (int i=0; i<res.key.allIntents.length; i++) {
4454 Intent intent = res.key.allIntents[i];
4455 if (intent.getPackage() != null && intent.getComponent() != null) {
4456 return false;
4457 }
4458 }
4459 return true;
4460 } catch (ClassCastException e) {
4461 }
4462 return false;
4463 }
4464
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004465 public void setProcessLimit(int max) {
4466 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4467 "setProcessLimit()");
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004468 synchronized (this) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07004469 mProcessLimit = max < 0 ? ProcessList.MAX_HIDDEN_APPS : max;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004470 mProcessLimitOverride = max;
4471 }
4472 trimApplications();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004473 }
4474
4475 public int getProcessLimit() {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004476 synchronized (this) {
4477 return mProcessLimitOverride;
4478 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004479 }
4480
4481 void foregroundTokenDied(ForegroundToken token) {
4482 synchronized (ActivityManagerService.this) {
4483 synchronized (mPidsSelfLocked) {
4484 ForegroundToken cur
4485 = mForegroundProcesses.get(token.pid);
4486 if (cur != token) {
4487 return;
4488 }
4489 mForegroundProcesses.remove(token.pid);
4490 ProcessRecord pr = mPidsSelfLocked.get(token.pid);
4491 if (pr == null) {
4492 return;
4493 }
4494 pr.forcingToForeground = null;
4495 pr.foregroundServices = false;
4496 }
4497 updateOomAdjLocked();
4498 }
4499 }
4500
4501 public void setProcessForeground(IBinder token, int pid, boolean isForeground) {
4502 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4503 "setProcessForeground()");
4504 synchronized(this) {
4505 boolean changed = false;
4506
4507 synchronized (mPidsSelfLocked) {
4508 ProcessRecord pr = mPidsSelfLocked.get(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004509 if (pr == null && isForeground) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004510 Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004511 return;
4512 }
4513 ForegroundToken oldToken = mForegroundProcesses.get(pid);
4514 if (oldToken != null) {
4515 oldToken.token.unlinkToDeath(oldToken, 0);
4516 mForegroundProcesses.remove(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004517 if (pr != null) {
4518 pr.forcingToForeground = null;
4519 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004520 changed = true;
4521 }
4522 if (isForeground && token != null) {
4523 ForegroundToken newToken = new ForegroundToken() {
4524 public void binderDied() {
4525 foregroundTokenDied(this);
4526 }
4527 };
4528 newToken.pid = pid;
4529 newToken.token = token;
4530 try {
4531 token.linkToDeath(newToken, 0);
4532 mForegroundProcesses.put(pid, newToken);
4533 pr.forcingToForeground = token;
4534 changed = true;
4535 } catch (RemoteException e) {
4536 // If the process died while doing this, we will later
4537 // do the cleanup with the process death link.
4538 }
4539 }
4540 }
4541
4542 if (changed) {
4543 updateOomAdjLocked();
4544 }
4545 }
4546 }
4547
4548 // =========================================================
4549 // PERMISSIONS
4550 // =========================================================
4551
4552 static class PermissionController extends IPermissionController.Stub {
4553 ActivityManagerService mActivityManagerService;
4554 PermissionController(ActivityManagerService activityManagerService) {
4555 mActivityManagerService = activityManagerService;
4556 }
4557
4558 public boolean checkPermission(String permission, int pid, int uid) {
4559 return mActivityManagerService.checkPermission(permission, pid,
4560 uid) == PackageManager.PERMISSION_GRANTED;
4561 }
4562 }
4563
4564 /**
4565 * This can be called with or without the global lock held.
4566 */
4567 int checkComponentPermission(String permission, int pid, int uid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004568 int owningUid, boolean exported) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004569 // We might be performing an operation on behalf of an indirect binder
4570 // invocation, e.g. via {@link #openContentUri}. Check and adjust the
4571 // client identity accordingly before proceeding.
4572 Identity tlsIdentity = sCallerIdentity.get();
4573 if (tlsIdentity != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004574 Slog.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004575 + tlsIdentity.pid + "," + tlsIdentity.uid + "}");
4576 uid = tlsIdentity.uid;
4577 pid = tlsIdentity.pid;
4578 }
4579
4580 // Root, system server and our own process get to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07004581 if (uid == 0 || uid == Process.SYSTEM_UID || pid == MY_PID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004582 return PackageManager.PERMISSION_GRANTED;
4583 }
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004584 // Isolated processes don't get any permissions.
4585 if (UserId.isIsolated(uid)) {
4586 return PackageManager.PERMISSION_DENIED;
4587 }
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004588 // If there is a uid that owns whatever is being accessed, it has
4589 // blanket access to it regardless of the permissions it requires.
Amith Yamasani742a6712011-05-04 14:49:28 -07004590 if (owningUid >= 0 && UserId.isSameApp(uid, owningUid)) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004591 return PackageManager.PERMISSION_GRANTED;
4592 }
4593 // If the target is not exported, then nobody else can get to it.
4594 if (!exported) {
4595 Slog.w(TAG, "Permission denied: checkComponentPermission() owningUid=" + owningUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004596 return PackageManager.PERMISSION_DENIED;
4597 }
4598 if (permission == null) {
4599 return PackageManager.PERMISSION_GRANTED;
4600 }
4601 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004602 return AppGlobals.getPackageManager()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004603 .checkUidPermission(permission, uid);
4604 } catch (RemoteException e) {
4605 // Should never happen, but if it does... deny!
Joe Onorato8a9b2202010-02-26 18:56:32 -08004606 Slog.e(TAG, "PackageManager is dead?!?", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004607 }
4608 return PackageManager.PERMISSION_DENIED;
4609 }
4610
4611 /**
4612 * As the only public entry point for permissions checking, this method
4613 * can enforce the semantic that requesting a check on a null global
4614 * permission is automatically denied. (Internally a null permission
4615 * string is used when calling {@link #checkComponentPermission} in cases
4616 * when only uid-based security is needed.)
4617 *
4618 * This can be called with or without the global lock held.
4619 */
4620 public int checkPermission(String permission, int pid, int uid) {
4621 if (permission == null) {
4622 return PackageManager.PERMISSION_DENIED;
4623 }
Amith Yamasani742a6712011-05-04 14:49:28 -07004624 return checkComponentPermission(permission, pid, UserId.getAppId(uid), -1, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004625 }
4626
4627 /**
4628 * Binder IPC calls go through the public entry point.
4629 * This can be called with or without the global lock held.
4630 */
4631 int checkCallingPermission(String permission) {
4632 return checkPermission(permission,
4633 Binder.getCallingPid(),
Amith Yamasani742a6712011-05-04 14:49:28 -07004634 UserId.getAppId(Binder.getCallingUid()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004635 }
4636
4637 /**
4638 * This can be called with or without the global lock held.
4639 */
4640 void enforceCallingPermission(String permission, String func) {
4641 if (checkCallingPermission(permission)
4642 == PackageManager.PERMISSION_GRANTED) {
4643 return;
4644 }
4645
4646 String msg = "Permission Denial: " + func + " from pid="
4647 + Binder.getCallingPid()
4648 + ", uid=" + Binder.getCallingUid()
4649 + " requires " + permission;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004650 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004651 throw new SecurityException(msg);
4652 }
4653
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004654 /**
4655 * Determine if UID is holding permissions required to access {@link Uri} in
4656 * the given {@link ProviderInfo}. Final permission checking is always done
4657 * in {@link ContentProvider}.
4658 */
4659 private final boolean checkHoldingPermissionsLocked(
4660 IPackageManager pm, ProviderInfo pi, Uri uri, int uid, int modeFlags) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004661 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4662 "checkHoldingPermissionsLocked: uri=" + uri + " uid=" + uid);
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004663
4664 if (pi.applicationInfo.uid == uid) {
4665 return true;
4666 } else if (!pi.exported) {
4667 return false;
4668 }
4669
4670 boolean readMet = (modeFlags & Intent.FLAG_GRANT_READ_URI_PERMISSION) == 0;
4671 boolean writeMet = (modeFlags & Intent.FLAG_GRANT_WRITE_URI_PERMISSION) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004672 try {
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004673 // check if target holds top-level <provider> permissions
4674 if (!readMet && pi.readPermission != null
4675 && (pm.checkUidPermission(pi.readPermission, uid) == PERMISSION_GRANTED)) {
4676 readMet = true;
4677 }
4678 if (!writeMet && pi.writePermission != null
4679 && (pm.checkUidPermission(pi.writePermission, uid) == PERMISSION_GRANTED)) {
4680 writeMet = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004681 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004682
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004683 // track if unprotected read/write is allowed; any denied
4684 // <path-permission> below removes this ability
4685 boolean allowDefaultRead = pi.readPermission == null;
4686 boolean allowDefaultWrite = pi.writePermission == null;
Dianne Hackborn48058e82010-09-27 16:53:23 -07004687
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004688 // check if target holds any <path-permission> that match uri
4689 final PathPermission[] pps = pi.pathPermissions;
4690 if (pps != null) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004691 final String path = uri.getPath();
4692 int i = pps.length;
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004693 while (i > 0 && (!readMet || !writeMet)) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004694 i--;
4695 PathPermission pp = pps[i];
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004696 if (pp.match(path)) {
4697 if (!readMet) {
4698 final String pprperm = pp.getReadPermission();
4699 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking read perm for "
4700 + pprperm + " for " + pp.getPath()
4701 + ": match=" + pp.match(path)
4702 + " check=" + pm.checkUidPermission(pprperm, uid));
4703 if (pprperm != null) {
4704 if (pm.checkUidPermission(pprperm, uid) == PERMISSION_GRANTED) {
4705 readMet = true;
4706 } else {
4707 allowDefaultRead = false;
4708 }
4709 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004710 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004711 if (!writeMet) {
4712 final String ppwperm = pp.getWritePermission();
4713 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking write perm "
4714 + ppwperm + " for " + pp.getPath()
4715 + ": match=" + pp.match(path)
4716 + " check=" + pm.checkUidPermission(ppwperm, uid));
4717 if (ppwperm != null) {
4718 if (pm.checkUidPermission(ppwperm, uid) == PERMISSION_GRANTED) {
4719 writeMet = true;
4720 } else {
4721 allowDefaultWrite = false;
4722 }
4723 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004724 }
4725 }
4726 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07004727 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004728
4729 // grant unprotected <provider> read/write, if not blocked by
4730 // <path-permission> above
4731 if (allowDefaultRead) readMet = true;
4732 if (allowDefaultWrite) writeMet = true;
4733
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004734 } catch (RemoteException e) {
4735 return false;
4736 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004737
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004738 return readMet && writeMet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004739 }
4740
4741 private final boolean checkUriPermissionLocked(Uri uri, int uid,
4742 int modeFlags) {
4743 // Root gets to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07004744 if (uid == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004745 return true;
4746 }
4747 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(uid);
4748 if (perms == null) return false;
4749 UriPermission perm = perms.get(uri);
4750 if (perm == null) return false;
4751 return (modeFlags&perm.modeFlags) == modeFlags;
4752 }
4753
4754 public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004755 enforceNotIsolatedCaller("checkUriPermission");
4756
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004757 // Another redirected-binder-call permissions check as in
4758 // {@link checkComponentPermission}.
4759 Identity tlsIdentity = sCallerIdentity.get();
4760 if (tlsIdentity != null) {
4761 uid = tlsIdentity.uid;
4762 pid = tlsIdentity.pid;
4763 }
4764
Amith Yamasani742a6712011-05-04 14:49:28 -07004765 uid = UserId.getAppId(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004766 // Our own process gets to do everything.
4767 if (pid == MY_PID) {
4768 return PackageManager.PERMISSION_GRANTED;
4769 }
4770 synchronized(this) {
4771 return checkUriPermissionLocked(uri, uid, modeFlags)
4772 ? PackageManager.PERMISSION_GRANTED
4773 : PackageManager.PERMISSION_DENIED;
4774 }
4775 }
4776
Dianne Hackborn39792d22010-08-19 18:01:52 -07004777 /**
4778 * Check if the targetPkg can be granted permission to access uri by
4779 * the callingUid using the given modeFlags. Throws a security exception
4780 * if callingUid is not allowed to do this. Returns the uid of the target
4781 * if the URI permission grant should be performed; returns -1 if it is not
4782 * needed (for example targetPkg already has permission to access the URI).
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004783 * If you already know the uid of the target, you can supply it in
4784 * lastTargetUid else set that to -1.
Dianne Hackborn39792d22010-08-19 18:01:52 -07004785 */
4786 int checkGrantUriPermissionLocked(int callingUid, String targetPkg,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004787 Uri uri, int modeFlags, int lastTargetUid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004788 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4789 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4790 if (modeFlags == 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004791 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004792 }
4793
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004794 if (targetPkg != null) {
4795 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4796 "Checking grant " + targetPkg + " permission to " + uri);
4797 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004798
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004799 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004800
4801 // If this is not a content: uri, we can't do anything with it.
4802 if (!ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004803 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004804 "Can't grant URI permission for non-content URI: " + uri);
Dianne Hackborn39792d22010-08-19 18:01:52 -07004805 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004806 }
4807
4808 String name = uri.getAuthority();
4809 ProviderInfo pi = null;
Amith Yamasani742a6712011-05-04 14:49:28 -07004810 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
4811 UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004812 if (cpr != null) {
4813 pi = cpr.info;
4814 } else {
4815 try {
4816 pi = pm.resolveContentProvider(name,
Amith Yamasani483f3b02012-03-13 16:08:00 -07004817 PackageManager.GET_URI_PERMISSION_PATTERNS, UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004818 } catch (RemoteException ex) {
4819 }
4820 }
4821 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07004822 Slog.w(TAG, "No content provider found for permission check: " + uri.toSafeString());
Dianne Hackborn39792d22010-08-19 18:01:52 -07004823 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004824 }
4825
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004826 int targetUid = lastTargetUid;
4827 if (targetUid < 0 && targetPkg != null) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004828 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07004829 targetUid = pm.getPackageUid(targetPkg, UserId.getUserId(callingUid));
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004830 if (targetUid < 0) {
4831 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4832 "Can't grant URI permission no uid for: " + targetPkg);
4833 return -1;
4834 }
4835 } catch (RemoteException ex) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004836 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004837 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004838 }
4839
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004840 if (targetUid >= 0) {
4841 // First... does the target actually need this permission?
4842 if (checkHoldingPermissionsLocked(pm, pi, uri, targetUid, modeFlags)) {
4843 // No need to grant the target this permission.
4844 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4845 "Target " + targetPkg + " already has full permission to " + uri);
4846 return -1;
4847 }
4848 } else {
4849 // First... there is no target package, so can anyone access it?
4850 boolean allowed = pi.exported;
4851 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
4852 if (pi.readPermission != null) {
4853 allowed = false;
4854 }
4855 }
4856 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
4857 if (pi.writePermission != null) {
4858 allowed = false;
4859 }
4860 }
4861 if (allowed) {
4862 return -1;
4863 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004864 }
4865
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004866 // Second... is the provider allowing granting of URI permissions?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004867 if (!pi.grantUriPermissions) {
4868 throw new SecurityException("Provider " + pi.packageName
4869 + "/" + pi.name
4870 + " does not allow granting of Uri permissions (uri "
4871 + uri + ")");
4872 }
4873 if (pi.uriPermissionPatterns != null) {
4874 final int N = pi.uriPermissionPatterns.length;
4875 boolean allowed = false;
4876 for (int i=0; i<N; i++) {
4877 if (pi.uriPermissionPatterns[i] != null
4878 && pi.uriPermissionPatterns[i].match(uri.getPath())) {
4879 allowed = true;
4880 break;
4881 }
4882 }
4883 if (!allowed) {
4884 throw new SecurityException("Provider " + pi.packageName
4885 + "/" + pi.name
4886 + " does not allow granting of permission to path of Uri "
4887 + uri);
4888 }
4889 }
4890
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004891 // Third... does the caller itself have permission to access
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004892 // this uri?
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004893 if (callingUid != Process.myUid()) {
4894 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
4895 if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
4896 throw new SecurityException("Uid " + callingUid
4897 + " does not have permission to uri " + uri);
4898 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004899 }
4900 }
4901
Dianne Hackborn39792d22010-08-19 18:01:52 -07004902 return targetUid;
4903 }
4904
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004905 public int checkGrantUriPermission(int callingUid, String targetPkg,
4906 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004907 enforceNotIsolatedCaller("checkGrantUriPermission");
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004908 synchronized(this) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004909 return checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004910 }
4911 }
4912
Dianne Hackborn39792d22010-08-19 18:01:52 -07004913 void grantUriPermissionUncheckedLocked(int targetUid, String targetPkg,
4914 Uri uri, int modeFlags, UriPermissionOwner owner) {
4915 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4916 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4917 if (modeFlags == 0) {
4918 return;
4919 }
4920
4921 // So here we are: the caller has the assumed permission
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004922 // to the uri, and the target doesn't. Let's now give this to
4923 // the target.
4924
Joe Onorato8a9b2202010-02-26 18:56:32 -08004925 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn39792d22010-08-19 18:01:52 -07004926 "Granting " + targetPkg + "/" + targetUid + " permission to " + uri);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004927
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004928 HashMap<Uri, UriPermission> targetUris
4929 = mGrantedUriPermissions.get(targetUid);
4930 if (targetUris == null) {
4931 targetUris = new HashMap<Uri, UriPermission>();
4932 mGrantedUriPermissions.put(targetUid, targetUris);
4933 }
4934
4935 UriPermission perm = targetUris.get(uri);
4936 if (perm == null) {
4937 perm = new UriPermission(targetUid, uri);
4938 targetUris.put(uri, perm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004939 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07004940
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004941 perm.modeFlags |= modeFlags;
Dianne Hackborn39792d22010-08-19 18:01:52 -07004942 if (owner == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004943 perm.globalModeFlags |= modeFlags;
Vairavan Srinivasan91c12c22011-01-21 18:26:06 -08004944 } else {
4945 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
4946 perm.readOwners.add(owner);
4947 owner.addReadPermission(perm);
4948 }
4949 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
4950 perm.writeOwners.add(owner);
4951 owner.addWritePermission(perm);
4952 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004953 }
4954 }
4955
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004956 void grantUriPermissionLocked(int callingUid, String targetPkg, Uri uri,
4957 int modeFlags, UriPermissionOwner owner) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004958 if (targetPkg == null) {
4959 throw new NullPointerException("targetPkg");
4960 }
4961
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004962 int targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn39792d22010-08-19 18:01:52 -07004963 if (targetUid < 0) {
4964 return;
4965 }
4966
4967 grantUriPermissionUncheckedLocked(targetUid, targetPkg, uri, modeFlags, owner);
4968 }
4969
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004970 static class NeededUriGrants extends ArrayList<Uri> {
4971 final String targetPkg;
4972 final int targetUid;
4973 final int flags;
4974
4975 NeededUriGrants(String _targetPkg, int _targetUid, int _flags) {
4976 targetPkg = _targetPkg;
4977 targetUid = _targetUid;
4978 flags = _flags;
4979 }
4980 }
4981
Dianne Hackborn39792d22010-08-19 18:01:52 -07004982 /**
4983 * Like checkGrantUriPermissionLocked, but takes an Intent.
4984 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004985 NeededUriGrants checkGrantUriPermissionFromIntentLocked(int callingUid,
4986 String targetPkg, Intent intent, int mode, NeededUriGrants needed) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07004987 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004988 "Checking URI perm to data=" + (intent != null ? intent.getData() : null)
4989 + " clip=" + (intent != null ? intent.getClipData() : null)
Dianne Hackbornb424b632010-08-18 15:59:05 -07004990 + " from " + intent + "; flags=0x"
4991 + Integer.toHexString(intent != null ? intent.getFlags() : 0));
4992
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004993 if (targetPkg == null) {
4994 throw new NullPointerException("targetPkg");
4995 }
4996
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004997 if (intent == null) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004998 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004999 }
5000 Uri data = intent.getData();
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005001 ClipData clip = intent.getClipData();
5002 if (data == null && clip == null) {
5003 return null;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005004 }
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005005 if (data != null) {
5006 int target = checkGrantUriPermissionLocked(callingUid, targetPkg, data,
5007 mode, needed != null ? needed.targetUid : -1);
5008 if (target > 0) {
5009 if (needed == null) {
5010 needed = new NeededUriGrants(targetPkg, target, mode);
5011 }
5012 needed.add(data);
5013 }
5014 }
5015 if (clip != null) {
5016 for (int i=0; i<clip.getItemCount(); i++) {
5017 Uri uri = clip.getItemAt(i).getUri();
5018 if (uri != null) {
5019 int target = -1;
5020 target = checkGrantUriPermissionLocked(callingUid, targetPkg, uri,
5021 mode, needed != null ? needed.targetUid : -1);
5022 if (target > 0) {
5023 if (needed == null) {
5024 needed = new NeededUriGrants(targetPkg, target, mode);
5025 }
5026 needed.add(uri);
5027 }
5028 } else {
5029 Intent clipIntent = clip.getItemAt(i).getIntent();
5030 if (clipIntent != null) {
5031 NeededUriGrants newNeeded = checkGrantUriPermissionFromIntentLocked(
5032 callingUid, targetPkg, clipIntent, mode, needed);
5033 if (newNeeded != null) {
5034 needed = newNeeded;
5035 }
5036 }
5037 }
5038 }
5039 }
5040
5041 return needed;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005042 }
5043
5044 /**
5045 * Like grantUriPermissionUncheckedLocked, but takes an Intent.
5046 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005047 void grantUriPermissionUncheckedFromIntentLocked(NeededUriGrants needed,
5048 UriPermissionOwner owner) {
5049 if (needed != null) {
5050 for (int i=0; i<needed.size(); i++) {
5051 grantUriPermissionUncheckedLocked(needed.targetUid, needed.targetPkg,
5052 needed.get(i), needed.flags, owner);
5053 }
5054 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005055 }
5056
5057 void grantUriPermissionFromIntentLocked(int callingUid,
5058 String targetPkg, Intent intent, UriPermissionOwner owner) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005059 NeededUriGrants needed = checkGrantUriPermissionFromIntentLocked(callingUid, targetPkg,
Dianne Hackbornd9781fe2012-03-08 18:04:18 -08005060 intent, intent != null ? intent.getFlags() : 0, null);
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005061 if (needed == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005062 return;
5063 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005064
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005065 grantUriPermissionUncheckedFromIntentLocked(needed, owner);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005066 }
5067
5068 public void grantUriPermission(IApplicationThread caller, String targetPkg,
5069 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005070 enforceNotIsolatedCaller("grantUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005071 synchronized(this) {
5072 final ProcessRecord r = getRecordForAppLocked(caller);
5073 if (r == null) {
5074 throw new SecurityException("Unable to find app for caller "
5075 + caller
5076 + " when granting permission to uri " + uri);
5077 }
5078 if (targetPkg == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005079 throw new IllegalArgumentException("null target");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005080 }
5081 if (uri == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005082 throw new IllegalArgumentException("null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005083 }
5084
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005085 grantUriPermissionLocked(r.uid, targetPkg, uri, modeFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005086 null);
5087 }
5088 }
5089
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005090 void removeUriPermissionIfNeededLocked(UriPermission perm) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005091 if ((perm.modeFlags&(Intent.FLAG_GRANT_READ_URI_PERMISSION
5092 |Intent.FLAG_GRANT_WRITE_URI_PERMISSION)) == 0) {
5093 HashMap<Uri, UriPermission> perms
5094 = mGrantedUriPermissions.get(perm.uid);
5095 if (perms != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005096 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005097 "Removing " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005098 perms.remove(perm.uri);
5099 if (perms.size() == 0) {
5100 mGrantedUriPermissions.remove(perm.uid);
5101 }
5102 }
5103 }
5104 }
5105
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005106 private void revokeUriPermissionLocked(int callingUid, Uri uri,
5107 int modeFlags) {
5108 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5109 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5110 if (modeFlags == 0) {
5111 return;
5112 }
5113
Joe Onorato8a9b2202010-02-26 18:56:32 -08005114 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005115 "Revoking all granted permissions to " + uri);
5116
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005117 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005118
5119 final String authority = uri.getAuthority();
5120 ProviderInfo pi = null;
Amith Yamasani483f3b02012-03-13 16:08:00 -07005121 int userId = UserId.getUserId(callingUid);
5122 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005123 if (cpr != null) {
5124 pi = cpr.info;
5125 } else {
5126 try {
5127 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005128 PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005129 } catch (RemoteException ex) {
5130 }
5131 }
5132 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005133 Slog.w(TAG, "No content provider found for permission revoke: " + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005134 return;
5135 }
5136
5137 // Does the caller have this permission on the URI?
Dianne Hackborn48058e82010-09-27 16:53:23 -07005138 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005139 // Right now, if you are not the original owner of the permission,
5140 // you are not allowed to revoke it.
5141 //if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5142 throw new SecurityException("Uid " + callingUid
5143 + " does not have permission to uri " + uri);
5144 //}
5145 }
5146
5147 // Go through all of the permissions and remove any that match.
5148 final List<String> SEGMENTS = uri.getPathSegments();
5149 if (SEGMENTS != null) {
5150 final int NS = SEGMENTS.size();
5151 int N = mGrantedUriPermissions.size();
5152 for (int i=0; i<N; i++) {
5153 HashMap<Uri, UriPermission> perms
5154 = mGrantedUriPermissions.valueAt(i);
5155 Iterator<UriPermission> it = perms.values().iterator();
5156 toploop:
5157 while (it.hasNext()) {
5158 UriPermission perm = it.next();
5159 Uri targetUri = perm.uri;
5160 if (!authority.equals(targetUri.getAuthority())) {
5161 continue;
5162 }
5163 List<String> targetSegments = targetUri.getPathSegments();
5164 if (targetSegments == null) {
5165 continue;
5166 }
5167 if (targetSegments.size() < NS) {
5168 continue;
5169 }
5170 for (int j=0; j<NS; j++) {
5171 if (!SEGMENTS.get(j).equals(targetSegments.get(j))) {
5172 continue toploop;
5173 }
5174 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08005175 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005176 "Revoking " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005177 perm.clearModes(modeFlags);
5178 if (perm.modeFlags == 0) {
5179 it.remove();
5180 }
5181 }
5182 if (perms.size() == 0) {
5183 mGrantedUriPermissions.remove(
5184 mGrantedUriPermissions.keyAt(i));
5185 N--;
5186 i--;
5187 }
5188 }
5189 }
5190 }
5191
5192 public void revokeUriPermission(IApplicationThread caller, Uri uri,
5193 int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005194 enforceNotIsolatedCaller("revokeUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005195 synchronized(this) {
5196 final ProcessRecord r = getRecordForAppLocked(caller);
5197 if (r == null) {
5198 throw new SecurityException("Unable to find app for caller "
5199 + caller
5200 + " when revoking permission to uri " + uri);
5201 }
5202 if (uri == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005203 Slog.w(TAG, "revokeUriPermission: null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005204 return;
5205 }
5206
5207 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5208 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5209 if (modeFlags == 0) {
5210 return;
5211 }
5212
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005213 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005214
5215 final String authority = uri.getAuthority();
5216 ProviderInfo pi = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005217 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005218 if (cpr != null) {
5219 pi = cpr.info;
5220 } else {
5221 try {
5222 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005223 PackageManager.GET_URI_PERMISSION_PATTERNS, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005224 } catch (RemoteException ex) {
5225 }
5226 }
5227 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005228 Slog.w(TAG, "No content provider found for permission revoke: "
5229 + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005230 return;
5231 }
5232
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005233 revokeUriPermissionLocked(r.uid, uri, modeFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005234 }
5235 }
5236
Dianne Hackborn7e269642010-08-25 19:50:20 -07005237 @Override
5238 public IBinder newUriPermissionOwner(String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005239 enforceNotIsolatedCaller("newUriPermissionOwner");
Dianne Hackborn7e269642010-08-25 19:50:20 -07005240 synchronized(this) {
5241 UriPermissionOwner owner = new UriPermissionOwner(this, name);
5242 return owner.getExternalTokenLocked();
5243 }
5244 }
5245
5246 @Override
5247 public void grantUriPermissionFromOwner(IBinder token, int fromUid, String targetPkg,
5248 Uri uri, int modeFlags) {
5249 synchronized(this) {
5250 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5251 if (owner == null) {
5252 throw new IllegalArgumentException("Unknown owner: " + token);
5253 }
5254 if (fromUid != Binder.getCallingUid()) {
5255 if (Binder.getCallingUid() != Process.myUid()) {
5256 // Only system code can grant URI permissions on behalf
5257 // of other users.
5258 throw new SecurityException("nice try");
5259 }
5260 }
5261 if (targetPkg == null) {
5262 throw new IllegalArgumentException("null target");
5263 }
5264 if (uri == null) {
5265 throw new IllegalArgumentException("null uri");
5266 }
5267
5268 grantUriPermissionLocked(fromUid, targetPkg, uri, modeFlags, owner);
5269 }
5270 }
5271
5272 @Override
5273 public void revokeUriPermissionFromOwner(IBinder token, Uri uri, int mode) {
5274 synchronized(this) {
5275 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5276 if (owner == null) {
5277 throw new IllegalArgumentException("Unknown owner: " + token);
5278 }
5279
5280 if (uri == null) {
5281 owner.removeUriPermissionsLocked(mode);
5282 } else {
5283 owner.removeUriPermissionLocked(uri, mode);
5284 }
5285 }
5286 }
5287
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005288 public void showWaitingForDebugger(IApplicationThread who, boolean waiting) {
5289 synchronized (this) {
5290 ProcessRecord app =
5291 who != null ? getRecordForAppLocked(who) : null;
5292 if (app == null) return;
5293
5294 Message msg = Message.obtain();
5295 msg.what = WAIT_FOR_DEBUGGER_MSG;
5296 msg.obj = app;
5297 msg.arg1 = waiting ? 1 : 0;
5298 mHandler.sendMessage(msg);
5299 }
5300 }
5301
5302 public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07005303 final long homeAppMem = mProcessList.getMemLevel(ProcessList.HOME_APP_ADJ);
5304 final long hiddenAppMem = mProcessList.getMemLevel(ProcessList.HIDDEN_APP_MIN_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005305 outInfo.availMem = Process.getFreeMemory();
Dianne Hackborn7d608422011-08-07 16:24:18 -07005306 outInfo.threshold = homeAppMem;
5307 outInfo.lowMemory = outInfo.availMem < (homeAppMem + ((hiddenAppMem-homeAppMem)/2));
5308 outInfo.hiddenAppThreshold = hiddenAppMem;
5309 outInfo.secondaryServerThreshold = mProcessList.getMemLevel(
Dianne Hackborne02c88a2011-10-28 13:58:15 -07005310 ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07005311 outInfo.visibleAppThreshold = mProcessList.getMemLevel(
5312 ProcessList.VISIBLE_APP_ADJ);
5313 outInfo.foregroundAppThreshold = mProcessList.getMemLevel(
5314 ProcessList.FOREGROUND_APP_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005315 }
5316
5317 // =========================================================
5318 // TASK MANAGEMENT
5319 // =========================================================
5320
5321 public List getTasks(int maxNum, int flags,
5322 IThumbnailReceiver receiver) {
5323 ArrayList list = new ArrayList();
5324
5325 PendingThumbnailsRecord pending = null;
5326 IApplicationThread topThumbnail = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005327 ActivityRecord topRecord = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005328
5329 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005330 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005331 TAG, "getTasks: max=" + maxNum + ", flags=" + flags
5332 + ", receiver=" + receiver);
5333
5334 if (checkCallingPermission(android.Manifest.permission.GET_TASKS)
5335 != PackageManager.PERMISSION_GRANTED) {
5336 if (receiver != null) {
5337 // If the caller wants to wait for pending thumbnails,
5338 // it ain't gonna get them.
5339 try {
5340 receiver.finished();
5341 } catch (RemoteException ex) {
5342 }
5343 }
5344 String msg = "Permission Denial: getTasks() from pid="
5345 + Binder.getCallingPid()
5346 + ", uid=" + Binder.getCallingUid()
5347 + " requires " + android.Manifest.permission.GET_TASKS;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005348 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005349 throw new SecurityException(msg);
5350 }
5351
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005352 int pos = mMainStack.mHistory.size()-1;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005353 ActivityRecord next =
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005354 pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005355 ActivityRecord top = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005356 TaskRecord curTask = null;
5357 int numActivities = 0;
5358 int numRunning = 0;
5359 while (pos >= 0 && maxNum > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005360 final ActivityRecord r = next;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005361 pos--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005362 next = pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005363
5364 // Initialize state for next task if needed.
5365 if (top == null ||
5366 (top.state == ActivityState.INITIALIZING
5367 && top.task == r.task)) {
5368 top = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005369 curTask = r.task;
5370 numActivities = numRunning = 0;
5371 }
5372
5373 // Add 'r' into the current task.
5374 numActivities++;
5375 if (r.app != null && r.app.thread != null) {
5376 numRunning++;
5377 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005378
Joe Onorato8a9b2202010-02-26 18:56:32 -08005379 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005380 TAG, r.intent.getComponent().flattenToShortString()
5381 + ": task=" + r.task);
5382
5383 // If the next one is a different task, generate a new
5384 // TaskInfo entry for what we have.
5385 if (next == null || next.task != curTask) {
5386 ActivityManager.RunningTaskInfo ci
5387 = new ActivityManager.RunningTaskInfo();
5388 ci.id = curTask.taskId;
5389 ci.baseActivity = r.intent.getComponent();
5390 ci.topActivity = top.intent.getComponent();
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005391 if (top.thumbHolder != null) {
5392 ci.description = top.thumbHolder.lastDescription;
5393 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005394 ci.numActivities = numActivities;
5395 ci.numRunning = numRunning;
5396 //System.out.println(
5397 // "#" + maxNum + ": " + " descr=" + ci.description);
5398 if (ci.thumbnail == null && receiver != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005399 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005400 TAG, "State=" + top.state + "Idle=" + top.idle
5401 + " app=" + top.app
5402 + " thr=" + (top.app != null ? top.app.thread : null));
5403 if (top.state == ActivityState.RESUMED
5404 || top.state == ActivityState.PAUSING) {
5405 if (top.idle && top.app != null
5406 && top.app.thread != null) {
5407 topRecord = top;
5408 topThumbnail = top.app.thread;
5409 } else {
5410 top.thumbnailNeeded = true;
5411 }
5412 }
5413 if (pending == null) {
5414 pending = new PendingThumbnailsRecord(receiver);
5415 }
5416 pending.pendingRecords.add(top);
5417 }
5418 list.add(ci);
5419 maxNum--;
5420 top = null;
5421 }
5422 }
5423
5424 if (pending != null) {
5425 mPendingThumbnails.add(pending);
5426 }
5427 }
5428
Joe Onorato8a9b2202010-02-26 18:56:32 -08005429 if (localLOGV) Slog.v(TAG, "We have pending thumbnails: " + pending);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005430
5431 if (topThumbnail != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005432 if (localLOGV) Slog.v(TAG, "Requesting top thumbnail");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005433 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08005434 topThumbnail.requestThumbnail(topRecord.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005435 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005436 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005437 sendPendingThumbnail(null, topRecord.appToken, null, null, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005438 }
5439 }
5440
5441 if (pending == null && receiver != null) {
5442 // In this case all thumbnails were available and the client
5443 // is being asked to be told when the remaining ones come in...
5444 // which is unusually, since the top-most currently running
5445 // activity should never have a canned thumbnail! Oh well.
5446 try {
5447 receiver.finished();
5448 } catch (RemoteException ex) {
5449 }
5450 }
5451
5452 return list;
5453 }
5454
5455 public List<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum,
5456 int flags) {
Amith Yamasani742a6712011-05-04 14:49:28 -07005457 final int callingUid = Binder.getCallingUid();
5458 // If it's the system uid asking, then use the current user id.
5459 // TODO: Make sure that there aren't any other legitimate calls from the system uid that
5460 // require the entire list.
5461 final int callingUserId = callingUid == Process.SYSTEM_UID
5462 ? mCurrentUserId : UserId.getUserId(callingUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005463 synchronized (this) {
5464 enforceCallingPermission(android.Manifest.permission.GET_TASKS,
5465 "getRecentTasks()");
5466
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005467 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005468
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005469 final int N = mRecentTasks.size();
5470 ArrayList<ActivityManager.RecentTaskInfo> res
5471 = new ArrayList<ActivityManager.RecentTaskInfo>(
5472 maxNum < N ? maxNum : N);
5473 for (int i=0; i<N && maxNum > 0; i++) {
5474 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005475 // Only add calling user's recent tasks
5476 if (tr.userId != callingUserId) continue;
Dianne Hackborn905577f2011-09-07 18:31:28 -07005477 // Return the entry if desired by the caller. We always return
5478 // the first entry, because callers always expect this to be the
Amith Yamasani742a6712011-05-04 14:49:28 -07005479 // foreground app. We may filter others if the caller has
Dianne Hackborn905577f2011-09-07 18:31:28 -07005480 // not supplied RECENT_WITH_EXCLUDED and there is some reason
5481 // we should exclude the entry.
Amith Yamasani742a6712011-05-04 14:49:28 -07005482
Dianne Hackborn905577f2011-09-07 18:31:28 -07005483 if (i == 0
5484 || ((flags&ActivityManager.RECENT_WITH_EXCLUDED) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005485 || (tr.intent == null)
5486 || ((tr.intent.getFlags()
5487 &Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) == 0)) {
5488 ActivityManager.RecentTaskInfo rti
5489 = new ActivityManager.RecentTaskInfo();
5490 rti.id = tr.numActivities > 0 ? tr.taskId : -1;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005491 rti.persistentId = tr.taskId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005492 rti.baseIntent = new Intent(
5493 tr.intent != null ? tr.intent : tr.affinityIntent);
5494 rti.origActivity = tr.origActivity;
Dianne Hackbornd2835932010-12-13 16:28:46 -08005495 rti.description = tr.lastDescription;
5496
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005497 if ((flags&ActivityManager.RECENT_IGNORE_UNAVAILABLE) != 0) {
5498 // Check whether this activity is currently available.
5499 try {
5500 if (rti.origActivity != null) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07005501 if (pm.getActivityInfo(rti.origActivity, 0, callingUserId)
5502 == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005503 continue;
5504 }
5505 } else if (rti.baseIntent != null) {
5506 if (pm.queryIntentActivities(rti.baseIntent,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005507 null, 0, callingUserId) == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005508 continue;
5509 }
5510 }
5511 } catch (RemoteException e) {
5512 // Will never happen.
5513 }
5514 }
5515
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005516 res.add(rti);
5517 maxNum--;
5518 }
5519 }
5520 return res;
5521 }
5522 }
5523
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005524 private TaskRecord taskForIdLocked(int id) {
5525 final int N = mRecentTasks.size();
5526 for (int i=0; i<N; i++) {
5527 TaskRecord tr = mRecentTasks.get(i);
5528 if (tr.taskId == id) {
5529 return tr;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005530 }
5531 }
5532 return null;
5533 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005534
5535 public ActivityManager.TaskThumbnails getTaskThumbnails(int id) {
5536 synchronized (this) {
5537 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
5538 "getTaskThumbnails()");
5539 TaskRecord tr = taskForIdLocked(id);
5540 if (tr != null) {
5541 return mMainStack.getTaskThumbnailsLocked(tr);
5542 }
5543 }
5544 return null;
5545 }
5546
5547 public boolean removeSubTask(int taskId, int subTaskIndex) {
5548 synchronized (this) {
5549 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5550 "removeSubTask()");
5551 long ident = Binder.clearCallingIdentity();
5552 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005553 return mMainStack.removeTaskActivitiesLocked(taskId, subTaskIndex,
5554 true) != null;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005555 } finally {
5556 Binder.restoreCallingIdentity(ident);
5557 }
5558 }
5559 }
5560
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005561 private void cleanUpRemovedTaskLocked(TaskRecord tr, int flags) {
5562 final boolean killProcesses = (flags&ActivityManager.REMOVE_TASK_KILL_PROCESS) != 0;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005563 Intent baseIntent = new Intent(
5564 tr.intent != null ? tr.intent : tr.affinityIntent);
5565 ComponentName component = baseIntent.getComponent();
5566 if (component == null) {
5567 Slog.w(TAG, "Now component for base intent of task: " + tr);
5568 return;
5569 }
5570
5571 // Find any running services associated with this app.
5572 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005573 for (ServiceRecord sr : mServiceMap.getAllServices(tr.userId)) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005574 if (sr.packageName.equals(component.getPackageName())) {
5575 services.add(sr);
5576 }
5577 }
5578
5579 // Take care of any running services associated with the app.
5580 for (int i=0; i<services.size(); i++) {
5581 ServiceRecord sr = services.get(i);
5582 if (sr.startRequested) {
5583 if ((sr.serviceInfo.flags&ServiceInfo.FLAG_STOP_WITH_TASK) != 0) {
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005584 Slog.i(TAG, "Stopping service " + sr.shortName + ": remove task");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005585 stopServiceLocked(sr);
5586 } else {
5587 sr.pendingStarts.add(new ServiceRecord.StartItem(sr, true,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005588 sr.makeNextStartId(), baseIntent, null));
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005589 if (sr.app != null && sr.app.thread != null) {
5590 sendServiceArgsLocked(sr, false);
5591 }
5592 }
5593 }
5594 }
5595
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005596 if (killProcesses) {
5597 // Find any running processes associated with this app.
5598 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
5599 SparseArray<ProcessRecord> appProcs
5600 = mProcessNames.getMap().get(component.getPackageName());
5601 if (appProcs != null) {
5602 for (int i=0; i<appProcs.size(); i++) {
5603 procs.add(appProcs.valueAt(i));
5604 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005605 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005606
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005607 // Kill the running processes.
5608 for (int i=0; i<procs.size(); i++) {
5609 ProcessRecord pr = procs.get(i);
5610 if (pr.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
5611 Slog.i(TAG, "Killing " + pr.toShortString() + ": remove task");
5612 EventLog.writeEvent(EventLogTags.AM_KILL, pr.pid,
5613 pr.processName, pr.setAdj, "remove task");
5614 Process.killProcessQuiet(pr.pid);
5615 } else {
5616 pr.waitingToKill = "remove task";
5617 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005618 }
5619 }
5620 }
5621
5622 public boolean removeTask(int taskId, int flags) {
5623 synchronized (this) {
5624 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5625 "removeTask()");
5626 long ident = Binder.clearCallingIdentity();
5627 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005628 ActivityRecord r = mMainStack.removeTaskActivitiesLocked(taskId, -1,
5629 false);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005630 if (r != null) {
5631 mRecentTasks.remove(r.task);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005632 cleanUpRemovedTaskLocked(r.task, flags);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005633 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005634 } else {
5635 TaskRecord tr = null;
5636 int i=0;
5637 while (i < mRecentTasks.size()) {
5638 TaskRecord t = mRecentTasks.get(i);
5639 if (t.taskId == taskId) {
5640 tr = t;
5641 break;
5642 }
5643 i++;
5644 }
5645 if (tr != null) {
5646 if (tr.numActivities <= 0) {
5647 // Caller is just removing a recent task that is
5648 // not actively running. That is easy!
5649 mRecentTasks.remove(i);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005650 cleanUpRemovedTaskLocked(tr, flags);
5651 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005652 } else {
5653 Slog.w(TAG, "removeTask: task " + taskId
5654 + " does not have activities to remove, "
5655 + " but numActivities=" + tr.numActivities
5656 + ": " + tr);
5657 }
5658 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005659 }
5660 } finally {
5661 Binder.restoreCallingIdentity(ident);
5662 }
5663 }
5664 return false;
5665 }
Dianne Hackbornd94df452011-02-16 18:53:31 -08005666
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005667 private final int findAffinityTaskTopLocked(int startIndex, String affinity) {
5668 int j;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005669 TaskRecord startTask = ((ActivityRecord)mMainStack.mHistory.get(startIndex)).task;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005670 TaskRecord jt = startTask;
5671
5672 // First look backwards
5673 for (j=startIndex-1; j>=0; j--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005674 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005675 if (r.task != jt) {
5676 jt = r.task;
5677 if (affinity.equals(jt.affinity)) {
5678 return j;
5679 }
5680 }
5681 }
5682
5683 // Now look forwards
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005684 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005685 jt = startTask;
5686 for (j=startIndex+1; j<N; j++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005687 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005688 if (r.task != jt) {
5689 if (affinity.equals(jt.affinity)) {
5690 return j;
5691 }
5692 jt = r.task;
5693 }
5694 }
5695
5696 // Might it be at the top?
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005697 if (affinity.equals(((ActivityRecord)mMainStack.mHistory.get(N-1)).task.affinity)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005698 return N-1;
5699 }
5700
5701 return -1;
5702 }
5703
5704 /**
Dianne Hackbornb06ea702009-07-13 13:07:51 -07005705 * TODO: Add mController hook
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005706 */
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005707 public void moveTaskToFront(int task, int flags, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005708 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5709 "moveTaskToFront()");
5710
5711 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005712 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5713 Binder.getCallingUid(), "Task to front")) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005714 ActivityOptions.abort(options);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005715 return;
5716 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005717 final long origId = Binder.clearCallingIdentity();
5718 try {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005719 TaskRecord tr = taskForIdLocked(task);
5720 if (tr != null) {
5721 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5722 mMainStack.mUserLeaving = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005723 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005724 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5725 // Caller wants the home activity moved with it. To accomplish this,
5726 // we'll just move the home task to the top first.
5727 mMainStack.moveHomeToFrontLocked();
5728 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005729 mMainStack.moveTaskToFrontLocked(tr, null, options);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005730 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005731 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005732 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
5733 ActivityRecord hr = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005734 if (hr.task.taskId == task) {
Dianne Hackbornd94df452011-02-16 18:53:31 -08005735 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5736 mMainStack.mUserLeaving = true;
5737 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005738 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5739 // Caller wants the home activity moved with it. To accomplish this,
5740 // we'll just move the home task to the top first.
5741 mMainStack.moveHomeToFrontLocked();
5742 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005743 mMainStack.moveTaskToFrontLocked(hr.task, null, options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005744 return;
5745 }
5746 }
5747 } finally {
5748 Binder.restoreCallingIdentity(origId);
5749 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005750 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005751 }
5752 }
5753
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005754 public void moveTaskToBack(int task) {
5755 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5756 "moveTaskToBack()");
5757
5758 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005759 if (mMainStack.mResumedActivity != null
5760 && mMainStack.mResumedActivity.task.taskId == task) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005761 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5762 Binder.getCallingUid(), "Task to back")) {
5763 return;
5764 }
5765 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005766 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005767 mMainStack.moveTaskToBackLocked(task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005768 Binder.restoreCallingIdentity(origId);
5769 }
5770 }
5771
5772 /**
5773 * Moves an activity, and all of the other activities within the same task, to the bottom
5774 * of the history stack. The activity's order within the task is unchanged.
5775 *
5776 * @param token A reference to the activity we wish to move
5777 * @param nonRoot If false then this only works if the activity is the root
5778 * of a task; if true it will work for any activity in a task.
5779 * @return Returns true if the move completed, false if not.
5780 */
5781 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005782 enforceNotIsolatedCaller("moveActivityTaskToBack");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005783 synchronized(this) {
5784 final long origId = Binder.clearCallingIdentity();
5785 int taskId = getTaskForActivityLocked(token, !nonRoot);
5786 if (taskId >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005787 return mMainStack.moveTaskToBackLocked(taskId, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005788 }
5789 Binder.restoreCallingIdentity(origId);
5790 }
5791 return false;
5792 }
5793
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005794 public void moveTaskBackwards(int task) {
5795 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5796 "moveTaskBackwards()");
5797
5798 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005799 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5800 Binder.getCallingUid(), "Task backwards")) {
5801 return;
5802 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005803 final long origId = Binder.clearCallingIdentity();
5804 moveTaskBackwardsLocked(task);
5805 Binder.restoreCallingIdentity(origId);
5806 }
5807 }
5808
5809 private final void moveTaskBackwardsLocked(int task) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005810 Slog.e(TAG, "moveTaskBackwards not yet implemented!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005811 }
5812
5813 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
5814 synchronized(this) {
5815 return getTaskForActivityLocked(token, onlyRoot);
5816 }
5817 }
5818
5819 int getTaskForActivityLocked(IBinder token, boolean onlyRoot) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005820 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005821 TaskRecord lastTask = null;
5822 for (int i=0; i<N; i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005823 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005824 if (r.appToken == token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005825 if (!onlyRoot || lastTask != r.task) {
5826 return r.task.taskId;
5827 }
5828 return -1;
5829 }
5830 lastTask = r.task;
5831 }
5832
5833 return -1;
5834 }
5835
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005836 // =========================================================
5837 // THUMBNAILS
5838 // =========================================================
5839
5840 public void reportThumbnail(IBinder token,
5841 Bitmap thumbnail, CharSequence description) {
5842 //System.out.println("Report thumbnail for " + token + ": " + thumbnail);
5843 final long origId = Binder.clearCallingIdentity();
5844 sendPendingThumbnail(null, token, thumbnail, description, true);
5845 Binder.restoreCallingIdentity(origId);
5846 }
5847
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005848 final void sendPendingThumbnail(ActivityRecord r, IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005849 Bitmap thumbnail, CharSequence description, boolean always) {
5850 TaskRecord task = null;
5851 ArrayList receivers = null;
5852
5853 //System.out.println("Send pending thumbnail: " + r);
5854
5855 synchronized(this) {
5856 if (r == null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07005857 r = mMainStack.isInStackLocked(token);
5858 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005859 return;
5860 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005861 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005862 if (thumbnail == null && r.thumbHolder != null) {
5863 thumbnail = r.thumbHolder.lastThumbnail;
5864 description = r.thumbHolder.lastDescription;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005865 }
5866 if (thumbnail == null && !always) {
5867 // If there is no thumbnail, and this entry is not actually
5868 // going away, then abort for now and pick up the next
5869 // thumbnail we get.
5870 return;
5871 }
5872 task = r.task;
5873
5874 int N = mPendingThumbnails.size();
5875 int i=0;
5876 while (i<N) {
5877 PendingThumbnailsRecord pr =
5878 (PendingThumbnailsRecord)mPendingThumbnails.get(i);
5879 //System.out.println("Looking in " + pr.pendingRecords);
5880 if (pr.pendingRecords.remove(r)) {
5881 if (receivers == null) {
5882 receivers = new ArrayList();
5883 }
5884 receivers.add(pr);
5885 if (pr.pendingRecords.size() == 0) {
5886 pr.finished = true;
5887 mPendingThumbnails.remove(i);
5888 N--;
5889 continue;
5890 }
5891 }
5892 i++;
5893 }
5894 }
5895
5896 if (receivers != null) {
5897 final int N = receivers.size();
5898 for (int i=0; i<N; i++) {
5899 try {
5900 PendingThumbnailsRecord pr =
5901 (PendingThumbnailsRecord)receivers.get(i);
5902 pr.receiver.newThumbnail(
5903 task != null ? task.taskId : -1, thumbnail, description);
5904 if (pr.finished) {
5905 pr.receiver.finished();
5906 }
5907 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005908 Slog.w(TAG, "Exception thrown when sending thumbnail", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005909 }
5910 }
5911 }
5912 }
5913
5914 // =========================================================
5915 // CONTENT PROVIDERS
5916 // =========================================================
5917
Jeff Brown10e89712011-07-08 18:52:57 -07005918 private final List<ProviderInfo> generateApplicationProvidersLocked(ProcessRecord app) {
5919 List<ProviderInfo> providers = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005920 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005921 providers = AppGlobals.getPackageManager().
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005922 queryContentProviders(app.processName, app.uid,
Dianne Hackborn1655be42009-05-08 14:29:01 -07005923 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005924 } catch (RemoteException ex) {
5925 }
Amith Yamasani742a6712011-05-04 14:49:28 -07005926 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005927 Slog.v(TAG_MU, "generateApplicationProvidersLocked, app.info.uid = " + app.uid);
5928 int userId = app.userId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005929 if (providers != null) {
5930 final int N = providers.size();
5931 for (int i=0; i<N; i++) {
5932 ProviderInfo cpi =
5933 (ProviderInfo)providers.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005934
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07005935 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07005936 ContentProviderRecord cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005937 if (cpr == null) {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08005938 cpr = new ContentProviderRecord(this, cpi, app.info, comp);
Amith Yamasani742a6712011-05-04 14:49:28 -07005939 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005940 }
Amith Yamasani742a6712011-05-04 14:49:28 -07005941 if (DEBUG_MU)
5942 Slog.v(TAG_MU, "generateApplicationProvidersLocked, cpi.uid = " + cpr.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005943 app.pubProviders.put(cpi.name, cpr);
5944 app.addPackage(cpi.applicationInfo.packageName);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07005945 ensurePackageDexOpt(cpi.applicationInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005946 }
5947 }
5948 return providers;
5949 }
5950
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005951 /**
5952 * Check if {@link ProcessRecord} has a possible chance at accessing the
5953 * given {@link ProviderInfo}. Final permission checking is always done
5954 * in {@link ContentProvider}.
5955 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005956 private final String checkContentProviderPermissionLocked(
Dianne Hackbornb424b632010-08-18 15:59:05 -07005957 ProviderInfo cpi, ProcessRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005958 final int callingPid = (r != null) ? r.pid : Binder.getCallingPid();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005959 final int callingUid = (r != null) ? r.uid : Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005960 if (checkComponentPermission(cpi.readPermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005961 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005962 == PackageManager.PERMISSION_GRANTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005963 return null;
5964 }
5965 if (checkComponentPermission(cpi.writePermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005966 cpi.applicationInfo.uid, cpi.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005967 == PackageManager.PERMISSION_GRANTED) {
5968 return null;
5969 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07005970
5971 PathPermission[] pps = cpi.pathPermissions;
5972 if (pps != null) {
5973 int i = pps.length;
5974 while (i > 0) {
5975 i--;
5976 PathPermission pp = pps[i];
5977 if (checkComponentPermission(pp.getReadPermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005978 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005979 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07005980 return null;
5981 }
5982 if (checkComponentPermission(pp.getWritePermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005983 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackborn2af632f2009-07-08 14:56:37 -07005984 == PackageManager.PERMISSION_GRANTED) {
5985 return null;
5986 }
5987 }
5988 }
5989
Dianne Hackbornb424b632010-08-18 15:59:05 -07005990 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(callingUid);
5991 if (perms != null) {
5992 for (Map.Entry<Uri, UriPermission> uri : perms.entrySet()) {
5993 if (uri.getKey().getAuthority().equals(cpi.authority)) {
5994 return null;
5995 }
5996 }
5997 }
5998
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005999 String msg;
6000 if (!cpi.exported) {
6001 msg = "Permission Denial: opening provider " + cpi.name
6002 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6003 + ", uid=" + callingUid + ") that is not exported from uid "
6004 + cpi.applicationInfo.uid;
6005 } else {
6006 msg = "Permission Denial: opening provider " + cpi.name
6007 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6008 + ", uid=" + callingUid + ") requires "
6009 + cpi.readPermission + " or " + cpi.writePermission;
6010 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08006011 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006012 return msg;
6013 }
6014
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006015 boolean incProviderCount(ProcessRecord r, final ContentProviderRecord cpr,
6016 IBinder externalProcessToken) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006017 if (r != null) {
6018 Integer cnt = r.conProviders.get(cpr);
6019 if (DEBUG_PROVIDER) Slog.v(TAG,
6020 "Adding provider requested by "
6021 + r.processName + " from process "
6022 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
6023 + " cnt=" + (cnt == null ? 1 : cnt));
6024 if (cnt == null) {
6025 cpr.clients.add(r);
6026 r.conProviders.put(cpr, new Integer(1));
6027 return true;
6028 } else {
6029 r.conProviders.put(cpr, new Integer(cnt.intValue()+1));
6030 }
6031 } else {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006032 cpr.addExternalProcessHandleLocked(externalProcessToken);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006033 }
6034 return false;
6035 }
6036
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006037 boolean decProviderCount(ProcessRecord r, final ContentProviderRecord cpr,
6038 IBinder externalProcessToken) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006039 if (r != null) {
6040 Integer cnt = r.conProviders.get(cpr);
6041 if (DEBUG_PROVIDER) Slog.v(TAG,
6042 "Removing provider requested by "
6043 + r.processName + " from process "
6044 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
6045 + " cnt=" + cnt);
6046 if (cnt == null || cnt.intValue() <= 1) {
6047 cpr.clients.remove(r);
6048 r.conProviders.remove(cpr);
6049 return true;
6050 } else {
6051 r.conProviders.put(cpr, new Integer(cnt.intValue()-1));
6052 }
6053 } else {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006054 cpr.removeExternalProcessHandleLocked(externalProcessToken);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006055 }
6056 return false;
6057 }
6058
Amith Yamasani742a6712011-05-04 14:49:28 -07006059 private final ContentProviderHolder getContentProviderImpl(IApplicationThread caller,
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006060 String name, IBinder token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006061 ContentProviderRecord cpr;
6062 ProviderInfo cpi = null;
6063
6064 synchronized(this) {
6065 ProcessRecord r = null;
6066 if (caller != null) {
6067 r = getRecordForAppLocked(caller);
6068 if (r == null) {
6069 throw new SecurityException(
6070 "Unable to find app for caller " + caller
6071 + " (pid=" + Binder.getCallingPid()
6072 + ") when getting content provider " + name);
6073 }
6074 }
6075
6076 // First check if this content provider has been published...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006077 int userId = UserId.getUserId(r != null ? r.uid : Binder.getCallingUid());
Amith Yamasani742a6712011-05-04 14:49:28 -07006078 cpr = mProviderMap.getProviderByName(name, userId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006079 boolean providerRunning = cpr != null;
6080 if (providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006081 cpi = cpr.info;
Dianne Hackbornb424b632010-08-18 15:59:05 -07006082 String msg;
6083 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6084 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006085 }
6086
6087 if (r != null && cpr.canRunHere(r)) {
6088 // This provider has been published or is in the process
6089 // of being published... but it is also allowed to run
6090 // in the caller's process, so don't make a connection
6091 // and just let the caller instantiate its own instance.
6092 if (cpr.provider != null) {
6093 // don't give caller the provider object, it needs
6094 // to make its own.
6095 cpr = new ContentProviderRecord(cpr);
6096 }
6097 return cpr;
6098 }
6099
6100 final long origId = Binder.clearCallingIdentity();
6101
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006102 // In this case the provider instance already exists, so we can
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006103 // return it right away.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006104 final boolean countChanged = incProviderCount(r, cpr, token);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006105 if (countChanged) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006106 if (cpr.proc != null && r.setAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006107 // If this is a perceptible app accessing the provider,
Dianne Hackborn906497c2010-05-10 15:57:38 -07006108 // make sure to count it as being accessed and thus
6109 // back up on the LRU list. This is good because
6110 // content providers are often expensive to start.
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006111 updateLruProcessLocked(cpr.proc, false, true);
Dianne Hackborn906497c2010-05-10 15:57:38 -07006112 }
Dianne Hackborn6f86c0e2010-05-11 14:20:52 -07006113 }
6114
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006115 if (cpr.proc != null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006116 if (false) {
6117 if (cpr.name.flattenToShortString().equals(
6118 "com.android.providers.calendar/.CalendarProvider2")) {
6119 Slog.v(TAG, "****************** KILLING "
6120 + cpr.name.flattenToShortString());
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006121 Process.killProcess(cpr.proc.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006122 }
6123 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006124 boolean success = updateOomAdjLocked(cpr.proc);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006125 if (DEBUG_PROVIDER) Slog.i(TAG, "Adjust success: " + success);
6126 // NOTE: there is still a race here where a signal could be
6127 // pending on the process even though we managed to update its
6128 // adj level. Not sure what to do about this, but at least
6129 // the race is now smaller.
6130 if (!success) {
6131 // Uh oh... it looks like the provider's process
6132 // has been killed on us. We need to wait for a new
6133 // process to be started, and make sure its death
6134 // doesn't kill our process.
6135 Slog.i(TAG,
6136 "Existing provider " + cpr.name.flattenToShortString()
6137 + " is crashing; detaching " + r);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006138 boolean lastRef = decProviderCount(r, cpr, token);
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006139 appDiedLocked(cpr.proc, cpr.proc.pid, cpr.proc.thread);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006140 if (!lastRef) {
6141 // This wasn't the last ref our process had on
6142 // the provider... we have now been killed, bail.
6143 return null;
6144 }
6145 providerRunning = false;
6146 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006147 }
6148
6149 Binder.restoreCallingIdentity(origId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006150 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006151
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006152 if (!providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006153 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006154 cpi = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07006155 resolveContentProvider(name,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006156 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006157 } catch (RemoteException ex) {
6158 }
6159 if (cpi == null) {
6160 return null;
6161 }
6162
Amith Yamasani483f3b02012-03-13 16:08:00 -07006163 cpi.applicationInfo = getAppInfoForUser(cpi.applicationInfo, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07006164
Dianne Hackbornb424b632010-08-18 15:59:05 -07006165 String msg;
6166 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6167 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006168 }
6169
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07006170 if (!mProcessesReady && !mDidUpdate && !mWaitingUpdate
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006171 && !cpi.processName.equals("system")) {
6172 // If this content provider does not run in the system
6173 // process, and the system is not yet ready to run other
6174 // processes, then fail fast instead of hanging.
6175 throw new IllegalArgumentException(
6176 "Attempt to launch content provider before system ready");
6177 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006178
6179 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani483f3b02012-03-13 16:08:00 -07006180 cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006181 final boolean firstClass = cpr == null;
6182 if (firstClass) {
6183 try {
6184 ApplicationInfo ai =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006185 AppGlobals.getPackageManager().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006186 getApplicationInfo(
6187 cpi.applicationInfo.packageName,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006188 STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006189 if (ai == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006190 Slog.w(TAG, "No package info for content provider "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006191 + cpi.name);
6192 return null;
6193 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006194 ai = getAppInfoForUser(ai, userId);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006195 cpr = new ContentProviderRecord(this, cpi, ai, comp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006196 } catch (RemoteException ex) {
6197 // pm is in same process, this will never happen.
6198 }
6199 }
6200
6201 if (r != null && cpr.canRunHere(r)) {
6202 // If this is a multiprocess provider, then just return its
6203 // info and allow the caller to instantiate it. Only do
6204 // this if the provider is the same user as the caller's
6205 // process, or can run as root (so can be in any process).
6206 return cpr;
6207 }
6208
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006209 if (DEBUG_PROVIDER) {
6210 RuntimeException e = new RuntimeException("here");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006211 Slog.w(TAG, "LAUNCHING REMOTE PROVIDER (myuid " + r.uid
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006212 + " pruid " + cpr.appInfo.uid + "): " + cpr.info.name, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006213 }
6214
6215 // This is single process, and our app is now connecting to it.
6216 // See if we are already in the process of launching this
6217 // provider.
6218 final int N = mLaunchingProviders.size();
6219 int i;
6220 for (i=0; i<N; i++) {
6221 if (mLaunchingProviders.get(i) == cpr) {
6222 break;
6223 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006224 }
6225
6226 // If the provider is not already being launched, then get it
6227 // started.
6228 if (i >= N) {
6229 final long origId = Binder.clearCallingIdentity();
Dianne Hackborne7f97212011-02-24 14:40:20 -08006230
6231 try {
6232 // Content provider is now in use, its package can't be stopped.
6233 try {
6234 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07006235 cpr.appInfo.packageName, false, userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006236 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006237 } catch (IllegalArgumentException e) {
6238 Slog.w(TAG, "Failed trying to unstop package "
6239 + cpr.appInfo.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006240 }
6241
6242 ProcessRecord proc = startProcessLocked(cpi.processName,
6243 cpr.appInfo, false, 0, "content provider",
6244 new ComponentName(cpi.applicationInfo.packageName,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006245 cpi.name), false, false);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006246 if (proc == null) {
6247 Slog.w(TAG, "Unable to launch app "
6248 + cpi.applicationInfo.packageName + "/"
6249 + cpi.applicationInfo.uid + " for provider "
6250 + name + ": process is bad");
6251 return null;
6252 }
6253 cpr.launchingApp = proc;
6254 mLaunchingProviders.add(cpr);
6255 } finally {
6256 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006257 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006258 }
6259
6260 // Make sure the provider is published (the same provider class
6261 // may be published under multiple names).
6262 if (firstClass) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006263 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006264 }
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006265
Amith Yamasani742a6712011-05-04 14:49:28 -07006266 mProviderMap.putProviderByName(name, cpr);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006267 incProviderCount(r, cpr, token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006268 }
6269 }
6270
6271 // Wait for the provider to be published...
6272 synchronized (cpr) {
6273 while (cpr.provider == null) {
6274 if (cpr.launchingApp == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006275 Slog.w(TAG, "Unable to launch app "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006276 + cpi.applicationInfo.packageName + "/"
6277 + cpi.applicationInfo.uid + " for provider "
6278 + name + ": launching app became null");
Doug Zongker2bec3d42009-12-04 12:52:44 -08006279 EventLog.writeEvent(EventLogTags.AM_PROVIDER_LOST_PROCESS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006280 cpi.applicationInfo.packageName,
6281 cpi.applicationInfo.uid, name);
6282 return null;
6283 }
6284 try {
Amith Yamasani742a6712011-05-04 14:49:28 -07006285 if (DEBUG_MU) {
6286 Slog.v(TAG_MU, "Waiting to start provider " + cpr + " launchingApp="
6287 + cpr.launchingApp);
6288 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006289 cpr.wait();
6290 } catch (InterruptedException ex) {
6291 }
6292 }
6293 }
6294 return cpr;
6295 }
6296
6297 public final ContentProviderHolder getContentProvider(
6298 IApplicationThread caller, String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006299 enforceNotIsolatedCaller("getContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006300 if (caller == null) {
6301 String msg = "null IApplicationThread when getting content provider "
6302 + name;
Joe Onorato8a9b2202010-02-26 18:56:32 -08006303 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006304 throw new SecurityException(msg);
6305 }
6306
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006307 return getContentProviderImpl(caller, name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006308 }
6309
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006310 public ContentProviderHolder getContentProviderExternal(String name, IBinder token) {
6311 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6312 "Do not have permission in call getContentProviderExternal()");
6313 return getContentProviderExternalUnchecked(name, token);
6314 }
6315
6316 private ContentProviderHolder getContentProviderExternalUnchecked(String name,IBinder token) {
6317 return getContentProviderImpl(null, name, token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006318 }
6319
6320 /**
6321 * Drop a content provider from a ProcessRecord's bookkeeping
6322 * @param cpr
6323 */
6324 public void removeContentProvider(IApplicationThread caller, String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006325 enforceNotIsolatedCaller("removeContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006326 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006327 int userId = UserId.getUserId(Binder.getCallingUid());
6328 ContentProviderRecord cpr = mProviderMap.getProviderByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006329 if(cpr == null) {
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006330 // remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006331 if (DEBUG_PROVIDER) Slog.v(TAG, name +
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006332 " provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006333 return;
6334 }
6335 final ProcessRecord r = getRecordForAppLocked(caller);
6336 if (r == null) {
6337 throw new SecurityException(
6338 "Unable to find app for caller " + caller +
6339 " when removing content provider " + name);
6340 }
6341 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006342 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006343 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp, userId);
6344 if (DEBUG_PROVIDER) Slog.v(TAG, "Removing provider requested by "
6345 + r.info.processName + " from process "
6346 + localCpr.appInfo.processName);
6347 if (localCpr.launchingApp == r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006348 //should not happen. taken care of as a local provider
Joe Onorato8a9b2202010-02-26 18:56:32 -08006349 Slog.w(TAG, "removeContentProvider called on local provider: "
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006350 + cpr.info.name + " in process " + r.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006351 return;
6352 } else {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006353 if (decProviderCount(r, localCpr, null)) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006354 updateOomAdjLocked();
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07006355 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006356 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006357 }
6358 }
6359
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006360 public void removeContentProviderExternal(String name, IBinder token) {
6361 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6362 "Do not have permission in call removeContentProviderExternal()");
6363 removeContentProviderExternalUnchecked(name, token);
6364 }
6365
6366 private void removeContentProviderExternalUnchecked(String name, IBinder token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006367 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006368 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
6369 Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006370 if(cpr == null) {
6371 //remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006372 if(localLOGV) Slog.v(TAG, name+" content provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006373 return;
6374 }
6375
6376 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006377 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006378 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp,
6379 Binder.getOrigCallingUser());
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006380 if (localCpr.hasExternalProcessHandles()) {
6381 if (localCpr.removeExternalProcessHandleLocked(token)) {
6382 updateOomAdjLocked();
6383 } else {
6384 Slog.e(TAG, "Attmpt to remove content provider " + localCpr
6385 + " with no external reference for token: "
6386 + token + ".");
6387 }
6388 } else {
6389 Slog.e(TAG, "Attmpt to remove content provider: " + localCpr
6390 + " with no external references.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006391 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006392 }
6393 }
6394
6395 public final void publishContentProviders(IApplicationThread caller,
6396 List<ContentProviderHolder> providers) {
6397 if (providers == null) {
6398 return;
6399 }
6400
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006401 enforceNotIsolatedCaller("publishContentProviders");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006402 synchronized(this) {
6403 final ProcessRecord r = getRecordForAppLocked(caller);
Amith Yamasani742a6712011-05-04 14:49:28 -07006404 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006405 Slog.v(TAG_MU, "ProcessRecord uid = " + r.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006406 if (r == null) {
6407 throw new SecurityException(
6408 "Unable to find app for caller " + caller
6409 + " (pid=" + Binder.getCallingPid()
6410 + ") when publishing content providers");
6411 }
6412
6413 final long origId = Binder.clearCallingIdentity();
6414
6415 final int N = providers.size();
6416 for (int i=0; i<N; i++) {
6417 ContentProviderHolder src = providers.get(i);
6418 if (src == null || src.info == null || src.provider == null) {
6419 continue;
6420 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07006421 ContentProviderRecord dst = r.pubProviders.get(src.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006422 if (DEBUG_MU)
6423 Slog.v(TAG_MU, "ContentProviderRecord uid = " + dst.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006424 if (dst != null) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006425 ComponentName comp = new ComponentName(dst.info.packageName, dst.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006426 mProviderMap.putProviderByClass(comp, dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006427 String names[] = dst.info.authority.split(";");
6428 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006429 mProviderMap.putProviderByName(names[j], dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006430 }
6431
6432 int NL = mLaunchingProviders.size();
6433 int j;
6434 for (j=0; j<NL; j++) {
6435 if (mLaunchingProviders.get(j) == dst) {
6436 mLaunchingProviders.remove(j);
6437 j--;
6438 NL--;
6439 }
6440 }
6441 synchronized (dst) {
6442 dst.provider = src.provider;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006443 dst.proc = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006444 dst.notifyAll();
6445 }
6446 updateOomAdjLocked(r);
6447 }
6448 }
6449
6450 Binder.restoreCallingIdentity(origId);
6451 }
6452 }
6453
6454 public static final void installSystemProviders() {
Jeff Brown10e89712011-07-08 18:52:57 -07006455 List<ProviderInfo> providers;
Josh Bartel2ecce342010-02-25 10:55:48 -06006456 synchronized (mSelf) {
6457 ProcessRecord app = mSelf.mProcessNames.get("system", Process.SYSTEM_UID);
6458 providers = mSelf.generateApplicationProvidersLocked(app);
Dianne Hackborn5c83a5f2010-03-12 16:46:46 -08006459 if (providers != null) {
6460 for (int i=providers.size()-1; i>=0; i--) {
6461 ProviderInfo pi = (ProviderInfo)providers.get(i);
6462 if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6463 Slog.w(TAG, "Not installing system proc provider " + pi.name
6464 + ": not system .apk");
6465 providers.remove(i);
6466 }
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006467 }
6468 }
6469 }
Josh Bartel2ecce342010-02-25 10:55:48 -06006470 if (providers != null) {
6471 mSystemThread.installSystemProviders(providers);
6472 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08006473
6474 mSelf.mCoreSettingsObserver = new CoreSettingsObserver(mSelf);
Mark Brophyc6350272011-08-05 16:16:39 +01006475
6476 mSelf.mUsageStatsService.monitorPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006477 }
6478
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006479 /**
6480 * Allows app to retrieve the MIME type of a URI without having permission
6481 * to access its content provider.
6482 *
6483 * CTS tests for this functionality can be run with "runtest cts-appsecurity".
6484 *
6485 * Test cases are at cts/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/
6486 * src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java
6487 */
6488 public String getProviderMimeType(Uri uri) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006489 enforceNotIsolatedCaller("getProviderMimeType");
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006490 final String name = uri.getAuthority();
6491 final long ident = Binder.clearCallingIdentity();
6492 ContentProviderHolder holder = null;
6493
6494 try {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006495 holder = getContentProviderExternalUnchecked(name, null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006496 if (holder != null) {
6497 return holder.provider.getType(uri);
6498 }
6499 } catch (RemoteException e) {
6500 Log.w(TAG, "Content provider dead retrieving " + uri, e);
6501 return null;
6502 } finally {
6503 if (holder != null) {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006504 removeContentProviderExternalUnchecked(name, null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006505 }
6506 Binder.restoreCallingIdentity(ident);
6507 }
6508
6509 return null;
6510 }
6511
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006512 // =========================================================
6513 // GLOBAL MANAGEMENT
6514 // =========================================================
6515
6516 final ProcessRecord newProcessRecordLocked(IApplicationThread thread,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006517 ApplicationInfo info, String customProcess, boolean isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006518 String proc = customProcess != null ? customProcess : info.processName;
6519 BatteryStatsImpl.Uid.Proc ps = null;
6520 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006521 int uid = info.uid;
6522 if (isolated) {
6523 int userId = UserId.getUserId(uid);
6524 int stepsLeft = Process.LAST_ISOLATED_UID - Process.FIRST_ISOLATED_UID + 1;
6525 uid = 0;
6526 while (true) {
6527 if (mNextIsolatedProcessUid < Process.FIRST_ISOLATED_UID
6528 || mNextIsolatedProcessUid > Process.LAST_ISOLATED_UID) {
6529 mNextIsolatedProcessUid = Process.FIRST_ISOLATED_UID;
6530 }
6531 uid = UserId.getUid(userId, mNextIsolatedProcessUid);
6532 mNextIsolatedProcessUid++;
6533 if (mIsolatedProcesses.indexOfKey(uid) < 0) {
6534 // No process for this uid, use it.
6535 break;
6536 }
6537 stepsLeft--;
6538 if (stepsLeft <= 0) {
6539 return null;
6540 }
6541 }
6542 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006543 synchronized (stats) {
6544 ps = stats.getProcessStatsLocked(info.uid, proc);
6545 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006546 return new ProcessRecord(ps, thread, info, proc, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006547 }
6548
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006549 final ProcessRecord addAppLocked(ApplicationInfo info, boolean isolated) {
6550 ProcessRecord app;
6551 if (!isolated) {
6552 app = getProcessRecordLocked(info.processName, info.uid);
6553 } else {
6554 app = null;
6555 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006556
6557 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006558 app = newProcessRecordLocked(null, info, null, isolated);
6559 mProcessNames.put(info.processName, app.uid, app);
6560 if (isolated) {
6561 mIsolatedProcesses.put(app.uid, app);
6562 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08006563 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006564 }
6565
Dianne Hackborne7f97212011-02-24 14:40:20 -08006566 // This package really, really can not be stopped.
6567 try {
6568 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07006569 info.packageName, false, UserId.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -08006570 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006571 } catch (IllegalArgumentException e) {
6572 Slog.w(TAG, "Failed trying to unstop package "
6573 + info.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006574 }
6575
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006576 if ((info.flags&(ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT))
6577 == (ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT)) {
6578 app.persistent = true;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07006579 app.maxAdj = ProcessList.PERSISTENT_PROC_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006580 }
6581 if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) {
6582 mPersistentStartingProcesses.add(app);
6583 startProcessLocked(app, "added application", app.processName);
6584 }
6585
6586 return app;
6587 }
6588
6589 public void unhandledBack() {
6590 enforceCallingPermission(android.Manifest.permission.FORCE_BACK,
6591 "unhandledBack()");
6592
6593 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006594 int count = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08006595 if (DEBUG_SWITCH) Slog.d(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006596 TAG, "Performing unhandledBack(): stack size = " + count);
6597 if (count > 1) {
6598 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006599 mMainStack.finishActivityLocked((ActivityRecord)mMainStack.mHistory.get(count-1),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006600 count-1, Activity.RESULT_CANCELED, null, "unhandled-back");
6601 Binder.restoreCallingIdentity(origId);
6602 }
6603 }
6604 }
6605
6606 public ParcelFileDescriptor openContentUri(Uri uri) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006607 enforceNotIsolatedCaller("openContentUri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006608 String name = uri.getAuthority();
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006609 ContentProviderHolder cph = getContentProviderExternalUnchecked(name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006610 ParcelFileDescriptor pfd = null;
6611 if (cph != null) {
6612 // We record the binder invoker's uid in thread-local storage before
6613 // going to the content provider to open the file. Later, in the code
6614 // that handles all permissions checks, we look for this uid and use
6615 // that rather than the Activity Manager's own uid. The effect is that
6616 // we do the check against the caller's permissions even though it looks
6617 // to the content provider like the Activity Manager itself is making
6618 // the request.
6619 sCallerIdentity.set(new Identity(
6620 Binder.getCallingPid(), Binder.getCallingUid()));
6621 try {
6622 pfd = cph.provider.openFile(uri, "r");
6623 } catch (FileNotFoundException e) {
6624 // do nothing; pfd will be returned null
6625 } finally {
6626 // Ensure that whatever happens, we clean up the identity state
6627 sCallerIdentity.remove();
6628 }
6629
6630 // We've got the fd now, so we're done with the provider.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006631 removeContentProviderExternalUnchecked(name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006632 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006633 Slog.d(TAG, "Failed to get provider for authority '" + name + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006634 }
6635 return pfd;
6636 }
6637
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006638 // Actually is sleeping or shutting down or whatever else in the future
6639 // is an inactive state.
6640 public boolean isSleeping() {
6641 return mSleeping || mShuttingDown;
6642 }
6643
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006644 public void goingToSleep() {
6645 synchronized(this) {
6646 mSleeping = true;
6647 mWindowManager.setEventDispatching(false);
6648
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006649 mMainStack.stopIfSleepingLocked();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006650
6651 // Initialize the wake times of all processes.
Dianne Hackborn287952c2010-09-22 22:34:31 -07006652 checkExcessivePowerUsageLocked(false);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006653 mHandler.removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
6654 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07006655 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006656 }
6657 }
6658
Dianne Hackborn55280a92009-05-07 15:53:46 -07006659 public boolean shutdown(int timeout) {
6660 if (checkCallingPermission(android.Manifest.permission.SHUTDOWN)
6661 != PackageManager.PERMISSION_GRANTED) {
6662 throw new SecurityException("Requires permission "
6663 + android.Manifest.permission.SHUTDOWN);
6664 }
6665
6666 boolean timedout = false;
6667
6668 synchronized(this) {
6669 mShuttingDown = true;
6670 mWindowManager.setEventDispatching(false);
6671
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006672 if (mMainStack.mResumedActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006673 mMainStack.stopIfSleepingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07006674 final long endTime = System.currentTimeMillis() + timeout;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006675 while (mMainStack.mResumedActivity != null
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08006676 || mMainStack.mPausingActivity != null) {
Dianne Hackborn55280a92009-05-07 15:53:46 -07006677 long delay = endTime - System.currentTimeMillis();
6678 if (delay <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006679 Slog.w(TAG, "Activity manager shutdown timed out");
Dianne Hackborn55280a92009-05-07 15:53:46 -07006680 timedout = true;
6681 break;
6682 }
6683 try {
6684 this.wait();
6685 } catch (InterruptedException e) {
6686 }
6687 }
6688 }
6689 }
6690
6691 mUsageStatsService.shutdown();
6692 mBatteryStatsService.shutdown();
6693
6694 return timedout;
6695 }
6696
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006697 public final void activitySlept(IBinder token) {
6698 if (localLOGV) Slog.v(
6699 TAG, "Activity slept: token=" + token);
6700
6701 ActivityRecord r = null;
6702
6703 final long origId = Binder.clearCallingIdentity();
6704
6705 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006706 r = mMainStack.isInStackLocked(token);
6707 if (r != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006708 mMainStack.activitySleptLocked(r);
6709 }
6710 }
6711
6712 Binder.restoreCallingIdentity(origId);
6713 }
6714
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006715 public void wakingUp() {
6716 synchronized(this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006717 mWindowManager.setEventDispatching(true);
6718 mSleeping = false;
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006719 mMainStack.awakeFromSleepingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006720 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006721 }
6722 }
6723
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006724 public void stopAppSwitches() {
6725 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
6726 != PackageManager.PERMISSION_GRANTED) {
6727 throw new SecurityException("Requires permission "
6728 + android.Manifest.permission.STOP_APP_SWITCHES);
6729 }
6730
6731 synchronized(this) {
6732 mAppSwitchesAllowedTime = SystemClock.uptimeMillis()
6733 + APP_SWITCH_DELAY_TIME;
6734 mDidAppSwitch = false;
6735 mHandler.removeMessages(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
6736 Message msg = mHandler.obtainMessage(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
6737 mHandler.sendMessageDelayed(msg, APP_SWITCH_DELAY_TIME);
6738 }
6739 }
6740
6741 public void resumeAppSwitches() {
6742 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
6743 != PackageManager.PERMISSION_GRANTED) {
6744 throw new SecurityException("Requires permission "
6745 + android.Manifest.permission.STOP_APP_SWITCHES);
6746 }
6747
6748 synchronized(this) {
6749 // Note that we don't execute any pending app switches... we will
6750 // let those wait until either the timeout, or the next start
6751 // activity request.
6752 mAppSwitchesAllowedTime = 0;
6753 }
6754 }
6755
6756 boolean checkAppSwitchAllowedLocked(int callingPid, int callingUid,
6757 String name) {
6758 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
6759 return true;
6760 }
6761
6762 final int perm = checkComponentPermission(
6763 android.Manifest.permission.STOP_APP_SWITCHES, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006764 callingUid, -1, true);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006765 if (perm == PackageManager.PERMISSION_GRANTED) {
6766 return true;
6767 }
6768
Joe Onorato8a9b2202010-02-26 18:56:32 -08006769 Slog.w(TAG, name + " request from " + callingUid + " stopped");
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006770 return false;
6771 }
6772
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006773 public void setDebugApp(String packageName, boolean waitForDebugger,
6774 boolean persistent) {
6775 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
6776 "setDebugApp()");
6777
6778 // Note that this is not really thread safe if there are multiple
6779 // callers into it at the same time, but that's not a situation we
6780 // care about.
6781 if (persistent) {
6782 final ContentResolver resolver = mContext.getContentResolver();
6783 Settings.System.putString(
6784 resolver, Settings.System.DEBUG_APP,
6785 packageName);
6786 Settings.System.putInt(
6787 resolver, Settings.System.WAIT_FOR_DEBUGGER,
6788 waitForDebugger ? 1 : 0);
6789 }
6790
6791 synchronized (this) {
6792 if (!persistent) {
6793 mOrigDebugApp = mDebugApp;
6794 mOrigWaitForDebugger = mWaitForDebugger;
6795 }
6796 mDebugApp = packageName;
6797 mWaitForDebugger = waitForDebugger;
6798 mDebugTransient = !persistent;
6799 if (packageName != null) {
6800 final long origId = Binder.clearCallingIdentity();
Amith Yamasani483f3b02012-03-13 16:08:00 -07006801 forceStopPackageLocked(packageName, -1, false, false, true, true, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006802 Binder.restoreCallingIdentity(origId);
6803 }
6804 }
6805 }
6806
Siva Velusamy92a8b222012-03-09 16:24:04 -08006807 void setOpenGlTraceApp(ApplicationInfo app, String processName) {
6808 synchronized (this) {
6809 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
6810 if (!isDebuggable) {
6811 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
6812 throw new SecurityException("Process not debuggable: " + app.packageName);
6813 }
6814 }
6815
6816 mOpenGlTraceApp = processName;
6817 }
6818 }
6819
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07006820 void setProfileApp(ApplicationInfo app, String processName, String profileFile,
6821 ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
6822 synchronized (this) {
6823 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
6824 if (!isDebuggable) {
6825 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
6826 throw new SecurityException("Process not debuggable: " + app.packageName);
6827 }
6828 }
6829 mProfileApp = processName;
6830 mProfileFile = profileFile;
6831 if (mProfileFd != null) {
6832 try {
6833 mProfileFd.close();
6834 } catch (IOException e) {
6835 }
6836 mProfileFd = null;
6837 }
6838 mProfileFd = profileFd;
6839 mProfileType = 0;
6840 mAutoStopProfiler = autoStopProfiler;
6841 }
6842 }
6843
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006844 public void setAlwaysFinish(boolean enabled) {
6845 enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH,
6846 "setAlwaysFinish()");
6847
6848 Settings.System.putInt(
6849 mContext.getContentResolver(),
6850 Settings.System.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0);
6851
6852 synchronized (this) {
6853 mAlwaysFinishActivities = enabled;
6854 }
6855 }
6856
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006857 public void setActivityController(IActivityController controller) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006858 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006859 "setActivityController()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006860 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006861 mController = controller;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006862 }
6863 }
6864
Dianne Hackborn9327f4f2010-01-29 10:38:29 -08006865 public boolean isUserAMonkey() {
6866 // For now the fact that there is a controller implies
6867 // we have a monkey.
6868 synchronized (this) {
6869 return mController != null;
6870 }
6871 }
6872
Jeff Sharkeya4620792011-05-20 15:29:23 -07006873 public void registerProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08006874 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
6875 "registerProcessObserver()");
6876 synchronized (this) {
6877 mProcessObservers.register(observer);
6878 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07006879 }
6880
6881 public void unregisterProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08006882 synchronized (this) {
6883 mProcessObservers.unregister(observer);
6884 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07006885 }
6886
Daniel Sandler69a48172010-06-23 16:29:36 -04006887 public void setImmersive(IBinder token, boolean immersive) {
6888 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006889 ActivityRecord r = mMainStack.isInStackLocked(token);
6890 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04006891 throw new IllegalArgumentException();
6892 }
Daniel Sandler69a48172010-06-23 16:29:36 -04006893 r.immersive = immersive;
6894 }
6895 }
6896
6897 public boolean isImmersive(IBinder token) {
6898 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006899 ActivityRecord r = mMainStack.isInStackLocked(token);
6900 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04006901 throw new IllegalArgumentException();
6902 }
Daniel Sandler69a48172010-06-23 16:29:36 -04006903 return r.immersive;
6904 }
6905 }
6906
6907 public boolean isTopActivityImmersive() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006908 enforceNotIsolatedCaller("startActivity");
Daniel Sandler69a48172010-06-23 16:29:36 -04006909 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006910 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Daniel Sandler69a48172010-06-23 16:29:36 -04006911 return (r != null) ? r.immersive : false;
6912 }
6913 }
6914
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006915 public final void enterSafeMode() {
6916 synchronized(this) {
6917 // It only makes sense to do this before the system is ready
6918 // and started launching other packages.
6919 if (!mSystemReady) {
6920 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006921 AppGlobals.getPackageManager().enterSafeMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006922 } catch (RemoteException e) {
6923 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006924 }
6925 }
6926 }
6927
Jeff Brownb09abc12011-01-13 21:08:27 -08006928 public final void showSafeModeOverlay() {
6929 View v = LayoutInflater.from(mContext).inflate(
6930 com.android.internal.R.layout.safe_mode, null);
6931 WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
6932 lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
6933 lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
6934 lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
6935 lp.gravity = Gravity.BOTTOM | Gravity.LEFT;
6936 lp.format = v.getBackground().getOpacity();
6937 lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
6938 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
6939 ((WindowManager)mContext.getSystemService(
6940 Context.WINDOW_SERVICE)).addView(v, lp);
6941 }
6942
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006943 public void noteWakeupAlarm(IIntentSender sender) {
6944 if (!(sender instanceof PendingIntentRecord)) {
6945 return;
6946 }
6947 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
6948 synchronized (stats) {
6949 if (mBatteryStatsService.isOnBattery()) {
6950 mBatteryStatsService.enforceCallingPermission();
6951 PendingIntentRecord rec = (PendingIntentRecord)sender;
6952 int MY_UID = Binder.getCallingUid();
6953 int uid = rec.uid == MY_UID ? Process.SYSTEM_UID : rec.uid;
6954 BatteryStatsImpl.Uid.Pkg pkg =
6955 stats.getPackageStatsLocked(uid, rec.key.packageName);
6956 pkg.incWakeupsLocked();
6957 }
6958 }
6959 }
6960
Dianne Hackborn64825172011-03-02 21:32:58 -08006961 public boolean killPids(int[] pids, String pReason, boolean secure) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006962 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006963 throw new SecurityException("killPids only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006964 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006965 String reason = (pReason == null) ? "Unknown" : pReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006966 // XXX Note: don't acquire main activity lock here, because the window
6967 // manager calls in with its locks held.
6968
6969 boolean killed = false;
6970 synchronized (mPidsSelfLocked) {
6971 int[] types = new int[pids.length];
6972 int worstType = 0;
6973 for (int i=0; i<pids.length; i++) {
6974 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
6975 if (proc != null) {
6976 int type = proc.setAdj;
6977 types[i] = type;
6978 if (type > worstType) {
6979 worstType = type;
6980 }
6981 }
6982 }
6983
Dianne Hackborn64825172011-03-02 21:32:58 -08006984 // If the worst oom_adj is somewhere in the hidden proc LRU range,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006985 // then constrain it so we will kill all hidden procs.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07006986 if (worstType < ProcessList.HIDDEN_APP_MAX_ADJ
6987 && worstType > ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07006988 worstType = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006989 }
Dianne Hackborn64825172011-03-02 21:32:58 -08006990
6991 // If this is not a secure call, don't let it kill processes that
6992 // are important.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07006993 if (!secure && worstType < ProcessList.SERVICE_ADJ) {
6994 worstType = ProcessList.SERVICE_ADJ;
Dianne Hackborn64825172011-03-02 21:32:58 -08006995 }
6996
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006997 Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006998 for (int i=0; i<pids.length; i++) {
6999 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7000 if (proc == null) {
7001 continue;
7002 }
7003 int adj = proc.setAdj;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007004 if (adj >= worstType && !proc.killedBackground) {
Dianne Hackborn8633e682010-04-22 16:03:41 -07007005 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007006 EventLog.writeEvent(EventLogTags.AM_KILL, proc.pid,
7007 proc.processName, adj, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007008 killed = true;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007009 proc.killedBackground = true;
7010 Process.killProcessQuiet(pids[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007011 }
7012 }
7013 }
7014 return killed;
7015 }
Jeff Sharkeyb9a07012012-03-22 17:00:04 -07007016
7017 @Override
7018 public boolean killProcessesBelowForeground(String reason) {
7019 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7020 throw new SecurityException("killProcessesBelowForeground() only available to system");
7021 }
7022
7023 return killProcessesBelowAdj(ProcessList.FOREGROUND_APP_ADJ, reason);
7024 }
7025
7026 private boolean killProcessesBelowAdj(int belowAdj, String reason) {
7027 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7028 throw new SecurityException("killProcessesBelowAdj() only available to system");
7029 }
7030
7031 boolean killed = false;
7032 synchronized (mPidsSelfLocked) {
7033 final int size = mPidsSelfLocked.size();
7034 for (int i = 0; i < size; i++) {
7035 final int pid = mPidsSelfLocked.keyAt(i);
7036 final ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7037 if (proc == null) continue;
7038
7039 final int adj = proc.setAdj;
7040 if (adj > belowAdj && !proc.killedBackground) {
7041 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
7042 EventLog.writeEvent(
7043 EventLogTags.AM_KILL, proc.pid, proc.processName, adj, reason);
7044 killed = true;
7045 proc.killedBackground = true;
7046 Process.killProcessQuiet(pid);
7047 }
7048 }
7049 }
7050 return killed;
7051 }
7052
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007053 public final void startRunning(String pkg, String cls, String action,
7054 String data) {
7055 synchronized(this) {
7056 if (mStartRunning) {
7057 return;
7058 }
7059 mStartRunning = true;
7060 mTopComponent = pkg != null && cls != null
7061 ? new ComponentName(pkg, cls) : null;
7062 mTopAction = action != null ? action : Intent.ACTION_MAIN;
7063 mTopData = data;
7064 if (!mSystemReady) {
7065 return;
7066 }
7067 }
7068
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007069 systemReady(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007070 }
7071
7072 private void retrieveSettings() {
7073 final ContentResolver resolver = mContext.getContentResolver();
7074 String debugApp = Settings.System.getString(
7075 resolver, Settings.System.DEBUG_APP);
7076 boolean waitForDebugger = Settings.System.getInt(
7077 resolver, Settings.System.WAIT_FOR_DEBUGGER, 0) != 0;
7078 boolean alwaysFinishActivities = Settings.System.getInt(
7079 resolver, Settings.System.ALWAYS_FINISH_ACTIVITIES, 0) != 0;
7080
7081 Configuration configuration = new Configuration();
7082 Settings.System.getConfiguration(resolver, configuration);
7083
7084 synchronized (this) {
7085 mDebugApp = mOrigDebugApp = debugApp;
7086 mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger;
7087 mAlwaysFinishActivities = alwaysFinishActivities;
7088 // This happens before any activities are started, so we can
7089 // change mConfiguration in-place.
Dianne Hackborn813075a62011-11-14 17:45:19 -08007090 updateConfigurationLocked(configuration, null, false, true);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007091 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Initial config: " + mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007092 }
7093 }
7094
7095 public boolean testIsSystemReady() {
7096 // no need to synchronize(this) just to read & return the value
7097 return mSystemReady;
7098 }
7099
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007100 private static File getCalledPreBootReceiversFile() {
7101 File dataDir = Environment.getDataDirectory();
7102 File systemDir = new File(dataDir, "system");
7103 File fname = new File(systemDir, "called_pre_boots.dat");
7104 return fname;
7105 }
Dianne Hackborn661cd522011-08-22 00:26:20 -07007106
7107 static final int LAST_DONE_VERSION = 10000;
7108
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007109 private static ArrayList<ComponentName> readLastDonePreBootReceivers() {
7110 ArrayList<ComponentName> lastDoneReceivers = new ArrayList<ComponentName>();
7111 File file = getCalledPreBootReceiversFile();
7112 FileInputStream fis = null;
7113 try {
7114 fis = new FileInputStream(file);
7115 DataInputStream dis = new DataInputStream(new BufferedInputStream(fis, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007116 int fvers = dis.readInt();
7117 if (fvers == LAST_DONE_VERSION) {
7118 String vers = dis.readUTF();
7119 String codename = dis.readUTF();
7120 String build = dis.readUTF();
7121 if (android.os.Build.VERSION.RELEASE.equals(vers)
7122 && android.os.Build.VERSION.CODENAME.equals(codename)
7123 && android.os.Build.VERSION.INCREMENTAL.equals(build)) {
7124 int num = dis.readInt();
7125 while (num > 0) {
7126 num--;
7127 String pkg = dis.readUTF();
7128 String cls = dis.readUTF();
7129 lastDoneReceivers.add(new ComponentName(pkg, cls));
7130 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007131 }
7132 }
7133 } catch (FileNotFoundException e) {
7134 } catch (IOException e) {
7135 Slog.w(TAG, "Failure reading last done pre-boot receivers", e);
7136 } finally {
7137 if (fis != null) {
7138 try {
7139 fis.close();
7140 } catch (IOException e) {
7141 }
7142 }
7143 }
7144 return lastDoneReceivers;
7145 }
7146
7147 private static void writeLastDonePreBootReceivers(ArrayList<ComponentName> list) {
7148 File file = getCalledPreBootReceiversFile();
7149 FileOutputStream fos = null;
7150 DataOutputStream dos = null;
7151 try {
7152 Slog.i(TAG, "Writing new set of last done pre-boot receivers...");
7153 fos = new FileOutputStream(file);
7154 dos = new DataOutputStream(new BufferedOutputStream(fos, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007155 dos.writeInt(LAST_DONE_VERSION);
7156 dos.writeUTF(android.os.Build.VERSION.RELEASE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007157 dos.writeUTF(android.os.Build.VERSION.CODENAME);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007158 dos.writeUTF(android.os.Build.VERSION.INCREMENTAL);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007159 dos.writeInt(list.size());
7160 for (int i=0; i<list.size(); i++) {
7161 dos.writeUTF(list.get(i).getPackageName());
7162 dos.writeUTF(list.get(i).getClassName());
7163 }
7164 } catch (IOException e) {
7165 Slog.w(TAG, "Failure writing last done pre-boot receivers", e);
7166 file.delete();
7167 } finally {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07007168 FileUtils.sync(fos);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007169 if (dos != null) {
7170 try {
7171 dos.close();
7172 } catch (IOException e) {
7173 // TODO Auto-generated catch block
7174 e.printStackTrace();
7175 }
7176 }
7177 }
7178 }
7179
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007180 public void systemReady(final Runnable goingCallback) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007181 synchronized(this) {
7182 if (mSystemReady) {
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007183 if (goingCallback != null) goingCallback.run();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007184 return;
7185 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007186
7187 // Check to see if there are any update receivers to run.
7188 if (!mDidUpdate) {
7189 if (mWaitingUpdate) {
7190 return;
7191 }
7192 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
7193 List<ResolveInfo> ris = null;
7194 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007195 ris = AppGlobals.getPackageManager().queryIntentReceivers(
Amith Yamasani483f3b02012-03-13 16:08:00 -07007196 intent, null, 0, 0);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007197 } catch (RemoteException e) {
7198 }
7199 if (ris != null) {
7200 for (int i=ris.size()-1; i>=0; i--) {
7201 if ((ris.get(i).activityInfo.applicationInfo.flags
7202 &ApplicationInfo.FLAG_SYSTEM) == 0) {
7203 ris.remove(i);
7204 }
7205 }
7206 intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007207
7208 ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers();
7209
7210 final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007211 for (int i=0; i<ris.size(); i++) {
7212 ActivityInfo ai = ris.get(i).activityInfo;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007213 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7214 if (lastDoneReceivers.contains(comp)) {
7215 ris.remove(i);
7216 i--;
7217 }
7218 }
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07007219
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007220 for (int i=0; i<ris.size(); i++) {
7221 ActivityInfo ai = ris.get(i).activityInfo;
7222 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7223 doneReceivers.add(comp);
7224 intent.setComponent(comp);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007225 IIntentReceiver finisher = null;
Dianne Hackbornd6847842010-01-12 18:14:19 -08007226 if (i == ris.size()-1) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007227 finisher = new IIntentReceiver.Stub() {
7228 public void performReceive(Intent intent, int resultCode,
Dianne Hackborn68d881c2009-10-05 13:58:17 -07007229 String data, Bundle extras, boolean ordered,
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007230 boolean sticky) {
7231 // The raw IIntentReceiver interface is called
7232 // with the AM lock held, so redispatch to
7233 // execute our code without the lock.
7234 mHandler.post(new Runnable() {
7235 public void run() {
7236 synchronized (ActivityManagerService.this) {
7237 mDidUpdate = true;
7238 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007239 writeLastDonePreBootReceivers(doneReceivers);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007240 showBootMessage(mContext.getText(
7241 R.string.android_upgrading_complete),
7242 false);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007243 systemReady(goingCallback);
7244 }
7245 });
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007246 }
7247 };
7248 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08007249 Slog.i(TAG, "Sending system update to: " + intent.getComponent());
Amith Yamasani742a6712011-05-04 14:49:28 -07007250 /* TODO: Send this to all users */
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007251 broadcastIntentLocked(null, null, intent, null, finisher,
Amith Yamasani742a6712011-05-04 14:49:28 -07007252 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID,
Amith Yamasanic600e21f2012-02-14 16:08:07 -08007253 0 /* UserId zero */);
Dianne Hackbornd6847842010-01-12 18:14:19 -08007254 if (finisher != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007255 mWaitingUpdate = true;
7256 }
7257 }
7258 }
7259 if (mWaitingUpdate) {
7260 return;
7261 }
7262 mDidUpdate = true;
7263 }
7264
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007265 mSystemReady = true;
7266 if (!mStartRunning) {
7267 return;
7268 }
7269 }
7270
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007271 ArrayList<ProcessRecord> procsToKill = null;
7272 synchronized(mPidsSelfLocked) {
7273 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
7274 ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7275 if (!isAllowedWhileBooting(proc.info)){
7276 if (procsToKill == null) {
7277 procsToKill = new ArrayList<ProcessRecord>();
7278 }
7279 procsToKill.add(proc);
7280 }
7281 }
7282 }
7283
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007284 synchronized(this) {
7285 if (procsToKill != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007286 for (int i=procsToKill.size()-1; i>=0; i--) {
7287 ProcessRecord proc = procsToKill.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007288 Slog.i(TAG, "Removing system update proc: " + proc);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007289 removeProcessLocked(proc, true, false, "system update done");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007290 }
7291 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007292
7293 // Now that we have cleaned up any update processes, we
7294 // are ready to start launching real processes and know that
7295 // we won't trample on them any more.
7296 mProcessesReady = true;
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007297 }
7298
Joe Onorato8a9b2202010-02-26 18:56:32 -08007299 Slog.i(TAG, "System now ready");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007300 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007301 SystemClock.uptimeMillis());
7302
7303 synchronized(this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007304 // Make sure we have no pre-ready processes sitting around.
7305
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007306 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
7307 ResolveInfo ri = mContext.getPackageManager()
7308 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST),
Dianne Hackborn1655be42009-05-08 14:29:01 -07007309 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007310 CharSequence errorMsg = null;
7311 if (ri != null) {
7312 ActivityInfo ai = ri.activityInfo;
7313 ApplicationInfo app = ai.applicationInfo;
7314 if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7315 mTopAction = Intent.ACTION_FACTORY_TEST;
7316 mTopData = null;
7317 mTopComponent = new ComponentName(app.packageName,
7318 ai.name);
7319 } else {
7320 errorMsg = mContext.getResources().getText(
7321 com.android.internal.R.string.factorytest_not_system);
7322 }
7323 } else {
7324 errorMsg = mContext.getResources().getText(
7325 com.android.internal.R.string.factorytest_no_action);
7326 }
7327 if (errorMsg != null) {
7328 mTopAction = null;
7329 mTopData = null;
7330 mTopComponent = null;
7331 Message msg = Message.obtain();
7332 msg.what = SHOW_FACTORY_ERROR_MSG;
7333 msg.getData().putCharSequence("msg", errorMsg);
7334 mHandler.sendMessage(msg);
7335 }
7336 }
7337 }
7338
7339 retrieveSettings();
7340
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007341 if (goingCallback != null) goingCallback.run();
7342
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007343 synchronized (this) {
7344 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
7345 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007346 List apps = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07007347 getPersistentApplications(STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007348 if (apps != null) {
7349 int N = apps.size();
7350 int i;
7351 for (i=0; i<N; i++) {
7352 ApplicationInfo info
7353 = (ApplicationInfo)apps.get(i);
7354 if (info != null &&
7355 !info.packageName.equals("android")) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007356 addAppLocked(info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007357 }
7358 }
7359 }
7360 } catch (RemoteException ex) {
7361 // pm is in same process, this will never happen.
7362 }
7363 }
7364
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007365 // Start up initial activity.
7366 mBooting = true;
7367
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007368 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007369 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007370 Message msg = Message.obtain();
7371 msg.what = SHOW_UID_ERROR_MSG;
7372 mHandler.sendMessage(msg);
7373 }
7374 } catch (RemoteException e) {
7375 }
7376
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007377 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007378 }
7379 }
7380
Dan Egnorb7f03672009-12-09 16:22:32 -08007381 private boolean makeAppCrashingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007382 String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007383 app.crashing = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007384 app.crashingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007385 ActivityManager.ProcessErrorStateInfo.CRASHED, null, shortMsg, longMsg, stackTrace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007386 startAppProblemLocked(app);
7387 app.stopFreezingAllLocked();
7388 return handleAppCrashLocked(app);
7389 }
7390
Dan Egnorb7f03672009-12-09 16:22:32 -08007391 private void makeAppNotRespondingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007392 String activity, String shortMsg, String longMsg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007393 app.notResponding = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007394 app.notRespondingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007395 ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING,
7396 activity, shortMsg, longMsg, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007397 startAppProblemLocked(app);
7398 app.stopFreezingAllLocked();
7399 }
7400
7401 /**
7402 * Generate a process error record, suitable for attachment to a ProcessRecord.
7403 *
7404 * @param app The ProcessRecord in which the error occurred.
7405 * @param condition Crashing, Application Not Responding, etc. Values are defined in
7406 * ActivityManager.AppErrorStateInfo
Dan Egnor60d87622009-12-16 16:32:58 -08007407 * @param activity The activity associated with the crash, if known.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007408 * @param shortMsg Short message describing the crash.
7409 * @param longMsg Long message describing the crash.
Dan Egnorb7f03672009-12-09 16:22:32 -08007410 * @param stackTrace Full crash stack trace, may be null.
7411 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007412 * @return Returns a fully-formed AppErrorStateInfo record.
7413 */
7414 private ActivityManager.ProcessErrorStateInfo generateProcessError(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007415 int condition, String activity, String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007416 ActivityManager.ProcessErrorStateInfo report = new ActivityManager.ProcessErrorStateInfo();
Dan Egnorb7f03672009-12-09 16:22:32 -08007417
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007418 report.condition = condition;
7419 report.processName = app.processName;
7420 report.pid = app.pid;
7421 report.uid = app.info.uid;
Dan Egnor60d87622009-12-16 16:32:58 -08007422 report.tag = activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007423 report.shortMsg = shortMsg;
7424 report.longMsg = longMsg;
Dan Egnorb7f03672009-12-09 16:22:32 -08007425 report.stackTrace = stackTrace;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007426
7427 return report;
7428 }
7429
Dan Egnor42471dd2010-01-07 17:25:22 -08007430 void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007431 synchronized (this) {
7432 app.crashing = false;
7433 app.crashingReport = null;
7434 app.notResponding = false;
7435 app.notRespondingReport = null;
7436 if (app.anrDialog == fromDialog) {
7437 app.anrDialog = null;
7438 }
7439 if (app.waitDialog == fromDialog) {
7440 app.waitDialog = null;
7441 }
7442 if (app.pid > 0 && app.pid != MY_PID) {
Dan Egnor42471dd2010-01-07 17:25:22 -08007443 handleAppCrashLocked(app);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007444 Slog.i(ActivityManagerService.TAG, "Killing " + app + ": user's request");
Dianne Hackborn8633e682010-04-22 16:03:41 -07007445 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
7446 app.processName, app.setAdj, "user's request after error");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007447 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007448 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007449 }
7450 }
Dan Egnor42471dd2010-01-07 17:25:22 -08007451
Dan Egnorb7f03672009-12-09 16:22:32 -08007452 private boolean handleAppCrashLocked(ProcessRecord app) {
Mike Lockwood86548c42011-09-13 17:21:46 -04007453 if (mHeadless) {
7454 Log.e(TAG, "handleAppCrashLocked: " + app.processName);
7455 return false;
7456 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007457 long now = SystemClock.uptimeMillis();
7458
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007459 Long crashTime;
7460 if (!app.isolated) {
7461 crashTime = mProcessCrashTimes.get(app.info.processName, app.uid);
7462 } else {
7463 crashTime = null;
7464 }
Dianne Hackborn7d608422011-08-07 16:24:18 -07007465 if (crashTime != null && now < crashTime+ProcessList.MIN_CRASH_INTERVAL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007466 // This process loses!
Joe Onorato8a9b2202010-02-26 18:56:32 -08007467 Slog.w(TAG, "Process " + app.info.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007468 + " has crashed too many times: killing!");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007469 EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007470 app.info.processName, app.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007471 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
7472 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007473 if (r.app == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007474 Slog.w(TAG, " Force finishing activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007475 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007476 r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED, null, "crashed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007477 }
7478 }
7479 if (!app.persistent) {
7480 // We don't want to start this process again until the user
7481 // explicitly does so... but for persistent process, we really
7482 // need to keep it running. If a persistent process is actually
7483 // repeatedly crashing, then badness for everyone.
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007484 EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007485 app.info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007486 if (!app.isolated) {
7487 // XXX We don't have a way to mark isolated processes
7488 // as bad, since they don't have a peristent identity.
7489 mBadProcesses.put(app.info.processName, app.uid, now);
7490 mProcessCrashTimes.remove(app.info.processName, app.uid);
7491 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007492 app.bad = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007493 app.removed = true;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07007494 // Don't let services in this process be restarted and potentially
7495 // annoy the user repeatedly. Unless it is persistent, since those
7496 // processes run critical code.
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007497 removeProcessLocked(app, false, false, "crash");
Dianne Hackborncb44d962011-03-10 17:02:27 -08007498 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007499 return false;
7500 }
Dianne Hackborncb44d962011-03-10 17:02:27 -08007501 mMainStack.resumeTopActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007502 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007503 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Kevin Hester-Chowd87a9be2012-03-05 08:01:00 -08007504 if (r != null && r.app == app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007505 // If the top running activity is from this crashing
7506 // process, then terminate it to avoid getting in a loop.
7507 Slog.w(TAG, " Force finishing activity "
7508 + r.intent.getComponent().flattenToShortString());
Dianne Hackbornbe707852011-11-11 14:32:10 -08007509 int index = mMainStack.indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007510 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007511 Activity.RESULT_CANCELED, null, "crashed");
Dianne Hackborn070783f2010-12-29 16:46:28 -08007512 // Also terminate any activities below it that aren't yet
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007513 // stopped, to avoid a situation where one will get
7514 // re-start our crashing activity once it gets resumed again.
7515 index--;
7516 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007517 r = (ActivityRecord)mMainStack.mHistory.get(index);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007518 if (r.state == ActivityState.RESUMED
7519 || r.state == ActivityState.PAUSING
7520 || r.state == ActivityState.PAUSED) {
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08007521 if (!r.isHomeActivity || mHomeProcess != r.app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007522 Slog.w(TAG, " Force finishing activity "
7523 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007524 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007525 Activity.RESULT_CANCELED, null, "crashed");
7526 }
7527 }
7528 }
7529 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007530 }
7531
7532 // Bump up the crash count of any services currently running in the proc.
7533 if (app.services.size() != 0) {
7534 // Any services running in the application need to be placed
7535 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -07007536 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007537 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07007538 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007539 sr.crashCount++;
7540 }
7541 }
Mattias Larssona4fd0072010-06-22 22:37:03 +02007542
7543 // If the crashing process is what we consider to be the "home process" and it has been
7544 // replaced by a third-party app, clear the package preferred activities from packages
7545 // with a home activity running in the process to prevent a repeatedly crashing app
7546 // from blocking the user to manually clear the list.
7547 if (app == mHomeProcess && mHomeProcess.activities.size() > 0
7548 && (mHomeProcess.info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
7549 Iterator it = mHomeProcess.activities.iterator();
7550 while (it.hasNext()) {
Jean-Baptiste Queru5ea89f72010-07-30 09:30:31 -07007551 ActivityRecord r = (ActivityRecord)it.next();
Mattias Larssona4fd0072010-06-22 22:37:03 +02007552 if (r.isHomeActivity) {
7553 Log.i(TAG, "Clearing package preferred activities from " + r.packageName);
7554 try {
7555 ActivityThread.getPackageManager()
7556 .clearPackagePreferredActivities(r.packageName);
7557 } catch (RemoteException c) {
7558 // pm is in same process, this will never happen.
7559 }
7560 }
7561 }
7562 }
7563
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007564 if (!app.isolated) {
7565 // XXX Can't keep track of crash times for isolated processes,
7566 // because they don't have a perisistent identity.
7567 mProcessCrashTimes.put(app.info.processName, app.uid, now);
7568 }
7569
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007570 return true;
7571 }
7572
7573 void startAppProblemLocked(ProcessRecord app) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08007574 app.errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver(
7575 mContext, app.info.packageName, app.info.flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007576 skipCurrentReceiverLocked(app);
7577 }
7578
7579 void skipCurrentReceiverLocked(ProcessRecord app) {
Christopher Tatef46723b2012-01-26 14:19:24 -08007580 for (BroadcastQueue queue : mBroadcastQueues) {
7581 queue.skipCurrentReceiverLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007582 }
7583 }
7584
Dan Egnor60d87622009-12-16 16:32:58 -08007585 /**
7586 * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes.
7587 * The application process will exit immediately after this call returns.
7588 * @param app object of the crashing app, null for the system server
7589 * @param crashInfo describing the exception
7590 */
7591 public void handleApplicationCrash(IBinder app, ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007592 ProcessRecord r = findAppProcess(app, "Crash");
Jeff Sharkeya353d262011-10-28 11:12:06 -07007593 final String processName = app == null ? "system_server"
7594 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08007595
7596 EventLog.writeEvent(EventLogTags.AM_CRASH, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07007597 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08007598 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08007599 crashInfo.exceptionClassName,
7600 crashInfo.exceptionMessage,
7601 crashInfo.throwFileName,
7602 crashInfo.throwLineNumber);
7603
Jeff Sharkeya353d262011-10-28 11:12:06 -07007604 addErrorToDropBox("crash", r, processName, null, null, null, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08007605
7606 crashApplication(r, crashInfo);
7607 }
7608
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007609 public void handleApplicationStrictModeViolation(
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007610 IBinder app,
7611 int violationMask,
7612 StrictMode.ViolationInfo info) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007613 ProcessRecord r = findAppProcess(app, "StrictMode");
7614 if (r == null) {
7615 return;
7616 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007617
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007618 if ((violationMask & StrictMode.PENALTY_DROPBOX) != 0) {
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08007619 Integer stackFingerprint = info.hashCode();
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007620 boolean logIt = true;
7621 synchronized (mAlreadyLoggedViolatedStacks) {
7622 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) {
7623 logIt = false;
7624 // TODO: sub-sample into EventLog for these, with
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007625 // the info.durationMillis? Then we'd get
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007626 // the relative pain numbers, without logging all
7627 // the stack traces repeatedly. We'd want to do
7628 // likewise in the client code, which also does
7629 // dup suppression, before the Binder call.
7630 } else {
7631 if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) {
7632 mAlreadyLoggedViolatedStacks.clear();
7633 }
7634 mAlreadyLoggedViolatedStacks.add(stackFingerprint);
7635 }
7636 }
7637 if (logIt) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007638 logStrictModeViolationToDropBox(r, info);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007639 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007640 }
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007641
7642 if ((violationMask & StrictMode.PENALTY_DIALOG) != 0) {
7643 AppErrorResult result = new AppErrorResult();
7644 synchronized (this) {
7645 final long origId = Binder.clearCallingIdentity();
7646
7647 Message msg = Message.obtain();
7648 msg.what = SHOW_STRICT_MODE_VIOLATION_MSG;
7649 HashMap<String, Object> data = new HashMap<String, Object>();
7650 data.put("result", result);
7651 data.put("app", r);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007652 data.put("violationMask", violationMask);
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007653 data.put("info", info);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007654 msg.obj = data;
7655 mHandler.sendMessage(msg);
7656
7657 Binder.restoreCallingIdentity(origId);
7658 }
7659 int res = result.get();
Dianne Hackbornb424b632010-08-18 15:59:05 -07007660 Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007661 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007662 }
7663
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007664 // Depending on the policy in effect, there could be a bunch of
7665 // these in quick succession so we try to batch these together to
7666 // minimize disk writes, number of dropbox entries, and maximize
7667 // compression, by having more fewer, larger records.
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007668 private void logStrictModeViolationToDropBox(
7669 ProcessRecord process,
7670 StrictMode.ViolationInfo info) {
7671 if (info == null) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007672 return;
7673 }
7674 final boolean isSystemApp = process == null ||
7675 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM |
7676 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07007677 final String processName = process == null ? "unknown" : process.processName;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007678 final String dropboxTag = isSystemApp ? "system_app_strictmode" : "data_app_strictmode";
7679 final DropBoxManager dbox = (DropBoxManager)
7680 mContext.getSystemService(Context.DROPBOX_SERVICE);
7681
7682 // Exit early if the dropbox isn't configured to accept this report type.
7683 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
7684
7685 boolean bufferWasEmpty;
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007686 boolean needsFlush;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007687 final StringBuilder sb = isSystemApp ? mStrictModeBuffer : new StringBuilder(1024);
7688 synchronized (sb) {
7689 bufferWasEmpty = sb.length() == 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07007690 appendDropBoxProcessHeaders(process, processName, sb);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007691 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
7692 sb.append("System-App: ").append(isSystemApp).append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007693 sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n");
7694 if (info.violationNumThisLoop != 0) {
7695 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n");
7696 }
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07007697 if (info.numAnimationsRunning != 0) {
7698 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n");
7699 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07007700 if (info.broadcastIntentAction != null) {
7701 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n");
7702 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08007703 if (info.durationMillis != -1) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007704 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n");
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007705 }
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08007706 if (info.numInstances != -1) {
7707 sb.append("Instance-Count: ").append(info.numInstances).append("\n");
7708 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08007709 if (info.tags != null) {
7710 for (String tag : info.tags) {
7711 sb.append("Span-Tag: ").append(tag).append("\n");
7712 }
7713 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007714 sb.append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007715 if (info.crashInfo != null && info.crashInfo.stackTrace != null) {
7716 sb.append(info.crashInfo.stackTrace);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007717 }
7718 sb.append("\n");
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007719
7720 // Only buffer up to ~64k. Various logging bits truncate
7721 // things at 128k.
7722 needsFlush = (sb.length() > 64 * 1024);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007723 }
7724
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007725 // Flush immediately if the buffer's grown too large, or this
7726 // is a non-system app. Non-system apps are isolated with a
7727 // different tag & policy and not batched.
7728 //
7729 // Batching is useful during internal testing with
7730 // StrictMode settings turned up high. Without batching,
7731 // thousands of separate files could be created on boot.
7732 if (!isSystemApp || needsFlush) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007733 new Thread("Error dump: " + dropboxTag) {
7734 @Override
7735 public void run() {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007736 String report;
7737 synchronized (sb) {
7738 report = sb.toString();
7739 sb.delete(0, sb.length());
7740 sb.trimToSize();
7741 }
7742 if (report.length() != 0) {
7743 dbox.addText(dropboxTag, report);
7744 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007745 }
7746 }.start();
7747 return;
7748 }
7749
7750 // System app batching:
7751 if (!bufferWasEmpty) {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007752 // An existing dropbox-writing thread is outstanding, so
7753 // we don't need to start it up. The existing thread will
7754 // catch the buffer appends we just did.
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007755 return;
7756 }
7757
7758 // Worker thread to both batch writes and to avoid blocking the caller on I/O.
7759 // (After this point, we shouldn't access AMS internal data structures.)
7760 new Thread("Error dump: " + dropboxTag) {
7761 @Override
7762 public void run() {
7763 // 5 second sleep to let stacks arrive and be batched together
7764 try {
7765 Thread.sleep(5000); // 5 seconds
7766 } catch (InterruptedException e) {}
7767
7768 String errorReport;
7769 synchronized (mStrictModeBuffer) {
7770 errorReport = mStrictModeBuffer.toString();
7771 if (errorReport.length() == 0) {
7772 return;
7773 }
7774 mStrictModeBuffer.delete(0, mStrictModeBuffer.length());
7775 mStrictModeBuffer.trimToSize();
7776 }
7777 dbox.addText(dropboxTag, errorReport);
7778 }
7779 }.start();
7780 }
7781
Dan Egnor60d87622009-12-16 16:32:58 -08007782 /**
7783 * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors.
7784 * @param app object of the crashing app, null for the system server
7785 * @param tag reported by the caller
7786 * @param crashInfo describing the context of the error
7787 * @return true if the process should exit immediately (WTF is fatal)
7788 */
7789 public boolean handleApplicationWtf(IBinder app, String tag,
Dan Egnorb7f03672009-12-09 16:22:32 -08007790 ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007791 ProcessRecord r = findAppProcess(app, "WTF");
Jeff Sharkeya353d262011-10-28 11:12:06 -07007792 final String processName = app == null ? "system_server"
7793 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08007794
7795 EventLog.writeEvent(EventLogTags.AM_WTF, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07007796 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08007797 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08007798 tag, crashInfo.exceptionMessage);
7799
Jeff Sharkeya353d262011-10-28 11:12:06 -07007800 addErrorToDropBox("wtf", r, processName, null, null, tag, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08007801
Dianne Hackborn1ab43772011-03-15 14:38:02 -07007802 if (r != null && r.pid != Process.myPid() &&
7803 Settings.Secure.getInt(mContext.getContentResolver(),
7804 Settings.Secure.WTF_IS_FATAL, 0) != 0) {
Dan Egnor60d87622009-12-16 16:32:58 -08007805 crashApplication(r, crashInfo);
7806 return true;
7807 } else {
7808 return false;
7809 }
7810 }
7811
7812 /**
7813 * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit})
7814 * @return the corresponding {@link ProcessRecord} object, or null if none could be found
7815 */
Dianne Hackborncb44d962011-03-10 17:02:27 -08007816 private ProcessRecord findAppProcess(IBinder app, String reason) {
Dan Egnor60d87622009-12-16 16:32:58 -08007817 if (app == null) {
7818 return null;
7819 }
7820
7821 synchronized (this) {
7822 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
7823 final int NA = apps.size();
7824 for (int ia=0; ia<NA; ia++) {
7825 ProcessRecord p = apps.valueAt(ia);
7826 if (p.thread != null && p.thread.asBinder() == app) {
7827 return p;
7828 }
7829 }
7830 }
7831
Dianne Hackborncb44d962011-03-10 17:02:27 -08007832 Slog.w(TAG, "Can't find mystery application for " + reason
7833 + " from pid=" + Binder.getCallingPid()
7834 + " uid=" + Binder.getCallingUid() + ": " + app);
Dan Egnor60d87622009-12-16 16:32:58 -08007835 return null;
7836 }
7837 }
7838
7839 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007840 * Utility function for addErrorToDropBox and handleStrictModeViolation's logging
7841 * to append various headers to the dropbox log text.
Dan Egnor60d87622009-12-16 16:32:58 -08007842 */
Jeff Sharkeya353d262011-10-28 11:12:06 -07007843 private void appendDropBoxProcessHeaders(ProcessRecord process, String processName,
7844 StringBuilder sb) {
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08007845 // Watchdog thread ends up invoking this function (with
7846 // a null ProcessRecord) to add the stack file to dropbox.
7847 // Do not acquire a lock on this (am) in such cases, as it
7848 // could cause a potential deadlock, if and when watchdog
7849 // is invoked due to unavailability of lock on am and it
7850 // would prevent watchdog from killing system_server.
7851 if (process == null) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07007852 sb.append("Process: ").append(processName).append("\n");
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08007853 return;
7854 }
Brad Fitzpatrick1e02d362010-09-10 09:19:50 -07007855 // Note: ProcessRecord 'process' is guarded by the service
7856 // instance. (notably process.pkgList, which could otherwise change
7857 // concurrently during execution of this method)
7858 synchronized (this) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07007859 sb.append("Process: ").append(processName).append("\n");
Dan Egnora455d192010-03-12 08:52:28 -08007860 int flags = process.info.flags;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007861 IPackageManager pm = AppGlobals.getPackageManager();
Dan Egnora455d192010-03-12 08:52:28 -08007862 sb.append("Flags: 0x").append(Integer.toString(flags, 16)).append("\n");
7863 for (String pkg : process.pkgList) {
7864 sb.append("Package: ").append(pkg);
Dan Egnor42471dd2010-01-07 17:25:22 -08007865 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07007866 PackageInfo pi = pm.getPackageInfo(pkg, 0, 0);
Dan Egnora455d192010-03-12 08:52:28 -08007867 if (pi != null) {
7868 sb.append(" v").append(pi.versionCode);
7869 if (pi.versionName != null) {
7870 sb.append(" (").append(pi.versionName).append(")");
7871 }
7872 }
7873 } catch (RemoteException e) {
7874 Slog.e(TAG, "Error getting package info: " + pkg, e);
Dan Egnor60d87622009-12-16 16:32:58 -08007875 }
Dan Egnora455d192010-03-12 08:52:28 -08007876 sb.append("\n");
Dan Egnor60d87622009-12-16 16:32:58 -08007877 }
Dan Egnora455d192010-03-12 08:52:28 -08007878 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007879 }
7880
7881 private static String processClass(ProcessRecord process) {
7882 if (process == null || process.pid == MY_PID) {
7883 return "system_server";
7884 } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
7885 return "system_app";
7886 } else {
7887 return "data_app";
7888 }
7889 }
7890
7891 /**
7892 * Write a description of an error (crash, WTF, ANR) to the drop box.
7893 * @param eventType to include in the drop box tag ("crash", "wtf", etc.)
7894 * @param process which caused the error, null means the system server
7895 * @param activity which triggered the error, null if unknown
7896 * @param parent activity related to the error, null if unknown
7897 * @param subject line related to the error, null if absent
7898 * @param report in long form describing the error, null if absent
7899 * @param logFile to include in the report, null if none
7900 * @param crashInfo giving an application stack trace, null if absent
7901 */
7902 public void addErrorToDropBox(String eventType,
Jeff Sharkeya353d262011-10-28 11:12:06 -07007903 ProcessRecord process, String processName, ActivityRecord activity,
7904 ActivityRecord parent, String subject,
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007905 final String report, final File logFile,
7906 final ApplicationErrorReport.CrashInfo crashInfo) {
7907 // NOTE -- this must never acquire the ActivityManagerService lock,
7908 // otherwise the watchdog may be prevented from resetting the system.
7909
7910 final String dropboxTag = processClass(process) + "_" + eventType;
7911 final DropBoxManager dbox = (DropBoxManager)
7912 mContext.getSystemService(Context.DROPBOX_SERVICE);
7913
7914 // Exit early if the dropbox isn't configured to accept this report type.
7915 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
7916
7917 final StringBuilder sb = new StringBuilder(1024);
Jeff Sharkeya353d262011-10-28 11:12:06 -07007918 appendDropBoxProcessHeaders(process, processName, sb);
Dan Egnora455d192010-03-12 08:52:28 -08007919 if (activity != null) {
7920 sb.append("Activity: ").append(activity.shortComponentName).append("\n");
7921 }
7922 if (parent != null && parent.app != null && parent.app.pid != process.pid) {
7923 sb.append("Parent-Process: ").append(parent.app.processName).append("\n");
7924 }
7925 if (parent != null && parent != activity) {
7926 sb.append("Parent-Activity: ").append(parent.shortComponentName).append("\n");
7927 }
7928 if (subject != null) {
7929 sb.append("Subject: ").append(subject).append("\n");
7930 }
7931 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
Christian Lindeberg03d2ca62010-09-28 14:52:20 +02007932 if (Debug.isDebuggerConnected()) {
7933 sb.append("Debugger: Connected\n");
7934 }
Dan Egnora455d192010-03-12 08:52:28 -08007935 sb.append("\n");
7936
7937 // Do the rest in a worker thread to avoid blocking the caller on I/O
7938 // (After this point, we shouldn't access AMS internal data structures.)
7939 Thread worker = new Thread("Error dump: " + dropboxTag) {
7940 @Override
7941 public void run() {
7942 if (report != null) {
7943 sb.append(report);
7944 }
7945 if (logFile != null) {
7946 try {
7947 sb.append(FileUtils.readTextFile(logFile, 128 * 1024, "\n\n[[TRUNCATED]]"));
7948 } catch (IOException e) {
7949 Slog.e(TAG, "Error reading " + logFile, e);
7950 }
7951 }
7952 if (crashInfo != null && crashInfo.stackTrace != null) {
7953 sb.append(crashInfo.stackTrace);
7954 }
7955
7956 String setting = Settings.Secure.ERROR_LOGCAT_PREFIX + dropboxTag;
7957 int lines = Settings.Secure.getInt(mContext.getContentResolver(), setting, 0);
7958 if (lines > 0) {
7959 sb.append("\n");
7960
7961 // Merge several logcat streams, and take the last N lines
7962 InputStreamReader input = null;
7963 try {
7964 java.lang.Process logcat = new ProcessBuilder("/system/bin/logcat",
7965 "-v", "time", "-b", "events", "-b", "system", "-b", "main",
7966 "-t", String.valueOf(lines)).redirectErrorStream(true).start();
7967
7968 try { logcat.getOutputStream().close(); } catch (IOException e) {}
7969 try { logcat.getErrorStream().close(); } catch (IOException e) {}
7970 input = new InputStreamReader(logcat.getInputStream());
7971
7972 int num;
7973 char[] buf = new char[8192];
7974 while ((num = input.read(buf)) > 0) sb.append(buf, 0, num);
7975 } catch (IOException e) {
7976 Slog.e(TAG, "Error running logcat", e);
7977 } finally {
7978 if (input != null) try { input.close(); } catch (IOException e) {}
7979 }
7980 }
7981
7982 dbox.addText(dropboxTag, sb.toString());
Dan Egnor60d87622009-12-16 16:32:58 -08007983 }
Dan Egnora455d192010-03-12 08:52:28 -08007984 };
7985
7986 if (process == null || process.pid == MY_PID) {
7987 worker.run(); // We may be about to die -- need to run this synchronously
7988 } else {
7989 worker.start();
Dan Egnor60d87622009-12-16 16:32:58 -08007990 }
7991 }
7992
7993 /**
7994 * Bring up the "unexpected error" dialog box for a crashing app.
7995 * Deal with edge cases (intercepts from instrumented applications,
7996 * ActivityController, error intent receivers, that sort of thing).
7997 * @param r the application crashing
7998 * @param crashInfo describing the failure
7999 */
8000 private void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008001 long timeMillis = System.currentTimeMillis();
8002 String shortMsg = crashInfo.exceptionClassName;
8003 String longMsg = crashInfo.exceptionMessage;
8004 String stackTrace = crashInfo.stackTrace;
8005 if (shortMsg != null && longMsg != null) {
8006 longMsg = shortMsg + ": " + longMsg;
8007 } else if (shortMsg != null) {
8008 longMsg = shortMsg;
8009 }
8010
Dan Egnor60d87622009-12-16 16:32:58 -08008011 AppErrorResult result = new AppErrorResult();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008012 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008013 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008014 try {
8015 String name = r != null ? r.processName : null;
8016 int pid = r != null ? r.pid : Binder.getCallingPid();
Dan Egnor60d87622009-12-16 16:32:58 -08008017 if (!mController.appCrashed(name, pid,
Dan Egnorb7f03672009-12-09 16:22:32 -08008018 shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008019 Slog.w(TAG, "Force-killing crashed app " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008020 + " at watcher's request");
8021 Process.killProcess(pid);
Dan Egnorb7f03672009-12-09 16:22:32 -08008022 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008023 }
8024 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008025 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008026 }
8027 }
8028
8029 final long origId = Binder.clearCallingIdentity();
8030
8031 // If this process is running instrumentation, finish it.
8032 if (r != null && r.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008033 Slog.w(TAG, "Error in app " + r.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008034 + " running instrumentation " + r.instrumentationClass + ":");
Joe Onorato8a9b2202010-02-26 18:56:32 -08008035 if (shortMsg != null) Slog.w(TAG, " " + shortMsg);
8036 if (longMsg != null) Slog.w(TAG, " " + longMsg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008037 Bundle info = new Bundle();
8038 info.putString("shortMsg", shortMsg);
8039 info.putString("longMsg", longMsg);
8040 finishInstrumentationLocked(r, Activity.RESULT_CANCELED, info);
8041 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008042 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008043 }
8044
Dan Egnor60d87622009-12-16 16:32:58 -08008045 // If we can't identify the process or it's already exceeded its crash quota,
8046 // quit right away without showing a crash dialog.
8047 if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008048 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008049 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008050 }
8051
8052 Message msg = Message.obtain();
8053 msg.what = SHOW_ERROR_MSG;
8054 HashMap data = new HashMap();
8055 data.put("result", result);
8056 data.put("app", r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008057 msg.obj = data;
8058 mHandler.sendMessage(msg);
8059
8060 Binder.restoreCallingIdentity(origId);
8061 }
8062
8063 int res = result.get();
8064
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008065 Intent appErrorIntent = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008066 synchronized (this) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008067 if (r != null && !r.isolated) {
8068 // XXX Can't keep track of crash time for isolated processes,
8069 // since they don't have a persistent identity.
8070 mProcessCrashTimes.put(r.info.processName, r.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008071 SystemClock.uptimeMillis());
8072 }
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008073 if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008074 appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008075 }
8076 }
8077
8078 if (appErrorIntent != null) {
8079 try {
8080 mContext.startActivity(appErrorIntent);
8081 } catch (ActivityNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008082 Slog.w(TAG, "bug report receiver dissappeared", e);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008083 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008084 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008085 }
Dan Egnorb7f03672009-12-09 16:22:32 -08008086
8087 Intent createAppErrorIntentLocked(ProcessRecord r,
8088 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
8089 ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008090 if (report == null) {
8091 return null;
8092 }
8093 Intent result = new Intent(Intent.ACTION_APP_ERROR);
8094 result.setComponent(r.errorReportReceiver);
8095 result.putExtra(Intent.EXTRA_BUG_REPORT, report);
8096 result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
8097 return result;
8098 }
8099
Dan Egnorb7f03672009-12-09 16:22:32 -08008100 private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r,
8101 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008102 if (r.errorReportReceiver == null) {
8103 return null;
8104 }
8105
8106 if (!r.crashing && !r.notResponding) {
8107 return null;
8108 }
8109
Dan Egnorb7f03672009-12-09 16:22:32 -08008110 ApplicationErrorReport report = new ApplicationErrorReport();
8111 report.packageName = r.info.packageName;
8112 report.installerPackageName = r.errorReportReceiver.getPackageName();
8113 report.processName = r.processName;
8114 report.time = timeMillis;
Jacek Surazskie0ee6ef2010-01-07 16:23:03 +01008115 report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008116
Dan Egnorb7f03672009-12-09 16:22:32 -08008117 if (r.crashing) {
8118 report.type = ApplicationErrorReport.TYPE_CRASH;
8119 report.crashInfo = crashInfo;
8120 } else if (r.notResponding) {
8121 report.type = ApplicationErrorReport.TYPE_ANR;
8122 report.anrInfo = new ApplicationErrorReport.AnrInfo();
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008123
Dan Egnorb7f03672009-12-09 16:22:32 -08008124 report.anrInfo.activity = r.notRespondingReport.tag;
8125 report.anrInfo.cause = r.notRespondingReport.shortMsg;
8126 report.anrInfo.info = r.notRespondingReport.longMsg;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008127 }
8128
Dan Egnorb7f03672009-12-09 16:22:32 -08008129 return report;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008130 }
8131
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008132 public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008133 enforceNotIsolatedCaller("getProcessesInErrorState");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008134 // assume our apps are happy - lazy create the list
8135 List<ActivityManager.ProcessErrorStateInfo> errList = null;
8136
8137 synchronized (this) {
8138
8139 // iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008140 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8141 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008142 if ((app.thread != null) && (app.crashing || app.notResponding)) {
8143 // This one's in trouble, so we'll generate a report for it
8144 // crashes are higher priority (in case there's a crash *and* an anr)
8145 ActivityManager.ProcessErrorStateInfo report = null;
8146 if (app.crashing) {
8147 report = app.crashingReport;
8148 } else if (app.notResponding) {
8149 report = app.notRespondingReport;
8150 }
8151
8152 if (report != null) {
8153 if (errList == null) {
8154 errList = new ArrayList<ActivityManager.ProcessErrorStateInfo>(1);
8155 }
8156 errList.add(report);
8157 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008158 Slog.w(TAG, "Missing app error report, app = " + app.processName +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008159 " crashing = " + app.crashing +
8160 " notResponding = " + app.notResponding);
8161 }
8162 }
8163 }
8164 }
8165
8166 return errList;
8167 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07008168
8169 static int oomAdjToImportance(int adj, ActivityManager.RunningAppProcessInfo currApp) {
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008170 if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008171 if (currApp != null) {
8172 currApp.lru = adj - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
8173 }
8174 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008175 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
8176 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008177 } else if (adj >= ProcessList.HOME_APP_ADJ) {
8178 if (currApp != null) {
8179 currApp.lru = 0;
8180 }
8181 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008182 } else if (adj >= ProcessList.SERVICE_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008183 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
8184 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
8185 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
8186 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
8187 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
8188 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
8189 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
8190 } else {
8191 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
8192 }
8193 }
8194
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008195 private void fillInProcMemInfo(ProcessRecord app,
8196 ActivityManager.RunningAppProcessInfo outInfo) {
8197 outInfo.pid = app.pid;
8198 outInfo.uid = app.info.uid;
8199 if (mHeavyWeightProcess == app) {
8200 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_CANT_SAVE_STATE;
8201 }
8202 if (app.persistent) {
8203 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_PERSISTENT;
8204 }
8205 outInfo.lastTrimLevel = app.trimMemoryLevel;
8206 int adj = app.curAdj;
8207 outInfo.importance = oomAdjToImportance(adj, outInfo);
8208 outInfo.importanceReasonCode = app.adjTypeCode;
8209 }
8210
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008211 public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008212 enforceNotIsolatedCaller("getRunningAppProcesses");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008213 // Lazy instantiation of list
8214 List<ActivityManager.RunningAppProcessInfo> runList = null;
8215 synchronized (this) {
8216 // Iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008217 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8218 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008219 if ((app.thread != null) && (!app.crashing && !app.notResponding)) {
8220 // Generate process state info for running application
8221 ActivityManager.RunningAppProcessInfo currApp =
8222 new ActivityManager.RunningAppProcessInfo(app.processName,
8223 app.pid, app.getPackageList());
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008224 fillInProcMemInfo(app, currApp);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008225 if (app.adjSource instanceof ProcessRecord) {
8226 currApp.importanceReasonPid = ((ProcessRecord)app.adjSource).pid;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008227 currApp.importanceReasonImportance = oomAdjToImportance(
8228 app.adjSourceOom, null);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008229 } else if (app.adjSource instanceof ActivityRecord) {
8230 ActivityRecord r = (ActivityRecord)app.adjSource;
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008231 if (r.app != null) currApp.importanceReasonPid = r.app.pid;
8232 }
8233 if (app.adjTarget instanceof ComponentName) {
8234 currApp.importanceReasonComponent = (ComponentName)app.adjTarget;
8235 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08008236 //Slog.v(TAG, "Proc " + app.processName + ": imp=" + currApp.importance
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008237 // + " lru=" + currApp.lru);
8238 if (runList == null) {
8239 runList = new ArrayList<ActivityManager.RunningAppProcessInfo>();
8240 }
8241 runList.add(currApp);
8242 }
8243 }
8244 }
8245 return runList;
8246 }
8247
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008248 public List<ApplicationInfo> getRunningExternalApplications() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008249 enforceNotIsolatedCaller("getRunningExternalApplications");
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008250 List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses();
8251 List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>();
8252 if (runningApps != null && runningApps.size() > 0) {
8253 Set<String> extList = new HashSet<String>();
8254 for (ActivityManager.RunningAppProcessInfo app : runningApps) {
8255 if (app.pkgList != null) {
8256 for (String pkg : app.pkgList) {
8257 extList.add(pkg);
8258 }
8259 }
8260 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008261 IPackageManager pm = AppGlobals.getPackageManager();
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008262 for (String pkg : extList) {
8263 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07008264 ApplicationInfo info = pm.getApplicationInfo(pkg, 0, UserId.getCallingUserId());
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008265 if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
8266 retList.add(info);
8267 }
8268 } catch (RemoteException e) {
8269 }
8270 }
8271 }
8272 return retList;
8273 }
8274
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008275 @Override
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008276 public void getMyMemoryState(ActivityManager.RunningAppProcessInfo outInfo) {
8277 enforceNotIsolatedCaller("getMyMemoryState");
8278 synchronized (this) {
8279 ProcessRecord proc;
8280 synchronized (mPidsSelfLocked) {
8281 proc = mPidsSelfLocked.get(Binder.getCallingPid());
8282 }
8283 fillInProcMemInfo(proc, outInfo);
8284 }
8285 }
8286
8287 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008288 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008289 if (checkCallingPermission(android.Manifest.permission.DUMP)
8290 != PackageManager.PERMISSION_GRANTED) {
8291 pw.println("Permission Denial: can't dump ActivityManager from from pid="
8292 + Binder.getCallingPid()
8293 + ", uid=" + Binder.getCallingUid()
8294 + " without permission "
8295 + android.Manifest.permission.DUMP);
8296 return;
8297 }
8298
8299 boolean dumpAll = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008300 boolean dumpClient = false;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008301 String dumpPackage = null;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008302
8303 int opti = 0;
8304 while (opti < args.length) {
8305 String opt = args[opti];
8306 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
8307 break;
8308 }
8309 opti++;
8310 if ("-a".equals(opt)) {
8311 dumpAll = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008312 } else if ("-c".equals(opt)) {
8313 dumpClient = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008314 } else if ("-h".equals(opt)) {
8315 pw.println("Activity manager dump options:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008316 pw.println(" [-a] [-c] [-h] [cmd] ...");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008317 pw.println(" cmd may be one of:");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008318 pw.println(" a[ctivities]: activity stack state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008319 pw.println(" b[roadcasts] [PACKAGE_NAME]: broadcast state");
8320 pw.println(" i[ntents] [PACKAGE_NAME]: pending intent state");
8321 pw.println(" p[rocesses] [PACKAGE_NAME]: process state");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008322 pw.println(" o[om]: out of memory management");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008323 pw.println(" prov[iders] [COMP_SPEC ...]: content provider state");
Marco Nelissen18cb2872011-11-15 11:19:53 -08008324 pw.println(" provider [COMP_SPEC]: provider client-side state");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008325 pw.println(" s[ervices] [COMP_SPEC ...]: service state");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008326 pw.println(" service [COMP_SPEC]: service client-side state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008327 pw.println(" package [PACKAGE_NAME]: all state related to given package");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008328 pw.println(" all: dump all activities");
8329 pw.println(" top: dump the top activity");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008330 pw.println(" cmd may also be a COMP_SPEC to dump activities.");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008331 pw.println(" COMP_SPEC may be a component name (com.foo/.myApp),");
8332 pw.println(" a partial substring in a component name, a");
8333 pw.println(" hex object identifier.");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008334 pw.println(" -a: include all available server state.");
8335 pw.println(" -c: include client state.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008336 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008337 } else {
8338 pw.println("Unknown argument: " + opt + "; use -h for help");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008339 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008340 }
8341
8342 // Is the caller requesting to dump a particular piece of data?
8343 if (opti < args.length) {
8344 String cmd = args[opti];
8345 opti++;
8346 if ("activities".equals(cmd) || "a".equals(cmd)) {
8347 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008348 dumpActivitiesLocked(fd, pw, args, opti, true, dumpClient, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008349 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008350 return;
8351 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008352 String[] newArgs;
8353 String name;
8354 if (opti >= args.length) {
8355 name = null;
8356 newArgs = EMPTY_STRING_ARRAY;
8357 } else {
8358 name = args[opti];
8359 opti++;
8360 newArgs = new String[args.length - opti];
8361 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8362 args.length - opti);
8363 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008364 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008365 dumpBroadcastsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008366 }
8367 return;
8368 } else if ("intents".equals(cmd) || "i".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008369 String[] newArgs;
8370 String name;
8371 if (opti >= args.length) {
8372 name = null;
8373 newArgs = EMPTY_STRING_ARRAY;
8374 } else {
8375 name = args[opti];
8376 opti++;
8377 newArgs = new String[args.length - opti];
8378 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8379 args.length - opti);
8380 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008381 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008382 dumpPendingIntentsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008383 }
8384 return;
8385 } else if ("processes".equals(cmd) || "p".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008386 String[] newArgs;
8387 String name;
8388 if (opti >= args.length) {
8389 name = null;
8390 newArgs = EMPTY_STRING_ARRAY;
8391 } else {
8392 name = args[opti];
8393 opti++;
8394 newArgs = new String[args.length - opti];
8395 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8396 args.length - opti);
8397 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008398 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008399 dumpProcessesLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008400 }
8401 return;
Dianne Hackborn287952c2010-09-22 22:34:31 -07008402 } else if ("oom".equals(cmd) || "o".equals(cmd)) {
8403 synchronized (this) {
8404 dumpOomLocked(fd, pw, args, opti, true);
8405 }
8406 return;
Marco Nelissen18cb2872011-11-15 11:19:53 -08008407 } else if ("provider".equals(cmd)) {
8408 String[] newArgs;
8409 String name;
8410 if (opti >= args.length) {
8411 name = null;
8412 newArgs = EMPTY_STRING_ARRAY;
8413 } else {
8414 name = args[opti];
8415 opti++;
8416 newArgs = new String[args.length - opti];
8417 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
8418 }
8419 if (!dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) {
8420 pw.println("No providers match: " + name);
8421 pw.println("Use -h for help.");
8422 }
8423 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008424 } else if ("providers".equals(cmd) || "prov".equals(cmd)) {
8425 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008426 dumpProvidersLocked(fd, pw, args, opti, true, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008427 }
8428 return;
8429 } else if ("service".equals(cmd)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008430 String[] newArgs;
8431 String name;
8432 if (opti >= args.length) {
8433 name = null;
8434 newArgs = EMPTY_STRING_ARRAY;
8435 } else {
8436 name = args[opti];
8437 opti++;
8438 newArgs = new String[args.length - opti];
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008439 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8440 args.length - opti);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008441 }
8442 if (!dumpService(fd, pw, name, newArgs, 0, dumpAll)) {
8443 pw.println("No services match: " + name);
8444 pw.println("Use -h for help.");
8445 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008446 return;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008447 } else if ("package".equals(cmd)) {
8448 String[] newArgs;
8449 if (opti >= args.length) {
8450 pw.println("package: no package name specified");
8451 pw.println("Use -h for help.");
8452 return;
8453 } else {
8454 dumpPackage = args[opti];
8455 opti++;
8456 newArgs = new String[args.length - opti];
8457 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8458 args.length - opti);
8459 args = newArgs;
8460 opti = 0;
8461 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008462 } else if ("services".equals(cmd) || "s".equals(cmd)) {
8463 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008464 dumpServicesLocked(fd, pw, args, opti, true, dumpClient, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008465 }
8466 return;
Dianne Hackborn625ac272010-09-17 18:29:22 -07008467 } else {
8468 // Dumping a single activity?
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008469 if (!dumpActivity(fd, pw, cmd, args, opti, dumpAll)) {
8470 pw.println("Bad activity command, or no activities match: " + cmd);
8471 pw.println("Use -h for help.");
Dianne Hackborn625ac272010-09-17 18:29:22 -07008472 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08008473 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008474 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008475 }
8476
8477 // No piece of data specified, dump everything.
8478 synchronized (this) {
8479 boolean needSep;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008480 needSep = dumpPendingIntentsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008481 if (needSep) {
8482 pw.println(" ");
8483 }
8484 if (dumpAll) {
8485 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008486 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008487 needSep = dumpBroadcastsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008488 if (needSep) {
8489 pw.println(" ");
8490 }
8491 if (dumpAll) {
8492 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008493 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008494 needSep = dumpProvidersLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008495 if (needSep) {
8496 pw.println(" ");
8497 }
8498 if (dumpAll) {
8499 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008500 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008501 needSep = dumpServicesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008502 if (needSep) {
8503 pw.println(" ");
8504 }
8505 if (dumpAll) {
8506 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008507 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008508 needSep = dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008509 if (needSep) {
8510 pw.println(" ");
8511 }
8512 if (dumpAll) {
8513 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008514 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008515 dumpProcessesLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008516 }
8517 }
8518
8519 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008520 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008521 pw.println("ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
8522 pw.println(" Main stack:");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008523 dumpHistoryList(fd, pw, mMainStack.mHistory, " ", "Hist", true, !dumpAll, dumpClient,
8524 dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008525 pw.println(" ");
8526 pw.println(" Running activities (most recent first):");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008527 dumpHistoryList(fd, pw, mMainStack.mLRUActivities, " ", "Run", false, !dumpAll, false,
8528 dumpPackage);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008529 if (mMainStack.mWaitingVisibleActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008530 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008531 pw.println(" Activities waiting for another to become visible:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008532 dumpHistoryList(fd, pw, mMainStack.mWaitingVisibleActivities, " ", "Wait", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008533 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008534 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008535 if (mMainStack.mStoppingActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008536 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008537 pw.println(" Activities waiting to stop:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008538 dumpHistoryList(fd, pw, mMainStack.mStoppingActivities, " ", "Stop", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008539 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008540 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008541 if (mMainStack.mGoingToSleepActivities.size() > 0) {
8542 pw.println(" ");
8543 pw.println(" Activities waiting to sleep:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008544 dumpHistoryList(fd, pw, mMainStack.mGoingToSleepActivities, " ", "Sleep", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008545 !dumpAll, false, dumpPackage);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008546 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008547 if (mMainStack.mFinishingActivities.size() > 0) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008548 pw.println(" ");
8549 pw.println(" Activities waiting to finish:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008550 dumpHistoryList(fd, pw, mMainStack.mFinishingActivities, " ", "Fin", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008551 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008552 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008553
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008554 pw.println(" ");
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08008555 if (mMainStack.mPausingActivity != null) {
8556 pw.println(" mPausingActivity: " + mMainStack.mPausingActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008557 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008558 pw.println(" mResumedActivity: " + mMainStack.mResumedActivity);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008559 pw.println(" mFocusedActivity: " + mFocusedActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008560 if (dumpAll) {
8561 pw.println(" mLastPausedActivity: " + mMainStack.mLastPausedActivity);
8562 pw.println(" mSleepTimeout: " + mMainStack.mSleepTimeout);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07008563 pw.println(" mDismissKeyguardOnNextActivity: "
8564 + mMainStack.mDismissKeyguardOnNextActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008565 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008566
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008567 if (mRecentTasks.size() > 0) {
8568 pw.println();
8569 pw.println(" Recent tasks:");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008570
8571 final int N = mRecentTasks.size();
8572 for (int i=0; i<N; i++) {
8573 TaskRecord tr = mRecentTasks.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008574 if (dumpPackage != null) {
8575 if (tr.realActivity == null ||
8576 !dumpPackage.equals(tr.realActivity)) {
8577 continue;
8578 }
8579 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008580 pw.print(" * Recent #"); pw.print(i); pw.print(": ");
8581 pw.println(tr);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008582 if (dumpAll) {
8583 mRecentTasks.get(i).dump(pw, " ");
8584 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008585 }
8586 }
8587
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008588 if (dumpAll) {
8589 pw.println(" ");
8590 pw.println(" mCurTask: " + mCurTask);
8591 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008592
8593 return true;
8594 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008595
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008596 boolean dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008597 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008598 boolean needSep = false;
8599 int numPers = 0;
8600
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008601 pw.println("ACTIVITY MANAGER RUNNING PROCESSES (dumpsys activity processes)");
8602
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008603 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008604 for (SparseArray<ProcessRecord> procs : mProcessNames.getMap().values()) {
8605 final int NA = procs.size();
8606 for (int ia=0; ia<NA; ia++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008607 ProcessRecord r = procs.valueAt(ia);
8608 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8609 continue;
8610 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008611 if (!needSep) {
8612 pw.println(" All known processes:");
8613 needSep = true;
8614 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008615 pw.print(r.persistent ? " *PERS*" : " *APP*");
8616 pw.print(" UID "); pw.print(procs.keyAt(ia));
8617 pw.print(" "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008618 r.dump(pw, " ");
8619 if (r.persistent) {
8620 numPers++;
8621 }
8622 }
8623 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008624 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008625
8626 if (mIsolatedProcesses.size() > 0) {
8627 if (needSep) pw.println(" ");
8628 needSep = true;
8629 pw.println(" Isolated process list (sorted by uid):");
8630 for (int i=0; i<mIsolatedProcesses.size(); i++) {
8631 ProcessRecord r = mIsolatedProcesses.valueAt(i);
8632 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8633 continue;
8634 }
8635 pw.println(String.format("%sIsolated #%2d: %s",
8636 " ", i, r.toString()));
8637 }
8638 }
8639
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008640 if (mLruProcesses.size() > 0) {
8641 if (needSep) pw.println(" ");
8642 needSep = true;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008643 pw.println(" Process LRU list (sorted by oom_adj):");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008644 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008645 "Proc", "PERS", false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008646 needSep = true;
8647 }
8648
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008649 if (dumpAll) {
8650 synchronized (mPidsSelfLocked) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008651 boolean printed = false;
8652 for (int i=0; i<mPidsSelfLocked.size(); i++) {
8653 ProcessRecord r = mPidsSelfLocked.valueAt(i);
8654 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8655 continue;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008656 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008657 if (!printed) {
8658 if (needSep) pw.println(" ");
8659 needSep = true;
8660 pw.println(" PID mappings:");
8661 printed = true;
8662 }
8663 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i));
8664 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008665 }
8666 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008667 }
8668
8669 if (mForegroundProcesses.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008670 synchronized (mPidsSelfLocked) {
8671 boolean printed = false;
8672 for (int i=0; i<mForegroundProcesses.size(); i++) {
8673 ProcessRecord r = mPidsSelfLocked.get(
8674 mForegroundProcesses.valueAt(i).pid);
8675 if (dumpPackage != null && (r == null
8676 || !dumpPackage.equals(r.info.packageName))) {
8677 continue;
8678 }
8679 if (!printed) {
8680 if (needSep) pw.println(" ");
8681 needSep = true;
8682 pw.println(" Foreground Processes:");
8683 printed = true;
8684 }
8685 pw.print(" PID #"); pw.print(mForegroundProcesses.keyAt(i));
8686 pw.print(": "); pw.println(mForegroundProcesses.valueAt(i));
8687 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008688 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008689 }
8690
8691 if (mPersistentStartingProcesses.size() > 0) {
8692 if (needSep) pw.println(" ");
8693 needSep = true;
8694 pw.println(" Persisent processes that are starting:");
8695 dumpProcessList(pw, this, mPersistentStartingProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008696 "Starting Norm", "Restarting PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008697 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008698
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008699 if (mRemovedProcesses.size() > 0) {
8700 if (needSep) pw.println(" ");
8701 needSep = true;
8702 pw.println(" Processes that are being removed:");
8703 dumpProcessList(pw, this, mRemovedProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008704 "Removed Norm", "Removed PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008705 }
8706
8707 if (mProcessesOnHold.size() > 0) {
8708 if (needSep) pw.println(" ");
8709 needSep = true;
8710 pw.println(" Processes that are on old until the system is ready:");
8711 dumpProcessList(pw, this, mProcessesOnHold, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008712 "OnHold Norm", "OnHold PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008713 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008714
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008715 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008716
8717 if (mProcessCrashTimes.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008718 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008719 long now = SystemClock.uptimeMillis();
8720 for (Map.Entry<String, SparseArray<Long>> procs
8721 : mProcessCrashTimes.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008722 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008723 SparseArray<Long> uids = procs.getValue();
8724 final int N = uids.size();
8725 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008726 int puid = uids.keyAt(i);
8727 ProcessRecord r = mProcessNames.get(pname, puid);
8728 if (dumpPackage != null && (r == null
8729 || !dumpPackage.equals(r.info.packageName))) {
8730 continue;
8731 }
8732 if (!printed) {
8733 if (needSep) pw.println(" ");
8734 needSep = true;
8735 pw.println(" Time since processes crashed:");
8736 printed = true;
8737 }
8738 pw.print(" Process "); pw.print(pname);
8739 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008740 pw.print(": last crashed ");
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008741 TimeUtils.formatDuration(now-uids.valueAt(i), pw);
8742 pw.println(" ago");
Dianne Hackbornfd12af42009-08-27 00:44:33 -07008743 }
8744 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008745 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008746
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008747 if (mBadProcesses.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008748 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008749 for (Map.Entry<String, SparseArray<Long>> procs
8750 : mBadProcesses.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008751 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008752 SparseArray<Long> uids = procs.getValue();
8753 final int N = uids.size();
8754 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008755 int puid = uids.keyAt(i);
8756 ProcessRecord r = mProcessNames.get(pname, puid);
8757 if (dumpPackage != null && (r == null
8758 || !dumpPackage.equals(r.info.packageName))) {
8759 continue;
8760 }
8761 if (!printed) {
8762 if (needSep) pw.println(" ");
8763 needSep = true;
8764 pw.println(" Bad processes:");
8765 }
8766 pw.print(" Bad process "); pw.print(pname);
8767 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008768 pw.print(": crashed at time ");
8769 pw.println(uids.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008770 }
8771 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008772 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008773
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008774 pw.println();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008775 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07008776 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn50685602011-12-01 12:23:37 -08008777 if (dumpAll) {
8778 StringBuilder sb = new StringBuilder(128);
8779 sb.append(" mPreviousProcessVisibleTime: ");
8780 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
8781 pw.println(sb);
8782 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07008783 if (mHeavyWeightProcess != null) {
8784 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
8785 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008786 pw.println(" mConfiguration: " + mConfiguration);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008787 if (dumpAll) {
8788 pw.println(" mConfigWillChange: " + mMainStack.mConfigWillChange);
Dianne Hackborn3d0724d2011-05-12 15:39:41 -07008789 if (mCompatModePackages.getPackages().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008790 boolean printed = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07008791 for (Map.Entry<String, Integer> entry
8792 : mCompatModePackages.getPackages().entrySet()) {
8793 String pkg = entry.getKey();
8794 int mode = entry.getValue();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008795 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
8796 continue;
8797 }
8798 if (!printed) {
8799 pw.println(" mScreenCompatPackages:");
8800 printed = true;
8801 }
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07008802 pw.print(" "); pw.print(pkg); pw.print(": ");
8803 pw.print(mode); pw.println();
8804 }
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07008805 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008806 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008807 pw.println(" mSleeping=" + mSleeping + " mShuttingDown=" + mShuttingDown);
8808 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
8809 || mOrigWaitForDebugger) {
8810 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp
8811 + " mDebugTransient=" + mDebugTransient
8812 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger);
8813 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08008814 if (mOpenGlTraceApp != null) {
8815 pw.println(" mOpenGlTraceApp=" + mOpenGlTraceApp);
8816 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07008817 if (mProfileApp != null || mProfileProc != null || mProfileFile != null
8818 || mProfileFd != null) {
8819 pw.println(" mProfileApp=" + mProfileApp + " mProfileProc=" + mProfileProc);
8820 pw.println(" mProfileFile=" + mProfileFile + " mProfileFd=" + mProfileFd);
8821 pw.println(" mProfileType=" + mProfileType + " mAutoStopProfiler="
8822 + mAutoStopProfiler);
8823 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008824 if (mAlwaysFinishActivities || mController != null) {
8825 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities
8826 + " mController=" + mController);
8827 }
8828 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008829 pw.println(" Total persistent processes: " + numPers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008830 pw.println(" mStartRunning=" + mStartRunning
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07008831 + " mProcessesReady=" + mProcessesReady
8832 + " mSystemReady=" + mSystemReady);
8833 pw.println(" mBooting=" + mBooting
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008834 + " mBooted=" + mBooted
8835 + " mFactoryTest=" + mFactoryTest);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008836 pw.print(" mLastPowerCheckRealtime=");
8837 TimeUtils.formatDuration(mLastPowerCheckRealtime, pw);
8838 pw.println("");
8839 pw.print(" mLastPowerCheckUptime=");
8840 TimeUtils.formatDuration(mLastPowerCheckUptime, pw);
8841 pw.println("");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008842 pw.println(" mGoingToSleep=" + mMainStack.mGoingToSleep);
8843 pw.println(" mLaunchingActivity=" + mMainStack.mLaunchingActivity);
Dianne Hackborn906497c2010-05-10 15:57:38 -07008844 pw.println(" mAdjSeq=" + mAdjSeq + " mLruSeq=" + mLruSeq);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008845 pw.println(" mNumServiceProcs=" + mNumServiceProcs
8846 + " mNewNumServiceProcs=" + mNewNumServiceProcs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008847 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008848
8849 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008850 }
8851
Dianne Hackborn287952c2010-09-22 22:34:31 -07008852 boolean dumpProcessesToGc(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008853 int opti, boolean needSep, boolean dumpAll, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07008854 if (mProcessesToGc.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008855 boolean printed = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -07008856 long now = SystemClock.uptimeMillis();
8857 for (int i=0; i<mProcessesToGc.size(); i++) {
8858 ProcessRecord proc = mProcessesToGc.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008859 if (dumpPackage != null && !dumpPackage.equals(proc.info.packageName)) {
8860 continue;
8861 }
8862 if (!printed) {
8863 if (needSep) pw.println(" ");
8864 needSep = true;
8865 pw.println(" Processes that are waiting to GC:");
8866 printed = true;
8867 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008868 pw.print(" Process "); pw.println(proc);
8869 pw.print(" lowMem="); pw.print(proc.reportLowMemory);
8870 pw.print(", last gced=");
8871 pw.print(now-proc.lastRequestedGc);
8872 pw.print(" ms ago, last lowMem=");
8873 pw.print(now-proc.lastLowMemory);
8874 pw.println(" ms ago");
8875
8876 }
8877 }
8878 return needSep;
8879 }
8880
8881 boolean dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args,
8882 int opti, boolean dumpAll) {
8883 boolean needSep = false;
8884
8885 if (mLruProcesses.size() > 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07008886 if (needSep) pw.println(" ");
8887 needSep = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -07008888 pw.println(" OOM levels:");
Dianne Hackborn7d608422011-08-07 16:24:18 -07008889 pw.print(" SYSTEM_ADJ: "); pw.println(ProcessList.SYSTEM_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008890 pw.print(" PERSISTENT_PROC_ADJ: "); pw.println(ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07008891 pw.print(" FOREGROUND_APP_ADJ: "); pw.println(ProcessList.FOREGROUND_APP_ADJ);
8892 pw.print(" VISIBLE_APP_ADJ: "); pw.println(ProcessList.VISIBLE_APP_ADJ);
8893 pw.print(" PERCEPTIBLE_APP_ADJ: "); pw.println(ProcessList.PERCEPTIBLE_APP_ADJ);
8894 pw.print(" HEAVY_WEIGHT_APP_ADJ: "); pw.println(ProcessList.HEAVY_WEIGHT_APP_ADJ);
8895 pw.print(" BACKUP_APP_ADJ: "); pw.println(ProcessList.BACKUP_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008896 pw.print(" SERVICE_ADJ: "); pw.println(ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07008897 pw.print(" HOME_APP_ADJ: "); pw.println(ProcessList.HOME_APP_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07008898 pw.print(" PREVIOUS_APP_ADJ: "); pw.println(ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008899 pw.print(" SERVICE_B_ADJ: "); pw.println(ProcessList.SERVICE_B_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07008900 pw.print(" HIDDEN_APP_MIN_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008901 pw.print(" HIDDEN_APP_MAX_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MAX_ADJ);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07008902
8903 if (needSep) pw.println(" ");
8904 needSep = true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07008905 pw.println(" Process OOM control:");
Dianne Hackborn905577f2011-09-07 18:31:28 -07008906 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008907 "Proc", "PERS", true, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008908 needSep = true;
8909 }
8910
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008911 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008912
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008913 pw.println();
Dianne Hackborn287952c2010-09-22 22:34:31 -07008914 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07008915 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008916 if (mHeavyWeightProcess != null) {
8917 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
8918 }
8919
8920 return true;
8921 }
8922
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008923 /**
8924 * There are three ways to call this:
8925 * - no service specified: dump all the services
8926 * - a flattened component name that matched an existing service was specified as the
8927 * first arg: dump that one service
8928 * - the first arg isn't the flattened component name of an existing service:
8929 * dump all services whose component contains the first arg as a substring
8930 */
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008931 protected boolean dumpService(FileDescriptor fd, PrintWriter pw, String name, String[] args,
8932 int opti, boolean dumpAll) {
8933 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008934
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008935 if ("all".equals(name)) {
Dianne Hackborn14bfa392010-07-24 19:58:06 -07008936 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07008937 try {
8938 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
8939 for (UserInfo user : users) {
8940 for (ServiceRecord r1 : mServiceMap.getAllServices(user.id)) {
8941 services.add(r1);
8942 }
8943 }
8944 } catch (RemoteException re) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008945 }
8946 }
8947 } else {
8948 ComponentName componentName = name != null
8949 ? ComponentName.unflattenFromString(name) : null;
8950 int objectId = 0;
8951 if (componentName == null) {
8952 // Not a '/' separated full component name; maybe an object ID?
8953 try {
8954 objectId = Integer.parseInt(name, 16);
8955 name = null;
8956 componentName = null;
8957 } catch (RuntimeException e) {
8958 }
8959 }
8960
8961 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07008962 try {
8963 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
8964 for (UserInfo user : users) {
8965 for (ServiceRecord r1 : mServiceMap.getAllServices(user.id)) {
8966 if (componentName != null) {
8967 if (r1.name.equals(componentName)) {
8968 services.add(r1);
8969 }
8970 } else if (name != null) {
8971 if (r1.name.flattenToString().contains(name)) {
8972 services.add(r1);
8973 }
8974 } else if (System.identityHashCode(r1) == objectId) {
8975 services.add(r1);
8976 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008977 }
Dianne Hackborn14bfa392010-07-24 19:58:06 -07008978 }
Amith Yamasani742a6712011-05-04 14:49:28 -07008979 } catch (RemoteException re) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008980 }
8981 }
8982 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008983
8984 if (services.size() <= 0) {
8985 return false;
8986 }
8987
8988 boolean needSep = false;
8989 for (int i=0; i<services.size(); i++) {
8990 if (needSep) {
8991 pw.println();
8992 }
8993 needSep = true;
8994 dumpService("", fd, pw, services.get(i), args, dumpAll);
8995 }
8996 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008997 }
8998
8999 /**
9000 * Invokes IApplicationThread.dumpService() on the thread of the specified service if
9001 * there is a thread associated with the service.
9002 */
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009003 private void dumpService(String prefix, FileDescriptor fd, PrintWriter pw,
9004 final ServiceRecord r, String[] args, boolean dumpAll) {
9005 String innerPrefix = prefix + " ";
9006 synchronized (this) {
9007 pw.print(prefix); pw.print("SERVICE ");
9008 pw.print(r.shortName); pw.print(" ");
9009 pw.print(Integer.toHexString(System.identityHashCode(r)));
9010 pw.print(" pid=");
9011 if (r.app != null) pw.println(r.app.pid);
9012 else pw.println("(not running)");
9013 if (dumpAll) {
9014 r.dump(pw, innerPrefix);
9015 }
9016 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009017 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009018 pw.print(prefix); pw.println(" Client:");
9019 pw.flush();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009020 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009021 TransferPipe tp = new TransferPipe();
9022 try {
9023 r.app.thread.dumpService(tp.getWriteFd().getFileDescriptor(), r, args);
9024 tp.setBufferPrefix(prefix + " ");
9025 tp.go(fd);
9026 } finally {
9027 tp.kill();
9028 }
9029 } catch (IOException e) {
9030 pw.println(prefix + " Failure while dumping the service: " + e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009031 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009032 pw.println(prefix + " Got a RemoteException while dumping the service");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009033 }
9034 }
9035 }
9036
Marco Nelissen18cb2872011-11-15 11:19:53 -08009037 /**
9038 * There are three ways to call this:
9039 * - no provider specified: dump all the providers
9040 * - a flattened component name that matched an existing provider was specified as the
9041 * first arg: dump that one provider
9042 * - the first arg isn't the flattened component name of an existing provider:
9043 * dump all providers whose component contains the first arg as a substring
9044 */
9045 protected boolean dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9046 int opti, boolean dumpAll) {
Marco Nelissende7408c2012-02-08 14:57:38 -08009047 return mProviderMap.dumpProvider(fd, pw, name, args, opti, dumpAll);
Marco Nelissen18cb2872011-11-15 11:19:53 -08009048 }
9049
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009050 static class ItemMatcher {
9051 ArrayList<ComponentName> components;
9052 ArrayList<String> strings;
9053 ArrayList<Integer> objects;
9054 boolean all;
9055
9056 ItemMatcher() {
9057 all = true;
9058 }
9059
9060 void build(String name) {
9061 ComponentName componentName = ComponentName.unflattenFromString(name);
9062 if (componentName != null) {
9063 if (components == null) {
9064 components = new ArrayList<ComponentName>();
9065 }
9066 components.add(componentName);
9067 all = false;
9068 } else {
9069 int objectId = 0;
9070 // Not a '/' separated full component name; maybe an object ID?
9071 try {
9072 objectId = Integer.parseInt(name, 16);
9073 if (objects == null) {
9074 objects = new ArrayList<Integer>();
9075 }
9076 objects.add(objectId);
9077 all = false;
9078 } catch (RuntimeException e) {
9079 // Not an integer; just do string match.
9080 if (strings == null) {
9081 strings = new ArrayList<String>();
9082 }
9083 strings.add(name);
9084 all = false;
9085 }
9086 }
9087 }
9088
9089 int build(String[] args, int opti) {
9090 for (; opti<args.length; opti++) {
9091 String name = args[opti];
9092 if ("--".equals(name)) {
9093 return opti+1;
9094 }
9095 build(name);
9096 }
9097 return opti;
9098 }
9099
9100 boolean match(Object object, ComponentName comp) {
9101 if (all) {
9102 return true;
9103 }
9104 if (components != null) {
9105 for (int i=0; i<components.size(); i++) {
9106 if (components.get(i).equals(comp)) {
9107 return true;
9108 }
9109 }
9110 }
9111 if (objects != null) {
9112 for (int i=0; i<objects.size(); i++) {
9113 if (System.identityHashCode(object) == objects.get(i)) {
9114 return true;
9115 }
9116 }
9117 }
9118 if (strings != null) {
9119 String flat = comp.flattenToString();
9120 for (int i=0; i<strings.size(); i++) {
9121 if (flat.contains(strings.get(i))) {
9122 return true;
9123 }
9124 }
9125 }
9126 return false;
9127 }
9128 }
9129
Dianne Hackborn625ac272010-09-17 18:29:22 -07009130 /**
9131 * There are three things that cmd can be:
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009132 * - a flattened component name that matches an existing activity
Dianne Hackborn625ac272010-09-17 18:29:22 -07009133 * - the cmd arg isn't the flattened component name of an existing activity:
9134 * dump all activity whose component contains the cmd as a substring
9135 * - A hex number of the ActivityRecord object instance.
9136 */
9137 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9138 int opti, boolean dumpAll) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009139 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009140
9141 if ("all".equals(name)) {
9142 synchronized (this) {
9143 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009144 activities.add(r1);
9145 }
9146 }
Dianne Hackbornf9302322011-06-14 18:36:14 -07009147 } else if ("top".equals(name)) {
9148 synchronized (this) {
9149 final int N = mMainStack.mHistory.size();
9150 if (N > 0) {
9151 activities.add((ActivityRecord)mMainStack.mHistory.get(N-1));
9152 }
9153 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009154 } else {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009155 ItemMatcher matcher = new ItemMatcher();
9156 matcher.build(name);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009157
9158 synchronized (this) {
9159 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009160 if (matcher.match(r1, r1.intent.getComponent())) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009161 activities.add(r1);
9162 }
9163 }
9164 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009165 }
9166
9167 if (activities.size() <= 0) {
9168 return false;
9169 }
9170
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009171 String[] newArgs = new String[args.length - opti];
9172 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
9173
Dianne Hackborn30d71892010-12-11 10:37:55 -08009174 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009175 boolean needSep = false;
Dianne Hackborn30d71892010-12-11 10:37:55 -08009176 for (int i=activities.size()-1; i>=0; i--) {
9177 ActivityRecord r = (ActivityRecord)activities.get(i);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009178 if (needSep) {
9179 pw.println();
9180 }
9181 needSep = true;
9182 synchronized (this) {
9183 if (lastTask != r.task) {
9184 lastTask = r.task;
9185 pw.print("TASK "); pw.print(lastTask.affinity);
9186 pw.print(" id="); pw.println(lastTask.taskId);
9187 if (dumpAll) {
9188 lastTask.dump(pw, " ");
9189 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08009190 }
9191 }
9192 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009193 }
9194 return true;
9195 }
9196
9197 /**
9198 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
9199 * there is a thread associated with the activity.
9200 */
Dianne Hackborn30d71892010-12-11 10:37:55 -08009201 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009202 final ActivityRecord r, String[] args, boolean dumpAll) {
9203 String innerPrefix = prefix + " ";
Dianne Hackborn30d71892010-12-11 10:37:55 -08009204 synchronized (this) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009205 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
9206 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
9207 pw.print(" pid=");
Dianne Hackborn30d71892010-12-11 10:37:55 -08009208 if (r.app != null) pw.println(r.app.pid);
9209 else pw.println("(not running)");
9210 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009211 r.dump(pw, innerPrefix);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009212 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009213 }
9214 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009215 // flush anything that is already in the PrintWriter since the thread is going
9216 // to write to the file descriptor directly
9217 pw.flush();
Dianne Hackborn625ac272010-09-17 18:29:22 -07009218 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009219 TransferPipe tp = new TransferPipe();
9220 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009221 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9222 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009223 tp.go(fd);
9224 } finally {
9225 tp.kill();
9226 }
9227 } catch (IOException e) {
9228 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009229 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009230 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
Dianne Hackborn625ac272010-09-17 18:29:22 -07009231 }
9232 }
9233 }
9234
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009235 boolean dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009236 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009237 boolean needSep = false;
9238
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009239 pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009240 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009241 if (mRegisteredReceivers.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009242 boolean printed = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009243 Iterator it = mRegisteredReceivers.values().iterator();
9244 while (it.hasNext()) {
9245 ReceiverList r = (ReceiverList)it.next();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009246 if (dumpPackage != null && (r.app == null ||
9247 !dumpPackage.equals(r.app.info.packageName))) {
9248 continue;
9249 }
9250 if (!printed) {
9251 pw.println(" Registered Receivers:");
9252 needSep = true;
9253 printed = true;
9254 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009255 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009256 r.dump(pw, " ");
9257 }
9258 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009259
9260 if (mReceiverResolver.dump(pw, needSep ?
9261 "\n Receiver Resolver Table:" : " Receiver Resolver Table:",
9262 " ", dumpPackage, false)) {
9263 needSep = true;
9264 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009265 }
Christopher Tatef46723b2012-01-26 14:19:24 -08009266
9267 for (BroadcastQueue q : mBroadcastQueues) {
9268 needSep = q.dumpLocked(fd, pw, args, opti, dumpAll, dumpPackage, needSep);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009269 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009270
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009271 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009272
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009273 if (mStickyBroadcasts != null && dumpPackage == null) {
9274 if (needSep) {
9275 pw.println();
9276 }
9277 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009278 pw.println(" Sticky broadcasts:");
9279 StringBuilder sb = new StringBuilder(128);
9280 for (Map.Entry<String, ArrayList<Intent>> ent
9281 : mStickyBroadcasts.entrySet()) {
9282 pw.print(" * Sticky action "); pw.print(ent.getKey());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009283 if (dumpAll) {
9284 pw.println(":");
9285 ArrayList<Intent> intents = ent.getValue();
9286 final int N = intents.size();
9287 for (int i=0; i<N; i++) {
9288 sb.setLength(0);
9289 sb.append(" Intent: ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009290 intents.get(i).toShortString(sb, false, true, false, false);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009291 pw.println(sb.toString());
9292 Bundle bundle = intents.get(i).getExtras();
9293 if (bundle != null) {
9294 pw.print(" ");
9295 pw.println(bundle.toString());
9296 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009297 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009298 } else {
9299 pw.println("");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009300 }
9301 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009302 needSep = true;
9303 }
9304
9305 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009306 pw.println();
Christopher Tatef46723b2012-01-26 14:19:24 -08009307 for (BroadcastQueue queue : mBroadcastQueues) {
9308 pw.println(" mBroadcastsScheduled [" + queue.mQueueName + "]="
9309 + queue.mBroadcastsScheduled);
9310 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009311 pw.println(" mHandler:");
9312 mHandler.dump(new PrintWriterPrinter(pw), " ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009313 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009314 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009315
9316 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009317 }
9318
Marco Nelissen18cb2872011-11-15 11:19:53 -08009319 /**
9320 * Prints a list of ServiceRecords (dumpsys activity services)
9321 */
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009322 boolean dumpServicesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009323 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009324 boolean needSep = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009325
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009326 ItemMatcher matcher = new ItemMatcher();
9327 matcher.build(args, opti);
9328
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009329 pw.println("ACTIVITY MANAGER SERVICES (dumpsys activity services)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009330 try {
9331 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
9332 for (UserInfo user : users) {
9333 if (mServiceMap.getAllServices(user.id).size() > 0) {
9334 boolean printed = false;
9335 long nowReal = SystemClock.elapsedRealtime();
9336 Iterator<ServiceRecord> it = mServiceMap.getAllServices(
9337 user.id).iterator();
9338 needSep = false;
9339 while (it.hasNext()) {
9340 ServiceRecord r = it.next();
9341 if (!matcher.match(r, r.name)) {
9342 continue;
9343 }
9344 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9345 continue;
9346 }
9347 if (!printed) {
9348 pw.println(" Active services:");
9349 printed = true;
9350 }
9351 if (needSep) {
9352 pw.println();
9353 }
9354 pw.print(" * ");
9355 pw.println(r);
9356 if (dumpAll) {
9357 r.dump(pw, " ");
9358 needSep = true;
9359 } else {
9360 pw.print(" app=");
9361 pw.println(r.app);
9362 pw.print(" created=");
9363 TimeUtils.formatDuration(r.createTime, nowReal, pw);
9364 pw.print(" started=");
9365 pw.print(r.startRequested);
9366 pw.print(" connections=");
9367 pw.println(r.connections.size());
9368 if (r.connections.size() > 0) {
9369 pw.println(" Connections:");
9370 for (ArrayList<ConnectionRecord> clist : r.connections.values()) {
9371 for (int i = 0; i < clist.size(); i++) {
9372 ConnectionRecord conn = clist.get(i);
9373 pw.print(" ");
9374 pw.print(conn.binding.intent.intent.getIntent()
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009375 .toShortString(false, false, false, false));
Amith Yamasani742a6712011-05-04 14:49:28 -07009376 pw.print(" -> ");
9377 ProcessRecord proc = conn.binding.client;
9378 pw.println(proc != null ? proc.toShortString() : "null");
9379 }
9380 }
Dianne Hackborn8ec8d412011-11-14 18:27:24 -08009381 }
9382 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009383 if (dumpClient && r.app != null && r.app.thread != null) {
9384 pw.println(" Client:");
9385 pw.flush();
9386 try {
9387 TransferPipe tp = new TransferPipe();
9388 try {
9389 r.app.thread.dumpService(tp.getWriteFd().getFileDescriptor(),
9390 r, args);
9391 tp.setBufferPrefix(" ");
9392 // Short timeout, since blocking here can
9393 // deadlock with the application.
9394 tp.go(fd, 2000);
9395 } finally {
9396 tp.kill();
9397 }
9398 } catch (IOException e) {
9399 pw.println(" Failure while dumping the service: " + e);
9400 } catch (RemoteException e) {
9401 pw.println(" Got a RemoteException while dumping the service");
9402 }
9403 needSep = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009404 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009405 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009406 needSep = printed;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009407 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009408 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009409 } catch (RemoteException re) {
9410
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009411 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009412
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009413 if (mPendingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009414 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009415 for (int i=0; i<mPendingServices.size(); i++) {
9416 ServiceRecord r = mPendingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009417 if (!matcher.match(r, r.name)) {
9418 continue;
9419 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009420 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9421 continue;
9422 }
9423 if (!printed) {
9424 if (needSep) pw.println(" ");
9425 needSep = true;
9426 pw.println(" Pending services:");
9427 printed = true;
9428 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009429 pw.print(" * Pending "); pw.println(r);
9430 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009431 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009432 needSep = true;
9433 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009434
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009435 if (mRestartingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009436 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009437 for (int i=0; i<mRestartingServices.size(); i++) {
9438 ServiceRecord r = mRestartingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009439 if (!matcher.match(r, r.name)) {
9440 continue;
9441 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009442 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9443 continue;
9444 }
9445 if (!printed) {
9446 if (needSep) pw.println(" ");
9447 needSep = true;
9448 pw.println(" Restarting services:");
9449 printed = true;
9450 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009451 pw.print(" * Restarting "); pw.println(r);
9452 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009453 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009454 needSep = true;
9455 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009456
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009457 if (mStoppingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009458 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009459 for (int i=0; i<mStoppingServices.size(); i++) {
9460 ServiceRecord r = mStoppingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009461 if (!matcher.match(r, r.name)) {
9462 continue;
9463 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009464 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9465 continue;
9466 }
9467 if (!printed) {
9468 if (needSep) pw.println(" ");
9469 needSep = true;
9470 pw.println(" Stopping services:");
9471 printed = true;
9472 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009473 pw.print(" * Stopping "); pw.println(r);
9474 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009475 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009476 needSep = true;
9477 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009478
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009479 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009480 if (mServiceConnections.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009481 boolean printed = false;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009482 Iterator<ArrayList<ConnectionRecord>> it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009483 = mServiceConnections.values().iterator();
9484 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009485 ArrayList<ConnectionRecord> r = it.next();
9486 for (int i=0; i<r.size(); i++) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009487 ConnectionRecord cr = r.get(i);
9488 if (!matcher.match(cr.binding.service, cr.binding.service.name)) {
9489 continue;
9490 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009491 if (dumpPackage != null && (cr.binding.client == null
9492 || !dumpPackage.equals(cr.binding.client.info.packageName))) {
9493 continue;
9494 }
9495 if (!printed) {
9496 if (needSep) pw.println(" ");
9497 needSep = true;
9498 pw.println(" Connection bindings to services:");
9499 printed = true;
9500 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009501 pw.print(" * "); pw.println(cr);
9502 cr.dump(pw, " ");
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009503 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009504 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009505 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009506 }
9507 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009508
9509 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009510 }
9511
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009512 boolean dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009513 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07009514 boolean needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009515
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009516 ItemMatcher matcher = new ItemMatcher();
9517 matcher.build(args, opti);
9518
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009519 pw.println("ACTIVITY MANAGER CONTENT PROVIDERS (dumpsys activity providers)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009520
9521 mProviderMap.dumpProvidersLocked(pw, dumpAll);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009522
9523 if (mLaunchingProviders.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009524 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009525 for (int i=mLaunchingProviders.size()-1; i>=0; i--) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009526 ContentProviderRecord r = mLaunchingProviders.get(i);
9527 if (dumpPackage != null && !dumpPackage.equals(r.name.getPackageName())) {
9528 continue;
9529 }
9530 if (!printed) {
9531 if (needSep) pw.println(" ");
9532 needSep = true;
9533 pw.println(" Launching content providers:");
9534 printed = true;
9535 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009536 pw.print(" Launching #"); pw.print(i); pw.print(": ");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009537 pw.println(r);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009538 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009539 }
9540
9541 if (mGrantedUriPermissions.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009542 if (needSep) pw.println();
9543 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009544 pw.println("Granted Uri Permissions:");
9545 for (int i=0; i<mGrantedUriPermissions.size(); i++) {
9546 int uid = mGrantedUriPermissions.keyAt(i);
9547 HashMap<Uri, UriPermission> perms
9548 = mGrantedUriPermissions.valueAt(i);
9549 pw.print(" * UID "); pw.print(uid);
9550 pw.println(" holds:");
9551 for (UriPermission perm : perms.values()) {
9552 pw.print(" "); pw.println(perm);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009553 if (dumpAll) {
9554 perm.dump(pw, " ");
9555 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009556 }
9557 }
9558 needSep = true;
9559 }
9560
9561 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009562 }
9563
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009564 boolean dumpPendingIntentsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009565 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009566 boolean needSep = false;
9567
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009568 if (mIntentSenderRecords.size() > 0) {
9569 boolean printed = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009570 Iterator<WeakReference<PendingIntentRecord>> it
9571 = mIntentSenderRecords.values().iterator();
9572 while (it.hasNext()) {
9573 WeakReference<PendingIntentRecord> ref = it.next();
9574 PendingIntentRecord rec = ref != null ? ref.get(): null;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009575 if (dumpPackage != null && (rec == null
9576 || !dumpPackage.equals(rec.key.packageName))) {
9577 continue;
9578 }
9579 if (!printed) {
9580 pw.println("ACTIVITY MANAGER PENDING INTENTS (dumpsys activity intents)");
9581 printed = true;
9582 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009583 needSep = true;
9584 if (rec != null) {
9585 pw.print(" * "); pw.println(rec);
9586 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009587 rec.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009588 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009589 } else {
9590 pw.print(" * "); pw.println(ref);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009591 }
9592 }
9593 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009594
9595 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009596 }
9597
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009598 private static final void dumpHistoryList(FileDescriptor fd, PrintWriter pw, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009599 String prefix, String label, boolean complete, boolean brief, boolean client,
9600 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009601 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009602 boolean needNL = false;
9603 final String innerPrefix = prefix + " ";
9604 final String[] args = new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009605 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009606 final ActivityRecord r = (ActivityRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009607 if (dumpPackage != null && !dumpPackage.equals(r.packageName)) {
9608 continue;
9609 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07009610 final boolean full = !brief && (complete || !r.isInHistory());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009611 if (needNL) {
9612 pw.println(" ");
9613 needNL = false;
9614 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009615 if (lastTask != r.task) {
9616 lastTask = r.task;
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009617 pw.print(prefix);
9618 pw.print(full ? "* " : " ");
9619 pw.println(lastTask);
9620 if (full) {
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009621 lastTask.dump(pw, prefix + " ");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009622 } else if (complete) {
9623 // Complete + brief == give a summary. Isn't that obvious?!?
9624 if (lastTask.intent != null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009625 pw.print(prefix); pw.print(" ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009626 pw.println(lastTask.intent.toInsecureStringWithClip());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009627 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009628 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009629 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009630 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label);
9631 pw.print(" #"); pw.print(i); pw.print(": ");
9632 pw.println(r);
9633 if (full) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009634 r.dump(pw, innerPrefix);
9635 } else if (complete) {
9636 // Complete + brief == give a summary. Isn't that obvious?!?
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009637 pw.print(innerPrefix); pw.println(r.intent.toInsecureString());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009638 if (r.app != null) {
9639 pw.print(innerPrefix); pw.println(r.app);
9640 }
9641 }
9642 if (client && r.app != null && r.app.thread != null) {
9643 // flush anything that is already in the PrintWriter since the thread is going
9644 // to write to the file descriptor directly
9645 pw.flush();
9646 try {
9647 TransferPipe tp = new TransferPipe();
9648 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009649 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9650 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009651 // Short timeout, since blocking here can
9652 // deadlock with the application.
9653 tp.go(fd, 2000);
9654 } finally {
9655 tp.kill();
9656 }
9657 } catch (IOException e) {
9658 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
9659 } catch (RemoteException e) {
9660 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
9661 }
9662 needNL = true;
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009663 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009664 }
9665 }
9666
Dianne Hackborn09c916b2009-12-08 14:50:51 -08009667 private static String buildOomTag(String prefix, String space, int val, int base) {
9668 if (val == base) {
9669 if (space == null) return prefix;
9670 return prefix + " ";
9671 }
9672 return prefix + "+" + Integer.toString(val-base);
9673 }
9674
9675 private static final int dumpProcessList(PrintWriter pw,
9676 ActivityManagerService service, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009677 String prefix, String normalLabel, String persistentLabel,
9678 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009679 int numPers = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07009680 final int N = list.size()-1;
9681 for (int i=N; i>=0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009682 ProcessRecord r = (ProcessRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009683 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9684 continue;
9685 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009686 pw.println(String.format("%s%s #%2d: %s",
9687 prefix, (r.persistent ? persistentLabel : normalLabel),
9688 i, r.toString()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009689 if (r.persistent) {
9690 numPers++;
9691 }
9692 }
9693 return numPers;
9694 }
9695
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009696 private static final boolean dumpProcessOomList(PrintWriter pw,
Dianne Hackborn905577f2011-09-07 18:31:28 -07009697 ActivityManagerService service, List<ProcessRecord> origList,
Dianne Hackborn287952c2010-09-22 22:34:31 -07009698 String prefix, String normalLabel, String persistentLabel,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009699 boolean inclDetails, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009700
Dianne Hackborn905577f2011-09-07 18:31:28 -07009701 ArrayList<Pair<ProcessRecord, Integer>> list
9702 = new ArrayList<Pair<ProcessRecord, Integer>>(origList.size());
9703 for (int i=0; i<origList.size(); i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009704 ProcessRecord r = origList.get(i);
9705 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9706 continue;
9707 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07009708 list.add(new Pair<ProcessRecord, Integer>(origList.get(i), i));
9709 }
9710
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009711 if (list.size() <= 0) {
9712 return false;
9713 }
9714
Dianne Hackborn905577f2011-09-07 18:31:28 -07009715 Comparator<Pair<ProcessRecord, Integer>> comparator
9716 = new Comparator<Pair<ProcessRecord, Integer>>() {
9717 @Override
9718 public int compare(Pair<ProcessRecord, Integer> object1,
9719 Pair<ProcessRecord, Integer> object2) {
9720 if (object1.first.setAdj != object2.first.setAdj) {
9721 return object1.first.setAdj > object2.first.setAdj ? -1 : 1;
9722 }
9723 if (object1.second.intValue() != object2.second.intValue()) {
9724 return object1.second.intValue() > object2.second.intValue() ? -1 : 1;
9725 }
9726 return 0;
9727 }
9728 };
9729
9730 Collections.sort(list, comparator);
9731
Dianne Hackborn287952c2010-09-22 22:34:31 -07009732 final long curRealtime = SystemClock.elapsedRealtime();
9733 final long realtimeSince = curRealtime - service.mLastPowerCheckRealtime;
9734 final long curUptime = SystemClock.uptimeMillis();
9735 final long uptimeSince = curUptime - service.mLastPowerCheckUptime;
9736
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009737 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07009738 ProcessRecord r = list.get(i).first;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009739 String oomAdj;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009740 if (r.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07009741 oomAdj = buildOomTag("bak", " ", r.setAdj, ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009742 } else if (r.setAdj >= ProcessList.SERVICE_B_ADJ) {
9743 oomAdj = buildOomTag("svcb ", null, r.setAdj, ProcessList.SERVICE_B_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009744 } else if (r.setAdj >= ProcessList.PREVIOUS_APP_ADJ) {
9745 oomAdj = buildOomTag("prev ", null, r.setAdj, ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009746 } else if (r.setAdj >= ProcessList.HOME_APP_ADJ) {
9747 oomAdj = buildOomTag("home ", null, r.setAdj, ProcessList.HOME_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009748 } else if (r.setAdj >= ProcessList.SERVICE_ADJ) {
9749 oomAdj = buildOomTag("svc ", null, r.setAdj, ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009750 } else if (r.setAdj >= ProcessList.BACKUP_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08009751 oomAdj = buildOomTag("bkup ", null, r.setAdj, ProcessList.BACKUP_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009752 } else if (r.setAdj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
9753 oomAdj = buildOomTag("hvy ", null, r.setAdj, ProcessList.HEAVY_WEIGHT_APP_ADJ);
9754 } else if (r.setAdj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
9755 oomAdj = buildOomTag("prcp ", null, r.setAdj, ProcessList.PERCEPTIBLE_APP_ADJ);
9756 } else if (r.setAdj >= ProcessList.VISIBLE_APP_ADJ) {
9757 oomAdj = buildOomTag("vis ", null, r.setAdj, ProcessList.VISIBLE_APP_ADJ);
9758 } else if (r.setAdj >= ProcessList.FOREGROUND_APP_ADJ) {
9759 oomAdj = buildOomTag("fore ", null, r.setAdj, ProcessList.FOREGROUND_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009760 } else if (r.setAdj >= ProcessList.PERSISTENT_PROC_ADJ) {
9761 oomAdj = buildOomTag("pers ", null, r.setAdj, ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009762 } else if (r.setAdj >= ProcessList.SYSTEM_ADJ) {
9763 oomAdj = buildOomTag("sys ", null, r.setAdj, ProcessList.SYSTEM_ADJ);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009764 } else {
9765 oomAdj = Integer.toString(r.setAdj);
9766 }
9767 String schedGroup;
9768 switch (r.setSchedGroup) {
9769 case Process.THREAD_GROUP_BG_NONINTERACTIVE:
9770 schedGroup = "B";
9771 break;
9772 case Process.THREAD_GROUP_DEFAULT:
9773 schedGroup = "F";
9774 break;
9775 default:
9776 schedGroup = Integer.toString(r.setSchedGroup);
9777 break;
9778 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07009779 String foreground;
9780 if (r.foregroundActivities) {
9781 foreground = "A";
9782 } else if (r.foregroundServices) {
9783 foreground = "S";
9784 } else {
9785 foreground = " ";
9786 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07009787 pw.println(String.format("%s%s #%2d: adj=%s/%s%s trm=%2d %s (%s)",
Dianne Hackborn287952c2010-09-22 22:34:31 -07009788 prefix, (r.persistent ? persistentLabel : normalLabel),
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009789 (origList.size()-1)-list.get(i).second, oomAdj, schedGroup,
9790 foreground, r.trimMemoryLevel, r.toShortString(), r.adjType));
Dianne Hackborn287952c2010-09-22 22:34:31 -07009791 if (r.adjSource != null || r.adjTarget != null) {
9792 pw.print(prefix);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009793 pw.print(" ");
Dianne Hackborn287952c2010-09-22 22:34:31 -07009794 if (r.adjTarget instanceof ComponentName) {
9795 pw.print(((ComponentName)r.adjTarget).flattenToShortString());
9796 } else if (r.adjTarget != null) {
9797 pw.print(r.adjTarget.toString());
9798 } else {
9799 pw.print("{null}");
9800 }
9801 pw.print("<=");
9802 if (r.adjSource instanceof ProcessRecord) {
9803 pw.print("Proc{");
9804 pw.print(((ProcessRecord)r.adjSource).toShortString());
9805 pw.println("}");
9806 } else if (r.adjSource != null) {
9807 pw.println(r.adjSource.toString());
9808 } else {
9809 pw.println("{null}");
9810 }
9811 }
9812 if (inclDetails) {
9813 pw.print(prefix);
9814 pw.print(" ");
9815 pw.print("oom: max="); pw.print(r.maxAdj);
9816 pw.print(" hidden="); pw.print(r.hiddenAdj);
9817 pw.print(" curRaw="); pw.print(r.curRawAdj);
9818 pw.print(" setRaw="); pw.print(r.setRawAdj);
9819 pw.print(" cur="); pw.print(r.curAdj);
9820 pw.print(" set="); pw.println(r.setAdj);
9821 pw.print(prefix);
9822 pw.print(" ");
9823 pw.print("keeping="); pw.print(r.keeping);
9824 pw.print(" hidden="); pw.print(r.hidden);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009825 pw.print(" empty="); pw.print(r.empty);
9826 pw.print(" hasAboveClient="); pw.println(r.hasAboveClient);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009827
9828 if (!r.keeping) {
9829 if (r.lastWakeTime != 0) {
9830 long wtime;
9831 BatteryStatsImpl stats = service.mBatteryStatsService.getActiveStatistics();
9832 synchronized (stats) {
9833 wtime = stats.getProcessWakeTime(r.info.uid,
9834 r.pid, curRealtime);
9835 }
9836 long timeUsed = wtime - r.lastWakeTime;
9837 pw.print(prefix);
9838 pw.print(" ");
9839 pw.print("keep awake over ");
9840 TimeUtils.formatDuration(realtimeSince, pw);
9841 pw.print(" used ");
9842 TimeUtils.formatDuration(timeUsed, pw);
9843 pw.print(" (");
9844 pw.print((timeUsed*100)/realtimeSince);
9845 pw.println("%)");
9846 }
9847 if (r.lastCpuTime != 0) {
9848 long timeUsed = r.curCpuTime - r.lastCpuTime;
9849 pw.print(prefix);
9850 pw.print(" ");
9851 pw.print("run cpu over ");
9852 TimeUtils.formatDuration(uptimeSince, pw);
9853 pw.print(" used ");
9854 TimeUtils.formatDuration(timeUsed, pw);
9855 pw.print(" (");
9856 pw.print((timeUsed*100)/uptimeSince);
9857 pw.println("%)");
9858 }
9859 }
9860 }
9861 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009862 return true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009863 }
9864
Dianne Hackbornb437e092011-08-05 17:50:29 -07009865 ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, String[] args) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009866 ArrayList<ProcessRecord> procs;
9867 synchronized (this) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009868 if (args != null && args.length > start
9869 && args[start].charAt(0) != '-') {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009870 procs = new ArrayList<ProcessRecord>();
9871 int pid = -1;
9872 try {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009873 pid = Integer.parseInt(args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009874 } catch (NumberFormatException e) {
9875
9876 }
9877 for (int i=mLruProcesses.size()-1; i>=0; i--) {
9878 ProcessRecord proc = mLruProcesses.get(i);
9879 if (proc.pid == pid) {
9880 procs.add(proc);
Dianne Hackbornb437e092011-08-05 17:50:29 -07009881 } else if (proc.processName.equals(args[start])) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009882 procs.add(proc);
9883 }
9884 }
9885 if (procs.size() <= 0) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009886 pw.println("No process found for: " + args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009887 return null;
9888 }
9889 } else {
9890 procs = new ArrayList<ProcessRecord>(mLruProcesses);
9891 }
9892 }
9893 return procs;
9894 }
9895
9896 final void dumpGraphicsHardwareUsage(FileDescriptor fd,
9897 PrintWriter pw, String[] args) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009898 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009899 if (procs == null) {
9900 return;
9901 }
9902
9903 long uptime = SystemClock.uptimeMillis();
9904 long realtime = SystemClock.elapsedRealtime();
9905 pw.println("Applications Graphics Acceleration Info:");
9906 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
9907
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009908 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
9909 ProcessRecord r = procs.get(i);
Chet Haase9c1e23b2011-03-24 10:51:31 -07009910 if (r.thread != null) {
9911 pw.println("\n** Graphics info for pid " + r.pid + " [" + r.processName + "] **");
9912 pw.flush();
9913 try {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009914 TransferPipe tp = new TransferPipe();
9915 try {
9916 r.thread.dumpGfxInfo(tp.getWriteFd().getFileDescriptor(), args);
9917 tp.go(fd);
9918 } finally {
9919 tp.kill();
9920 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009921 } catch (IOException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009922 pw.println("Failure while dumping the app: " + r);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009923 pw.flush();
Chet Haase9c1e23b2011-03-24 10:51:31 -07009924 } catch (RemoteException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009925 pw.println("Got a RemoteException while dumping the app " + r);
Chet Haase9c1e23b2011-03-24 10:51:31 -07009926 pw.flush();
9927 }
9928 }
9929 }
Chet Haase9c1e23b2011-03-24 10:51:31 -07009930 }
9931
Jeff Brown6754ba22011-12-14 20:20:01 -08009932 final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) {
9933 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
9934 if (procs == null) {
9935 return;
9936 }
9937
9938 pw.println("Applications Database Info:");
9939
9940 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
9941 ProcessRecord r = procs.get(i);
9942 if (r.thread != null) {
9943 pw.println("\n** Database info for pid " + r.pid + " [" + r.processName + "] **");
9944 pw.flush();
9945 try {
9946 TransferPipe tp = new TransferPipe();
9947 try {
9948 r.thread.dumpDbInfo(tp.getWriteFd().getFileDescriptor(), args);
9949 tp.go(fd);
9950 } finally {
9951 tp.kill();
9952 }
9953 } catch (IOException e) {
9954 pw.println("Failure while dumping the app: " + r);
9955 pw.flush();
9956 } catch (RemoteException e) {
9957 pw.println("Got a RemoteException while dumping the app " + r);
9958 pw.flush();
9959 }
9960 }
9961 }
9962 }
9963
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009964 final static class MemItem {
9965 final String label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009966 final String shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009967 final long pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009968 final int id;
Dianne Hackborna4bacb82011-08-24 15:12:38 -07009969 ArrayList<MemItem> subitems;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009970
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009971 public MemItem(String _label, String _shortLabel, long _pss, int _id) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009972 label = _label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009973 shortLabel = _shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009974 pss = _pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009975 id = _id;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009976 }
9977 }
9978
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009979 static final void dumpMemItems(PrintWriter pw, String prefix, ArrayList<MemItem> items,
Dianne Hackbornb437e092011-08-05 17:50:29 -07009980 boolean sort) {
9981 if (sort) {
9982 Collections.sort(items, new Comparator<MemItem>() {
9983 @Override
9984 public int compare(MemItem lhs, MemItem rhs) {
9985 if (lhs.pss < rhs.pss) {
9986 return 1;
9987 } else if (lhs.pss > rhs.pss) {
9988 return -1;
9989 }
9990 return 0;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009991 }
Dianne Hackbornb437e092011-08-05 17:50:29 -07009992 });
9993 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009994
9995 for (int i=0; i<items.size(); i++) {
9996 MemItem mi = items.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009997 pw.print(prefix); pw.printf("%7d kB: ", mi.pss); pw.println(mi.label);
Dianne Hackborna4bacb82011-08-24 15:12:38 -07009998 if (mi.subitems != null) {
9999 dumpMemItems(pw, prefix + " ", mi.subitems, true);
10000 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010001 }
10002 }
10003
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010004 // These are in KB.
10005 static final long[] DUMP_MEM_BUCKETS = new long[] {
10006 5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024,
10007 120*1024, 160*1024, 200*1024,
10008 250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024,
10009 1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024
10010 };
10011
Dianne Hackborn672342c2011-11-29 11:29:02 -080010012 static final void appendMemBucket(StringBuilder out, long memKB, String label,
10013 boolean stackLike) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010014 int start = label.lastIndexOf('.');
10015 if (start >= 0) start++;
10016 else start = 0;
10017 int end = label.length();
10018 for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) {
10019 if (DUMP_MEM_BUCKETS[i] >= memKB) {
10020 long bucket = DUMP_MEM_BUCKETS[i]/1024;
10021 out.append(bucket);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010022 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010023 out.append(label, start, end);
10024 return;
10025 }
10026 }
10027 out.append(memKB/1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010028 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010029 out.append(label, start, end);
10030 }
10031
10032 static final int[] DUMP_MEM_OOM_ADJ = new int[] {
10033 ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ, ProcessList.FOREGROUND_APP_ADJ,
10034 ProcessList.VISIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ,
10035 ProcessList.BACKUP_APP_ADJ, ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ,
10036 ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.HIDDEN_APP_MAX_ADJ
10037 };
10038 static final String[] DUMP_MEM_OOM_LABEL = new String[] {
10039 "System", "Persistent", "Foreground",
10040 "Visible", "Perceptible", "Heavy Weight",
10041 "Backup", "A Services", "Home", "Previous",
10042 "B Services", "Background"
10043 };
10044
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010045 final void dumpApplicationMemoryUsage(FileDescriptor fd,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010046 PrintWriter pw, String prefix, String[] args, boolean brief,
Dianne Hackborn672342c2011-11-29 11:29:02 -080010047 PrintWriter categoryPw, StringBuilder outTag, StringBuilder outStack) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010048 boolean dumpAll = false;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010049 boolean oomOnly = false;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010050
10051 int opti = 0;
10052 while (opti < args.length) {
10053 String opt = args[opti];
10054 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
10055 break;
10056 }
10057 opti++;
10058 if ("-a".equals(opt)) {
10059 dumpAll = true;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010060 } else if ("--oom".equals(opt)) {
10061 oomOnly = true;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010062 } else if ("-h".equals(opt)) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010063 pw.println("meminfo dump options: [-a] [--oom] [process]");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010064 pw.println(" -a: include all available information for each process.");
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010065 pw.println(" --oom: only show processes organized by oom adj.");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010066 pw.println("If [process] is specified it can be the name or ");
10067 pw.println("pid of a specific process to dump.");
10068 return;
10069 } else {
10070 pw.println("Unknown argument: " + opt + "; use -h for help");
10071 }
10072 }
10073
10074 ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010075 if (procs == null) {
10076 return;
10077 }
10078
Dianne Hackborn6447ca32009-04-07 19:50:08 -070010079 final boolean isCheckinRequest = scanArgs(args, "--checkin");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010080 long uptime = SystemClock.uptimeMillis();
10081 long realtime = SystemClock.elapsedRealtime();
Dianne Hackbornb437e092011-08-05 17:50:29 -070010082
10083 if (procs.size() == 1 || isCheckinRequest) {
10084 dumpAll = true;
10085 }
10086
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010087 if (isCheckinRequest) {
10088 // short checkin version
10089 pw.println(uptime + "," + realtime);
10090 pw.flush();
10091 } else {
10092 pw.println("Applications Memory Usage (kB):");
10093 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10094 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010095
Dianne Hackbornb437e092011-08-05 17:50:29 -070010096 String[] innerArgs = new String[args.length-opti];
10097 System.arraycopy(args, opti, innerArgs, 0, args.length-opti);
10098
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010099 ArrayList<MemItem> procMems = new ArrayList<MemItem>();
10100 long nativePss=0, dalvikPss=0, otherPss=0;
10101 long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
10102
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010103 long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length];
10104 ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[])
10105 new ArrayList[DUMP_MEM_OOM_LABEL.length];
Dianne Hackbornb437e092011-08-05 17:50:29 -070010106
10107 long totalPss = 0;
10108
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010109 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10110 ProcessRecord r = procs.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010111 if (r.thread != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010112 if (!isCheckinRequest && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010113 pw.println("\n** MEMINFO in pid " + r.pid + " [" + r.processName + "] **");
10114 pw.flush();
10115 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010116 Debug.MemoryInfo mi = null;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010117 if (dumpAll) {
10118 try {
10119 mi = r.thread.dumpMemInfo(fd, isCheckinRequest, dumpAll, innerArgs);
10120 } catch (RemoteException e) {
10121 if (!isCheckinRequest) {
10122 pw.println("Got RemoteException!");
10123 pw.flush();
10124 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010125 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010126 } else {
10127 mi = new Debug.MemoryInfo();
10128 Debug.getMemoryInfo(r.pid, mi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010129 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010130
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010131 if (!isCheckinRequest && mi != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010132 long myTotalPss = mi.getTotalPss();
10133 totalPss += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010134 MemItem pssItem = new MemItem(r.processName + " (pid " + r.pid + ")",
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010135 r.processName, myTotalPss, 0);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010136 procMems.add(pssItem);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010137
10138 nativePss += mi.nativePss;
10139 dalvikPss += mi.dalvikPss;
10140 otherPss += mi.otherPss;
10141 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
10142 long mem = mi.getOtherPss(j);
10143 miscPss[j] += mem;
10144 otherPss -= mem;
10145 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010146
10147 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010148 if (r.setAdj <= DUMP_MEM_OOM_ADJ[oomIndex]
10149 || oomIndex == (oomPss.length-1)) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010150 oomPss[oomIndex] += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010151 if (oomProcs[oomIndex] == null) {
10152 oomProcs[oomIndex] = new ArrayList<MemItem>();
10153 }
10154 oomProcs[oomIndex].add(pssItem);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010155 break;
10156 }
10157 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010158 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010159 }
10160 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010161
10162 if (!isCheckinRequest && procs.size() > 1) {
10163 ArrayList<MemItem> catMems = new ArrayList<MemItem>();
10164
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010165 catMems.add(new MemItem("Native", "Native", nativePss, -1));
10166 catMems.add(new MemItem("Dalvik", "Dalvik", dalvikPss, -2));
10167 catMems.add(new MemItem("Unknown", "Unknown", otherPss, -3));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010168 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010169 String label = Debug.MemoryInfo.getOtherLabel(j);
10170 catMems.add(new MemItem(label, label, miscPss[j], j));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010171 }
10172
Dianne Hackbornb437e092011-08-05 17:50:29 -070010173 ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
10174 for (int j=0; j<oomPss.length; j++) {
10175 if (oomPss[j] != 0) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010176 String label = DUMP_MEM_OOM_LABEL[j];
10177 MemItem item = new MemItem(label, label, oomPss[j],
10178 DUMP_MEM_OOM_ADJ[j]);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010179 item.subitems = oomProcs[j];
10180 oomMems.add(item);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010181 }
10182 }
10183
Dianne Hackborn672342c2011-11-29 11:29:02 -080010184 if (outTag != null || outStack != null) {
10185 if (outTag != null) {
10186 appendMemBucket(outTag, totalPss, "total", false);
10187 }
10188 if (outStack != null) {
10189 appendMemBucket(outStack, totalPss, "total", true);
10190 }
10191 boolean firstLine = true;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010192 for (int i=0; i<oomMems.size(); i++) {
10193 MemItem miCat = oomMems.get(i);
10194 if (miCat.subitems == null || miCat.subitems.size() < 1) {
10195 continue;
10196 }
10197 if (miCat.id < ProcessList.SERVICE_ADJ
10198 || miCat.id == ProcessList.HOME_APP_ADJ
10199 || miCat.id == ProcessList.PREVIOUS_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010200 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10201 outTag.append(" / ");
10202 }
10203 if (outStack != null) {
10204 if (miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10205 if (firstLine) {
10206 outStack.append(":");
10207 firstLine = false;
10208 }
10209 outStack.append("\n\t at ");
10210 } else {
10211 outStack.append("$");
10212 }
10213 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010214 for (int j=0; j<miCat.subitems.size(); j++) {
10215 MemItem mi = miCat.subitems.get(j);
10216 if (j > 0) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010217 if (outTag != null) {
10218 outTag.append(" ");
10219 }
10220 if (outStack != null) {
10221 outStack.append("$");
10222 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010223 }
Dianne Hackborn672342c2011-11-29 11:29:02 -080010224 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10225 appendMemBucket(outTag, mi.pss, mi.shortLabel, false);
10226 }
10227 if (outStack != null) {
10228 appendMemBucket(outStack, mi.pss, mi.shortLabel, true);
10229 }
10230 }
10231 if (outStack != null && miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10232 outStack.append("(");
10233 for (int k=0; k<DUMP_MEM_OOM_ADJ.length; k++) {
10234 if (DUMP_MEM_OOM_ADJ[k] == miCat.id) {
10235 outStack.append(DUMP_MEM_OOM_LABEL[k]);
10236 outStack.append(":");
10237 outStack.append(DUMP_MEM_OOM_ADJ[k]);
10238 }
10239 }
10240 outStack.append(")");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010241 }
10242 }
10243 }
10244 }
10245
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010246 if (!brief && !oomOnly) {
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010247 pw.println();
10248 pw.println("Total PSS by process:");
10249 dumpMemItems(pw, " ", procMems, true);
10250 pw.println();
10251 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010252 pw.println("Total PSS by OOM adjustment:");
10253 dumpMemItems(pw, " ", oomMems, false);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010254 if (!oomOnly) {
10255 PrintWriter out = categoryPw != null ? categoryPw : pw;
10256 out.println();
10257 out.println("Total PSS by category:");
10258 dumpMemItems(out, " ", catMems, true);
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010259 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010260 pw.println();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010261 pw.print("Total PSS: "); pw.print(totalPss); pw.println(" kB");
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010262 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010263 }
10264
10265 /**
10266 * Searches array of arguments for the specified string
10267 * @param args array of argument strings
10268 * @param value value to search for
10269 * @return true if the value is contained in the array
10270 */
10271 private static boolean scanArgs(String[] args, String value) {
10272 if (args != null) {
10273 for (String arg : args) {
10274 if (value.equals(arg)) {
10275 return true;
10276 }
10277 }
10278 }
10279 return false;
10280 }
10281
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010282 private final void killServicesLocked(ProcessRecord app,
10283 boolean allowRestart) {
10284 // Report disconnected services.
10285 if (false) {
10286 // XXX we are letting the client link to the service for
10287 // death notifications.
10288 if (app.services.size() > 0) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010289 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010290 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010291 ServiceRecord r = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010292 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010293 Iterator<ArrayList<ConnectionRecord>> jt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010294 = r.connections.values().iterator();
10295 while (jt.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010296 ArrayList<ConnectionRecord> cl = jt.next();
10297 for (int i=0; i<cl.size(); i++) {
10298 ConnectionRecord c = cl.get(i);
10299 if (c.binding.client != app) {
10300 try {
10301 //c.conn.connected(r.className, null);
10302 } catch (Exception e) {
10303 // todo: this should be asynchronous!
10304 Slog.w(TAG, "Exception thrown disconnected servce "
10305 + r.shortName
10306 + " from app " + app.processName, e);
10307 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010308 }
10309 }
10310 }
10311 }
10312 }
10313 }
10314 }
10315
10316 // Clean up any connections this application has to other services.
10317 if (app.connections.size() > 0) {
10318 Iterator<ConnectionRecord> it = app.connections.iterator();
10319 while (it.hasNext()) {
10320 ConnectionRecord r = it.next();
10321 removeConnectionLocked(r, app, null);
10322 }
10323 }
10324 app.connections.clear();
10325
10326 if (app.services.size() != 0) {
10327 // Any services running in the application need to be placed
10328 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -070010329 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010330 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010331 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010332 synchronized (sr.stats.getBatteryStats()) {
10333 sr.stats.stopLaunchedLocked();
10334 }
10335 sr.app = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010336 sr.isolatedProc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010337 sr.executeNesting = 0;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010338 if (mStoppingServices.remove(sr)) {
10339 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
10340 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010341
10342 boolean hasClients = sr.bindings.size() > 0;
10343 if (hasClients) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010344 Iterator<IntentBindRecord> bindings
10345 = sr.bindings.values().iterator();
10346 while (bindings.hasNext()) {
10347 IntentBindRecord b = bindings.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -080010348 if (DEBUG_SERVICE) Slog.v(TAG, "Killing binding " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010349 + ": shouldUnbind=" + b.hasBound);
10350 b.binder = null;
10351 b.requested = b.received = b.hasBound = false;
10352 }
10353 }
10354
Dianne Hackborn070783f2010-12-29 16:46:28 -080010355 if (sr.crashCount >= 2 && (sr.serviceInfo.applicationInfo.flags
10356 &ApplicationInfo.FLAG_PERSISTENT) == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010357 Slog.w(TAG, "Service crashed " + sr.crashCount
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010358 + " times, stopping: " + sr);
Doug Zongker2bec3d42009-12-04 12:52:44 -080010359 EventLog.writeEvent(EventLogTags.AM_SERVICE_CRASHED_TOO_MUCH,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010360 sr.crashCount, sr.shortName, app.pid);
10361 bringDownServiceLocked(sr, true);
10362 } else if (!allowRestart) {
10363 bringDownServiceLocked(sr, true);
10364 } else {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010365 boolean canceled = scheduleServiceRestartLocked(sr, true);
10366
10367 // Should the service remain running? Note that in the
10368 // extreme case of so many attempts to deliver a command
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010369 // that it failed we also will stop it here.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010370 if (sr.startRequested && (sr.stopIfKilled || canceled)) {
10371 if (sr.pendingStarts.size() == 0) {
10372 sr.startRequested = false;
10373 if (!hasClients) {
10374 // Whoops, no reason to restart!
10375 bringDownServiceLocked(sr, true);
10376 }
10377 }
10378 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010379 }
10380 }
10381
10382 if (!allowRestart) {
10383 app.services.clear();
10384 }
10385 }
10386
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010387 // Make sure we have no more records on the stopping list.
10388 int i = mStoppingServices.size();
10389 while (i > 0) {
10390 i--;
10391 ServiceRecord sr = mStoppingServices.get(i);
10392 if (sr.app == app) {
10393 mStoppingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010394 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010395 }
10396 }
10397
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010398 app.executingServices.clear();
10399 }
10400
10401 private final void removeDyingProviderLocked(ProcessRecord proc,
10402 ContentProviderRecord cpr) {
10403 synchronized (cpr) {
10404 cpr.launchingApp = null;
10405 cpr.notifyAll();
10406 }
10407
Amith Yamasani742a6712011-05-04 14:49:28 -070010408 mProviderMap.removeProviderByClass(cpr.name, UserId.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010409 String names[] = cpr.info.authority.split(";");
10410 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010411 mProviderMap.removeProviderByName(names[j], UserId.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010412 }
10413
10414 Iterator<ProcessRecord> cit = cpr.clients.iterator();
10415 while (cit.hasNext()) {
10416 ProcessRecord capp = cit.next();
10417 if (!capp.persistent && capp.thread != null
10418 && capp.pid != 0
10419 && capp.pid != MY_PID) {
Dianne Hackborn8633e682010-04-22 16:03:41 -070010420 Slog.i(TAG, "Kill " + capp.processName
10421 + " (pid " + capp.pid + "): provider " + cpr.info.name
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010422 + " in dying process " + (proc != null ? proc.processName : "??"));
Dianne Hackborn8633e682010-04-22 16:03:41 -070010423 EventLog.writeEvent(EventLogTags.AM_KILL, capp.pid,
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010424 capp.processName, capp.setAdj, "dying provider "
10425 + cpr.name.toShortString());
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070010426 Process.killProcessQuiet(capp.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010427 }
10428 }
10429
10430 mLaunchingProviders.remove(cpr);
10431 }
10432
10433 /**
10434 * Main code for cleaning up a process when it has gone away. This is
10435 * called both as a result of the process dying, or directly when stopping
10436 * a process when running in single process mode.
10437 */
10438 private final void cleanUpApplicationRecordLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010439 boolean restarting, boolean allowRestart, int index) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010440 if (index >= 0) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010441 mLruProcesses.remove(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010442 }
10443
Dianne Hackborn36124872009-10-08 16:22:03 -070010444 mProcessesToGc.remove(app);
10445
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010446 // Dismiss any open dialogs.
10447 if (app.crashDialog != null) {
10448 app.crashDialog.dismiss();
10449 app.crashDialog = null;
10450 }
10451 if (app.anrDialog != null) {
10452 app.anrDialog.dismiss();
10453 app.anrDialog = null;
10454 }
10455 if (app.waitDialog != null) {
10456 app.waitDialog.dismiss();
10457 app.waitDialog = null;
10458 }
10459
10460 app.crashing = false;
10461 app.notResponding = false;
10462
10463 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -070010464 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010465 app.thread = null;
10466 app.forcingToForeground = null;
10467 app.foregroundServices = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010468 app.foregroundActivities = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070010469 app.hasShownUi = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010470 app.hasAboveClient = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010471
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010472 killServicesLocked(app, allowRestart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010473
10474 boolean restart = false;
10475
10476 int NL = mLaunchingProviders.size();
10477
10478 // Remove published content providers.
10479 if (!app.pubProviders.isEmpty()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010480 Iterator<ContentProviderRecord> it = app.pubProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010481 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010482 ContentProviderRecord cpr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010483 cpr.provider = null;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010484 cpr.proc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010485
10486 // See if someone is waiting for this provider... in which
10487 // case we don't remove it, but just let it restart.
10488 int i = 0;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010489 if (!app.bad && allowRestart) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010490 for (; i<NL; i++) {
10491 if (mLaunchingProviders.get(i) == cpr) {
10492 restart = true;
10493 break;
10494 }
10495 }
10496 } else {
10497 i = NL;
10498 }
10499
10500 if (i >= NL) {
10501 removeDyingProviderLocked(app, cpr);
10502 NL = mLaunchingProviders.size();
10503 }
10504 }
10505 app.pubProviders.clear();
10506 }
10507
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010508 // Take care of any launching providers waiting for this process.
10509 if (checkAppInLaunchingProvidersLocked(app, false)) {
10510 restart = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010511 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010512
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010513 // Unregister from connected content providers.
10514 if (!app.conProviders.isEmpty()) {
Dianne Hackborn0c3154d2009-10-06 17:18:05 -070010515 Iterator it = app.conProviders.keySet().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010516 while (it.hasNext()) {
10517 ContentProviderRecord cpr = (ContentProviderRecord)it.next();
10518 cpr.clients.remove(app);
10519 }
10520 app.conProviders.clear();
10521 }
10522
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010523 // At this point there may be remaining entries in mLaunchingProviders
10524 // where we were the only one waiting, so they are no longer of use.
10525 // Look for these and clean up if found.
10526 // XXX Commented out for now. Trying to figure out a way to reproduce
10527 // the actual situation to identify what is actually going on.
10528 if (false) {
10529 for (int i=0; i<NL; i++) {
10530 ContentProviderRecord cpr = (ContentProviderRecord)
10531 mLaunchingProviders.get(i);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080010532 if (cpr.clients.size() <= 0 && !cpr.hasExternalProcessHandles()) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010533 synchronized (cpr) {
10534 cpr.launchingApp = null;
10535 cpr.notifyAll();
10536 }
10537 }
10538 }
10539 }
10540
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010541 skipCurrentReceiverLocked(app);
10542
10543 // Unregister any receivers.
10544 if (app.receivers.size() > 0) {
10545 Iterator<ReceiverList> it = app.receivers.iterator();
10546 while (it.hasNext()) {
10547 removeReceiverLocked(it.next());
10548 }
10549 app.receivers.clear();
10550 }
10551
Christopher Tate181fafa2009-05-14 11:12:14 -070010552 // If the app is undergoing backup, tell the backup manager about it
10553 if (mBackupTarget != null && app.pid == mBackupTarget.app.pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010554 if (DEBUG_BACKUP) Slog.d(TAG, "App " + mBackupTarget.appInfo + " died during backup");
Christopher Tate181fafa2009-05-14 11:12:14 -070010555 try {
10556 IBackupManager bm = IBackupManager.Stub.asInterface(
10557 ServiceManager.getService(Context.BACKUP_SERVICE));
10558 bm.agentDisconnected(app.info.packageName);
10559 } catch (RemoteException e) {
10560 // can't happen; backup manager is local
10561 }
10562 }
10563
Jeff Sharkey287bd832011-05-28 19:36:26 -070010564 mHandler.obtainMessage(DISPATCH_PROCESS_DIED, app.pid, app.info.uid, null).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010565
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010566 // If the caller is restarting this app, then leave it in its
10567 // current lists and let the caller take care of it.
10568 if (restarting) {
10569 return;
10570 }
10571
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010572 if (!app.persistent || app.isolated) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010573 if (DEBUG_PROCESSES) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010574 "Removing non-persistent process during cleanup: " + app);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010575 mProcessNames.remove(app.processName, app.uid);
10576 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -070010577 if (mHeavyWeightProcess == app) {
10578 mHeavyWeightProcess = null;
10579 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
10580 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010581 } else if (!app.removed) {
10582 // This app is persistent, so we need to keep its record around.
10583 // If it is not already on the pending app list, add it there
10584 // and start a new process for it.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010585 if (mPersistentStartingProcesses.indexOf(app) < 0) {
10586 mPersistentStartingProcesses.add(app);
10587 restart = true;
10588 }
10589 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070010590 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
10591 "Clean-up removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010592 mProcessesOnHold.remove(app);
10593
The Android Open Source Project4df24232009-03-05 14:34:35 -080010594 if (app == mHomeProcess) {
10595 mHomeProcess = null;
10596 }
Dianne Hackbornf35fe232011-11-01 19:25:20 -070010597 if (app == mPreviousProcess) {
10598 mPreviousProcess = null;
10599 }
10600
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010601 if (restart && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010602 // We have components that still need to be running in the
10603 // process, so re-launch it.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010604 mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010605 startProcessLocked(app, "restart", app.processName);
10606 } else if (app.pid > 0 && app.pid != MY_PID) {
10607 // Goodbye!
10608 synchronized (mPidsSelfLocked) {
10609 mPidsSelfLocked.remove(app.pid);
10610 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
10611 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010612 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010613 }
10614 }
10615
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010616 boolean checkAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) {
10617 // Look through the content providers we are waiting to have launched,
10618 // and if any run in this process then either schedule a restart of
10619 // the process or kill the client waiting for it if this process has
10620 // gone bad.
10621 int NL = mLaunchingProviders.size();
10622 boolean restart = false;
10623 for (int i=0; i<NL; i++) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010624 ContentProviderRecord cpr = mLaunchingProviders.get(i);
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010625 if (cpr.launchingApp == app) {
10626 if (!alwaysBad && !app.bad) {
10627 restart = true;
10628 } else {
10629 removeDyingProviderLocked(app, cpr);
10630 NL = mLaunchingProviders.size();
10631 }
10632 }
10633 }
10634 return restart;
10635 }
10636
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010637 // =========================================================
10638 // SERVICES
10639 // =========================================================
10640
10641 ActivityManager.RunningServiceInfo makeRunningServiceInfoLocked(ServiceRecord r) {
10642 ActivityManager.RunningServiceInfo info =
10643 new ActivityManager.RunningServiceInfo();
10644 info.service = r.name;
10645 if (r.app != null) {
10646 info.pid = r.app.pid;
10647 }
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010648 info.uid = r.appInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010649 info.process = r.processName;
10650 info.foreground = r.isForeground;
10651 info.activeSince = r.createTime;
10652 info.started = r.startRequested;
10653 info.clientCount = r.connections.size();
10654 info.crashCount = r.crashCount;
10655 info.lastActivityTime = r.lastActivity;
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010656 if (r.isForeground) {
10657 info.flags |= ActivityManager.RunningServiceInfo.FLAG_FOREGROUND;
10658 }
10659 if (r.startRequested) {
10660 info.flags |= ActivityManager.RunningServiceInfo.FLAG_STARTED;
10661 }
Dan Egnor42471dd2010-01-07 17:25:22 -080010662 if (r.app != null && r.app.pid == MY_PID) {
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010663 info.flags |= ActivityManager.RunningServiceInfo.FLAG_SYSTEM_PROCESS;
10664 }
10665 if (r.app != null && r.app.persistent) {
10666 info.flags |= ActivityManager.RunningServiceInfo.FLAG_PERSISTENT_PROCESS;
10667 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010668
10669 for (ArrayList<ConnectionRecord> connl : r.connections.values()) {
10670 for (int i=0; i<connl.size(); i++) {
10671 ConnectionRecord conn = connl.get(i);
10672 if (conn.clientLabel != 0) {
10673 info.clientPackage = conn.binding.client.info.packageName;
10674 info.clientLabel = conn.clientLabel;
10675 return info;
10676 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010677 }
10678 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010679 return info;
10680 }
10681
10682 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum,
10683 int flags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010684 enforceNotIsolatedCaller("getServices");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010685 synchronized (this) {
10686 ArrayList<ActivityManager.RunningServiceInfo> res
10687 = new ArrayList<ActivityManager.RunningServiceInfo>();
10688
Amith Yamasani742a6712011-05-04 14:49:28 -070010689 int userId = UserId.getUserId(Binder.getCallingUid());
10690 if (mServiceMap.getAllServices(userId).size() > 0) {
10691 Iterator<ServiceRecord> it
10692 = mServiceMap.getAllServices(userId).iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010693 while (it.hasNext() && res.size() < maxNum) {
10694 res.add(makeRunningServiceInfoLocked(it.next()));
10695 }
10696 }
10697
10698 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
10699 ServiceRecord r = mRestartingServices.get(i);
10700 ActivityManager.RunningServiceInfo info =
10701 makeRunningServiceInfoLocked(r);
10702 info.restarting = r.nextRestartTime;
10703 res.add(info);
10704 }
10705
10706 return res;
10707 }
10708 }
10709
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010710 public PendingIntent getRunningServiceControlPanel(ComponentName name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010711 enforceNotIsolatedCaller("getRunningServiceControlPanel");
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010712 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010713 int userId = UserId.getUserId(Binder.getCallingUid());
10714 ServiceRecord r = mServiceMap.getServiceByName(name, userId);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010715 if (r != null) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010716 for (ArrayList<ConnectionRecord> conn : r.connections.values()) {
10717 for (int i=0; i<conn.size(); i++) {
10718 if (conn.get(i).clientIntent != null) {
10719 return conn.get(i).clientIntent;
10720 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010721 }
10722 }
10723 }
10724 }
10725 return null;
10726 }
10727
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010728 private final ServiceRecord findServiceLocked(ComponentName name,
10729 IBinder token) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010730 ServiceRecord r = mServiceMap.getServiceByName(name, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010731 return r == token ? r : null;
10732 }
10733
10734 private final class ServiceLookupResult {
10735 final ServiceRecord record;
10736 final String permission;
10737
10738 ServiceLookupResult(ServiceRecord _record, String _permission) {
10739 record = _record;
10740 permission = _permission;
10741 }
10742 };
10743
10744 private ServiceLookupResult findServiceLocked(Intent service,
Amith Yamasani483f3b02012-03-13 16:08:00 -070010745 String resolvedType, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010746 ServiceRecord r = null;
10747 if (service.getComponent() != null) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070010748 r = mServiceMap.getServiceByName(service.getComponent(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010749 }
10750 if (r == null) {
10751 Intent.FilterComparison filter = new Intent.FilterComparison(service);
Amith Yamasani483f3b02012-03-13 16:08:00 -070010752 r = mServiceMap.getServiceByIntent(filter, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010753 }
10754
10755 if (r == null) {
10756 try {
10757 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070010758 AppGlobals.getPackageManager().resolveService(
Amith Yamasani483f3b02012-03-13 16:08:00 -070010759 service, resolvedType, 0, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010760 ServiceInfo sInfo =
10761 rInfo != null ? rInfo.serviceInfo : null;
10762 if (sInfo == null) {
10763 return null;
10764 }
10765
10766 ComponentName name = new ComponentName(
10767 sInfo.applicationInfo.packageName, sInfo.name);
Amith Yamasani742a6712011-05-04 14:49:28 -070010768 r = mServiceMap.getServiceByName(name, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010769 } catch (RemoteException ex) {
10770 // pm is in same process, this will never happen.
10771 }
10772 }
10773 if (r != null) {
10774 int callingPid = Binder.getCallingPid();
10775 int callingUid = Binder.getCallingUid();
10776 if (checkComponentPermission(r.permission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010777 callingPid, callingUid, r.appInfo.uid, r.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010778 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010779 if (!r.exported) {
10780 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
10781 + " from pid=" + callingPid
10782 + ", uid=" + callingUid
10783 + " that is not exported from uid " + r.appInfo.uid);
10784 return new ServiceLookupResult(null, "not exported from uid "
10785 + r.appInfo.uid);
10786 }
Joe Onorato8a9b2202010-02-26 18:56:32 -080010787 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010788 + " from pid=" + callingPid
10789 + ", uid=" + callingUid
10790 + " requires " + r.permission);
10791 return new ServiceLookupResult(null, r.permission);
10792 }
10793 return new ServiceLookupResult(r, null);
10794 }
10795 return null;
10796 }
10797
10798 private class ServiceRestarter implements Runnable {
10799 private ServiceRecord mService;
10800
10801 void setService(ServiceRecord service) {
10802 mService = service;
10803 }
10804
10805 public void run() {
10806 synchronized(ActivityManagerService.this) {
10807 performServiceRestartLocked(mService);
10808 }
10809 }
10810 }
10811
10812 private ServiceLookupResult retrieveServiceLocked(Intent service,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010813 String resolvedType, int callingPid, int callingUid, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010814 ServiceRecord r = null;
Amith Yamasani742a6712011-05-04 14:49:28 -070010815 if (DEBUG_SERVICE)
10816 Slog.v(TAG, "retrieveServiceLocked: " + service + " type=" + resolvedType
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010817 + " callingUid=" + callingUid);
Amith Yamasani742a6712011-05-04 14:49:28 -070010818
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010819 if (service.getComponent() != null) {
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010820 r = mServiceMap.getServiceByName(service.getComponent(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010821 }
Amith Yamasani742a6712011-05-04 14:49:28 -070010822 if (r == null) {
10823 Intent.FilterComparison filter = new Intent.FilterComparison(service);
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010824 r = mServiceMap.getServiceByIntent(filter, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -070010825 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010826 if (r == null) {
10827 try {
10828 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070010829 AppGlobals.getPackageManager().resolveService(
Amith Yamasani483f3b02012-03-13 16:08:00 -070010830 service, resolvedType, STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010831 ServiceInfo sInfo =
10832 rInfo != null ? rInfo.serviceInfo : null;
10833 if (sInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010834 Slog.w(TAG, "Unable to start service " + service +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010835 ": not found");
10836 return null;
10837 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010838 if (userId > 0) {
10839 sInfo.applicationInfo = getAppInfoForUser(sInfo.applicationInfo, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -070010840 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010841 ComponentName name = new ComponentName(
10842 sInfo.applicationInfo.packageName, sInfo.name);
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010843 r = mServiceMap.getServiceByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010844 if (r == null) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010845 Intent.FilterComparison filter = new Intent.FilterComparison(
10846 service.cloneFilter());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010847 ServiceRestarter res = new ServiceRestarter();
10848 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
10849 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
10850 synchronized (stats) {
10851 ss = stats.getServiceStatsLocked(
10852 sInfo.applicationInfo.uid, sInfo.packageName,
10853 sInfo.name);
10854 }
Dianne Hackbornb1c4a2a2010-01-19 15:36:42 -080010855 r = new ServiceRecord(this, ss, name, filter, sInfo, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010856 res.setService(r);
Amith Yamasani742a6712011-05-04 14:49:28 -070010857 mServiceMap.putServiceByName(name, UserId.getUserId(r.appInfo.uid), r);
10858 mServiceMap.putServiceByIntent(filter, UserId.getUserId(r.appInfo.uid), r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010859
10860 // Make sure this component isn't in the pending list.
10861 int N = mPendingServices.size();
10862 for (int i=0; i<N; i++) {
10863 ServiceRecord pr = mPendingServices.get(i);
10864 if (pr.name.equals(name)) {
10865 mPendingServices.remove(i);
10866 i--;
10867 N--;
10868 }
10869 }
10870 }
10871 } catch (RemoteException ex) {
10872 // pm is in same process, this will never happen.
10873 }
10874 }
10875 if (r != null) {
10876 if (checkComponentPermission(r.permission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010877 callingPid, callingUid, r.appInfo.uid, r.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010878 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010879 if (!r.exported) {
10880 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
10881 + " from pid=" + callingPid
10882 + ", uid=" + callingUid
10883 + " that is not exported from uid " + r.appInfo.uid);
10884 return new ServiceLookupResult(null, "not exported from uid "
10885 + r.appInfo.uid);
10886 }
Joe Onorato8a9b2202010-02-26 18:56:32 -080010887 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010888 + " from pid=" + callingPid
10889 + ", uid=" + callingUid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010890 + " requires " + r.permission);
10891 return new ServiceLookupResult(null, r.permission);
10892 }
10893 return new ServiceLookupResult(r, null);
10894 }
10895 return null;
10896 }
10897
Dianne Hackborn287952c2010-09-22 22:34:31 -070010898 private final void bumpServiceExecutingLocked(ServiceRecord r, String why) {
10899 if (DEBUG_SERVICE) Log.v(TAG, ">>> EXECUTING "
10900 + why + " of " + r + " in app " + r.app);
10901 else if (DEBUG_SERVICE_EXECUTING) Log.v(TAG, ">>> EXECUTING "
10902 + why + " of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010903 long now = SystemClock.uptimeMillis();
10904 if (r.executeNesting == 0 && r.app != null) {
10905 if (r.app.executingServices.size() == 0) {
10906 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
10907 msg.obj = r.app;
10908 mHandler.sendMessageAtTime(msg, now+SERVICE_TIMEOUT);
10909 }
10910 r.app.executingServices.add(r);
10911 }
10912 r.executeNesting++;
10913 r.executingStart = now;
10914 }
10915
10916 private final void sendServiceArgsLocked(ServiceRecord r,
10917 boolean oomAdjusted) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010918 final int N = r.pendingStarts.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010919 if (N == 0) {
10920 return;
10921 }
10922
Dianne Hackborn39792d22010-08-19 18:01:52 -070010923 while (r.pendingStarts.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010924 try {
Dianne Hackborn39792d22010-08-19 18:01:52 -070010925 ServiceRecord.StartItem si = r.pendingStarts.remove(0);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010926 if (DEBUG_SERVICE) Slog.v(TAG, "Sending arguments to: "
10927 + r + " " + r.intent + " args=" + si.intent);
Dianne Hackborn3a28f222011-03-01 12:25:54 -080010928 if (si.intent == null && N > 1) {
10929 // If somehow we got a dummy null intent in the middle,
10930 // then skip it. DO NOT skip a null intent when it is
10931 // the only one in the list -- this is to support the
10932 // onStartCommand(null) case.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010933 continue;
10934 }
Dianne Hackborn39792d22010-08-19 18:01:52 -070010935 si.deliveredTime = SystemClock.uptimeMillis();
10936 r.deliveredStarts.add(si);
10937 si.deliveryCount++;
Dianne Hackborn21c241e2012-03-08 13:57:23 -080010938 if (si.neededGrants != null) {
10939 grantUriPermissionUncheckedFromIntentLocked(si.neededGrants,
10940 si.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -070010941 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070010942 bumpServiceExecutingLocked(r, "start");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010943 if (!oomAdjusted) {
10944 oomAdjusted = true;
10945 updateOomAdjLocked(r.app);
10946 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010947 int flags = 0;
10948 if (si.deliveryCount > 0) {
10949 flags |= Service.START_FLAG_RETRY;
10950 }
10951 if (si.doneExecutingCount > 0) {
10952 flags |= Service.START_FLAG_REDELIVERY;
10953 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070010954 r.app.thread.scheduleServiceArgs(r, si.taskRemoved, si.id, flags, si.intent);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010955 } catch (RemoteException e) {
10956 // Remote process gone... we'll let the normal cleanup take
10957 // care of this.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010958 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while scheduling start: " + r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010959 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010960 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010961 Slog.w(TAG, "Unexpected exception", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010962 break;
10963 }
10964 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010965 }
10966
10967 private final boolean requestServiceBindingLocked(ServiceRecord r,
10968 IntentBindRecord i, boolean rebind) {
10969 if (r.app == null || r.app.thread == null) {
10970 // If service is not currently running, can't yet bind.
10971 return false;
10972 }
10973 if ((!i.requested || rebind) && i.apps.size() > 0) {
10974 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070010975 bumpServiceExecutingLocked(r, "bind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010976 r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind);
10977 if (!rebind) {
10978 i.requested = true;
10979 }
10980 i.hasBound = true;
10981 i.doRebind = false;
10982 } catch (RemoteException e) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010983 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while binding " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010984 return false;
10985 }
10986 }
10987 return true;
10988 }
10989
10990 private final void requestServiceBindingsLocked(ServiceRecord r) {
10991 Iterator<IntentBindRecord> bindings = r.bindings.values().iterator();
10992 while (bindings.hasNext()) {
10993 IntentBindRecord i = bindings.next();
10994 if (!requestServiceBindingLocked(r, i, false)) {
10995 break;
10996 }
10997 }
10998 }
10999
11000 private final void realStartServiceLocked(ServiceRecord r,
11001 ProcessRecord app) throws RemoteException {
11002 if (app.thread == null) {
11003 throw new RemoteException();
11004 }
Amith Yamasani742a6712011-05-04 14:49:28 -070011005 if (DEBUG_MU)
11006 Slog.v(TAG_MU, "realStartServiceLocked, ServiceRecord.uid = " + r.appInfo.uid
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011007 + ", ProcessRecord.uid = " + app.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011008 r.app = app;
The Android Open Source Project10592532009-03-18 17:39:46 -070011009 r.restartTime = r.lastActivity = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011010
11011 app.services.add(r);
Dianne Hackborn287952c2010-09-22 22:34:31 -070011012 bumpServiceExecutingLocked(r, "create");
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011013 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011014
11015 boolean created = false;
11016 try {
Dianne Hackborna33e3f72009-09-29 17:28:24 -070011017 mStringBuilder.setLength(0);
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011018 r.intent.getIntent().toShortString(mStringBuilder, true, false, true, false);
Doug Zongker2bec3d42009-12-04 12:52:44 -080011019 EventLog.writeEvent(EventLogTags.AM_CREATE_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011020 System.identityHashCode(r), r.shortName,
Dianne Hackborna33e3f72009-09-29 17:28:24 -070011021 mStringBuilder.toString(), r.app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011022 synchronized (r.stats.getBatteryStats()) {
11023 r.stats.startLaunchedLocked();
11024 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -070011025 ensurePackageDexOpt(r.serviceInfo.packageName);
Dianne Hackborne2515ee2011-04-27 18:52:56 -040011026 app.thread.scheduleCreateService(r, r.serviceInfo,
11027 compatibilityInfoForPackageLocked(r.serviceInfo.applicationInfo));
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011028 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011029 created = true;
11030 } finally {
11031 if (!created) {
11032 app.services.remove(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011033 scheduleServiceRestartLocked(r, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011034 }
11035 }
11036
11037 requestServiceBindingsLocked(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011038
11039 // If the service is in the started state, and there are no
11040 // pending arguments, then fake up one so its onStartCommand() will
11041 // be called.
11042 if (r.startRequested && r.callStart && r.pendingStarts.size() == 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011043 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011044 null, null));
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011045 }
11046
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011047 sendServiceArgsLocked(r, true);
11048 }
11049
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011050 private final boolean scheduleServiceRestartLocked(ServiceRecord r,
11051 boolean allowCancel) {
11052 boolean canceled = false;
11053
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011054 final long now = SystemClock.uptimeMillis();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011055 long minDuration = SERVICE_RESTART_DURATION;
Dianne Hackborn6ccd2af2009-08-27 12:26:44 -070011056 long resetTime = SERVICE_RESET_RUN_DURATION;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011057
Dianne Hackborn070783f2010-12-29 16:46:28 -080011058 if ((r.serviceInfo.applicationInfo.flags
11059 &ApplicationInfo.FLAG_PERSISTENT) != 0) {
11060 minDuration /= 4;
11061 }
11062
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011063 // Any delivered but not yet finished starts should be put back
11064 // on the pending list.
11065 final int N = r.deliveredStarts.size();
11066 if (N > 0) {
11067 for (int i=N-1; i>=0; i--) {
11068 ServiceRecord.StartItem si = r.deliveredStarts.get(i);
Dianne Hackborn39792d22010-08-19 18:01:52 -070011069 si.removeUriPermissionsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011070 if (si.intent == null) {
11071 // We'll generate this again if needed.
11072 } else if (!allowCancel || (si.deliveryCount < ServiceRecord.MAX_DELIVERY_COUNT
11073 && si.doneExecutingCount < ServiceRecord.MAX_DONE_EXECUTING_COUNT)) {
11074 r.pendingStarts.add(0, si);
11075 long dur = SystemClock.uptimeMillis() - si.deliveredTime;
11076 dur *= 2;
11077 if (minDuration < dur) minDuration = dur;
11078 if (resetTime < dur) resetTime = dur;
11079 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011080 Slog.w(TAG, "Canceling start item " + si.intent + " in service "
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011081 + r.name);
11082 canceled = true;
11083 }
11084 }
11085 r.deliveredStarts.clear();
11086 }
11087
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011088 r.totalRestartCount++;
11089 if (r.restartDelay == 0) {
11090 r.restartCount++;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011091 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011092 } else {
11093 // If it has been a "reasonably long time" since the service
11094 // was started, then reset our restart duration back to
11095 // the beginning, so we don't infinitely increase the duration
11096 // on a service that just occasionally gets killed (which is
11097 // a normal case, due to process being killed to reclaim memory).
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011098 if (now > (r.restartTime+resetTime)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011099 r.restartCount = 1;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011100 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011101 } else {
Dianne Hackborn070783f2010-12-29 16:46:28 -080011102 if ((r.serviceInfo.applicationInfo.flags
11103 &ApplicationInfo.FLAG_PERSISTENT) != 0) {
11104 // Services in peristent processes will restart much more
11105 // quickly, since they are pretty important. (Think SystemUI).
11106 r.restartDelay += minDuration/2;
11107 } else {
11108 r.restartDelay *= SERVICE_RESTART_DURATION_FACTOR;
11109 if (r.restartDelay < minDuration) {
11110 r.restartDelay = minDuration;
11111 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011112 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011113 }
11114 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011115
11116 r.nextRestartTime = now + r.restartDelay;
11117
11118 // Make sure that we don't end up restarting a bunch of services
11119 // all at the same time.
11120 boolean repeat;
11121 do {
11122 repeat = false;
11123 for (int i=mRestartingServices.size()-1; i>=0; i--) {
11124 ServiceRecord r2 = mRestartingServices.get(i);
11125 if (r2 != r && r.nextRestartTime
11126 >= (r2.nextRestartTime-SERVICE_MIN_RESTART_TIME_BETWEEN)
11127 && r.nextRestartTime
11128 < (r2.nextRestartTime+SERVICE_MIN_RESTART_TIME_BETWEEN)) {
11129 r.nextRestartTime = r2.nextRestartTime + SERVICE_MIN_RESTART_TIME_BETWEEN;
11130 r.restartDelay = r.nextRestartTime - now;
11131 repeat = true;
11132 break;
11133 }
11134 }
11135 } while (repeat);
11136
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011137 if (!mRestartingServices.contains(r)) {
11138 mRestartingServices.add(r);
11139 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011140
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011141 r.cancelNotification();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011142
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011143 mHandler.removeCallbacks(r.restarter);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011144 mHandler.postAtTime(r.restarter, r.nextRestartTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011145 r.nextRestartTime = SystemClock.uptimeMillis() + r.restartDelay;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011146 Slog.w(TAG, "Scheduling restart of crashed service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011147 + r.shortName + " in " + r.restartDelay + "ms");
Doug Zongker2bec3d42009-12-04 12:52:44 -080011148 EventLog.writeEvent(EventLogTags.AM_SCHEDULE_SERVICE_RESTART,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011149 r.shortName, r.restartDelay);
11150
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011151 return canceled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011152 }
11153
11154 final void performServiceRestartLocked(ServiceRecord r) {
11155 if (!mRestartingServices.contains(r)) {
11156 return;
11157 }
11158 bringUpServiceLocked(r, r.intent.getIntent().getFlags(), true);
11159 }
11160
11161 private final boolean unscheduleServiceRestartLocked(ServiceRecord r) {
11162 if (r.restartDelay == 0) {
11163 return false;
11164 }
11165 r.resetRestartCounter();
11166 mRestartingServices.remove(r);
11167 mHandler.removeCallbacks(r.restarter);
11168 return true;
11169 }
11170
11171 private final boolean bringUpServiceLocked(ServiceRecord r,
11172 int intentFlags, boolean whileRestarting) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011173 //Slog.i(TAG, "Bring up service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011174 //r.dump(" ");
11175
Dianne Hackborn36124872009-10-08 16:22:03 -070011176 if (r.app != null && r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011177 sendServiceArgsLocked(r, false);
11178 return true;
11179 }
11180
11181 if (!whileRestarting && r.restartDelay > 0) {
11182 // If waiting for a restart, then do nothing.
11183 return true;
11184 }
11185
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011186 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing up " + r + " " + r.intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011187
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011188 // We are now bringing the service up, so no longer in the
11189 // restarting state.
11190 mRestartingServices.remove(r);
11191
Dianne Hackborne7f97212011-02-24 14:40:20 -080011192 // Service is now being launched, its package can't be stopped.
11193 try {
11194 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -070011195 r.packageName, false, r.userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -080011196 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080011197 } catch (IllegalArgumentException e) {
11198 Slog.w(TAG, "Failed trying to unstop package "
11199 + r.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080011200 }
11201
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011202 final boolean isolated = (r.serviceInfo.flags&ServiceInfo.FLAG_ISOLATED_PROCESS) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011203 final String appName = r.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011204 ProcessRecord app;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011205
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011206 if (!isolated) {
11207 app = getProcessRecordLocked(appName, r.appInfo.uid);
11208 if (DEBUG_MU)
11209 Slog.v(TAG_MU, "bringUpServiceLocked: appInfo.uid=" + r.appInfo.uid + " app=" + app);
11210 if (app != null && app.thread != null) {
11211 try {
11212 app.addPackage(r.appInfo.packageName);
11213 realStartServiceLocked(r, app);
11214 return true;
11215 } catch (RemoteException e) {
11216 Slog.w(TAG, "Exception when starting service " + r.shortName, e);
11217 }
11218
11219 // If a dead object exception was thrown -- fall through to
11220 // restart the application.
11221 }
11222 } else {
11223 // If this service runs in an isolated process, then each time
11224 // we call startProcessLocked() we will get a new isolated
11225 // process, starting another process if we are currently waiting
11226 // for a previous process to come up. To deal with this, we store
11227 // in the service any current isolated process it is running in or
11228 // waiting to have come up.
11229 app = r.isolatedProc;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011230 }
11231
Dianne Hackborn36124872009-10-08 16:22:03 -070011232 // Not running -- get it started, and enqueue this service record
11233 // to be executed when the app comes up.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011234 if (app == null) {
11235 if ((app=startProcessLocked(appName, r.appInfo, true, intentFlags,
11236 "service", r.name, false, isolated)) == null) {
11237 Slog.w(TAG, "Unable to launch app "
11238 + r.appInfo.packageName + "/"
11239 + r.appInfo.uid + " for service "
11240 + r.intent.getIntent() + ": process is bad");
11241 bringDownServiceLocked(r, true);
11242 return false;
11243 }
11244 if (isolated) {
11245 r.isolatedProc = app;
11246 }
Dianne Hackborn36124872009-10-08 16:22:03 -070011247 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011248
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011249 if (!mPendingServices.contains(r)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011250 mPendingServices.add(r);
11251 }
Dianne Hackborn36124872009-10-08 16:22:03 -070011252
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011253 return true;
11254 }
11255
11256 private final void bringDownServiceLocked(ServiceRecord r, boolean force) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011257 //Slog.i(TAG, "Bring down service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011258 //r.dump(" ");
11259
11260 // Does it still need to run?
11261 if (!force && r.startRequested) {
11262 return;
11263 }
11264 if (r.connections.size() > 0) {
11265 if (!force) {
11266 // XXX should probably keep a count of the number of auto-create
11267 // connections directly in the service.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011268 Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011269 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011270 ArrayList<ConnectionRecord> cr = it.next();
11271 for (int i=0; i<cr.size(); i++) {
11272 if ((cr.get(i).flags&Context.BIND_AUTO_CREATE) != 0) {
11273 return;
11274 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011275 }
11276 }
11277 }
11278
11279 // Report to all of the connections that the service is no longer
11280 // available.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011281 Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011282 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011283 ArrayList<ConnectionRecord> c = it.next();
11284 for (int i=0; i<c.size(); i++) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011285 ConnectionRecord cr = c.get(i);
11286 // There is still a connection to the service that is
11287 // being brought down. Mark it as dead.
11288 cr.serviceDead = true;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011289 try {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011290 cr.conn.connected(r.name, null);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011291 } catch (Exception e) {
11292 Slog.w(TAG, "Failure disconnecting service " + r.name +
11293 " to connection " + c.get(i).conn.asBinder() +
11294 " (in " + c.get(i).binding.client.processName + ")", e);
11295 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011296 }
11297 }
11298 }
11299
11300 // Tell the service that it has been unbound.
11301 if (r.bindings.size() > 0 && r.app != null && r.app.thread != null) {
11302 Iterator<IntentBindRecord> it = r.bindings.values().iterator();
11303 while (it.hasNext()) {
11304 IntentBindRecord ibr = it.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -080011305 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down binding " + ibr
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011306 + ": hasBound=" + ibr.hasBound);
11307 if (r.app != null && r.app.thread != null && ibr.hasBound) {
11308 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011309 bumpServiceExecutingLocked(r, "bring down unbind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011310 updateOomAdjLocked(r.app);
11311 ibr.hasBound = false;
11312 r.app.thread.scheduleUnbindService(r,
11313 ibr.intent.getIntent());
11314 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011315 Slog.w(TAG, "Exception when unbinding service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011316 + r.shortName, e);
11317 serviceDoneExecutingLocked(r, true);
11318 }
11319 }
11320 }
11321 }
11322
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011323 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down " + r + " " + r.intent);
Doug Zongker2bec3d42009-12-04 12:52:44 -080011324 EventLog.writeEvent(EventLogTags.AM_DESTROY_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011325 System.identityHashCode(r), r.shortName,
11326 (r.app != null) ? r.app.pid : -1);
11327
Amith Yamasani742a6712011-05-04 14:49:28 -070011328 mServiceMap.removeServiceByName(r.name, r.userId);
11329 mServiceMap.removeServiceByIntent(r.intent, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011330 r.totalRestartCount = 0;
11331 unscheduleServiceRestartLocked(r);
11332
11333 // Also make sure it is not on the pending list.
11334 int N = mPendingServices.size();
11335 for (int i=0; i<N; i++) {
11336 if (mPendingServices.get(i) == r) {
11337 mPendingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011338 if (DEBUG_SERVICE) Slog.v(TAG, "Removed pending: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011339 i--;
11340 N--;
11341 }
11342 }
11343
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011344 r.cancelNotification();
11345 r.isForeground = false;
11346 r.foregroundId = 0;
11347 r.foregroundNoti = null;
11348
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011349 // Clear start entries.
Dianne Hackborn39792d22010-08-19 18:01:52 -070011350 r.clearDeliveredStartsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011351 r.pendingStarts.clear();
11352
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011353 if (r.app != null) {
11354 synchronized (r.stats.getBatteryStats()) {
11355 r.stats.stopLaunchedLocked();
11356 }
11357 r.app.services.remove(r);
11358 if (r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011359 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011360 bumpServiceExecutingLocked(r, "stop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011361 mStoppingServices.add(r);
11362 updateOomAdjLocked(r.app);
11363 r.app.thread.scheduleStopService(r);
11364 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011365 Slog.w(TAG, "Exception when stopping service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011366 + r.shortName, e);
11367 serviceDoneExecutingLocked(r, true);
11368 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011369 updateServiceForegroundLocked(r.app, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011370 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011371 if (DEBUG_SERVICE) Slog.v(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011372 TAG, "Removed service that has no process: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011373 }
11374 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011375 if (DEBUG_SERVICE) Slog.v(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011376 TAG, "Removed service that is not running: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011377 }
Vairavan Srinivasana207ce22010-12-23 13:51:48 -080011378
11379 if (r.bindings.size() > 0) {
11380 r.bindings.clear();
11381 }
11382
11383 if (r.restarter instanceof ServiceRestarter) {
11384 ((ServiceRestarter)r.restarter).setService(null);
11385 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011386 }
11387
11388 ComponentName startServiceLocked(IApplicationThread caller,
11389 Intent service, String resolvedType,
11390 int callingPid, int callingUid) {
11391 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011392 if (DEBUG_SERVICE) Slog.v(TAG, "startService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011393 + " type=" + resolvedType + " args=" + service.getExtras());
11394
11395 if (caller != null) {
11396 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11397 if (callerApp == null) {
11398 throw new SecurityException(
11399 "Unable to find app for caller " + caller
11400 + " (pid=" + Binder.getCallingPid()
11401 + ") when starting service " + service);
11402 }
11403 }
11404
11405 ServiceLookupResult res =
11406 retrieveServiceLocked(service, resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011407 callingPid, callingUid, UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011408 if (res == null) {
11409 return null;
11410 }
11411 if (res.record == null) {
11412 return new ComponentName("!", res.permission != null
11413 ? res.permission : "private to package");
11414 }
11415 ServiceRecord r = res.record;
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011416 NeededUriGrants neededGrants = checkGrantUriPermissionFromIntentLocked(
11417 callingUid, r.packageName, service, service.getFlags(), null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011418 if (unscheduleServiceRestartLocked(r)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011419 if (DEBUG_SERVICE) Slog.v(TAG, "START SERVICE WHILE RESTART PENDING: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011420 }
11421 r.startRequested = true;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011422 r.callStart = false;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011423 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011424 service, neededGrants));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011425 r.lastActivity = SystemClock.uptimeMillis();
11426 synchronized (r.stats.getBatteryStats()) {
11427 r.stats.startRunningLocked();
11428 }
11429 if (!bringUpServiceLocked(r, service.getFlags(), false)) {
11430 return new ComponentName("!", "Service process is bad");
11431 }
11432 return r.name;
11433 }
11434 }
11435
11436 public ComponentName startService(IApplicationThread caller, Intent service,
11437 String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011438 enforceNotIsolatedCaller("startService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011439 // Refuse possible leaked file descriptors
11440 if (service != null && service.hasFileDescriptors() == true) {
11441 throw new IllegalArgumentException("File descriptors passed in Intent");
11442 }
11443
Amith Yamasani742a6712011-05-04 14:49:28 -070011444 if (DEBUG_SERVICE)
11445 Slog.v(TAG, "startService: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011446 synchronized(this) {
11447 final int callingPid = Binder.getCallingPid();
11448 final int callingUid = Binder.getCallingUid();
11449 final long origId = Binder.clearCallingIdentity();
11450 ComponentName res = startServiceLocked(caller, service,
11451 resolvedType, callingPid, callingUid);
11452 Binder.restoreCallingIdentity(origId);
11453 return res;
11454 }
11455 }
11456
11457 ComponentName startServiceInPackage(int uid,
11458 Intent service, String resolvedType) {
11459 synchronized(this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070011460 if (DEBUG_SERVICE)
11461 Slog.v(TAG, "startServiceInPackage: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011462 final long origId = Binder.clearCallingIdentity();
11463 ComponentName res = startServiceLocked(null, service,
11464 resolvedType, -1, uid);
11465 Binder.restoreCallingIdentity(origId);
11466 return res;
11467 }
11468 }
11469
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011470 private void stopServiceLocked(ServiceRecord service) {
11471 synchronized (service.stats.getBatteryStats()) {
11472 service.stats.stopRunningLocked();
11473 }
11474 service.startRequested = false;
11475 service.callStart = false;
11476 bringDownServiceLocked(service, false);
11477 }
11478
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011479 public int stopService(IApplicationThread caller, Intent service,
11480 String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011481 enforceNotIsolatedCaller("stopService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011482 // Refuse possible leaked file descriptors
11483 if (service != null && service.hasFileDescriptors() == true) {
11484 throw new IllegalArgumentException("File descriptors passed in Intent");
11485 }
11486
11487 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011488 if (DEBUG_SERVICE) Slog.v(TAG, "stopService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011489 + " type=" + resolvedType);
11490
11491 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11492 if (caller != null && callerApp == null) {
11493 throw new SecurityException(
11494 "Unable to find app for caller " + caller
11495 + " (pid=" + Binder.getCallingPid()
11496 + ") when stopping service " + service);
11497 }
11498
11499 // If this service is active, make sure it is stopped.
Amith Yamasani483f3b02012-03-13 16:08:00 -070011500 ServiceLookupResult r = findServiceLocked(service, resolvedType,
11501 callerApp == null ? UserId.getCallingUserId() : callerApp.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011502 if (r != null) {
11503 if (r.record != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011504 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011505 try {
11506 stopServiceLocked(r.record);
11507 } finally {
11508 Binder.restoreCallingIdentity(origId);
11509 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011510 return 1;
11511 }
11512 return -1;
11513 }
11514 }
11515
11516 return 0;
11517 }
11518
11519 public IBinder peekService(Intent service, String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011520 enforceNotIsolatedCaller("peekService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011521 // Refuse possible leaked file descriptors
11522 if (service != null && service.hasFileDescriptors() == true) {
11523 throw new IllegalArgumentException("File descriptors passed in Intent");
11524 }
11525
11526 IBinder ret = null;
11527
11528 synchronized(this) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070011529 ServiceLookupResult r = findServiceLocked(service, resolvedType,
11530 UserId.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011531
11532 if (r != null) {
11533 // r.record is null if findServiceLocked() failed the caller permission check
11534 if (r.record == null) {
11535 throw new SecurityException(
11536 "Permission Denial: Accessing service " + r.record.name
11537 + " from pid=" + Binder.getCallingPid()
11538 + ", uid=" + Binder.getCallingUid()
11539 + " requires " + r.permission);
11540 }
11541 IntentBindRecord ib = r.record.bindings.get(r.record.intent);
11542 if (ib != null) {
11543 ret = ib.binder;
11544 }
11545 }
11546 }
11547
11548 return ret;
11549 }
11550
11551 public boolean stopServiceToken(ComponentName className, IBinder token,
11552 int startId) {
11553 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011554 if (DEBUG_SERVICE) Slog.v(TAG, "stopServiceToken: " + className
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011555 + " " + token + " startId=" + startId);
11556 ServiceRecord r = findServiceLocked(className, token);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011557 if (r != null) {
11558 if (startId >= 0) {
11559 // Asked to only stop if done with all work. Note that
11560 // to avoid leaks, we will take this as dropping all
11561 // start items up to and including this one.
11562 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
11563 if (si != null) {
11564 while (r.deliveredStarts.size() > 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -070011565 ServiceRecord.StartItem cur = r.deliveredStarts.remove(0);
11566 cur.removeUriPermissionsLocked();
11567 if (cur == si) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011568 break;
11569 }
11570 }
11571 }
11572
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011573 if (r.getLastStartId() != startId) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011574 return false;
11575 }
11576
11577 if (r.deliveredStarts.size() > 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011578 Slog.w(TAG, "stopServiceToken startId " + startId
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011579 + " is last, but have " + r.deliveredStarts.size()
11580 + " remaining args");
11581 }
11582 }
11583
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011584 synchronized (r.stats.getBatteryStats()) {
11585 r.stats.stopRunningLocked();
11586 r.startRequested = false;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011587 r.callStart = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011588 }
11589 final long origId = Binder.clearCallingIdentity();
11590 bringDownServiceLocked(r, false);
11591 Binder.restoreCallingIdentity(origId);
11592 return true;
11593 }
11594 }
11595 return false;
11596 }
11597
11598 public void setServiceForeground(ComponentName className, IBinder token,
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011599 int id, Notification notification, boolean removeNotification) {
11600 final long origId = Binder.clearCallingIdentity();
11601 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011602 synchronized(this) {
11603 ServiceRecord r = findServiceLocked(className, token);
11604 if (r != null) {
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011605 if (id != 0) {
11606 if (notification == null) {
11607 throw new IllegalArgumentException("null notification");
11608 }
11609 if (r.foregroundId != id) {
11610 r.cancelNotification();
11611 r.foregroundId = id;
11612 }
11613 notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
11614 r.foregroundNoti = notification;
11615 r.isForeground = true;
11616 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011617 if (r.app != null) {
11618 updateServiceForegroundLocked(r.app, true);
11619 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011620 } else {
11621 if (r.isForeground) {
11622 r.isForeground = false;
11623 if (r.app != null) {
Dianne Hackborn8633e682010-04-22 16:03:41 -070011624 updateLruProcessLocked(r.app, false, true);
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011625 updateServiceForegroundLocked(r.app, true);
11626 }
11627 }
11628 if (removeNotification) {
11629 r.cancelNotification();
11630 r.foregroundId = 0;
11631 r.foregroundNoti = null;
11632 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011633 }
11634 }
11635 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011636 } finally {
11637 Binder.restoreCallingIdentity(origId);
11638 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011639 }
11640
11641 public void updateServiceForegroundLocked(ProcessRecord proc, boolean oomAdj) {
11642 boolean anyForeground = false;
Dianne Hackborn860755f2010-06-03 18:47:52 -070011643 for (ServiceRecord sr : proc.services) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011644 if (sr.isForeground) {
11645 anyForeground = true;
11646 break;
11647 }
11648 }
11649 if (anyForeground != proc.foregroundServices) {
11650 proc.foregroundServices = anyForeground;
11651 if (oomAdj) {
11652 updateOomAdjLocked();
11653 }
11654 }
11655 }
11656
11657 public int bindService(IApplicationThread caller, IBinder token,
11658 Intent service, String resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011659 IServiceConnection connection, int flags, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011660 enforceNotIsolatedCaller("bindService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011661 // Refuse possible leaked file descriptors
11662 if (service != null && service.hasFileDescriptors() == true) {
11663 throw new IllegalArgumentException("File descriptors passed in Intent");
11664 }
11665
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011666 checkValidCaller(Binder.getCallingUid(), userId);
11667
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011668 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011669 if (DEBUG_SERVICE) Slog.v(TAG, "bindService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011670 + " type=" + resolvedType + " conn=" + connection.asBinder()
11671 + " flags=0x" + Integer.toHexString(flags));
Amith Yamasani742a6712011-05-04 14:49:28 -070011672 if (DEBUG_MU)
11673 Slog.i(TAG_MU, "bindService uid=" + Binder.getCallingUid() + " origUid="
11674 + Binder.getOrigCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011675 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11676 if (callerApp == null) {
11677 throw new SecurityException(
11678 "Unable to find app for caller " + caller
11679 + " (pid=" + Binder.getCallingPid()
11680 + ") when binding service " + service);
11681 }
11682
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011683 ActivityRecord activity = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011684 if (token != null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070011685 activity = mMainStack.isInStackLocked(token);
11686 if (activity == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011687 Slog.w(TAG, "Binding with unknown activity: " + token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011688 return 0;
11689 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011690 }
11691
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011692 int clientLabel = 0;
11693 PendingIntent clientIntent = null;
11694
11695 if (callerApp.info.uid == Process.SYSTEM_UID) {
11696 // Hacky kind of thing -- allow system stuff to tell us
11697 // what they are, so we can report this elsewhere for
11698 // others to know why certain services are running.
11699 try {
11700 clientIntent = (PendingIntent)service.getParcelableExtra(
11701 Intent.EXTRA_CLIENT_INTENT);
11702 } catch (RuntimeException e) {
11703 }
11704 if (clientIntent != null) {
11705 clientLabel = service.getIntExtra(Intent.EXTRA_CLIENT_LABEL, 0);
11706 if (clientLabel != 0) {
11707 // There are no useful extras in the intent, trash them.
11708 // System code calling with this stuff just needs to know
11709 // this will happen.
11710 service = service.cloneFilter();
11711 }
11712 }
11713 }
11714
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011715 ServiceLookupResult res =
11716 retrieveServiceLocked(service, resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011717 Binder.getCallingPid(), Binder.getCallingUid(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011718 if (res == null) {
11719 return 0;
11720 }
11721 if (res.record == null) {
11722 return -1;
11723 }
11724 ServiceRecord s = res.record;
11725
11726 final long origId = Binder.clearCallingIdentity();
11727
11728 if (unscheduleServiceRestartLocked(s)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011729 if (DEBUG_SERVICE) Slog.v(TAG, "BIND SERVICE WHILE RESTART PENDING: "
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011730 + s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011731 }
11732
11733 AppBindRecord b = s.retrieveAppBindingLocked(service, callerApp);
11734 ConnectionRecord c = new ConnectionRecord(b, activity,
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011735 connection, flags, clientLabel, clientIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011736
11737 IBinder binder = connection.asBinder();
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011738 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
11739 if (clist == null) {
11740 clist = new ArrayList<ConnectionRecord>();
11741 s.connections.put(binder, clist);
11742 }
11743 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011744 b.connections.add(c);
11745 if (activity != null) {
11746 if (activity.connections == null) {
11747 activity.connections = new HashSet<ConnectionRecord>();
11748 }
11749 activity.connections.add(c);
11750 }
11751 b.client.connections.add(c);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070011752 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
11753 b.client.hasAboveClient = true;
11754 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011755 clist = mServiceConnections.get(binder);
11756 if (clist == null) {
11757 clist = new ArrayList<ConnectionRecord>();
11758 mServiceConnections.put(binder, clist);
11759 }
11760 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011761
11762 if ((flags&Context.BIND_AUTO_CREATE) != 0) {
11763 s.lastActivity = SystemClock.uptimeMillis();
11764 if (!bringUpServiceLocked(s, service.getFlags(), false)) {
11765 return 0;
11766 }
11767 }
11768
11769 if (s.app != null) {
11770 // This could have made the service more important.
11771 updateOomAdjLocked(s.app);
11772 }
11773
Joe Onorato8a9b2202010-02-26 18:56:32 -080011774 if (DEBUG_SERVICE) Slog.v(TAG, "Bind " + s + " with " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011775 + ": received=" + b.intent.received
11776 + " apps=" + b.intent.apps.size()
11777 + " doRebind=" + b.intent.doRebind);
11778
11779 if (s.app != null && b.intent.received) {
11780 // Service is already running, so we can immediately
11781 // publish the connection.
11782 try {
11783 c.conn.connected(s.name, b.intent.binder);
11784 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011785 Slog.w(TAG, "Failure sending service " + s.shortName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011786 + " to connection " + c.conn.asBinder()
11787 + " (in " + c.binding.client.processName + ")", e);
11788 }
11789
11790 // If this is the first app connected back to this binding,
11791 // and the service had previously asked to be told when
11792 // rebound, then do so.
11793 if (b.intent.apps.size() == 1 && b.intent.doRebind) {
11794 requestServiceBindingLocked(s, b.intent, true);
11795 }
11796 } else if (!b.intent.requested) {
11797 requestServiceBindingLocked(s, b.intent, false);
11798 }
11799
11800 Binder.restoreCallingIdentity(origId);
11801 }
11802
11803 return 1;
11804 }
11805
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070011806 void removeConnectionLocked(
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011807 ConnectionRecord c, ProcessRecord skipApp, ActivityRecord skipAct) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011808 IBinder binder = c.conn.asBinder();
11809 AppBindRecord b = c.binding;
11810 ServiceRecord s = b.service;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011811 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
11812 if (clist != null) {
11813 clist.remove(c);
11814 if (clist.size() == 0) {
11815 s.connections.remove(binder);
11816 }
11817 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011818 b.connections.remove(c);
11819 if (c.activity != null && c.activity != skipAct) {
11820 if (c.activity.connections != null) {
11821 c.activity.connections.remove(c);
11822 }
11823 }
11824 if (b.client != skipApp) {
11825 b.client.connections.remove(c);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070011826 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
11827 b.client.updateHasAboveClientLocked();
11828 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011829 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011830 clist = mServiceConnections.get(binder);
11831 if (clist != null) {
11832 clist.remove(c);
11833 if (clist.size() == 0) {
11834 mServiceConnections.remove(binder);
11835 }
11836 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011837
11838 if (b.connections.size() == 0) {
11839 b.intent.apps.remove(b.client);
11840 }
11841
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011842 if (!c.serviceDead) {
11843 if (DEBUG_SERVICE) Slog.v(TAG, "Disconnecting binding " + b.intent
11844 + ": shouldUnbind=" + b.intent.hasBound);
11845 if (s.app != null && s.app.thread != null && b.intent.apps.size() == 0
11846 && b.intent.hasBound) {
11847 try {
11848 bumpServiceExecutingLocked(s, "unbind");
11849 updateOomAdjLocked(s.app);
11850 b.intent.hasBound = false;
11851 // Assume the client doesn't want to know about a rebind;
11852 // we will deal with that later if it asks for one.
11853 b.intent.doRebind = false;
11854 s.app.thread.scheduleUnbindService(s, b.intent.intent.getIntent());
11855 } catch (Exception e) {
11856 Slog.w(TAG, "Exception when unbinding service " + s.shortName, e);
11857 serviceDoneExecutingLocked(s, true);
11858 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011859 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011860
11861 if ((c.flags&Context.BIND_AUTO_CREATE) != 0) {
11862 bringDownServiceLocked(s, false);
11863 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011864 }
11865 }
11866
11867 public boolean unbindService(IServiceConnection connection) {
11868 synchronized (this) {
11869 IBinder binder = connection.asBinder();
Joe Onorato8a9b2202010-02-26 18:56:32 -080011870 if (DEBUG_SERVICE) Slog.v(TAG, "unbindService: conn=" + binder);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011871 ArrayList<ConnectionRecord> clist = mServiceConnections.get(binder);
11872 if (clist == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011873 Slog.w(TAG, "Unbind failed: could not find connection for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011874 + connection.asBinder());
11875 return false;
11876 }
11877
11878 final long origId = Binder.clearCallingIdentity();
11879
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011880 while (clist.size() > 0) {
11881 ConnectionRecord r = clist.get(0);
11882 removeConnectionLocked(r, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011883
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011884 if (r.binding.service.app != null) {
11885 // This could have made the service less important.
11886 updateOomAdjLocked(r.binding.service.app);
11887 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011888 }
11889
11890 Binder.restoreCallingIdentity(origId);
11891 }
11892
11893 return true;
11894 }
11895
11896 public void publishService(IBinder token, Intent intent, IBinder service) {
11897 // Refuse possible leaked file descriptors
11898 if (intent != null && intent.hasFileDescriptors() == true) {
11899 throw new IllegalArgumentException("File descriptors passed in Intent");
11900 }
11901
11902 synchronized(this) {
11903 if (!(token instanceof ServiceRecord)) {
11904 throw new IllegalArgumentException("Invalid service token");
11905 }
11906 ServiceRecord r = (ServiceRecord)token;
11907
11908 final long origId = Binder.clearCallingIdentity();
11909
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011910 if (DEBUG_SERVICE) Slog.v(TAG, "PUBLISHING " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011911 + " " + intent + ": " + service);
11912 if (r != null) {
11913 Intent.FilterComparison filter
11914 = new Intent.FilterComparison(intent);
11915 IntentBindRecord b = r.bindings.get(filter);
11916 if (b != null && !b.received) {
11917 b.binder = service;
11918 b.requested = true;
11919 b.received = true;
11920 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011921 Iterator<ArrayList<ConnectionRecord>> it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011922 = r.connections.values().iterator();
11923 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011924 ArrayList<ConnectionRecord> clist = it.next();
11925 for (int i=0; i<clist.size(); i++) {
11926 ConnectionRecord c = clist.get(i);
11927 if (!filter.equals(c.binding.intent.intent)) {
11928 if (DEBUG_SERVICE) Slog.v(
11929 TAG, "Not publishing to: " + c);
11930 if (DEBUG_SERVICE) Slog.v(
11931 TAG, "Bound intent: " + c.binding.intent.intent);
11932 if (DEBUG_SERVICE) Slog.v(
11933 TAG, "Published intent: " + intent);
11934 continue;
11935 }
11936 if (DEBUG_SERVICE) Slog.v(TAG, "Publishing to: " + c);
11937 try {
11938 c.conn.connected(r.name, service);
11939 } catch (Exception e) {
11940 Slog.w(TAG, "Failure sending service " + r.name +
11941 " to connection " + c.conn.asBinder() +
11942 " (in " + c.binding.client.processName + ")", e);
11943 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011944 }
11945 }
11946 }
11947 }
11948
11949 serviceDoneExecutingLocked(r, mStoppingServices.contains(r));
11950
11951 Binder.restoreCallingIdentity(origId);
11952 }
11953 }
11954 }
11955
11956 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
11957 // Refuse possible leaked file descriptors
11958 if (intent != null && intent.hasFileDescriptors() == true) {
11959 throw new IllegalArgumentException("File descriptors passed in Intent");
11960 }
11961
11962 synchronized(this) {
11963 if (!(token instanceof ServiceRecord)) {
11964 throw new IllegalArgumentException("Invalid service token");
11965 }
11966 ServiceRecord r = (ServiceRecord)token;
11967
11968 final long origId = Binder.clearCallingIdentity();
11969
11970 if (r != null) {
11971 Intent.FilterComparison filter
11972 = new Intent.FilterComparison(intent);
11973 IntentBindRecord b = r.bindings.get(filter);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011974 if (DEBUG_SERVICE) Slog.v(TAG, "unbindFinished in " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011975 + " at " + b + ": apps="
11976 + (b != null ? b.apps.size() : 0));
Per Edelberg78f9fff2010-08-30 20:01:35 +020011977
11978 boolean inStopping = mStoppingServices.contains(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011979 if (b != null) {
Per Edelberg78f9fff2010-08-30 20:01:35 +020011980 if (b.apps.size() > 0 && !inStopping) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011981 // Applications have already bound since the last
11982 // unbind, so just rebind right here.
11983 requestServiceBindingLocked(r, b, true);
11984 } else {
11985 // Note to tell the service the next time there is
11986 // a new client.
11987 b.doRebind = true;
11988 }
11989 }
11990
Per Edelberg78f9fff2010-08-30 20:01:35 +020011991 serviceDoneExecutingLocked(r, inStopping);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011992
11993 Binder.restoreCallingIdentity(origId);
11994 }
11995 }
11996 }
11997
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011998 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011999 synchronized(this) {
12000 if (!(token instanceof ServiceRecord)) {
12001 throw new IllegalArgumentException("Invalid service token");
12002 }
12003 ServiceRecord r = (ServiceRecord)token;
12004 boolean inStopping = mStoppingServices.contains(token);
12005 if (r != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012006 if (r != token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012007 Slog.w(TAG, "Done executing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012008 + " with incorrect token: given " + token
12009 + ", expected " + r);
12010 return;
12011 }
12012
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012013 if (type == 1) {
12014 // This is a call from a service start... take care of
12015 // book-keeping.
12016 r.callStart = true;
12017 switch (res) {
12018 case Service.START_STICKY_COMPATIBILITY:
12019 case Service.START_STICKY: {
12020 // We are done with the associated start arguments.
12021 r.findDeliveredStart(startId, true);
12022 // Don't stop if killed.
12023 r.stopIfKilled = false;
12024 break;
12025 }
12026 case Service.START_NOT_STICKY: {
12027 // We are done with the associated start arguments.
12028 r.findDeliveredStart(startId, true);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070012029 if (r.getLastStartId() == startId) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012030 // There is no more work, and this service
12031 // doesn't want to hang around if killed.
12032 r.stopIfKilled = true;
12033 }
12034 break;
12035 }
12036 case Service.START_REDELIVER_INTENT: {
12037 // We'll keep this item until they explicitly
12038 // call stop for it, but keep track of the fact
12039 // that it was delivered.
12040 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
12041 if (si != null) {
12042 si.deliveryCount = 0;
12043 si.doneExecutingCount++;
12044 // Don't stop if killed.
12045 r.stopIfKilled = true;
12046 }
12047 break;
12048 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070012049 case Service.START_TASK_REMOVED_COMPLETE: {
12050 // Special processing for onTaskRemoved(). Don't
12051 // impact normal onStartCommand() processing.
12052 r.findDeliveredStart(startId, true);
12053 break;
12054 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012055 default:
12056 throw new IllegalArgumentException(
12057 "Unknown service start result: " + res);
12058 }
12059 if (res == Service.START_STICKY_COMPATIBILITY) {
12060 r.callStart = false;
12061 }
12062 }
Amith Yamasani742a6712011-05-04 14:49:28 -070012063 if (DEBUG_MU)
12064 Slog.v(TAG_MU, "before serviceDontExecutingLocked, uid="
12065 + Binder.getOrigCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012066 final long origId = Binder.clearCallingIdentity();
12067 serviceDoneExecutingLocked(r, inStopping);
12068 Binder.restoreCallingIdentity(origId);
12069 } else {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012070 Slog.w(TAG, "Done executing unknown service from pid "
12071 + Binder.getCallingPid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012072 }
12073 }
12074 }
12075
12076 public void serviceDoneExecutingLocked(ServiceRecord r, boolean inStopping) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012077 if (DEBUG_SERVICE) Slog.v(TAG, "<<< DONE EXECUTING " + r
12078 + ": nesting=" + r.executeNesting
12079 + ", inStopping=" + inStopping + ", app=" + r.app);
Dianne Hackborn287952c2010-09-22 22:34:31 -070012080 else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG, "<<< DONE EXECUTING " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012081 r.executeNesting--;
12082 if (r.executeNesting <= 0 && r.app != null) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012083 if (DEBUG_SERVICE) Slog.v(TAG,
12084 "Nesting at 0 of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012085 r.app.executingServices.remove(r);
12086 if (r.app.executingServices.size() == 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012087 if (DEBUG_SERVICE || DEBUG_SERVICE_EXECUTING) Slog.v(TAG,
12088 "No more executingServices of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012089 mHandler.removeMessages(SERVICE_TIMEOUT_MSG, r.app);
12090 }
12091 if (inStopping) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012092 if (DEBUG_SERVICE) Slog.v(TAG,
12093 "doneExecuting remove stopping " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012094 mStoppingServices.remove(r);
Mattias Petersson3996b412010-10-27 09:32:51 +020012095 r.bindings.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012096 }
12097 updateOomAdjLocked(r.app);
12098 }
12099 }
12100
12101 void serviceTimeout(ProcessRecord proc) {
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012102 String anrMessage = null;
12103
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012104 synchronized(this) {
12105 if (proc.executingServices.size() == 0 || proc.thread == null) {
12106 return;
12107 }
12108 long maxTime = SystemClock.uptimeMillis() - SERVICE_TIMEOUT;
12109 Iterator<ServiceRecord> it = proc.executingServices.iterator();
12110 ServiceRecord timeout = null;
12111 long nextTime = 0;
12112 while (it.hasNext()) {
12113 ServiceRecord sr = it.next();
12114 if (sr.executingStart < maxTime) {
12115 timeout = sr;
12116 break;
12117 }
12118 if (sr.executingStart > nextTime) {
12119 nextTime = sr.executingStart;
12120 }
12121 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012122 if (timeout != null && mLruProcesses.contains(proc)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012123 Slog.w(TAG, "Timeout executing service: " + timeout);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012124 anrMessage = "Executing service " + timeout.shortName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012125 } else {
12126 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
12127 msg.obj = proc;
12128 mHandler.sendMessageAtTime(msg, nextTime+SERVICE_TIMEOUT);
12129 }
12130 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012131
12132 if (anrMessage != null) {
12133 appNotResponding(proc, null, null, anrMessage);
12134 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012135 }
12136
12137 // =========================================================
Christopher Tate181fafa2009-05-14 11:12:14 -070012138 // BACKUP AND RESTORE
12139 // =========================================================
12140
12141 // Cause the target app to be launched if necessary and its backup agent
12142 // instantiated. The backup agent will invoke backupAgentCreated() on the
12143 // activity manager to announce its creation.
12144 public boolean bindBackupAgent(ApplicationInfo app, int backupMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012145 if (DEBUG_BACKUP) Slog.v(TAG, "startBackupAgent: app=" + app + " mode=" + backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070012146 enforceCallingPermission("android.permission.BACKUP", "startBackupAgent");
12147
12148 synchronized(this) {
12149 // !!! TODO: currently no check here that we're already bound
12150 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
12151 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
12152 synchronized (stats) {
12153 ss = stats.getServiceStatsLocked(app.uid, app.packageName, app.name);
12154 }
12155
Dianne Hackborne7f97212011-02-24 14:40:20 -080012156 // Backup agent is now in use, its package can't be stopped.
12157 try {
12158 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -070012159 app.packageName, false, UserId.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -080012160 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080012161 } catch (IllegalArgumentException e) {
12162 Slog.w(TAG, "Failed trying to unstop package "
12163 + app.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080012164 }
12165
Christopher Tate181fafa2009-05-14 11:12:14 -070012166 BackupRecord r = new BackupRecord(ss, app, backupMode);
Christopher Tate4a627c72011-04-01 14:43:32 -070012167 ComponentName hostingName = (backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL)
12168 ? new ComponentName(app.packageName, app.backupAgentName)
12169 : new ComponentName("android", "FullBackupAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -070012170 // startProcessLocked() returns existing proc's record if it's already running
12171 ProcessRecord proc = startProcessLocked(app.processName, app,
Dianne Hackborna0c283e2012-02-09 10:47:01 -080012172 false, 0, "backup", hostingName, false, false);
Christopher Tate181fafa2009-05-14 11:12:14 -070012173 if (proc == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012174 Slog.e(TAG, "Unable to start backup agent process " + r);
Christopher Tate181fafa2009-05-14 11:12:14 -070012175 return false;
12176 }
12177
12178 r.app = proc;
12179 mBackupTarget = r;
12180 mBackupAppName = app.packageName;
12181
Christopher Tate6fa95972009-06-05 18:43:55 -070012182 // Try not to kill the process during backup
12183 updateOomAdjLocked(proc);
12184
Christopher Tate181fafa2009-05-14 11:12:14 -070012185 // If the process is already attached, schedule the creation of the backup agent now.
12186 // If it is not yet live, this will be done when it attaches to the framework.
12187 if (proc.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012188 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc already running: " + proc);
Christopher Tate181fafa2009-05-14 11:12:14 -070012189 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040012190 proc.thread.scheduleCreateBackupAgent(app,
12191 compatibilityInfoForPackageLocked(app), backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070012192 } catch (RemoteException e) {
Christopher Tate436344a2009-09-30 16:17:37 -070012193 // Will time out on the backup manager side
Christopher Tate181fafa2009-05-14 11:12:14 -070012194 }
12195 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012196 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc not running, waiting for attach");
Christopher Tate181fafa2009-05-14 11:12:14 -070012197 }
12198 // Invariants: at this point, the target app process exists and the application
12199 // is either already running or in the process of coming up. mBackupTarget and
12200 // mBackupAppName describe the app, so that when it binds back to the AM we
12201 // know that it's scheduled for a backup-agent operation.
12202 }
12203
12204 return true;
12205 }
12206
12207 // A backup agent has just come up
12208 public void backupAgentCreated(String agentPackageName, IBinder agent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012209 if (DEBUG_BACKUP) Slog.v(TAG, "backupAgentCreated: " + agentPackageName
Christopher Tate181fafa2009-05-14 11:12:14 -070012210 + " = " + agent);
12211
12212 synchronized(this) {
12213 if (!agentPackageName.equals(mBackupAppName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012214 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
Christopher Tate181fafa2009-05-14 11:12:14 -070012215 return;
12216 }
Dianne Hackborn06740692010-09-22 22:46:21 -070012217 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012218
Dianne Hackborn06740692010-09-22 22:46:21 -070012219 long oldIdent = Binder.clearCallingIdentity();
12220 try {
12221 IBackupManager bm = IBackupManager.Stub.asInterface(
12222 ServiceManager.getService(Context.BACKUP_SERVICE));
12223 bm.agentConnected(agentPackageName, agent);
12224 } catch (RemoteException e) {
12225 // can't happen; the backup manager service is local
12226 } catch (Exception e) {
12227 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: ");
12228 e.printStackTrace();
12229 } finally {
12230 Binder.restoreCallingIdentity(oldIdent);
Christopher Tate181fafa2009-05-14 11:12:14 -070012231 }
12232 }
12233
12234 // done with this agent
12235 public void unbindBackupAgent(ApplicationInfo appInfo) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012236 if (DEBUG_BACKUP) Slog.v(TAG, "unbindBackupAgent: " + appInfo);
Christopher Tate8a27f922009-06-26 11:49:18 -070012237 if (appInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012238 Slog.w(TAG, "unbind backup agent for null app");
Christopher Tate8a27f922009-06-26 11:49:18 -070012239 return;
12240 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012241
12242 synchronized(this) {
Christopher Tate8a27f922009-06-26 11:49:18 -070012243 if (mBackupAppName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012244 Slog.w(TAG, "Unbinding backup agent with no active backup");
Christopher Tate8a27f922009-06-26 11:49:18 -070012245 return;
12246 }
12247
Christopher Tate181fafa2009-05-14 11:12:14 -070012248 if (!mBackupAppName.equals(appInfo.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012249 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
Christopher Tate181fafa2009-05-14 11:12:14 -070012250 return;
12251 }
12252
Christopher Tate6fa95972009-06-05 18:43:55 -070012253 ProcessRecord proc = mBackupTarget.app;
12254 mBackupTarget = null;
12255 mBackupAppName = null;
12256
12257 // Not backing this app up any more; reset its OOM adjustment
12258 updateOomAdjLocked(proc);
12259
Christopher Tatec7b31e32009-06-10 15:49:30 -070012260 // If the app crashed during backup, 'thread' will be null here
12261 if (proc.thread != null) {
12262 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040012263 proc.thread.scheduleDestroyBackupAgent(appInfo,
12264 compatibilityInfoForPackageLocked(appInfo));
Christopher Tatec7b31e32009-06-10 15:49:30 -070012265 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012266 Slog.e(TAG, "Exception when unbinding backup agent:");
Christopher Tatec7b31e32009-06-10 15:49:30 -070012267 e.printStackTrace();
12268 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012269 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012270 }
12271 }
12272 // =========================================================
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012273 // BROADCASTS
12274 // =========================================================
12275
Josh Bartel7f208742010-02-25 11:01:44 -060012276 private final List getStickiesLocked(String action, IntentFilter filter,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012277 List cur) {
12278 final ContentResolver resolver = mContext.getContentResolver();
12279 final ArrayList<Intent> list = mStickyBroadcasts.get(action);
12280 if (list == null) {
12281 return cur;
12282 }
12283 int N = list.size();
12284 for (int i=0; i<N; i++) {
12285 Intent intent = list.get(i);
12286 if (filter.match(resolver, intent, true, TAG) >= 0) {
12287 if (cur == null) {
12288 cur = new ArrayList<Intent>();
12289 }
12290 cur.add(intent);
12291 }
12292 }
12293 return cur;
12294 }
12295
Christopher Tatef46723b2012-01-26 14:19:24 -080012296 boolean isPendingBroadcastProcessLocked(int pid) {
12297 return mFgBroadcastQueue.isPendingBroadcastProcessLocked(pid)
12298 || mBgBroadcastQueue.isPendingBroadcastProcessLocked(pid);
12299 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012300
Christopher Tatef46723b2012-01-26 14:19:24 -080012301 void skipPendingBroadcastLocked(int pid) {
12302 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
12303 for (BroadcastQueue queue : mBroadcastQueues) {
12304 queue.skipPendingBroadcastLocked(pid);
12305 }
12306 }
12307
12308 // The app just attached; send any pending broadcasts that it should receive
12309 boolean sendPendingBroadcastsLocked(ProcessRecord app) {
12310 boolean didSomething = false;
12311 for (BroadcastQueue queue : mBroadcastQueues) {
12312 didSomething |= queue.sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012313 }
Christopher Tatef46723b2012-01-26 14:19:24 -080012314 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012315 }
12316
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012317 public Intent registerReceiver(IApplicationThread caller, String callerPackage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012318 IIntentReceiver receiver, IntentFilter filter, String permission) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012319 enforceNotIsolatedCaller("registerReceiver");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012320 synchronized(this) {
12321 ProcessRecord callerApp = null;
12322 if (caller != null) {
12323 callerApp = getRecordForAppLocked(caller);
12324 if (callerApp == null) {
12325 throw new SecurityException(
12326 "Unable to find app for caller " + caller
12327 + " (pid=" + Binder.getCallingPid()
12328 + ") when registering receiver " + receiver);
12329 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012330 if (callerApp.info.uid != Process.SYSTEM_UID &&
12331 !callerApp.pkgList.contains(callerPackage)) {
12332 throw new SecurityException("Given caller package " + callerPackage
12333 + " is not running in process " + callerApp);
12334 }
12335 } else {
12336 callerPackage = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012337 }
12338
12339 List allSticky = null;
12340
12341 // Look for any matching sticky broadcasts...
12342 Iterator actions = filter.actionsIterator();
12343 if (actions != null) {
12344 while (actions.hasNext()) {
12345 String action = (String)actions.next();
Josh Bartel7f208742010-02-25 11:01:44 -060012346 allSticky = getStickiesLocked(action, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012347 }
12348 } else {
Josh Bartel7f208742010-02-25 11:01:44 -060012349 allSticky = getStickiesLocked(null, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012350 }
12351
12352 // The first sticky in the list is returned directly back to
12353 // the client.
12354 Intent sticky = allSticky != null ? (Intent)allSticky.get(0) : null;
12355
Joe Onorato8a9b2202010-02-26 18:56:32 -080012356 if (DEBUG_BROADCAST) Slog.v(TAG, "Register receiver " + filter
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012357 + ": " + sticky);
12358
12359 if (receiver == null) {
12360 return sticky;
12361 }
12362
12363 ReceiverList rl
12364 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
12365 if (rl == null) {
12366 rl = new ReceiverList(this, callerApp,
12367 Binder.getCallingPid(),
12368 Binder.getCallingUid(), receiver);
12369 if (rl.app != null) {
12370 rl.app.receivers.add(rl);
12371 } else {
12372 try {
12373 receiver.asBinder().linkToDeath(rl, 0);
12374 } catch (RemoteException e) {
12375 return sticky;
12376 }
12377 rl.linkedToDeath = true;
12378 }
12379 mRegisteredReceivers.put(receiver.asBinder(), rl);
12380 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012381 BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage, permission);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012382 rl.add(bf);
12383 if (!bf.debugCheck()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012384 Slog.w(TAG, "==> For Dynamic broadast");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012385 }
12386 mReceiverResolver.addFilter(bf);
12387
12388 // Enqueue broadcasts for all existing stickies that match
12389 // this filter.
12390 if (allSticky != null) {
12391 ArrayList receivers = new ArrayList();
12392 receivers.add(bf);
12393
12394 int N = allSticky.size();
12395 for (int i=0; i<N; i++) {
12396 Intent intent = (Intent)allSticky.get(i);
Christopher Tatef46723b2012-01-26 14:19:24 -080012397 BroadcastQueue queue = broadcastQueueForIntent(intent);
12398 BroadcastRecord r = new BroadcastRecord(queue, intent, null,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012399 null, -1, -1, null, receivers, null, 0, null, null,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012400 false, true, true);
Christopher Tatef46723b2012-01-26 14:19:24 -080012401 queue.enqueueParallelBroadcastLocked(r);
12402 queue.scheduleBroadcastsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012403 }
12404 }
12405
12406 return sticky;
12407 }
12408 }
12409
12410 public void unregisterReceiver(IIntentReceiver receiver) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012411 if (DEBUG_BROADCAST) Slog.v(TAG, "Unregister receiver: " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012412
Christopher Tatef46723b2012-01-26 14:19:24 -080012413 final long origId = Binder.clearCallingIdentity();
12414 try {
12415 boolean doTrim = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012416
Christopher Tatef46723b2012-01-26 14:19:24 -080012417 synchronized(this) {
12418 ReceiverList rl
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012419 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
Christopher Tatef46723b2012-01-26 14:19:24 -080012420 if (rl != null) {
12421 if (rl.curBroadcast != null) {
12422 BroadcastRecord r = rl.curBroadcast;
12423 final boolean doNext = finishReceiverLocked(
12424 receiver.asBinder(), r.resultCode, r.resultData,
12425 r.resultExtras, r.resultAbort, true);
12426 if (doNext) {
12427 doTrim = true;
12428 r.queue.processNextBroadcast(false);
12429 }
12430 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012431
Christopher Tatef46723b2012-01-26 14:19:24 -080012432 if (rl.app != null) {
12433 rl.app.receivers.remove(rl);
12434 }
12435 removeReceiverLocked(rl);
12436 if (rl.linkedToDeath) {
12437 rl.linkedToDeath = false;
12438 rl.receiver.asBinder().unlinkToDeath(rl, 0);
12439 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012440 }
12441 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012442
Christopher Tatef46723b2012-01-26 14:19:24 -080012443 // If we actually concluded any broadcasts, we might now be able
12444 // to trim the recipients' apps from our working set
12445 if (doTrim) {
12446 trimApplications();
12447 return;
12448 }
12449
12450 } finally {
12451 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012452 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012453 }
12454
12455 void removeReceiverLocked(ReceiverList rl) {
12456 mRegisteredReceivers.remove(rl.receiver.asBinder());
12457 int N = rl.size();
12458 for (int i=0; i<N; i++) {
12459 mReceiverResolver.removeFilter(rl.get(i));
12460 }
12461 }
12462
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012463 private final void sendPackageBroadcastLocked(int cmd, String[] packages) {
12464 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
12465 ProcessRecord r = mLruProcesses.get(i);
12466 if (r.thread != null) {
12467 try {
12468 r.thread.dispatchPackageBroadcast(cmd, packages);
12469 } catch (RemoteException ex) {
12470 }
12471 }
12472 }
12473 }
12474
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012475 private final int broadcastIntentLocked(ProcessRecord callerApp,
12476 String callerPackage, Intent intent, String resolvedType,
12477 IIntentReceiver resultTo, int resultCode, String resultData,
12478 Bundle map, String requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070012479 boolean ordered, boolean sticky, int callingPid, int callingUid,
12480 int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012481 intent = new Intent(intent);
12482
Dianne Hackborne7f97212011-02-24 14:40:20 -080012483 // By default broadcasts do not go to stopped apps.
12484 intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
12485
Joe Onorato8a9b2202010-02-26 18:56:32 -080012486 if (DEBUG_BROADCAST_LIGHT) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012487 TAG, (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
Amith Yamasani13593602012-03-22 16:16:17 -070012488 + " ordered=" + ordered + " userid=" + userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012489 if ((resultTo != null) && !ordered) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012490 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012491 }
12492
12493 // Handle special intents: if this broadcast is from the package
12494 // manager about a package being removed, we need to remove all of
12495 // its activities from the history stack.
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012496 final boolean uidRemoved = Intent.ACTION_UID_REMOVED.equals(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012497 intent.getAction());
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012498 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())
12499 || Intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction())
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080012500 || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012501 || uidRemoved) {
12502 if (checkComponentPermission(
12503 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080012504 callingPid, callingUid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012505 == PackageManager.PERMISSION_GRANTED) {
12506 if (uidRemoved) {
12507 final Bundle intentExtras = intent.getExtras();
12508 final int uid = intentExtras != null
12509 ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
12510 if (uid >= 0) {
12511 BatteryStatsImpl bs = mBatteryStatsService.getActiveStatistics();
12512 synchronized (bs) {
12513 bs.removeUidStatsLocked(uid);
12514 }
12515 }
12516 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012517 // If resources are unvailble just force stop all
12518 // those packages and flush the attribute cache as well.
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080012519 if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012520 String list[] = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
12521 if (list != null && (list.length > 0)) {
12522 for (String pkg : list) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070012523 forceStopPackageLocked(pkg, -1, false, true, true, false, userId);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012524 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012525 sendPackageBroadcastLocked(
12526 IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE, list);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012527 }
12528 } else {
12529 Uri data = intent.getData();
12530 String ssp;
12531 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
12532 if (!intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false)) {
12533 forceStopPackageLocked(ssp,
Amith Yamasani483f3b02012-03-13 16:08:00 -070012534 intent.getIntExtra(Intent.EXTRA_UID, -1), false, true, true,
12535 false, userId);
Dianne Hackbornde7faf62009-06-30 13:27:30 -070012536 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012537 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012538 sendPackageBroadcastLocked(IApplicationThread.PACKAGE_REMOVED,
12539 new String[] {ssp});
12540 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012541 }
12542 }
12543 }
12544 } else {
12545 String msg = "Permission Denial: " + intent.getAction()
12546 + " broadcast from " + callerPackage + " (pid=" + callingPid
12547 + ", uid=" + callingUid + ")"
12548 + " requires "
12549 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012550 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012551 throw new SecurityException(msg);
12552 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012553
12554 // Special case for adding a package: by default turn on compatibility
12555 // mode.
12556 } else if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -070012557 Uri data = intent.getData();
12558 String ssp;
12559 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
12560 mCompatModePackages.handlePackageAddedLocked(ssp,
12561 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false));
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012562 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012563 }
12564
12565 /*
12566 * If this is the time zone changed action, queue up a message that will reset the timezone
12567 * of all currently running processes. This message will get queued up before the broadcast
12568 * happens.
12569 */
12570 if (intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) {
12571 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
12572 }
12573
Robert Greenwalt03595d02010-11-02 14:08:23 -070012574 if (intent.ACTION_CLEAR_DNS_CACHE.equals(intent.getAction())) {
12575 mHandler.sendEmptyMessage(CLEAR_DNS_CACHE);
12576 }
12577
Robert Greenwalt434203a2010-10-11 16:00:27 -070012578 if (Proxy.PROXY_CHANGE_ACTION.equals(intent.getAction())) {
12579 ProxyProperties proxy = intent.getParcelableExtra("proxy");
12580 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY, proxy));
12581 }
12582
Dianne Hackborn854060af2009-07-09 18:14:31 -070012583 /*
12584 * Prevent non-system code (defined here to be non-persistent
12585 * processes) from sending protected broadcasts.
12586 */
12587 if (callingUid == Process.SYSTEM_UID || callingUid == Process.PHONE_UID
12588 || callingUid == Process.SHELL_UID || callingUid == 0) {
12589 // Always okay.
12590 } else if (callerApp == null || !callerApp.persistent) {
12591 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012592 if (AppGlobals.getPackageManager().isProtectedBroadcast(
Dianne Hackborn854060af2009-07-09 18:14:31 -070012593 intent.getAction())) {
12594 String msg = "Permission Denial: not allowed to send broadcast "
12595 + intent.getAction() + " from pid="
12596 + callingPid + ", uid=" + callingUid;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012597 Slog.w(TAG, msg);
Dianne Hackborn854060af2009-07-09 18:14:31 -070012598 throw new SecurityException(msg);
12599 }
12600 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012601 Slog.w(TAG, "Remote exception", e);
Dianne Hackborna4972e92012-03-14 10:38:05 -070012602 return ActivityManager.BROADCAST_SUCCESS;
Dianne Hackborn854060af2009-07-09 18:14:31 -070012603 }
12604 }
12605
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012606 // Add to the sticky list if requested.
12607 if (sticky) {
12608 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
12609 callingPid, callingUid)
12610 != PackageManager.PERMISSION_GRANTED) {
12611 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
12612 + callingPid + ", uid=" + callingUid
12613 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012614 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012615 throw new SecurityException(msg);
12616 }
12617 if (requiredPermission != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012618 Slog.w(TAG, "Can't broadcast sticky intent " + intent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012619 + " and enforce permission " + requiredPermission);
Dianne Hackborna4972e92012-03-14 10:38:05 -070012620 return ActivityManager.BROADCAST_STICKY_CANT_HAVE_PERMISSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012621 }
12622 if (intent.getComponent() != null) {
12623 throw new SecurityException(
12624 "Sticky broadcasts can't target a specific component");
12625 }
12626 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
12627 if (list == null) {
12628 list = new ArrayList<Intent>();
12629 mStickyBroadcasts.put(intent.getAction(), list);
12630 }
12631 int N = list.size();
12632 int i;
12633 for (i=0; i<N; i++) {
12634 if (intent.filterEquals(list.get(i))) {
12635 // This sticky already exists, replace it.
12636 list.set(i, new Intent(intent));
12637 break;
12638 }
12639 }
12640 if (i >= N) {
12641 list.add(new Intent(intent));
12642 }
12643 }
12644
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012645 // Figure out who all will receive this broadcast.
12646 List receivers = null;
12647 List<BroadcastFilter> registeredReceivers = null;
12648 try {
12649 if (intent.getComponent() != null) {
12650 // Broadcast is going to one specific receiver class...
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012651 ActivityInfo ai = AppGlobals.getPackageManager().
Amith Yamasani483f3b02012-03-13 16:08:00 -070012652 getReceiverInfo(intent.getComponent(), STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012653 if (ai != null) {
12654 receivers = new ArrayList();
12655 ResolveInfo ri = new ResolveInfo();
Amith Yamasani742a6712011-05-04 14:49:28 -070012656 ri.activityInfo = getActivityInfoForUser(ai, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012657 receivers.add(ri);
12658 }
12659 } else {
12660 // Need to resolve the intent to interested receivers...
12661 if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
12662 == 0) {
12663 receivers =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012664 AppGlobals.getPackageManager().queryIntentReceivers(
Amith Yamasani483f3b02012-03-13 16:08:00 -070012665 intent, resolvedType, STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012666 }
Amith Yamasani483f3b02012-03-13 16:08:00 -070012667 registeredReceivers = mReceiverResolver.queryIntent(intent, resolvedType, false,
12668 userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012669 }
12670 } catch (RemoteException ex) {
12671 // pm is in same process, this will never happen.
12672 }
12673
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012674 final boolean replacePending =
12675 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
12676
Joe Onorato8a9b2202010-02-26 18:56:32 -080012677 if (DEBUG_BROADCAST) Slog.v(TAG, "Enqueing broadcast: " + intent.getAction()
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012678 + " replacePending=" + replacePending);
12679
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012680 int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
12681 if (!ordered && NR > 0) {
12682 // If we are not serializing this broadcast, then send the
12683 // registered receivers separately so they don't wait for the
12684 // components to be launched.
Christopher Tatef46723b2012-01-26 14:19:24 -080012685 final BroadcastQueue queue = broadcastQueueForIntent(intent);
12686 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012687 callerPackage, callingPid, callingUid, requiredPermission,
12688 registeredReceivers, resultTo, resultCode, resultData, map,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012689 ordered, sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012690 if (DEBUG_BROADCAST) Slog.v(
Christopher Tatef46723b2012-01-26 14:19:24 -080012691 TAG, "Enqueueing parallel broadcast " + r);
12692 final boolean replaced = replacePending && queue.replaceParallelBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012693 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012694 queue.enqueueParallelBroadcastLocked(r);
12695 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012696 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012697 registeredReceivers = null;
12698 NR = 0;
12699 }
12700
12701 // Merge into one list.
12702 int ir = 0;
12703 if (receivers != null) {
12704 // A special case for PACKAGE_ADDED: do not allow the package
12705 // being added to see this broadcast. This prevents them from
12706 // using this as a back door to get run as soon as they are
12707 // installed. Maybe in the future we want to have a special install
12708 // broadcast or such for apps, but we'd like to deliberately make
12709 // this decision.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012710 String skipPackages[] = null;
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012711 if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
12712 || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
12713 || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012714 Uri data = intent.getData();
12715 if (data != null) {
12716 String pkgName = data.getSchemeSpecificPart();
12717 if (pkgName != null) {
12718 skipPackages = new String[] { pkgName };
12719 }
12720 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012721 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012722 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
The Android Open Source Project10592532009-03-18 17:39:46 -070012723 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012724 if (skipPackages != null && (skipPackages.length > 0)) {
12725 for (String skipPackage : skipPackages) {
12726 if (skipPackage != null) {
12727 int NT = receivers.size();
12728 for (int it=0; it<NT; it++) {
12729 ResolveInfo curt = (ResolveInfo)receivers.get(it);
12730 if (curt.activityInfo.packageName.equals(skipPackage)) {
12731 receivers.remove(it);
12732 it--;
12733 NT--;
12734 }
12735 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012736 }
12737 }
12738 }
12739
12740 int NT = receivers != null ? receivers.size() : 0;
12741 int it = 0;
12742 ResolveInfo curt = null;
12743 BroadcastFilter curr = null;
12744 while (it < NT && ir < NR) {
12745 if (curt == null) {
12746 curt = (ResolveInfo)receivers.get(it);
12747 }
12748 if (curr == null) {
12749 curr = registeredReceivers.get(ir);
12750 }
12751 if (curr.getPriority() >= curt.priority) {
12752 // Insert this broadcast record into the final list.
12753 receivers.add(it, curr);
12754 ir++;
12755 curr = null;
12756 it++;
12757 NT++;
12758 } else {
12759 // Skip to the next ResolveInfo in the final list.
12760 it++;
12761 curt = null;
12762 }
12763 }
12764 }
12765 while (ir < NR) {
12766 if (receivers == null) {
12767 receivers = new ArrayList();
12768 }
12769 receivers.add(registeredReceivers.get(ir));
12770 ir++;
12771 }
12772
12773 if ((receivers != null && receivers.size() > 0)
12774 || resultTo != null) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012775 BroadcastQueue queue = broadcastQueueForIntent(intent);
12776 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012777 callerPackage, callingPid, callingUid, requiredPermission,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012778 receivers, resultTo, resultCode, resultData, map, ordered,
12779 sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012780 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012781 TAG, "Enqueueing ordered broadcast " + r
Christopher Tatef46723b2012-01-26 14:19:24 -080012782 + ": prev had " + queue.mOrderedBroadcasts.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012783 if (DEBUG_BROADCAST) {
12784 int seq = r.intent.getIntExtra("seq", -1);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012785 Slog.i(TAG, "Enqueueing broadcast " + r.intent.getAction() + " seq=" + seq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012786 }
Christopher Tatef46723b2012-01-26 14:19:24 -080012787 boolean replaced = replacePending && queue.replaceOrderedBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012788 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012789 queue.enqueueOrderedBroadcastLocked(r);
12790 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012791 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012792 }
12793
Dianne Hackborna4972e92012-03-14 10:38:05 -070012794 return ActivityManager.BROADCAST_SUCCESS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012795 }
12796
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012797 final Intent verifyBroadcastLocked(Intent intent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012798 // Refuse possible leaked file descriptors
12799 if (intent != null && intent.hasFileDescriptors() == true) {
12800 throw new IllegalArgumentException("File descriptors passed in Intent");
12801 }
12802
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012803 int flags = intent.getFlags();
12804
12805 if (!mProcessesReady) {
12806 // if the caller really truly claims to know what they're doing, go
12807 // ahead and allow the broadcast without launching any receivers
12808 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
12809 intent = new Intent(intent);
12810 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
12811 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
12812 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
12813 + " before boot completion");
12814 throw new IllegalStateException("Cannot broadcast before boot completed");
12815 }
12816 }
12817
12818 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
12819 throw new IllegalArgumentException(
12820 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
12821 }
12822
12823 return intent;
12824 }
12825
12826 public final int broadcastIntent(IApplicationThread caller,
12827 Intent intent, String resolvedType, IIntentReceiver resultTo,
12828 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070012829 String requiredPermission, boolean serialized, boolean sticky, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012830 enforceNotIsolatedCaller("broadcastIntent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012831 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012832 intent = verifyBroadcastLocked(intent);
Dianne Hackborn9acc0302009-08-25 00:27:12 -070012833
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012834 final ProcessRecord callerApp = getRecordForAppLocked(caller);
12835 final int callingPid = Binder.getCallingPid();
12836 final int callingUid = Binder.getCallingUid();
12837 final long origId = Binder.clearCallingIdentity();
12838 int res = broadcastIntentLocked(callerApp,
12839 callerApp != null ? callerApp.info.packageName : null,
12840 intent, resolvedType, resultTo,
Amith Yamasani742a6712011-05-04 14:49:28 -070012841 resultCode, resultData, map, requiredPermission, serialized, sticky,
12842 callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012843 Binder.restoreCallingIdentity(origId);
12844 return res;
12845 }
12846 }
12847
12848 int broadcastIntentInPackage(String packageName, int uid,
12849 Intent intent, String resolvedType, IIntentReceiver resultTo,
12850 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070012851 String requiredPermission, boolean serialized, boolean sticky, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012852 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012853 intent = verifyBroadcastLocked(intent);
12854
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012855 final long origId = Binder.clearCallingIdentity();
12856 int res = broadcastIntentLocked(null, packageName, intent, resolvedType,
12857 resultTo, resultCode, resultData, map, requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070012858 serialized, sticky, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012859 Binder.restoreCallingIdentity(origId);
12860 return res;
12861 }
12862 }
12863
Amith Yamasani742a6712011-05-04 14:49:28 -070012864 // TODO: Use the userId; maybe mStickyBroadcasts need to be tied to the user.
12865 public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012866 // Refuse possible leaked file descriptors
12867 if (intent != null && intent.hasFileDescriptors() == true) {
12868 throw new IllegalArgumentException("File descriptors passed in Intent");
12869 }
12870
12871 synchronized(this) {
12872 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
12873 != PackageManager.PERMISSION_GRANTED) {
12874 String msg = "Permission Denial: unbroadcastIntent() from pid="
12875 + Binder.getCallingPid()
12876 + ", uid=" + Binder.getCallingUid()
12877 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012878 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012879 throw new SecurityException(msg);
12880 }
12881 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
12882 if (list != null) {
12883 int N = list.size();
12884 int i;
12885 for (i=0; i<N; i++) {
12886 if (intent.filterEquals(list.get(i))) {
12887 list.remove(i);
12888 break;
12889 }
12890 }
12891 }
12892 }
12893 }
12894
12895 private final boolean finishReceiverLocked(IBinder receiver, int resultCode,
12896 String resultData, Bundle resultExtras, boolean resultAbort,
12897 boolean explicit) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012898 final BroadcastRecord r = broadcastRecordForReceiverLocked(receiver);
12899 if (r == null) {
12900 Slog.w(TAG, "finishReceiver called but not found on queue");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012901 return false;
12902 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012903
Christopher Tatef46723b2012-01-26 14:19:24 -080012904 return r.queue.finishReceiverLocked(r, resultCode, resultData, resultExtras, resultAbort,
12905 explicit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012906 }
12907
12908 public void finishReceiver(IBinder who, int resultCode, String resultData,
12909 Bundle resultExtras, boolean resultAbort) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012910 if (DEBUG_BROADCAST) Slog.v(TAG, "Finish receiver: " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012911
12912 // Refuse possible leaked file descriptors
12913 if (resultExtras != null && resultExtras.hasFileDescriptors()) {
12914 throw new IllegalArgumentException("File descriptors passed in Bundle");
12915 }
12916
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012917 final long origId = Binder.clearCallingIdentity();
Christopher Tatef46723b2012-01-26 14:19:24 -080012918 try {
12919 boolean doNext = false;
12920 BroadcastRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012921
Christopher Tatef46723b2012-01-26 14:19:24 -080012922 synchronized(this) {
12923 r = broadcastRecordForReceiverLocked(who);
12924 if (r != null) {
12925 doNext = r.queue.finishReceiverLocked(r, resultCode,
12926 resultData, resultExtras, resultAbort, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012927 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012928 }
Jeff Brown4d94a762010-09-23 11:33:28 -070012929
Christopher Tatef46723b2012-01-26 14:19:24 -080012930 if (doNext) {
12931 r.queue.processNextBroadcast(false);
12932 }
12933 trimApplications();
12934 } finally {
12935 Binder.restoreCallingIdentity(origId);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012936 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012937 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012938
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012939 // =========================================================
12940 // INSTRUMENTATION
12941 // =========================================================
12942
12943 public boolean startInstrumentation(ComponentName className,
12944 String profileFile, int flags, Bundle arguments,
12945 IInstrumentationWatcher watcher) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012946 enforceNotIsolatedCaller("startInstrumentation");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012947 // Refuse possible leaked file descriptors
12948 if (arguments != null && arguments.hasFileDescriptors()) {
12949 throw new IllegalArgumentException("File descriptors passed in Bundle");
12950 }
12951
12952 synchronized(this) {
12953 InstrumentationInfo ii = null;
12954 ApplicationInfo ai = null;
12955 try {
12956 ii = mContext.getPackageManager().getInstrumentationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070012957 className, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012958 ai = mContext.getPackageManager().getApplicationInfo(
Amith Yamasani483f3b02012-03-13 16:08:00 -070012959 ii.targetPackage, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012960 } catch (PackageManager.NameNotFoundException e) {
12961 }
12962 if (ii == null) {
12963 reportStartInstrumentationFailure(watcher, className,
12964 "Unable to find instrumentation info for: " + className);
12965 return false;
12966 }
12967 if (ai == null) {
12968 reportStartInstrumentationFailure(watcher, className,
12969 "Unable to find instrumentation target package: " + ii.targetPackage);
12970 return false;
12971 }
12972
12973 int match = mContext.getPackageManager().checkSignatures(
12974 ii.targetPackage, ii.packageName);
12975 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
12976 String msg = "Permission Denial: starting instrumentation "
12977 + className + " from pid="
12978 + Binder.getCallingPid()
12979 + ", uid=" + Binder.getCallingPid()
12980 + " not allowed because package " + ii.packageName
12981 + " does not have a signature matching the target "
12982 + ii.targetPackage;
12983 reportStartInstrumentationFailure(watcher, className, msg);
12984 throw new SecurityException(msg);
12985 }
12986
Amith Yamasani483f3b02012-03-13 16:08:00 -070012987 int userId = UserId.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012988 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -070012989 // Instrumentation can kill and relaunch even persistent processes
Amith Yamasani483f3b02012-03-13 16:08:00 -070012990 forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true, userId);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080012991 ProcessRecord app = addAppLocked(ai, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012992 app.instrumentationClass = className;
Dianne Hackborn1655be42009-05-08 14:29:01 -070012993 app.instrumentationInfo = ai;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012994 app.instrumentationProfileFile = profileFile;
12995 app.instrumentationArguments = arguments;
12996 app.instrumentationWatcher = watcher;
12997 app.instrumentationResultClass = className;
12998 Binder.restoreCallingIdentity(origId);
12999 }
13000
13001 return true;
13002 }
13003
13004 /**
13005 * Report errors that occur while attempting to start Instrumentation. Always writes the
13006 * error to the logs, but if somebody is watching, send the report there too. This enables
13007 * the "am" command to report errors with more information.
13008 *
13009 * @param watcher The IInstrumentationWatcher. Null if there isn't one.
13010 * @param cn The component name of the instrumentation.
13011 * @param report The error report.
13012 */
13013 private void reportStartInstrumentationFailure(IInstrumentationWatcher watcher,
13014 ComponentName cn, String report) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013015 Slog.w(TAG, report);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013016 try {
13017 if (watcher != null) {
13018 Bundle results = new Bundle();
13019 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
13020 results.putString("Error", report);
13021 watcher.instrumentationStatus(cn, -1, results);
13022 }
13023 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013024 Slog.w(TAG, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013025 }
13026 }
13027
13028 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
13029 if (app.instrumentationWatcher != null) {
13030 try {
13031 // NOTE: IInstrumentationWatcher *must* be oneway here
13032 app.instrumentationWatcher.instrumentationFinished(
13033 app.instrumentationClass,
13034 resultCode,
13035 results);
13036 } catch (RemoteException e) {
13037 }
13038 }
13039 app.instrumentationWatcher = null;
13040 app.instrumentationClass = null;
Dianne Hackborn1655be42009-05-08 14:29:01 -070013041 app.instrumentationInfo = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013042 app.instrumentationProfileFile = null;
13043 app.instrumentationArguments = null;
13044
Amith Yamasani483f3b02012-03-13 16:08:00 -070013045 forceStopPackageLocked(app.processName, -1, false, false, true, true, app.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013046 }
13047
13048 public void finishInstrumentation(IApplicationThread target,
13049 int resultCode, Bundle results) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070013050 int userId = UserId.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013051 // Refuse possible leaked file descriptors
13052 if (results != null && results.hasFileDescriptors()) {
13053 throw new IllegalArgumentException("File descriptors passed in Intent");
13054 }
13055
13056 synchronized(this) {
13057 ProcessRecord app = getRecordForAppLocked(target);
13058 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013059 Slog.w(TAG, "finishInstrumentation: no app for " + target);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013060 return;
13061 }
13062 final long origId = Binder.clearCallingIdentity();
13063 finishInstrumentationLocked(app, resultCode, results);
13064 Binder.restoreCallingIdentity(origId);
13065 }
13066 }
13067
13068 // =========================================================
13069 // CONFIGURATION
13070 // =========================================================
13071
13072 public ConfigurationInfo getDeviceConfigurationInfo() {
13073 ConfigurationInfo config = new ConfigurationInfo();
13074 synchronized (this) {
13075 config.reqTouchScreen = mConfiguration.touchscreen;
13076 config.reqKeyboardType = mConfiguration.keyboard;
13077 config.reqNavigation = mConfiguration.navigation;
Dianne Hackbornfae76f52009-07-16 13:41:23 -070013078 if (mConfiguration.navigation == Configuration.NAVIGATION_DPAD
13079 || mConfiguration.navigation == Configuration.NAVIGATION_TRACKBALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013080 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
13081 }
Dianne Hackbornfae76f52009-07-16 13:41:23 -070013082 if (mConfiguration.keyboard != Configuration.KEYBOARD_UNDEFINED
13083 && mConfiguration.keyboard != Configuration.KEYBOARD_NOKEYS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013084 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
13085 }
Jack Palevichb90d28c2009-07-22 15:35:24 -070013086 config.reqGlEsVersion = GL_ES_VERSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013087 }
13088 return config;
13089 }
13090
13091 public Configuration getConfiguration() {
13092 Configuration ci;
13093 synchronized(this) {
13094 ci = new Configuration(mConfiguration);
13095 }
13096 return ci;
13097 }
13098
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013099 public void updatePersistentConfiguration(Configuration values) {
13100 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
13101 "updateConfiguration()");
13102 enforceCallingPermission(android.Manifest.permission.WRITE_SETTINGS,
13103 "updateConfiguration()");
13104 if (values == null) {
13105 throw new NullPointerException("Configuration must not be null");
13106 }
13107
13108 synchronized(this) {
13109 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn813075a62011-11-14 17:45:19 -080013110 updateConfigurationLocked(values, null, true, false);
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013111 Binder.restoreCallingIdentity(origId);
13112 }
13113 }
13114
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013115 public void updateConfiguration(Configuration values) {
13116 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
13117 "updateConfiguration()");
13118
13119 synchronized(this) {
13120 if (values == null && mWindowManager != null) {
13121 // sentinel: fetch the current configuration from the window manager
13122 values = mWindowManager.computeNewConfiguration();
13123 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013124
13125 if (mWindowManager != null) {
13126 mProcessList.applyDisplaySize(mWindowManager);
13127 }
13128
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013129 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013130 if (values != null) {
13131 Settings.System.clearConfiguration(values);
13132 }
Dianne Hackborn813075a62011-11-14 17:45:19 -080013133 updateConfigurationLocked(values, null, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013134 Binder.restoreCallingIdentity(origId);
13135 }
13136 }
13137
13138 /**
13139 * Do either or both things: (1) change the current configuration, and (2)
13140 * make sure the given activity is running with the (now) current
13141 * configuration. Returns true if the activity has been left running, or
13142 * false if <var>starting</var> is being destroyed to match the new
13143 * configuration.
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013144 * @param persistent TODO
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013145 */
Dianne Hackborna573f6a2012-02-09 16:12:18 -080013146 boolean updateConfigurationLocked(Configuration values,
Dianne Hackborn813075a62011-11-14 17:45:19 -080013147 ActivityRecord starting, boolean persistent, boolean initLocale) {
Mike Lockwood3a74bd32011-08-12 13:55:22 -070013148 // do nothing if we are headless
13149 if (mHeadless) return true;
13150
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013151 int changes = 0;
13152
13153 boolean kept = true;
13154
13155 if (values != null) {
13156 Configuration newConfig = new Configuration(mConfiguration);
13157 changes = newConfig.updateFrom(values);
13158 if (changes != 0) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013159 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013160 Slog.i(TAG, "Updating configuration to: " + values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013161 }
13162
Doug Zongker2bec3d42009-12-04 12:52:44 -080013163 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013164
Dianne Hackborn813075a62011-11-14 17:45:19 -080013165 if (values.locale != null && !initLocale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013166 saveLocaleLocked(values.locale,
13167 !values.locale.equals(mConfiguration.locale),
13168 values.userSetLocale);
13169 }
13170
Dianne Hackborne36d6e22010-02-17 19:46:25 -080013171 mConfigurationSeq++;
13172 if (mConfigurationSeq <= 0) {
13173 mConfigurationSeq = 1;
13174 }
13175 newConfig.seq = mConfigurationSeq;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013176 mConfiguration = newConfig;
Joe Onorato8a9b2202010-02-26 18:56:32 -080013177 Slog.i(TAG, "Config changed: " + newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013178
13179 final Configuration configCopy = new Configuration(mConfiguration);
Joe Onorato54a4a412011-11-02 20:50:08 -070013180
13181 // TODO: If our config changes, should we auto dismiss any currently
13182 // showing dialogs?
13183 mShowDialogs = shouldShowDialogs(newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013184
Dianne Hackborn826d17c2009-11-12 12:55:51 -080013185 AttributeCache ac = AttributeCache.instance();
13186 if (ac != null) {
Dianne Hackborn813075a62011-11-14 17:45:19 -080013187 ac.updateConfiguration(configCopy);
Dianne Hackborn826d17c2009-11-12 12:55:51 -080013188 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013189
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070013190 // Make sure all resources in our process are updated
13191 // right now, so that anyone who is going to retrieve
13192 // resource values after we return will be sure to get
13193 // the new ones. This is especially important during
13194 // boot, where the first config change needs to guarantee
13195 // all resources have that config before following boot
13196 // code is executed.
Dianne Hackborn813075a62011-11-14 17:45:19 -080013197 mSystemThread.applyConfigurationToResources(configCopy);
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070013198
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013199 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080013200 Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013201 msg.obj = new Configuration(configCopy);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080013202 mHandler.sendMessage(msg);
13203 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013204
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013205 for (int i=mLruProcesses.size()-1; i>=0; i--) {
13206 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013207 try {
13208 if (app.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013209 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending to proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013210 + app.processName + " new config " + mConfiguration);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013211 app.thread.scheduleConfigurationChanged(configCopy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013212 }
13213 } catch (Exception e) {
13214 }
13215 }
13216 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080013217 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
13218 | Intent.FLAG_RECEIVER_REPLACE_PENDING);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013219 broadcastIntentLocked(null, null, intent, null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070013220 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080013221 if ((changes&ActivityInfo.CONFIG_LOCALE) != 0) {
13222 broadcastIntentLocked(null, null,
13223 new Intent(Intent.ACTION_LOCALE_CHANGED),
13224 null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070013225 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080013226 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013227 }
13228 }
13229
13230 if (changes != 0 && starting == null) {
13231 // If the configuration changed, and the caller is not already
13232 // in the process of starting an activity, then find the top
13233 // activity to check if its configuration needs to change.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013234 starting = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013235 }
13236
13237 if (starting != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013238 kept = mMainStack.ensureActivityConfigurationLocked(starting, changes);
Dianne Hackborn5f4d6432010-12-21 20:40:11 -080013239 // And we need to make sure at this point that all other activities
13240 // are made visible with the correct configuration.
13241 mMainStack.ensureActivitiesVisibleLocked(starting, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013242 }
13243
Dianne Hackborne36d6e22010-02-17 19:46:25 -080013244 if (values != null && mWindowManager != null) {
13245 mWindowManager.setNewConfiguration(mConfiguration);
13246 }
13247
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013248 return kept;
13249 }
Joe Onorato54a4a412011-11-02 20:50:08 -070013250
13251 /**
13252 * Decide based on the configuration whether we should shouw the ANR,
13253 * crash, etc dialogs. The idea is that if there is no affordnace to
13254 * press the on-screen buttons, we shouldn't show the dialog.
13255 *
13256 * A thought: SystemUI might also want to get told about this, the Power
13257 * dialog / global actions also might want different behaviors.
13258 */
13259 private static final boolean shouldShowDialogs(Configuration config) {
13260 return !(config.keyboard == Configuration.KEYBOARD_NOKEYS
13261 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH);
13262 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013263
13264 /**
13265 * Save the locale. You must be inside a synchronized (this) block.
13266 */
13267 private void saveLocaleLocked(Locale l, boolean isDiff, boolean isPersist) {
13268 if(isDiff) {
13269 SystemProperties.set("user.language", l.getLanguage());
13270 SystemProperties.set("user.region", l.getCountry());
13271 }
13272
13273 if(isPersist) {
13274 SystemProperties.set("persist.sys.language", l.getLanguage());
13275 SystemProperties.set("persist.sys.country", l.getCountry());
13276 SystemProperties.set("persist.sys.localevar", l.getVariant());
13277 }
13278 }
13279
13280 // =========================================================
13281 // LIFETIME MANAGEMENT
13282 // =========================================================
13283
Christopher Tatef46723b2012-01-26 14:19:24 -080013284 // Returns which broadcast queue the app is the current [or imminent] receiver
13285 // on, or 'null' if the app is not an active broadcast recipient.
13286 private BroadcastQueue isReceivingBroadcast(ProcessRecord app) {
13287 BroadcastRecord r = app.curReceiver;
13288 if (r != null) {
13289 return r.queue;
13290 }
13291
13292 // It's not the current receiver, but it might be starting up to become one
13293 synchronized (this) {
13294 for (BroadcastQueue queue : mBroadcastQueues) {
13295 r = queue.mPendingBroadcast;
13296 if (r != null && r.curApp == app) {
13297 // found it; report which queue it's in
13298 return queue;
13299 }
13300 }
13301 }
13302
13303 return null;
13304 }
13305
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013306 private final int computeOomAdjLocked(ProcessRecord app, int hiddenAdj,
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013307 ProcessRecord TOP_APP, boolean recursed, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013308 if (mAdjSeq == app.adjSeq) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013309 // This adjustment has already been computed. If we are calling
13310 // from the top, we may have already computed our adjustment with
13311 // an earlier hidden adjustment that isn't really for us... if
13312 // so, use the new hidden adjustment.
13313 if (!recursed && app.hidden) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013314 app.curAdj = app.curRawAdj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013315 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013316 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013317 }
13318
13319 if (app.thread == null) {
13320 app.adjSeq = mAdjSeq;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013321 app.curSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013322 return (app.curAdj=ProcessList.HIDDEN_APP_MAX_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013323 }
13324
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013325 app.adjTypeCode = ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN;
13326 app.adjSource = null;
13327 app.adjTarget = null;
13328 app.empty = false;
13329 app.hidden = false;
13330
13331 final int activitiesSize = app.activities.size();
13332
Dianne Hackborn7d608422011-08-07 16:24:18 -070013333 if (app.maxAdj <= ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013334 // The max adjustment doesn't allow this app to be anything
13335 // below foreground, so it is not worth doing work for it.
13336 app.adjType = "fixed";
13337 app.adjSeq = mAdjSeq;
13338 app.curRawAdj = app.maxAdj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013339 app.foregroundActivities = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013340 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013341 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013342 // System process can do UI, and when they do we want to have
13343 // them trim their memory after the user leaves the UI. To
13344 // facilitate this, here we need to determine whether or not it
13345 // is currently showing UI.
13346 app.systemNoUi = true;
13347 if (app == TOP_APP) {
13348 app.systemNoUi = false;
13349 } else if (activitiesSize > 0) {
13350 for (int j = 0; j < activitiesSize; j++) {
13351 final ActivityRecord r = app.activities.get(j);
13352 if (r.visible) {
13353 app.systemNoUi = false;
13354 break;
13355 }
13356 }
13357 }
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013358 return (app.curAdj=app.maxAdj);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013359 }
13360
13361 final boolean hadForegroundActivities = app.foregroundActivities;
13362
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013363 app.foregroundActivities = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013364 app.keeping = false;
13365 app.systemNoUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013366
The Android Open Source Project4df24232009-03-05 14:34:35 -080013367 // Determine the importance of the process, starting with most
13368 // important to least, and assign an appropriate OOM adjustment.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013369 int adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013370 int schedGroup;
Christopher Tatef46723b2012-01-26 14:19:24 -080013371 BroadcastQueue queue;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013372 if (app == TOP_APP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013373 // The last app on the list is the foreground app.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013374 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013375 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013376 app.adjType = "top-activity";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013377 app.foregroundActivities = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013378 } else if (app.instrumentationClass != null) {
13379 // Don't want to kill running instrumentation.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013380 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013381 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013382 app.adjType = "instrumentation";
Christopher Tatef46723b2012-01-26 14:19:24 -080013383 } else if ((queue = isReceivingBroadcast(app)) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013384 // An app that is currently receiving a broadcast also
Christopher Tatef46723b2012-01-26 14:19:24 -080013385 // counts as being in the foreground for OOM killer purposes.
13386 // It's placed in a sched group based on the nature of the
13387 // broadcast as reflected by which queue it's active in.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013388 adj = ProcessList.FOREGROUND_APP_ADJ;
Christopher Tatef46723b2012-01-26 14:19:24 -080013389 schedGroup = (queue == mFgBroadcastQueue)
13390 ? Process.THREAD_GROUP_DEFAULT : Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013391 app.adjType = "broadcast";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013392 } else if (app.executingServices.size() > 0) {
13393 // An app that is currently executing a service callback also
13394 // counts as being in the foreground.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013395 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013396 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013397 app.adjType = "exec-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013398 } else if (activitiesSize > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013399 // This app is in the background with paused activities.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013400 // We inspect activities to potentially upgrade adjustment further below.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013401 adj = hiddenAdj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013402 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013403 app.hidden = true;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013404 app.adjType = "bg-activities";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013405 } else {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013406 // A very not-needed process. If this is lower in the lru list,
13407 // we will push it in to the empty bucket.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013408 adj = hiddenAdj;
13409 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013410 app.hidden = true;
13411 app.empty = true;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013412 app.adjType = "bg-empty";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013413 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013414
13415 // Examine all activities if not already foreground.
13416 if (!app.foregroundActivities && activitiesSize > 0) {
13417 for (int j = 0; j < activitiesSize; j++) {
13418 final ActivityRecord r = app.activities.get(j);
13419 if (r.visible) {
13420 // App has a visible activity; only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013421 if (adj > ProcessList.VISIBLE_APP_ADJ) {
13422 adj = ProcessList.VISIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013423 app.adjType = "visible";
13424 }
13425 schedGroup = Process.THREAD_GROUP_DEFAULT;
13426 app.hidden = false;
13427 app.foregroundActivities = true;
13428 break;
13429 } else if (r.state == ActivityState.PAUSING || r.state == ActivityState.PAUSED
13430 || r.state == ActivityState.STOPPING) {
13431 // Only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013432 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13433 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013434 app.adjType = "stopping";
13435 }
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -080013436 app.hidden = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013437 app.foregroundActivities = true;
13438 }
13439 }
13440 }
13441
Dianne Hackborn7d608422011-08-07 16:24:18 -070013442 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013443 if (app.foregroundServices) {
13444 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013445 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013446 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013447 app.adjType = "foreground-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013448 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013449 } else if (app.forcingToForeground != null) {
13450 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013451 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013452 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013453 app.adjType = "force-foreground";
13454 app.adjSource = app.forcingToForeground;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013455 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013456 }
13457 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013458
Dianne Hackborn7d608422011-08-07 16:24:18 -070013459 if (adj > ProcessList.HEAVY_WEIGHT_APP_ADJ && app == mHeavyWeightProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013460 // We don't want to kill the current heavy-weight process.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013461 adj = ProcessList.HEAVY_WEIGHT_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013462 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013463 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013464 app.adjType = "heavy";
13465 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013466
Dianne Hackborn7d608422011-08-07 16:24:18 -070013467 if (adj > ProcessList.HOME_APP_ADJ && app == mHomeProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013468 // This process is hosting what we currently consider to be the
13469 // home app, so we don't want to let it go into the background.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013470 adj = ProcessList.HOME_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013471 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013472 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013473 app.adjType = "home";
13474 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013475
Dianne Hackbornf35fe232011-11-01 19:25:20 -070013476 if (adj > ProcessList.PREVIOUS_APP_ADJ && app == mPreviousProcess
13477 && app.activities.size() > 0) {
13478 // This was the previous process that showed UI to the user.
13479 // We want to try to keep it around more aggressively, to give
13480 // a good experience around switching between two apps.
13481 adj = ProcessList.PREVIOUS_APP_ADJ;
13482 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
13483 app.hidden = false;
13484 app.adjType = "previous";
13485 }
13486
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013487 if (false) Slog.i(TAG, "OOM " + app + ": initial adj=" + adj
13488 + " reason=" + app.adjType);
13489
The Android Open Source Project4df24232009-03-05 14:34:35 -080013490 // By default, we use the computed adjustment. It may be changed if
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013491 // there are applications dependent on our services or providers, but
13492 // this gives us a baseline and makes sure we don't get into an
13493 // infinite recursion.
13494 app.adjSeq = mAdjSeq;
13495 app.curRawAdj = adj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013496
Christopher Tate6fa95972009-06-05 18:43:55 -070013497 if (mBackupTarget != null && app == mBackupTarget.app) {
13498 // If possible we want to avoid killing apps while they're being backed up
Dianne Hackborn7d608422011-08-07 16:24:18 -070013499 if (adj > ProcessList.BACKUP_APP_ADJ) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013500 if (DEBUG_BACKUP) Slog.v(TAG, "oom BACKUP_APP_ADJ for " + app);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013501 adj = ProcessList.BACKUP_APP_ADJ;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013502 app.adjType = "backup";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013503 app.hidden = false;
Christopher Tate6fa95972009-06-05 18:43:55 -070013504 }
13505 }
13506
Dianne Hackborn7d608422011-08-07 16:24:18 -070013507 if (app.services.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013508 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013509 final long now = SystemClock.uptimeMillis();
13510 // This process is more important if the top activity is
13511 // bound to the service.
Dianne Hackborn860755f2010-06-03 18:47:52 -070013512 Iterator<ServiceRecord> jt = app.services.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013513 while (jt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013514 ServiceRecord s = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013515 if (s.startRequested) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013516 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013517 // If this process has shown some UI, let it immediately
13518 // go to the LRU list because it may be pretty heavy with
13519 // UI stuff. We'll tag it with a label just to help
13520 // debug and understand what is going on.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013521 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013522 app.adjType = "started-bg-ui-services";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013523 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013524 } else {
13525 if (now < (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
13526 // This service has seen some activity within
13527 // recent memory, so we will keep its process ahead
13528 // of the background processes.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013529 if (adj > ProcessList.SERVICE_ADJ) {
13530 adj = ProcessList.SERVICE_ADJ;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013531 app.adjType = "started-services";
13532 app.hidden = false;
13533 }
13534 }
13535 // If we have let the service slide into the background
13536 // state, still have some text describing what it is doing
13537 // even though the service no longer has an impact.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013538 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013539 app.adjType = "started-bg-services";
13540 }
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080013541 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013542 // Don't kill this process because it is doing work; it
13543 // has said it is doing work.
13544 app.keeping = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013545 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013546 if (s.connections.size() > 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013547 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013548 Iterator<ArrayList<ConnectionRecord>> kt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013549 = s.connections.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013550 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013551 ArrayList<ConnectionRecord> clist = kt.next();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013552 for (int i=0; i<clist.size() && adj > ProcessList.FOREGROUND_APP_ADJ; i++) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013553 // XXX should compute this based on the max of
13554 // all connected clients.
13555 ConnectionRecord cr = clist.get(i);
13556 if (cr.binding.client == app) {
13557 // Binding to ourself is not interesting.
13558 continue;
13559 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013560 if ((cr.flags&Context.BIND_WAIVE_PRIORITY) == 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013561 ProcessRecord client = cr.binding.client;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013562 int clientAdj = adj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013563 int myHiddenAdj = hiddenAdj;
13564 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013565 if (client.hiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013566 myHiddenAdj = client.hiddenAdj;
13567 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013568 myHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013569 }
13570 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013571 clientAdj = computeOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013572 client, myHiddenAdj, TOP_APP, true, doingAll);
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013573 String adjType = null;
13574 if ((cr.flags&Context.BIND_ALLOW_OOM_MANAGEMENT) != 0) {
13575 // Not doing bind OOM management, so treat
13576 // this guy more like a started service.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013577 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013578 // If this process has shown some UI, let it immediately
13579 // go to the LRU list because it may be pretty heavy with
13580 // UI stuff. We'll tag it with a label just to help
13581 // debug and understand what is going on.
13582 if (adj > clientAdj) {
13583 adjType = "bound-bg-ui-services";
13584 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013585 app.hidden = false;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013586 clientAdj = adj;
13587 } else {
13588 if (now >= (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
13589 // This service has not seen activity within
13590 // recent memory, so allow it to drop to the
13591 // LRU list if there is no other reason to keep
13592 // it around. We'll also tag it with a label just
13593 // to help debug and undertand what is going on.
13594 if (adj > clientAdj) {
13595 adjType = "bound-bg-services";
13596 }
13597 clientAdj = adj;
13598 }
13599 }
13600 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013601 if (adj > clientAdj) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013602 // If this process has recently shown UI, and
13603 // the process that is binding to it is less
13604 // important than being visible, then we don't
13605 // care about the binding as much as we care
13606 // about letting this process get into the LRU
13607 // list to be killed and restarted if needed for
13608 // memory.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013609 if (app.hasShownUi && app != mHomeProcess
13610 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013611 adjType = "bound-bg-ui-services";
13612 } else {
13613 if ((cr.flags&(Context.BIND_ABOVE_CLIENT
13614 |Context.BIND_IMPORTANT)) != 0) {
13615 adj = clientAdj;
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070013616 } else if ((cr.flags&Context.BIND_NOT_VISIBLE) != 0
13617 && clientAdj < ProcessList.PERCEPTIBLE_APP_ADJ
13618 && adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13619 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13620 } else if (clientAdj > ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013621 adj = clientAdj;
13622 } else {
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070013623 app.pendingUiClean = true;
13624 if (adj > ProcessList.VISIBLE_APP_ADJ) {
13625 adj = ProcessList.VISIBLE_APP_ADJ;
13626 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013627 }
13628 if (!client.hidden) {
13629 app.hidden = false;
13630 }
13631 if (client.keeping) {
13632 app.keeping = true;
13633 }
13634 adjType = "service";
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013635 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013636 }
13637 if (adjType != null) {
13638 app.adjType = adjType;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013639 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13640 .REASON_SERVICE_IN_USE;
13641 app.adjSource = cr.binding.client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013642 app.adjSourceOom = clientAdj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013643 app.adjTarget = s.name;
13644 }
13645 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
13646 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
13647 schedGroup = Process.THREAD_GROUP_DEFAULT;
13648 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013649 }
13650 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013651 if ((cr.flags&Context.BIND_ADJUST_WITH_ACTIVITY) != 0) {
13652 ActivityRecord a = cr.activity;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013653 if (a != null && adj > ProcessList.FOREGROUND_APP_ADJ &&
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013654 (a.visible || a.state == ActivityState.RESUMED
13655 || a.state == ActivityState.PAUSING)) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013656 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013657 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
13658 schedGroup = Process.THREAD_GROUP_DEFAULT;
13659 }
13660 app.hidden = false;
13661 app.adjType = "service";
13662 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13663 .REASON_SERVICE_IN_USE;
13664 app.adjSource = a;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013665 app.adjSourceOom = adj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013666 app.adjTarget = s.name;
13667 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013668 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013669 }
13670 }
13671 }
13672 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013673
Dianne Hackborn287952c2010-09-22 22:34:31 -070013674 // Finally, if this process has active services running in it, we
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013675 // would like to avoid killing it unless it would prevent the current
13676 // application from running. By default we put the process in
13677 // with the rest of the background processes; as we scan through
13678 // its services we may bump it up from there.
13679 if (adj > hiddenAdj) {
13680 adj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013681 app.hidden = false;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013682 app.adjType = "bg-services";
13683 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013684 }
13685
Dianne Hackborn7d608422011-08-07 16:24:18 -070013686 if (app.pubProviders.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013687 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013688 Iterator<ContentProviderRecord> jt = app.pubProviders.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013689 while (jt.hasNext() && (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 ContentProviderRecord cpr = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013692 if (cpr.clients.size() != 0) {
13693 Iterator<ProcessRecord> kt = cpr.clients.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013694 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013695 ProcessRecord client = kt.next();
The Android Open Source Project10592532009-03-18 17:39:46 -070013696 if (client == app) {
13697 // Being our own client is not interesting.
13698 continue;
13699 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013700 int myHiddenAdj = hiddenAdj;
13701 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013702 if (client.hiddenAdj > ProcessList.FOREGROUND_APP_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013703 myHiddenAdj = client.hiddenAdj;
13704 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013705 myHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013706 }
13707 }
13708 int clientAdj = computeOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013709 client, myHiddenAdj, TOP_APP, true, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013710 if (adj > clientAdj) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013711 if (app.hasShownUi && app != mHomeProcess
13712 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013713 app.adjType = "bg-ui-provider";
13714 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013715 adj = clientAdj > ProcessList.FOREGROUND_APP_ADJ
13716 ? clientAdj : ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013717 app.adjType = "provider";
13718 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013719 if (!client.hidden) {
13720 app.hidden = false;
13721 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013722 if (client.keeping) {
13723 app.keeping = true;
13724 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070013725 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13726 .REASON_PROVIDER_IN_USE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013727 app.adjSource = client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013728 app.adjSourceOom = clientAdj;
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070013729 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013730 }
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013731 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
13732 schedGroup = Process.THREAD_GROUP_DEFAULT;
13733 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013734 }
13735 }
13736 // If the provider has external (non-framework) process
13737 // dependencies, ensure that its adjustment is at least
13738 // FOREGROUND_APP_ADJ.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080013739 if (cpr.hasExternalProcessHandles()) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013740 if (adj > ProcessList.FOREGROUND_APP_ADJ) {
13741 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013742 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013743 app.hidden = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013744 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013745 app.adjType = "provider";
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070013746 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013747 }
13748 }
13749 }
13750 }
13751
13752 app.curRawAdj = adj;
13753
Joe Onorato8a9b2202010-02-26 18:56:32 -080013754 //Slog.i(TAG, "OOM ADJ " + app + ": pid=" + app.pid +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013755 // " adj=" + adj + " curAdj=" + app.curAdj + " maxAdj=" + app.maxAdj);
13756 if (adj > app.maxAdj) {
13757 adj = app.maxAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013758 if (app.maxAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013759 schedGroup = Process.THREAD_GROUP_DEFAULT;
13760 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013761 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013762 if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070013763 app.keeping = true;
13764 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013765
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013766 if (app.hasAboveClient) {
13767 // If this process has bound to any services with BIND_ABOVE_CLIENT,
13768 // then we need to drop its adjustment to be lower than the service's
13769 // in order to honor the request. We want to drop it by one adjustment
13770 // level... but there is special meaning applied to various levels so
13771 // we will skip some of them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013772 if (adj < ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013773 // System process will not get dropped, ever
Dianne Hackborn7d608422011-08-07 16:24:18 -070013774 } else if (adj < ProcessList.VISIBLE_APP_ADJ) {
13775 adj = ProcessList.VISIBLE_APP_ADJ;
13776 } else if (adj < ProcessList.PERCEPTIBLE_APP_ADJ) {
13777 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13778 } else if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
13779 adj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013780 } else if (adj < ProcessList.HIDDEN_APP_MAX_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013781 adj++;
13782 }
13783 }
13784
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013785 if (adj == ProcessList.SERVICE_ADJ) {
13786 if (doingAll) {
13787 app.serviceb = mNewNumServiceProcs > (mNumServiceProcs/3);
13788 mNewNumServiceProcs++;
13789 }
13790 if (app.serviceb) {
13791 adj = ProcessList.SERVICE_B_ADJ;
13792 }
13793 } else {
13794 app.serviceb = false;
13795 }
13796
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013797 app.curAdj = adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013798 app.curSchedGroup = schedGroup;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013799
13800 if (hadForegroundActivities != app.foregroundActivities) {
Jeff Sharkey287bd832011-05-28 19:36:26 -070013801 mHandler.obtainMessage(DISPATCH_FOREGROUND_ACTIVITIES_CHANGED, app.pid, app.info.uid,
13802 app.foregroundActivities).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013803 }
13804
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013805 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013806 }
13807
13808 /**
13809 * Ask a given process to GC right now.
13810 */
13811 final void performAppGcLocked(ProcessRecord app) {
13812 try {
13813 app.lastRequestedGc = SystemClock.uptimeMillis();
13814 if (app.thread != null) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013815 if (app.reportLowMemory) {
13816 app.reportLowMemory = false;
13817 app.thread.scheduleLowMemory();
13818 } else {
13819 app.thread.processInBackground();
13820 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013821 }
13822 } catch (Exception e) {
13823 // whatever.
13824 }
13825 }
13826
13827 /**
13828 * Returns true if things are idle enough to perform GCs.
13829 */
Josh Bartel7f208742010-02-25 11:01:44 -060013830 private final boolean canGcNowLocked() {
Christopher Tatef46723b2012-01-26 14:19:24 -080013831 boolean processingBroadcasts = false;
13832 for (BroadcastQueue q : mBroadcastQueues) {
13833 if (q.mParallelBroadcasts.size() != 0 || q.mOrderedBroadcasts.size() != 0) {
13834 processingBroadcasts = true;
13835 }
13836 }
13837 return !processingBroadcasts
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013838 && (mSleeping || (mMainStack.mResumedActivity != null &&
13839 mMainStack.mResumedActivity.idle));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013840 }
13841
13842 /**
13843 * Perform GCs on all processes that are waiting for it, but only
13844 * if things are idle.
13845 */
13846 final void performAppGcsLocked() {
13847 final int N = mProcessesToGc.size();
13848 if (N <= 0) {
13849 return;
13850 }
Josh Bartel7f208742010-02-25 11:01:44 -060013851 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013852 while (mProcessesToGc.size() > 0) {
13853 ProcessRecord proc = mProcessesToGc.remove(0);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013854 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013855 if ((proc.lastRequestedGc+GC_MIN_INTERVAL)
13856 <= SystemClock.uptimeMillis()) {
13857 // To avoid spamming the system, we will GC processes one
13858 // at a time, waiting a few seconds between each.
13859 performAppGcLocked(proc);
13860 scheduleAppGcsLocked();
13861 return;
13862 } else {
13863 // It hasn't been long enough since we last GCed this
13864 // process... put it in the list to wait for its time.
13865 addProcessToGcListLocked(proc);
13866 break;
13867 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013868 }
13869 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013870
13871 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013872 }
13873 }
13874
13875 /**
13876 * If all looks good, perform GCs on all processes waiting for them.
13877 */
13878 final void performAppGcsIfAppropriateLocked() {
Josh Bartel7f208742010-02-25 11:01:44 -060013879 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013880 performAppGcsLocked();
13881 return;
13882 }
13883 // Still not idle, wait some more.
13884 scheduleAppGcsLocked();
13885 }
13886
13887 /**
13888 * Schedule the execution of all pending app GCs.
13889 */
13890 final void scheduleAppGcsLocked() {
13891 mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013892
13893 if (mProcessesToGc.size() > 0) {
13894 // Schedule a GC for the time to the next process.
13895 ProcessRecord proc = mProcessesToGc.get(0);
13896 Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG);
13897
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013898 long when = proc.lastRequestedGc + GC_MIN_INTERVAL;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013899 long now = SystemClock.uptimeMillis();
13900 if (when < (now+GC_TIMEOUT)) {
13901 when = now + GC_TIMEOUT;
13902 }
13903 mHandler.sendMessageAtTime(msg, when);
13904 }
13905 }
13906
13907 /**
13908 * Add a process to the array of processes waiting to be GCed. Keeps the
13909 * list in sorted order by the last GC time. The process can't already be
13910 * on the list.
13911 */
13912 final void addProcessToGcListLocked(ProcessRecord proc) {
13913 boolean added = false;
13914 for (int i=mProcessesToGc.size()-1; i>=0; i--) {
13915 if (mProcessesToGc.get(i).lastRequestedGc <
13916 proc.lastRequestedGc) {
13917 added = true;
13918 mProcessesToGc.add(i+1, proc);
13919 break;
13920 }
13921 }
13922 if (!added) {
13923 mProcessesToGc.add(0, proc);
13924 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013925 }
13926
13927 /**
13928 * Set up to ask a process to GC itself. This will either do it
13929 * immediately, or put it on the list of processes to gc the next
13930 * time things are idle.
13931 */
13932 final void scheduleAppGcLocked(ProcessRecord app) {
13933 long now = SystemClock.uptimeMillis();
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013934 if ((app.lastRequestedGc+GC_MIN_INTERVAL) > now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013935 return;
13936 }
13937 if (!mProcessesToGc.contains(app)) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013938 addProcessToGcListLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013939 scheduleAppGcsLocked();
13940 }
13941 }
13942
Dianne Hackborn287952c2010-09-22 22:34:31 -070013943 final void checkExcessivePowerUsageLocked(boolean doKills) {
13944 updateCpuStatsNow();
13945
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013946 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013947 boolean doWakeKills = doKills;
13948 boolean doCpuKills = doKills;
13949 if (mLastPowerCheckRealtime == 0) {
13950 doWakeKills = false;
13951 }
13952 if (mLastPowerCheckUptime == 0) {
13953 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013954 }
13955 if (stats.isScreenOn()) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070013956 doWakeKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013957 }
13958 final long curRealtime = SystemClock.elapsedRealtime();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013959 final long realtimeSince = curRealtime - mLastPowerCheckRealtime;
13960 final long curUptime = SystemClock.uptimeMillis();
13961 final long uptimeSince = curUptime - mLastPowerCheckUptime;
13962 mLastPowerCheckRealtime = curRealtime;
13963 mLastPowerCheckUptime = curUptime;
13964 if (realtimeSince < WAKE_LOCK_MIN_CHECK_DURATION) {
13965 doWakeKills = false;
13966 }
13967 if (uptimeSince < CPU_MIN_CHECK_DURATION) {
13968 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013969 }
13970 int i = mLruProcesses.size();
13971 while (i > 0) {
13972 i--;
13973 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013974 if (!app.keeping) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013975 long wtime;
13976 synchronized (stats) {
13977 wtime = stats.getProcessWakeTime(app.info.uid,
13978 app.pid, curRealtime);
13979 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013980 long wtimeUsed = wtime - app.lastWakeTime;
13981 long cputimeUsed = app.curCpuTime - app.lastCpuTime;
13982 if (DEBUG_POWER) {
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013983 StringBuilder sb = new StringBuilder(128);
13984 sb.append("Wake for ");
13985 app.toShortString(sb);
13986 sb.append(": over ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013987 TimeUtils.formatDuration(realtimeSince, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013988 sb.append(" used ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013989 TimeUtils.formatDuration(wtimeUsed, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013990 sb.append(" (");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013991 sb.append((wtimeUsed*100)/realtimeSince);
13992 sb.append("%)");
13993 Slog.i(TAG, sb.toString());
13994 sb.setLength(0);
13995 sb.append("CPU for ");
13996 app.toShortString(sb);
13997 sb.append(": over ");
13998 TimeUtils.formatDuration(uptimeSince, sb);
13999 sb.append(" used ");
14000 TimeUtils.formatDuration(cputimeUsed, sb);
14001 sb.append(" (");
14002 sb.append((cputimeUsed*100)/uptimeSince);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014003 sb.append("%)");
14004 Slog.i(TAG, sb.toString());
14005 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014006 // If a process has held a wake lock for more
14007 // than 50% of the time during this period,
14008 // that sounds pad. Kill!
Dianne Hackborn287952c2010-09-22 22:34:31 -070014009 if (doWakeKills && realtimeSince > 0
14010 && ((wtimeUsed*100)/realtimeSince) >= 50) {
14011 synchronized (stats) {
14012 stats.reportExcessiveWakeLocked(app.info.uid, app.processName,
14013 realtimeSince, wtimeUsed);
14014 }
14015 Slog.w(TAG, "Excessive wake lock in " + app.processName
14016 + " (pid " + app.pid + "): held " + wtimeUsed
14017 + " during " + realtimeSince);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014018 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14019 app.processName, app.setAdj, "excessive wake lock");
14020 Process.killProcessQuiet(app.pid);
Dianne Hackborn287952c2010-09-22 22:34:31 -070014021 } else if (doCpuKills && uptimeSince > 0
14022 && ((cputimeUsed*100)/uptimeSince) >= 50) {
14023 synchronized (stats) {
14024 stats.reportExcessiveCpuLocked(app.info.uid, app.processName,
14025 uptimeSince, cputimeUsed);
14026 }
14027 Slog.w(TAG, "Excessive CPU in " + app.processName
14028 + " (pid " + app.pid + "): used " + cputimeUsed
14029 + " during " + uptimeSince);
14030 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14031 app.processName, app.setAdj, "excessive cpu");
14032 Process.killProcessQuiet(app.pid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014033 } else {
14034 app.lastWakeTime = wtime;
Dianne Hackborn287952c2010-09-22 22:34:31 -070014035 app.lastCpuTime = app.curCpuTime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014036 }
14037 }
14038 }
14039 }
14040
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014041 private final boolean updateOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014042 ProcessRecord app, int hiddenAdj, ProcessRecord TOP_APP, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014043 app.hiddenAdj = hiddenAdj;
14044
14045 if (app.thread == null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014046 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014047 }
14048
Dianne Hackborn287952c2010-09-22 22:34:31 -070014049 final boolean wasKeeping = app.keeping;
14050
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014051 boolean success = true;
14052
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014053 computeOomAdjLocked(app, hiddenAdj, TOP_APP, false, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014054
Jeff Brown10e89712011-07-08 18:52:57 -070014055 if (app.curRawAdj != app.setRawAdj) {
Dianne Hackborn905577f2011-09-07 18:31:28 -070014056 if (false) {
14057 // Removing for now. Forcing GCs is not so useful anymore
14058 // with Dalvik, and the new memory level hint facility is
14059 // better for what we need to do these days.
14060 if (app.curRawAdj > ProcessList.FOREGROUND_APP_ADJ
14061 && app.setRawAdj <= ProcessList.FOREGROUND_APP_ADJ) {
14062 // If this app is transitioning from foreground to
14063 // non-foreground, have it do a gc.
14064 scheduleAppGcLocked(app);
14065 } else if (app.curRawAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
14066 && app.setRawAdj < ProcessList.HIDDEN_APP_MIN_ADJ) {
14067 // Likewise do a gc when an app is moving in to the
14068 // background (such as a service stopping).
14069 scheduleAppGcLocked(app);
14070 }
Jeff Brown10e89712011-07-08 18:52:57 -070014071 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070014072
Jeff Brown10e89712011-07-08 18:52:57 -070014073 if (wasKeeping && !app.keeping) {
14074 // This app is no longer something we want to keep. Note
14075 // its current wake lock time to later know to kill it if
14076 // it is not behaving well.
14077 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
14078 synchronized (stats) {
14079 app.lastWakeTime = stats.getProcessWakeTime(app.info.uid,
14080 app.pid, SystemClock.elapsedRealtime());
14081 }
14082 app.lastCpuTime = app.curCpuTime;
14083 }
14084
14085 app.setRawAdj = app.curRawAdj;
14086 }
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014087
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014088 if (app.curAdj != app.setAdj) {
14089 if (Process.setOomAdj(app.pid, app.curAdj)) {
Dianne Hackbornbbb09ac2011-11-30 11:31:29 -080014090 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014091 TAG, "Set " + app.pid + " " + app.processName +
14092 " adj " + app.curAdj + ": " + app.adjType);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014093 app.setAdj = app.curAdj;
Jeff Brown10e89712011-07-08 18:52:57 -070014094 } else {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014095 success = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014096 Slog.w(TAG, "Failed setting oom adj of " + app + " to " + app.curAdj);
Jeff Brown10e89712011-07-08 18:52:57 -070014097 }
14098 }
14099 if (app.setSchedGroup != app.curSchedGroup) {
14100 app.setSchedGroup = app.curSchedGroup;
14101 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
14102 "Setting process group of " + app.processName
14103 + " to " + app.curSchedGroup);
14104 if (app.waitingToKill != null &&
14105 app.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
14106 Slog.i(TAG, "Killing " + app.toShortString() + ": " + app.waitingToKill);
14107 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14108 app.processName, app.setAdj, app.waitingToKill);
14109 Process.killProcessQuiet(app.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014110 success = false;
Jeff Brown10e89712011-07-08 18:52:57 -070014111 } else {
14112 if (true) {
14113 long oldId = Binder.clearCallingIdentity();
14114 try {
14115 Process.setProcessGroup(app.pid, app.curSchedGroup);
14116 } catch (Exception e) {
14117 Slog.w(TAG, "Failed setting process group of " + app.pid
14118 + " to " + app.curSchedGroup);
14119 e.printStackTrace();
14120 } finally {
14121 Binder.restoreCallingIdentity(oldId);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014122 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014123 } else {
Jeff Brown10e89712011-07-08 18:52:57 -070014124 if (app.thread != null) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070014125 try {
Jeff Brown10e89712011-07-08 18:52:57 -070014126 app.thread.setSchedulingGroup(app.curSchedGroup);
14127 } catch (RemoteException e) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070014128 }
14129 }
14130 }
14131 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014132 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014133 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014134 }
14135
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014136 private final ActivityRecord resumedAppLocked() {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014137 ActivityRecord resumedActivity = mMainStack.mResumedActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014138 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -080014139 resumedActivity = mMainStack.mPausingActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014140 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014141 resumedActivity = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014142 }
14143 }
14144 return resumedActivity;
14145 }
14146
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014147 private final boolean updateOomAdjLocked(ProcessRecord app) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014148 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014149 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
14150 int curAdj = app.curAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070014151 final boolean wasHidden = curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
14152 && curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014153
14154 mAdjSeq++;
14155
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014156 boolean success = updateOomAdjLocked(app, app.hiddenAdj, TOP_APP, false);
Dianne Hackborn7d608422011-08-07 16:24:18 -070014157 final boolean nowHidden = app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
14158 && app.curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014159 if (nowHidden != wasHidden) {
14160 // Changed to/from hidden state, so apps after it in the LRU
14161 // list may also be changed.
14162 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014163 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014164 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014165 }
14166
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014167 final void updateOomAdjLocked() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014168 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014169 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
14170
14171 if (false) {
14172 RuntimeException e = new RuntimeException();
14173 e.fillInStackTrace();
Joe Onorato8a9b2202010-02-26 18:56:32 -080014174 Slog.i(TAG, "updateOomAdj: top=" + TOP_ACT, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014175 }
14176
14177 mAdjSeq++;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014178 mNewNumServiceProcs = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014179
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014180 // Let's determine how many processes we have running vs.
14181 // how many slots we have for background processes; we may want
14182 // to put multiple processes in a slot of there are enough of
14183 // them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014184 int numSlots = ProcessList.HIDDEN_APP_MAX_ADJ - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014185 int factor = (mLruProcesses.size()-4)/numSlots;
14186 if (factor < 1) factor = 1;
14187 int step = 0;
Dianne Hackborn8633e682010-04-22 16:03:41 -070014188 int numHidden = 0;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014189
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014190 // First update the OOM adjustment for each of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014191 // application processes based on their current state.
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014192 int i = mLruProcesses.size();
Dianne Hackborn7d608422011-08-07 16:24:18 -070014193 int curHiddenAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014194 while (i > 0) {
14195 i--;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014196 ProcessRecord app = mLruProcesses.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080014197 //Slog.i(TAG, "OOM " + app + ": cur hidden=" + curHiddenAdj);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014198 updateOomAdjLocked(app, curHiddenAdj, TOP_APP, true);
14199 if (curHiddenAdj < ProcessList.HIDDEN_APP_MAX_ADJ
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014200 && app.curAdj == curHiddenAdj) {
14201 step++;
14202 if (step >= factor) {
14203 step = 0;
14204 curHiddenAdj++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014205 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014206 }
14207 if (!app.killedBackground) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070014208 if (app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014209 numHidden++;
14210 if (numHidden > mProcessLimit) {
14211 Slog.i(TAG, "No longer want " + app.processName
14212 + " (pid " + app.pid + "): hidden #" + numHidden);
14213 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14214 app.processName, app.setAdj, "too many background");
14215 app.killedBackground = true;
14216 Process.killProcessQuiet(app.pid);
Dianne Hackborn8633e682010-04-22 16:03:41 -070014217 }
14218 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -080014219 if (!app.killedBackground && app.isolated && app.services.size() <= 0) {
14220 // If this is an isolated process, and there are no
14221 // services running in it, then the process is no longer
14222 // needed. We agressively kill these because we can by
14223 // definition not re-use the same process again, and it is
14224 // good to avoid having whatever code was running in them
14225 // left sitting around after no longer needed.
14226 Slog.i(TAG, "Isolated process " + app.processName
14227 + " (pid " + app.pid + ") no longer needed");
14228 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14229 app.processName, app.setAdj, "isolated not needed");
14230 app.killedBackground = true;
14231 Process.killProcessQuiet(app.pid);
14232 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014233 }
14234 }
14235
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014236 mNumServiceProcs = mNewNumServiceProcs;
14237
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014238 // Now determine the memory trimming level of background processes.
14239 // Unfortunately we need to start at the back of the list to do this
14240 // properly. We only do this if the number of background apps we
14241 // are managing to keep around is less than half the maximum we desire;
14242 // if we are keeping a good number around, we'll let them use whatever
14243 // memory they want.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014244 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/2)) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014245 final int N = mLruProcesses.size();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080014246 factor = numHidden/3;
14247 int minFactor = 2;
14248 if (mHomeProcess != null) minFactor++;
14249 if (mPreviousProcess != null) minFactor++;
14250 if (factor < minFactor) factor = minFactor;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014251 step = 0;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014252 int fgTrimLevel;
14253 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/5)) {
14254 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL;
14255 } else if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/3)) {
14256 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW;
14257 } else {
14258 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE;
14259 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014260 int curLevel = ComponentCallbacks2.TRIM_MEMORY_COMPLETE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014261 for (i=0; i<N; i++) {
14262 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080014263 if (app.curAdj >= ProcessList.HOME_APP_ADJ
14264 && app.curAdj != ProcessList.SERVICE_B_ADJ
14265 && !app.killedBackground) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014266 if (app.trimMemoryLevel < curLevel && app.thread != null) {
14267 try {
14268 app.thread.scheduleTrimMemory(curLevel);
14269 } catch (RemoteException e) {
14270 }
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080014271 if (false) {
14272 // For now we won't do this; our memory trimming seems
14273 // to be good enough at this point that destroying
14274 // activities causes more harm than good.
14275 if (curLevel >= ComponentCallbacks2.TRIM_MEMORY_COMPLETE
14276 && app != mHomeProcess && app != mPreviousProcess) {
14277 // For these apps we will also finish their activities
14278 // to help them free memory.
14279 mMainStack.destroyActivitiesLocked(app, false, "trim");
14280 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014281 }
14282 }
14283 app.trimMemoryLevel = curLevel;
14284 step++;
14285 if (step >= factor) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014286 step = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014287 switch (curLevel) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014288 case ComponentCallbacks2.TRIM_MEMORY_COMPLETE:
14289 curLevel = ComponentCallbacks2.TRIM_MEMORY_MODERATE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014290 break;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014291 case ComponentCallbacks2.TRIM_MEMORY_MODERATE:
14292 curLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014293 break;
14294 }
14295 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070014296 } else if (app.curAdj == ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014297 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014298 && app.thread != null) {
14299 try {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014300 app.thread.scheduleTrimMemory(
14301 ComponentCallbacks2.TRIM_MEMORY_BACKGROUND);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014302 } catch (RemoteException e) {
14303 }
14304 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014305 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014306 } else {
14307 if ((app.curAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
14308 && app.pendingUiClean) {
14309 // If this application is now in the background and it
14310 // had done UI, then give it the special trim level to
14311 // have it free UI resources.
14312 final int level = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
14313 if (app.trimMemoryLevel < level && app.thread != null) {
14314 try {
14315 app.thread.scheduleTrimMemory(level);
14316 } catch (RemoteException e) {
14317 }
14318 }
14319 app.pendingUiClean = false;
14320 }
14321 if (app.trimMemoryLevel < fgTrimLevel && app.thread != null) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014322 try {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014323 app.thread.scheduleTrimMemory(fgTrimLevel);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014324 } catch (RemoteException e) {
14325 }
14326 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014327 app.trimMemoryLevel = fgTrimLevel;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014328 }
14329 }
14330 } else {
14331 final int N = mLruProcesses.size();
14332 for (i=0; i<N; i++) {
14333 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -070014334 if ((app.curAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014335 && app.pendingUiClean) {
14336 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
14337 && app.thread != null) {
14338 try {
14339 app.thread.scheduleTrimMemory(
14340 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
14341 } catch (RemoteException e) {
14342 }
14343 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014344 app.pendingUiClean = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014345 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014346 app.trimMemoryLevel = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014347 }
14348 }
14349
14350 if (mAlwaysFinishActivities) {
Dianne Hackborn28695e02011-11-02 21:59:51 -070014351 mMainStack.destroyActivitiesLocked(null, false, "always-finish");
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014352 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014353 }
14354
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014355 final void trimApplications() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014356 synchronized (this) {
14357 int i;
14358
14359 // First remove any unused application processes whose package
14360 // has been removed.
14361 for (i=mRemovedProcesses.size()-1; i>=0; i--) {
14362 final ProcessRecord app = mRemovedProcesses.get(i);
14363 if (app.activities.size() == 0
14364 && app.curReceiver == null && app.services.size() == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080014365 Slog.i(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014366 TAG, "Exiting empty application process "
14367 + app.processName + " ("
14368 + (app.thread != null ? app.thread.asBinder() : null)
14369 + ")\n");
14370 if (app.pid > 0 && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070014371 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14372 app.processName, app.setAdj, "empty");
14373 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014374 } else {
14375 try {
14376 app.thread.scheduleExit();
14377 } catch (Exception e) {
14378 // Ignore exceptions.
14379 }
14380 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070014381 cleanUpApplicationRecordLocked(app, false, true, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014382 mRemovedProcesses.remove(i);
14383
14384 if (app.persistent) {
14385 if (app.persistent) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080014386 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014387 }
14388 }
14389 }
14390 }
14391
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014392 // Now update the oom adj for all processes.
14393 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014394 }
14395 }
14396
14397 /** This method sends the specified signal to each of the persistent apps */
14398 public void signalPersistentProcesses(int sig) throws RemoteException {
14399 if (sig != Process.SIGNAL_USR1) {
14400 throw new SecurityException("Only SIGNAL_USR1 is allowed");
14401 }
14402
14403 synchronized (this) {
14404 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
14405 != PackageManager.PERMISSION_GRANTED) {
14406 throw new SecurityException("Requires permission "
14407 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
14408 }
14409
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014410 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
14411 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014412 if (r.thread != null && r.persistent) {
14413 Process.sendSignal(r.pid, sig);
14414 }
14415 }
14416 }
14417 }
14418
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014419 private void stopProfilerLocked(ProcessRecord proc, String path, int profileType) {
14420 if (proc == null || proc == mProfileProc) {
14421 proc = mProfileProc;
14422 path = mProfileFile;
14423 profileType = mProfileType;
14424 clearProfilerLocked();
14425 }
14426 if (proc == null) {
14427 return;
14428 }
14429 try {
14430 proc.thread.profilerControl(false, path, null, profileType);
14431 } catch (RemoteException e) {
14432 throw new IllegalStateException("Process disappeared");
14433 }
14434 }
14435
14436 private void clearProfilerLocked() {
14437 if (mProfileFd != null) {
14438 try {
14439 mProfileFd.close();
14440 } catch (IOException e) {
14441 }
14442 }
14443 mProfileApp = null;
14444 mProfileProc = null;
14445 mProfileFile = null;
14446 mProfileType = 0;
14447 mAutoStopProfiler = false;
14448 }
14449
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014450 public boolean profileControl(String process, boolean start,
Romain Guy7eabe552011-07-21 14:56:34 -070014451 String path, ParcelFileDescriptor fd, int profileType) throws RemoteException {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014452
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014453 try {
14454 synchronized (this) {
14455 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14456 // its own permission.
14457 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14458 != PackageManager.PERMISSION_GRANTED) {
14459 throw new SecurityException("Requires permission "
14460 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014461 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014462
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014463 if (start && fd == null) {
14464 throw new IllegalArgumentException("null fd");
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014465 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014466
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014467 ProcessRecord proc = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014468 if (process != null) {
14469 try {
14470 int pid = Integer.parseInt(process);
14471 synchronized (mPidsSelfLocked) {
14472 proc = mPidsSelfLocked.get(pid);
14473 }
14474 } catch (NumberFormatException e) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014475 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014476
14477 if (proc == null) {
14478 HashMap<String, SparseArray<ProcessRecord>> all
14479 = mProcessNames.getMap();
14480 SparseArray<ProcessRecord> procs = all.get(process);
14481 if (procs != null && procs.size() > 0) {
14482 proc = procs.valueAt(0);
14483 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014484 }
14485 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014486
14487 if (start && (proc == null || proc.thread == null)) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014488 throw new IllegalArgumentException("Unknown process: " + process);
14489 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014490
14491 if (start) {
14492 stopProfilerLocked(null, null, 0);
14493 setProfileApp(proc.info, proc.processName, path, fd, false);
14494 mProfileProc = proc;
14495 mProfileType = profileType;
14496 try {
14497 fd = fd.dup();
14498 } catch (IOException e) {
14499 fd = null;
14500 }
14501 proc.thread.profilerControl(start, path, fd, profileType);
14502 fd = null;
14503 mProfileFd = null;
14504 } else {
14505 stopProfilerLocked(proc, path, profileType);
14506 if (fd != null) {
14507 try {
14508 fd.close();
14509 } catch (IOException e) {
14510 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014511 }
14512 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014513
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014514 return true;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014515 }
14516 } catch (RemoteException e) {
14517 throw new IllegalStateException("Process disappeared");
14518 } finally {
14519 if (fd != null) {
14520 try {
14521 fd.close();
14522 } catch (IOException e) {
14523 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014524 }
14525 }
14526 }
Andy McFadden824c5102010-07-09 16:26:57 -070014527
14528 public boolean dumpHeap(String process, boolean managed,
14529 String path, ParcelFileDescriptor fd) throws RemoteException {
14530
14531 try {
14532 synchronized (this) {
14533 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14534 // its own permission (same as profileControl).
14535 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14536 != PackageManager.PERMISSION_GRANTED) {
14537 throw new SecurityException("Requires permission "
14538 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
14539 }
14540
14541 if (fd == null) {
14542 throw new IllegalArgumentException("null fd");
14543 }
14544
14545 ProcessRecord proc = null;
14546 try {
14547 int pid = Integer.parseInt(process);
14548 synchronized (mPidsSelfLocked) {
14549 proc = mPidsSelfLocked.get(pid);
14550 }
14551 } catch (NumberFormatException e) {
14552 }
14553
14554 if (proc == null) {
14555 HashMap<String, SparseArray<ProcessRecord>> all
14556 = mProcessNames.getMap();
14557 SparseArray<ProcessRecord> procs = all.get(process);
14558 if (procs != null && procs.size() > 0) {
14559 proc = procs.valueAt(0);
14560 }
14561 }
14562
14563 if (proc == null || proc.thread == null) {
14564 throw new IllegalArgumentException("Unknown process: " + process);
14565 }
14566
Dianne Hackbornf02e57b2011-03-01 22:21:04 -080014567 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
14568 if (!isDebuggable) {
Andy McFadden824c5102010-07-09 16:26:57 -070014569 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
14570 throw new SecurityException("Process not debuggable: " + proc);
14571 }
14572 }
14573
14574 proc.thread.dumpHeap(managed, path, fd);
14575 fd = null;
14576 return true;
14577 }
14578 } catch (RemoteException e) {
14579 throw new IllegalStateException("Process disappeared");
14580 } finally {
14581 if (fd != null) {
14582 try {
14583 fd.close();
14584 } catch (IOException e) {
14585 }
14586 }
14587 }
14588 }
14589
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014590 /** In this method we try to acquire our lock to make sure that we have not deadlocked */
14591 public void monitor() {
14592 synchronized (this) { }
14593 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014594
Dianne Hackborna573f6a2012-02-09 16:12:18 -080014595 void onCoreSettingsChange(Bundle settings) {
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014596 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
14597 ProcessRecord processRecord = mLruProcesses.get(i);
14598 try {
14599 if (processRecord.thread != null) {
14600 processRecord.thread.setCoreSettings(settings);
14601 }
14602 } catch (RemoteException re) {
14603 /* ignore */
14604 }
14605 }
14606 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014607
14608 // Multi-user methods
14609
Amith Yamasani742a6712011-05-04 14:49:28 -070014610 private int mCurrentUserId;
14611 private SparseIntArray mLoggedInUsers = new SparseIntArray(5);
14612
14613 public boolean switchUser(int userId) {
14614 final int callingUid = Binder.getCallingUid();
14615 if (callingUid != 0 && callingUid != Process.myUid()) {
14616 Slog.e(TAG, "Trying to switch user from unauthorized app");
14617 return false;
14618 }
14619 if (mCurrentUserId == userId)
14620 return true;
14621
14622 synchronized (this) {
14623 // Check if user is already logged in, otherwise check if user exists first before
14624 // adding to the list of logged in users.
14625 if (mLoggedInUsers.indexOfKey(userId) < 0) {
14626 if (!userExists(userId)) {
14627 return false;
14628 }
14629 mLoggedInUsers.append(userId, userId);
14630 }
14631
14632 mCurrentUserId = userId;
14633 boolean haveActivities = mMainStack.switchUser(userId);
14634 if (!haveActivities) {
14635 startHomeActivityLocked(userId);
14636 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014637
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014638 }
Amith Yamasani13593602012-03-22 16:16:17 -070014639
14640 // Inform of user switch
14641 Intent addedIntent = new Intent(Intent.ACTION_USER_SWITCHED);
14642 addedIntent.putExtra(Intent.EXTRA_USERID, userId);
14643 mContext.sendBroadcast(addedIntent, android.Manifest.permission.MANAGE_ACCOUNTS);
14644
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014645 return true;
14646 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014647
Amith Yamasani13593602012-03-22 16:16:17 -070014648 private void onUserRemoved(Intent intent) {
14649 int extraUserId = intent.getIntExtra(Intent.EXTRA_USERID, -1);
14650 if (extraUserId < 1) return;
14651
14652 // Kill all the processes for the user
14653 ArrayList<Pair<String, Integer>> pkgAndUids = new ArrayList<Pair<String,Integer>>();
14654 synchronized (this) {
14655 HashMap<String,SparseArray<ProcessRecord>> map = mProcessNames.getMap();
14656 for (Entry<String, SparseArray<ProcessRecord>> uidMap : map.entrySet()) {
14657 SparseArray<ProcessRecord> uids = uidMap.getValue();
14658 for (int i = 0; i < uids.size(); i++) {
14659 if (UserId.getUserId(uids.keyAt(i)) == extraUserId) {
14660 pkgAndUids.add(new Pair<String,Integer>(uidMap.getKey(), uids.keyAt(i)));
14661 }
14662 }
14663 }
14664
14665 for (Pair<String,Integer> pkgAndUid : pkgAndUids) {
14666 forceStopPackageLocked(pkgAndUid.first, pkgAndUid.second,
14667 false, false, true, true, extraUserId);
14668 }
14669 }
14670 }
14671
Amith Yamasani742a6712011-05-04 14:49:28 -070014672 private boolean userExists(int userId) {
14673 try {
Amith Yamasani13593602012-03-22 16:16:17 -070014674 UserInfo user = AppGlobals.getPackageManager().getUser(userId);
14675 return user != null;
Amith Yamasani742a6712011-05-04 14:49:28 -070014676 } catch (RemoteException re) {
14677 // Won't happen, in same process
14678 }
14679
14680 return false;
14681 }
14682
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014683 private void checkValidCaller(int uid, int userId) {
14684 if (UserId.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) return;
14685
14686 throw new SecurityException("Caller uid=" + uid
14687 + " is not privileged to communicate with user=" + userId);
14688 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014689
14690 private int applyUserId(int uid, int userId) {
14691 return UserId.getUid(userId, uid);
14692 }
14693
14694 private ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080014695 if (info == null) return null;
Amith Yamasani742a6712011-05-04 14:49:28 -070014696 ApplicationInfo newInfo = new ApplicationInfo(info);
14697 newInfo.uid = applyUserId(info.uid, userId);
14698 if (newInfo.uid >= Process.FIRST_APPLICATION_UID) {
14699 newInfo.dataDir = USER_DATA_DIR + userId + "/"
14700 + info.packageName;
14701 }
14702 return newInfo;
14703 }
14704
14705 ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080014706 if (aInfo == null || aInfo.applicationInfo.uid < Process.FIRST_APPLICATION_UID
Amith Yamasani742a6712011-05-04 14:49:28 -070014707 || userId < 1) {
14708 return aInfo;
14709 }
14710
14711 ActivityInfo info = new ActivityInfo(aInfo);
14712 info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId);
14713 return info;
14714 }
14715
14716 static class ServiceMap {
14717
14718 private final SparseArray<HashMap<ComponentName, ServiceRecord>> mServicesByNamePerUser
14719 = new SparseArray<HashMap<ComponentName, ServiceRecord>>();
14720 private final SparseArray<HashMap<Intent.FilterComparison, ServiceRecord>>
14721 mServicesByIntentPerUser = new SparseArray<
14722 HashMap<Intent.FilterComparison, ServiceRecord>>();
14723
14724 ServiceRecord getServiceByName(ComponentName name, int callingUser) {
14725 // TODO: Deal with global services
14726 if (DEBUG_MU)
14727 Slog.v(TAG_MU, "getServiceByName(" + name + "), callingUser = " + callingUser);
14728 return getServices(callingUser).get(name);
14729 }
14730
14731 ServiceRecord getServiceByName(ComponentName name) {
14732 return getServiceByName(name, -1);
14733 }
14734
14735 ServiceRecord getServiceByIntent(Intent.FilterComparison filter, int callingUser) {
14736 // TODO: Deal with global services
14737 if (DEBUG_MU)
14738 Slog.v(TAG_MU, "getServiceByIntent(" + filter + "), callingUser = " + callingUser);
14739 return getServicesByIntent(callingUser).get(filter);
14740 }
14741
14742 ServiceRecord getServiceByIntent(Intent.FilterComparison filter) {
14743 return getServiceByIntent(filter, -1);
14744 }
14745
14746 void putServiceByName(ComponentName name, int callingUser, ServiceRecord value) {
14747 // TODO: Deal with global services
14748 getServices(callingUser).put(name, value);
14749 }
14750
14751 void putServiceByIntent(Intent.FilterComparison filter, int callingUser,
14752 ServiceRecord value) {
14753 // TODO: Deal with global services
14754 getServicesByIntent(callingUser).put(filter, value);
14755 }
14756
14757 void removeServiceByName(ComponentName name, int callingUser) {
14758 // TODO: Deal with global services
14759 ServiceRecord removed = getServices(callingUser).remove(name);
14760 if (DEBUG_MU)
14761 Slog.v(TAG, "removeServiceByName user=" + callingUser + " name=" + name
14762 + " removed=" + removed);
14763 }
14764
14765 void removeServiceByIntent(Intent.FilterComparison filter, int callingUser) {
14766 // TODO: Deal with global services
14767 ServiceRecord removed = getServicesByIntent(callingUser).remove(filter);
14768 if (DEBUG_MU)
14769 Slog.v(TAG_MU, "removeServiceByIntent user=" + callingUser + " intent=" + filter
14770 + " removed=" + removed);
14771 }
14772
14773 Collection<ServiceRecord> getAllServices(int callingUser) {
14774 // TODO: Deal with global services
14775 return getServices(callingUser).values();
14776 }
14777
14778 private HashMap<ComponentName, ServiceRecord> getServices(int callingUser) {
14779 HashMap map = mServicesByNamePerUser.get(callingUser);
14780 if (map == null) {
14781 map = new HashMap<ComponentName, ServiceRecord>();
14782 mServicesByNamePerUser.put(callingUser, map);
14783 }
14784 return map;
14785 }
14786
14787 private HashMap<Intent.FilterComparison, ServiceRecord> getServicesByIntent(
14788 int callingUser) {
14789 HashMap map = mServicesByIntentPerUser.get(callingUser);
14790 if (map == null) {
14791 map = new HashMap<Intent.FilterComparison, ServiceRecord>();
14792 mServicesByIntentPerUser.put(callingUser, map);
14793 }
14794 return map;
14795 }
14796 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014797}