blob: 7a39c84b70ee992bb235376efae58b389816095b [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;
37import android.app.ActivityThread;
38import android.app.AlertDialog;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070039import android.app.AppGlobals;
Jacek Surazskif5b9c722009-05-18 12:09:59 +020040import android.app.ApplicationErrorReport;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.app.Dialog;
Dianne Hackbornb06ea702009-07-13 13:07:51 -070042import android.app.IActivityController;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043import android.app.IApplicationThread;
44import android.app.IInstrumentationWatcher;
Dianne Hackborn860755f2010-06-03 18:47:52 -070045import android.app.INotificationManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -070046import android.app.IProcessObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080047import android.app.IServiceConnection;
48import android.app.IThumbnailReceiver;
49import android.app.Instrumentation;
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070050import android.app.Notification;
Dianne Hackborn860755f2010-06-03 18:47:52 -070051import android.app.NotificationManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.app.PendingIntent;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070053import android.app.Service;
Christopher Tate45281862010-03-05 15:46:30 -080054import android.app.backup.IBackupManager;
Jacek Surazskif5b9c722009-05-18 12:09:59 +020055import android.content.ActivityNotFoundException;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -080056import android.content.BroadcastReceiver;
Dianne Hackborn21c241e2012-03-08 13:57:23 -080057import android.content.ClipData;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070058import android.content.ComponentCallbacks2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059import android.content.ComponentName;
Jeff Sharkey110a6b62012-03-12 11:12:41 -070060import android.content.ContentProvider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061import android.content.ContentResolver;
62import android.content.Context;
Christian Mehlmauer7664e202010-07-20 08:46:17 +020063import android.content.DialogInterface;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064import android.content.Intent;
65import android.content.IntentFilter;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070066import android.content.IIntentReceiver;
67import android.content.IIntentSender;
Dianne Hackbornfa82f222009-09-17 15:14:12 -070068import android.content.IntentSender;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069import android.content.pm.ActivityInfo;
70import android.content.pm.ApplicationInfo;
71import android.content.pm.ConfigurationInfo;
72import android.content.pm.IPackageDataObserver;
73import android.content.pm.IPackageManager;
74import android.content.pm.InstrumentationInfo;
Dan Egnor66c40e72010-01-26 16:23:11 -080075import android.content.pm.PackageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076import android.content.pm.PackageManager;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070077import android.content.pm.PathPermission;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078import android.content.pm.ProviderInfo;
79import android.content.pm.ResolveInfo;
80import android.content.pm.ServiceInfo;
Amith Yamasani742a6712011-05-04 14:49:28 -070081import android.content.pm.UserInfo;
Dianne Hackborn860755f2010-06-03 18:47:52 -070082import android.content.pm.PackageManager.NameNotFoundException;
Dianne Hackborne2515ee2011-04-27 18:52:56 -040083import android.content.res.CompatibilityInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080084import android.content.res.Configuration;
85import android.graphics.Bitmap;
Robert Greenwalt434203a2010-10-11 16:00:27 -070086import android.net.Proxy;
87import android.net.ProxyProperties;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080088import android.net.Uri;
89import android.os.Binder;
Dan Egnor60d87622009-12-16 16:32:58 -080090import android.os.Build;
Dan Egnor42471dd2010-01-07 17:25:22 -080091import android.os.Bundle;
Dianne Hackborn3025ef32009-08-31 21:31:47 -070092import android.os.Debug;
Dan Egnor60d87622009-12-16 16:32:58 -080093import android.os.DropBoxManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080094import android.os.Environment;
Dan Egnor42471dd2010-01-07 17:25:22 -080095import android.os.FileObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080096import android.os.FileUtils;
97import android.os.Handler;
98import android.os.IBinder;
99import android.os.IPermissionController;
100import android.os.Looper;
101import android.os.Message;
102import android.os.Parcel;
103import android.os.ParcelFileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800104import android.os.Process;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700105import android.os.RemoteCallbackList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106import android.os.RemoteException;
107import android.os.ServiceManager;
Brad Fitzpatrick46d42382010-06-11 13:57:58 -0700108import android.os.StrictMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800109import android.os.SystemClock;
110import android.os.SystemProperties;
Amith Yamasani742a6712011-05-04 14:49:28 -0700111import android.os.UserId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800112import android.provider.Settings;
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700113import android.text.format.Time;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800114import android.util.EventLog;
Dianne Hackborn905577f2011-09-07 18:31:28 -0700115import android.util.Pair;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800116import android.util.Slog;
Joe Onorato5d3bea62010-03-01 13:44:29 -0800117import android.util.Log;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118import android.util.PrintWriterPrinter;
119import android.util.SparseArray;
Amith Yamasani742a6712011-05-04 14:49:28 -0700120import android.util.SparseIntArray;
Dianne Hackborn1ebccf52010-08-15 13:04:34 -0700121import android.util.TimeUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800122import android.view.Gravity;
123import android.view.LayoutInflater;
124import android.view.View;
125import android.view.WindowManager;
126import android.view.WindowManagerPolicy;
127
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700128import java.io.BufferedInputStream;
129import java.io.BufferedOutputStream;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700130import java.io.BufferedReader;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700131import java.io.DataInputStream;
132import java.io.DataOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800133import java.io.File;
134import java.io.FileDescriptor;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700135import java.io.FileInputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800136import java.io.FileNotFoundException;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700137import java.io.FileOutputStream;
Jacek Surazskif5b9c722009-05-18 12:09:59 +0200138import java.io.IOException;
Dan Egnora455d192010-03-12 08:52:28 -0800139import java.io.InputStreamReader;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800140import java.io.PrintWriter;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700141import java.io.StringWriter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800142import java.lang.IllegalStateException;
143import java.lang.ref.WeakReference;
144import java.util.ArrayList;
Amith Yamasani742a6712011-05-04 14:49:28 -0700145import java.util.Collection;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700146import java.util.Collections;
147import java.util.Comparator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800148import java.util.HashMap;
149import java.util.HashSet;
150import java.util.Iterator;
151import java.util.List;
152import java.util.Locale;
153import java.util.Map;
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -0700154import java.util.Set;
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700155import java.util.concurrent.atomic.AtomicBoolean;
156import java.util.concurrent.atomic.AtomicLong;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800157
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700158public final class ActivityManagerService extends ActivityManagerNative
159 implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
Amith Yamasani742a6712011-05-04 14:49:28 -0700160 private static final String USER_DATA_DIR = "/data/user/";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800161 static final String TAG = "ActivityManager";
Amith Yamasani742a6712011-05-04 14:49:28 -0700162 static final String TAG_MU = "ActivityManagerServiceMU";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800163 static final boolean DEBUG = false;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400164 static final boolean localLOGV = DEBUG;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800165 static final boolean DEBUG_SWITCH = localLOGV || false;
166 static final boolean DEBUG_TASKS = localLOGV || false;
167 static final boolean DEBUG_PAUSE = localLOGV || false;
168 static final boolean DEBUG_OOM_ADJ = localLOGV || false;
169 static final boolean DEBUG_TRANSITION = localLOGV || false;
170 static final boolean DEBUG_BROADCAST = localLOGV || false;
Christopher Tatef46723b2012-01-26 14:19:24 -0800171 static final boolean DEBUG_BACKGROUND_BROADCAST = DEBUG_BROADCAST || false;
Dianne Hackborn82f3f002009-06-16 18:49:05 -0700172 static final boolean DEBUG_BROADCAST_LIGHT = DEBUG_BROADCAST || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800173 static final boolean DEBUG_SERVICE = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700174 static final boolean DEBUG_SERVICE_EXECUTING = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800175 static final boolean DEBUG_VISBILITY = localLOGV || false;
176 static final boolean DEBUG_PROCESSES = localLOGV || false;
Dianne Hackborna1e989b2009-09-01 19:54:29 -0700177 static final boolean DEBUG_PROVIDER = localLOGV || false;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800178 static final boolean DEBUG_URI_PERMISSION = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800179 static final boolean DEBUG_USER_LEAVING = localLOGV || false;
The Android Open Source Project10592532009-03-18 17:39:46 -0700180 static final boolean DEBUG_RESULTS = localLOGV || false;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -0700181 static final boolean DEBUG_BACKUP = localLOGV || false;
Dianne Hackborndc6b6352009-09-30 14:20:09 -0700182 static final boolean DEBUG_CONFIGURATION = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700183 static final boolean DEBUG_POWER = localLOGV || false;
184 static final boolean DEBUG_POWER_QUICK = DEBUG_POWER || false;
Amith Yamasani742a6712011-05-04 14:49:28 -0700185 static final boolean DEBUG_MU = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800186 static final boolean VALIDATE_TOKENS = false;
187 static final boolean SHOW_ACTIVITY_START_TIME = true;
188
189 // Control over CPU and battery monitoring.
190 static final long BATTERY_STATS_TIME = 30*60*1000; // write battery stats every 30 minutes.
191 static final boolean MONITOR_CPU_USAGE = true;
192 static final long MONITOR_CPU_MIN_TIME = 5*1000; // don't sample cpu less than every 5 seconds.
193 static final long MONITOR_CPU_MAX_TIME = 0x0fffffff; // wait possibly forever for next cpu sample.
194 static final boolean MONITOR_THREAD_CPU_USAGE = false;
195
Dianne Hackborn1655be42009-05-08 14:29:01 -0700196 // The flags that are set for all calls we make to the package manager.
Dianne Hackborn11b822d2009-07-21 20:03:02 -0700197 static final int STOCK_PM_FLAGS = PackageManager.GET_SHARED_LIBRARY_FILES;
Dianne Hackborn1655be42009-05-08 14:29:01 -0700198
Dianne Hackbornf02e57b2011-03-01 22:21:04 -0800199 private static final String SYSTEM_DEBUGGABLE = "ro.debuggable";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800200
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700201 static final boolean IS_USER_BUILD = "user".equals(Build.TYPE);
202
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800203 // Maximum number of recent tasks that we can remember.
204 static final int MAX_RECENT_TASKS = 20;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700205
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700206 // Amount of time after a call to stopAppSwitches() during which we will
207 // prevent further untrusted switches from happening.
208 static final long APP_SWITCH_DELAY_TIME = 5*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800209
210 // How long we wait for a launched process to attach to the activity manager
211 // before we decide it's never going to come up for real.
212 static final int PROC_START_TIMEOUT = 10*1000;
213
Jeff Brown3f9dd282011-07-08 20:02:19 -0700214 // How long we wait for a launched process to attach to the activity manager
215 // before we decide it's never going to come up for real, when the process was
216 // started with a wrapper for instrumentation (such as Valgrind) because it
217 // could take much longer than usual.
218 static final int PROC_START_TIMEOUT_WITH_WRAPPER = 300*1000;
219
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800220 // How long to wait after going idle before forcing apps to GC.
221 static final int GC_TIMEOUT = 5*1000;
222
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700223 // The minimum amount of time between successive GC requests for a process.
224 static final int GC_MIN_INTERVAL = 60*1000;
225
Dianne Hackborn287952c2010-09-22 22:34:31 -0700226 // The rate at which we check for apps using excessive power -- 15 mins.
227 static final int POWER_CHECK_DELAY = (DEBUG_POWER_QUICK ? 2 : 15) * 60*1000;
228
229 // The minimum sample duration we will allow before deciding we have
230 // enough data on wake locks to start killing things.
231 static final int WAKE_LOCK_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
232
233 // The minimum sample duration we will allow before deciding we have
234 // enough data on CPU usage to start killing things.
235 static final int CPU_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700236
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800237 // How long we allow a receiver to run before giving up on it.
Christopher Tatef46723b2012-01-26 14:19:24 -0800238 static final int BROADCAST_FG_TIMEOUT = 10*1000;
239 static final int BROADCAST_BG_TIMEOUT = 60*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800240
241 // How long we wait for a service to finish executing.
242 static final int SERVICE_TIMEOUT = 20*1000;
243
244 // How long a service needs to be running until restarting its process
245 // is no longer considered to be a relaunch of the service.
246 static final int SERVICE_RESTART_DURATION = 5*1000;
247
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700248 // How long a service needs to be running until it will start back at
249 // SERVICE_RESTART_DURATION after being killed.
250 static final int SERVICE_RESET_RUN_DURATION = 60*1000;
251
252 // Multiplying factor to increase restart duration time by, for each time
253 // a service is killed before it has run for SERVICE_RESET_RUN_DURATION.
254 static final int SERVICE_RESTART_DURATION_FACTOR = 4;
255
256 // The minimum amount of time between restarting services that we allow.
257 // That is, when multiple services are restarting, we won't allow each
258 // to restart less than this amount of time from the last one.
259 static final int SERVICE_MIN_RESTART_TIME_BETWEEN = 10*1000;
260
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800261 // Maximum amount of time for there to be no activity on a service before
262 // we consider it non-essential and allow its process to go on the
263 // LRU background list.
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700264 static final int MAX_SERVICE_INACTIVITY = 30*60*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800265
266 // How long we wait until we timeout on key dispatching.
267 static final int KEY_DISPATCHING_TIMEOUT = 5*1000;
268
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800269 // How long we wait until we timeout on key dispatching during instrumentation.
270 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT = 60*1000;
271
Dan Egnor42471dd2010-01-07 17:25:22 -0800272 static final int MY_PID = Process.myPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800273
274 static final String[] EMPTY_STRING_ARRAY = new String[0];
275
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700276 public ActivityStack mMainStack;
Mike Lockwood3a74bd32011-08-12 13:55:22 -0700277
278 private final boolean mHeadless;
279
Joe Onorato54a4a412011-11-02 20:50:08 -0700280 // Whether we should show our dialogs (ANR, crash, etc) or just perform their
281 // default actuion automatically. Important for devices without direct input
282 // devices.
283 private boolean mShowDialogs = true;
284
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800285 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700286 * Description of a request to start a new activity, which has been held
287 * due to app switches being disabled.
288 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700289 static class PendingActivityLaunch {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700290 ActivityRecord r;
291 ActivityRecord sourceRecord;
Dianne Hackborna4972e92012-03-14 10:38:05 -0700292 int startFlags;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700293 }
294
295 final ArrayList<PendingActivityLaunch> mPendingActivityLaunches
296 = new ArrayList<PendingActivityLaunch>();
297
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800298
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800299 BroadcastQueue mFgBroadcastQueue;
300 BroadcastQueue mBgBroadcastQueue;
Christopher Tatef46723b2012-01-26 14:19:24 -0800301 // Convenient for easy iteration over the queues. Foreground is first
302 // so that dispatch of foreground broadcasts gets precedence.
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800303 final BroadcastQueue[] mBroadcastQueues = new BroadcastQueue[2];
Christopher Tatef46723b2012-01-26 14:19:24 -0800304
305 BroadcastQueue broadcastQueueForIntent(Intent intent) {
306 final boolean isFg = (intent.getFlags() & Intent.FLAG_RECEIVER_FOREGROUND) != 0;
307 if (DEBUG_BACKGROUND_BROADCAST) {
308 Slog.i(TAG, "Broadcast intent " + intent + " on "
309 + (isFg ? "foreground" : "background")
310 + " queue");
311 }
312 return (isFg) ? mFgBroadcastQueue : mBgBroadcastQueue;
313 }
314
315 BroadcastRecord broadcastRecordForReceiverLocked(IBinder receiver) {
316 for (BroadcastQueue queue : mBroadcastQueues) {
317 BroadcastRecord r = queue.getMatchingOrderedReceiver(receiver);
318 if (r != null) {
319 return r;
320 }
321 }
322 return null;
323 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800324
325 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800326 * Activity we have told the window manager to have key focus.
327 */
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700328 ActivityRecord mFocusedActivity = null;
Dianne Hackbornbfe319e2009-09-21 00:34:05 -0700329 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800330 * List of intents that were used to start the most recent tasks.
331 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700332 final ArrayList<TaskRecord> mRecentTasks = new ArrayList<TaskRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800333
334 /**
Dianne Hackborn7d608422011-08-07 16:24:18 -0700335 * Process management.
336 */
337 final ProcessList mProcessList = new ProcessList();
338
339 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800340 * All of the applications we currently have running organized by name.
341 * The keys are strings of the application package name (as
342 * returned by the package manager), and the keys are ApplicationRecord
343 * objects.
344 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700345 final ProcessMap<ProcessRecord> mProcessNames = new ProcessMap<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800346
347 /**
Dianne Hackborna0c283e2012-02-09 10:47:01 -0800348 * The currently running isolated processes.
349 */
350 final SparseArray<ProcessRecord> mIsolatedProcesses = new SparseArray<ProcessRecord>();
351
352 /**
353 * Counter for assigning isolated process uids, to avoid frequently reusing the
354 * same ones.
355 */
356 int mNextIsolatedProcessUid = 0;
357
358 /**
Dianne Hackborn860755f2010-06-03 18:47:52 -0700359 * The currently running heavy-weight process, if any.
360 */
361 ProcessRecord mHeavyWeightProcess = null;
362
363 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800364 * The last time that various processes have crashed.
365 */
366 final ProcessMap<Long> mProcessCrashTimes = new ProcessMap<Long>();
367
368 /**
369 * Set of applications that we consider to be bad, and will reject
370 * incoming broadcasts from (which the user has no control over).
371 * Processes are added to this set when they have crashed twice within
372 * a minimum amount of time; they are removed from it when they are
373 * later restarted (hopefully due to some user action). The value is the
374 * time it was added to the list.
375 */
376 final ProcessMap<Long> mBadProcesses = new ProcessMap<Long>();
377
378 /**
379 * All of the processes we currently have running organized by pid.
380 * The keys are the pid running the application.
381 *
382 * <p>NOTE: This object is protected by its own lock, NOT the global
383 * activity manager lock!
384 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700385 final SparseArray<ProcessRecord> mPidsSelfLocked = new SparseArray<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800386
387 /**
388 * All of the processes that have been forced to be foreground. The key
389 * is the pid of the caller who requested it (we hold a death
390 * link on it).
391 */
392 abstract class ForegroundToken implements IBinder.DeathRecipient {
393 int pid;
394 IBinder token;
395 }
396 final SparseArray<ForegroundToken> mForegroundProcesses
397 = new SparseArray<ForegroundToken>();
398
399 /**
400 * List of records for processes that someone had tried to start before the
401 * system was ready. We don't start them at that point, but ensure they
402 * are started by the time booting is complete.
403 */
404 final ArrayList<ProcessRecord> mProcessesOnHold
405 = new ArrayList<ProcessRecord>();
406
407 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800408 * List of persistent applications that are in the process
409 * of being started.
410 */
411 final ArrayList<ProcessRecord> mPersistentStartingProcesses
412 = new ArrayList<ProcessRecord>();
413
414 /**
415 * Processes that are being forcibly torn down.
416 */
417 final ArrayList<ProcessRecord> mRemovedProcesses
418 = new ArrayList<ProcessRecord>();
419
420 /**
421 * List of running applications, sorted by recent usage.
422 * The first entry in the list is the least recently used.
423 * It contains ApplicationRecord objects. This list does NOT include
424 * any persistent application records (since we never want to exit them).
425 */
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800426 final ArrayList<ProcessRecord> mLruProcesses
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800427 = new ArrayList<ProcessRecord>();
428
429 /**
430 * List of processes that should gc as soon as things are idle.
431 */
432 final ArrayList<ProcessRecord> mProcessesToGc
433 = new ArrayList<ProcessRecord>();
434
435 /**
The Android Open Source Project4df24232009-03-05 14:34:35 -0800436 * This is the process holding what we currently consider to be
437 * the "home" activity.
438 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700439 ProcessRecord mHomeProcess;
The Android Open Source Project4df24232009-03-05 14:34:35 -0800440
441 /**
Dianne Hackbornf35fe232011-11-01 19:25:20 -0700442 * This is the process holding the activity the user last visited that
443 * is in a different process from the one they are currently in.
444 */
445 ProcessRecord mPreviousProcess;
Dianne Hackborn50685602011-12-01 12:23:37 -0800446
447 /**
448 * The time at which the previous process was last visible.
449 */
450 long mPreviousProcessVisibleTime;
451
Dianne Hackbornf35fe232011-11-01 19:25:20 -0700452 /**
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400453 * Packages that the user has asked to have run in screen size
454 * compatibility mode instead of filling the screen.
455 */
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -0700456 final CompatModePackages mCompatModePackages;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400457
458 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800459 * Set of PendingResultRecord objects that are currently active.
460 */
461 final HashSet mPendingResultRecords = new HashSet();
462
463 /**
464 * Set of IntentSenderRecord objects that are currently active.
465 */
466 final HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>> mIntentSenderRecords
467 = new HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>>();
468
469 /**
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -0800470 * Fingerprints (hashCode()) of stack traces that we've
Brad Fitzpatrick143666f2010-06-14 12:40:21 -0700471 * already logged DropBox entries for. Guarded by itself. If
472 * something (rogue user app) forces this over
473 * MAX_DUP_SUPPRESSED_STACKS entries, the contents are cleared.
474 */
475 private final HashSet<Integer> mAlreadyLoggedViolatedStacks = new HashSet<Integer>();
476 private static final int MAX_DUP_SUPPRESSED_STACKS = 5000;
477
478 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -0700479 * Strict Mode background batched logging state.
480 *
481 * The string buffer is guarded by itself, and its lock is also
482 * used to determine if another batched write is already
483 * in-flight.
484 */
485 private final StringBuilder mStrictModeBuffer = new StringBuilder();
486
487 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800488 * Keeps track of all IIntentReceivers that have been registered for
489 * broadcasts. Hash keys are the receiver IBinder, hash value is
490 * a ReceiverList.
491 */
492 final HashMap mRegisteredReceivers = new HashMap();
493
494 /**
495 * Resolver for broadcast intents to registered receivers.
496 * Holds BroadcastFilter (subclass of IntentFilter).
497 */
498 final IntentResolver<BroadcastFilter, BroadcastFilter> mReceiverResolver
499 = new IntentResolver<BroadcastFilter, BroadcastFilter>() {
500 @Override
501 protected boolean allowFilterResult(
502 BroadcastFilter filter, List<BroadcastFilter> dest) {
503 IBinder target = filter.receiverList.receiver.asBinder();
504 for (int i=dest.size()-1; i>=0; i--) {
505 if (dest.get(i).receiverList.receiver.asBinder() == target) {
506 return false;
507 }
508 }
509 return true;
510 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700511
512 @Override
513 protected String packageForFilter(BroadcastFilter filter) {
514 return filter.packageName;
515 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800516 };
517
518 /**
519 * State of all active sticky broadcasts. Keys are the action of the
520 * sticky Intent, values are an ArrayList of all broadcasted intents with
521 * that action (which should usually be one).
522 */
523 final HashMap<String, ArrayList<Intent>> mStickyBroadcasts =
524 new HashMap<String, ArrayList<Intent>>();
525
Amith Yamasani742a6712011-05-04 14:49:28 -0700526 final ServiceMap mServiceMap = new ServiceMap();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800527
528 /**
529 * All currently bound service connections. Keys are the IBinder of
530 * the client's IServiceConnection.
531 */
Dianne Hackborn43d9ac82010-08-25 15:06:25 -0700532 final HashMap<IBinder, ArrayList<ConnectionRecord>> mServiceConnections
533 = new HashMap<IBinder, ArrayList<ConnectionRecord>>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800534
535 /**
536 * List of services that we have been asked to start,
537 * but haven't yet been able to. It is used to hold start requests
538 * while waiting for their corresponding application thread to get
539 * going.
540 */
541 final ArrayList<ServiceRecord> mPendingServices
542 = new ArrayList<ServiceRecord>();
543
544 /**
545 * List of services that are scheduled to restart following a crash.
546 */
547 final ArrayList<ServiceRecord> mRestartingServices
548 = new ArrayList<ServiceRecord>();
549
550 /**
551 * List of services that are in the process of being stopped.
552 */
553 final ArrayList<ServiceRecord> mStoppingServices
554 = new ArrayList<ServiceRecord>();
555
556 /**
Christopher Tate181fafa2009-05-14 11:12:14 -0700557 * Backup/restore process management
558 */
559 String mBackupAppName = null;
560 BackupRecord mBackupTarget = null;
561
562 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800563 * List of PendingThumbnailsRecord objects of clients who are still
564 * waiting to receive all of the thumbnails for a task.
565 */
566 final ArrayList mPendingThumbnails = new ArrayList();
567
568 /**
569 * List of HistoryRecord objects that have been finished and must
570 * still report back to a pending thumbnail receiver.
571 */
572 final ArrayList mCancelledThumbnails = new ArrayList();
573
Amith Yamasani742a6712011-05-04 14:49:28 -0700574 final ProviderMap mProviderMap = new ProviderMap();
575
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800576 /**
577 * List of content providers who have clients waiting for them. The
578 * application is currently being launched and the provider will be
579 * removed from this list once it is published.
580 */
Dianne Hackborn860755f2010-06-03 18:47:52 -0700581 final ArrayList<ContentProviderRecord> mLaunchingProviders
582 = new ArrayList<ContentProviderRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800583
584 /**
585 * Global set of specific Uri permissions that have been granted.
586 */
587 final private SparseArray<HashMap<Uri, UriPermission>> mGrantedUriPermissions
588 = new SparseArray<HashMap<Uri, UriPermission>>();
589
Svetoslav Ganov54d068e2011-03-02 12:58:40 -0800590 CoreSettingsObserver mCoreSettingsObserver;
591
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800592 /**
593 * Thread-local storage used to carry caller permissions over through
594 * indirect content-provider access.
595 * @see #ActivityManagerService.openContentUri()
596 */
597 private class Identity {
598 public int pid;
599 public int uid;
600
601 Identity(int _pid, int _uid) {
602 pid = _pid;
603 uid = _uid;
604 }
605 }
Amith Yamasani742a6712011-05-04 14:49:28 -0700606
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800607 private static ThreadLocal<Identity> sCallerIdentity = new ThreadLocal<Identity>();
608
609 /**
610 * All information we have collected about the runtime performance of
611 * any user id that can impact battery performance.
612 */
613 final BatteryStatsService mBatteryStatsService;
614
615 /**
616 * information about component usage
617 */
618 final UsageStatsService mUsageStatsService;
619
620 /**
621 * Current configuration information. HistoryRecord objects are given
622 * a reference to this object to indicate which configuration they are
623 * currently running in, so this object must be kept immutable.
624 */
625 Configuration mConfiguration = new Configuration();
626
627 /**
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800628 * Current sequencing integer of the configuration, for skipping old
629 * configurations.
630 */
631 int mConfigurationSeq = 0;
632
633 /**
Jack Palevichb90d28c2009-07-22 15:35:24 -0700634 * Hardware-reported OpenGLES version.
635 */
636 final int GL_ES_VERSION;
637
638 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800639 * List of initialization arguments to pass to all processes when binding applications to them.
640 * For example, references to the commonly used services.
641 */
642 HashMap<String, IBinder> mAppBindArgs;
643
644 /**
Dianne Hackbornf210d6b2009-04-13 18:42:49 -0700645 * Temporary to avoid allocations. Protected by main lock.
646 */
647 final StringBuilder mStringBuilder = new StringBuilder(256);
648
649 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800650 * Used to control how we initialize the service.
651 */
652 boolean mStartRunning = false;
653 ComponentName mTopComponent;
654 String mTopAction;
655 String mTopData;
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700656 boolean mProcessesReady = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800657 boolean mSystemReady = false;
658 boolean mBooting = false;
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700659 boolean mWaitingUpdate = false;
660 boolean mDidUpdate = false;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700661 boolean mOnBattery = false;
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700662 boolean mLaunchWarningShown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800663
664 Context mContext;
665
666 int mFactoryTest;
667
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -0700668 boolean mCheckedForSetup;
669
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800670 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700671 * The time at which we will allow normal application switches again,
672 * after a call to {@link #stopAppSwitches()}.
673 */
674 long mAppSwitchesAllowedTime;
675
676 /**
677 * This is set to true after the first switch after mAppSwitchesAllowedTime
678 * is set; any switches after that will clear the time.
679 */
680 boolean mDidAppSwitch;
681
682 /**
Dianne Hackborn287952c2010-09-22 22:34:31 -0700683 * Last time (in realtime) at which we checked for power usage.
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700684 */
Dianne Hackborn287952c2010-09-22 22:34:31 -0700685 long mLastPowerCheckRealtime;
686
687 /**
688 * Last time (in uptime) at which we checked for power usage.
689 */
690 long mLastPowerCheckUptime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700691
692 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800693 * Set while we are wanting to sleep, to prevent any
694 * activities from being started/resumed.
695 */
696 boolean mSleeping = false;
697
698 /**
Dianne Hackborn55280a92009-05-07 15:53:46 -0700699 * Set if we are shutting down the system, similar to sleeping.
700 */
701 boolean mShuttingDown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800702
703 /**
704 * Task identifier that activities are currently being started
705 * in. Incremented each time a new task is created.
706 * todo: Replace this with a TokenSpace class that generates non-repeating
707 * integers that won't wrap.
708 */
709 int mCurTask = 1;
710
711 /**
712 * Current sequence id for oom_adj computation traversal.
713 */
714 int mAdjSeq = 0;
715
716 /**
Dianne Hackborn906497c2010-05-10 15:57:38 -0700717 * Current sequence id for process LRU updating.
718 */
719 int mLruSeq = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800720
721 /**
Dianne Hackborne02c88a2011-10-28 13:58:15 -0700722 * Keep track of the number of service processes we last found, to
723 * determine on the next iteration which should be B services.
724 */
725 int mNumServiceProcs = 0;
726 int mNewNumServiceProcs = 0;
727
728 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800729 * System monitoring: number of processes that died since the last
730 * N procs were started.
731 */
732 int[] mProcDeaths = new int[20];
733
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700734 /**
735 * This is set if we had to do a delayed dexopt of an app before launching
736 * it, to increasing the ANR timeouts in that case.
737 */
738 boolean mDidDexOpt;
739
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800740 String mDebugApp = null;
741 boolean mWaitForDebugger = false;
742 boolean mDebugTransient = false;
743 String mOrigDebugApp = null;
744 boolean mOrigWaitForDebugger = false;
745 boolean mAlwaysFinishActivities = false;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700746 IActivityController mController = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700747 String mProfileApp = null;
748 ProcessRecord mProfileProc = null;
749 String mProfileFile;
750 ParcelFileDescriptor mProfileFd;
751 int mProfileType = 0;
752 boolean mAutoStopProfiler = false;
Siva Velusamy92a8b222012-03-09 16:24:04 -0800753 String mOpenGlTraceApp = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800754
Jeff Sharkeya4620792011-05-20 15:29:23 -0700755 final RemoteCallbackList<IProcessObserver> mProcessObservers
756 = new RemoteCallbackList<IProcessObserver>();
757
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800758 /**
759 * Callback of last caller to {@link #requestPss}.
760 */
761 Runnable mRequestPssCallback;
762
763 /**
764 * Remaining processes for which we are waiting results from the last
765 * call to {@link #requestPss}.
766 */
767 final ArrayList<ProcessRecord> mRequestPssList
768 = new ArrayList<ProcessRecord>();
769
770 /**
771 * Runtime statistics collection thread. This object's lock is used to
772 * protect all related state.
773 */
774 final Thread mProcessStatsThread;
775
776 /**
777 * Used to collect process stats when showing not responding dialog.
778 * Protected by mProcessStatsThread.
779 */
780 final ProcessStats mProcessStats = new ProcessStats(
781 MONITOR_THREAD_CPU_USAGE);
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700782 final AtomicLong mLastCpuTime = new AtomicLong(0);
783 final AtomicBoolean mProcessStatsMutexFree = new AtomicBoolean(true);
784
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800785 long mLastWriteTime = 0;
786
787 /**
788 * Set to true after the system has finished booting.
789 */
790 boolean mBooted = false;
791
Dianne Hackborn7d608422011-08-07 16:24:18 -0700792 int mProcessLimit = ProcessList.MAX_HIDDEN_APPS;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700793 int mProcessLimitOverride = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800794
795 WindowManagerService mWindowManager;
796
797 static ActivityManagerService mSelf;
798 static ActivityThread mSystemThread;
799
800 private final class AppDeathRecipient implements IBinder.DeathRecipient {
801 final ProcessRecord mApp;
802 final int mPid;
803 final IApplicationThread mAppThread;
804
805 AppDeathRecipient(ProcessRecord app, int pid,
806 IApplicationThread thread) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800807 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800808 TAG, "New death recipient " + this
809 + " for thread " + thread.asBinder());
810 mApp = app;
811 mPid = pid;
812 mAppThread = thread;
813 }
814
815 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800816 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800817 TAG, "Death received in " + this
818 + " for thread " + mAppThread.asBinder());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800819 synchronized(ActivityManagerService.this) {
820 appDiedLocked(mApp, mPid, mAppThread);
821 }
822 }
823 }
824
825 static final int SHOW_ERROR_MSG = 1;
826 static final int SHOW_NOT_RESPONDING_MSG = 2;
827 static final int SHOW_FACTORY_ERROR_MSG = 3;
828 static final int UPDATE_CONFIGURATION_MSG = 4;
829 static final int GC_BACKGROUND_PROCESSES_MSG = 5;
830 static final int WAIT_FOR_DEBUGGER_MSG = 6;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800831 static final int SERVICE_TIMEOUT_MSG = 12;
832 static final int UPDATE_TIME_ZONE = 13;
833 static final int SHOW_UID_ERROR_MSG = 14;
834 static final int IM_FEELING_LUCKY_MSG = 15;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800835 static final int PROC_START_TIMEOUT_MSG = 20;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700836 static final int DO_PENDING_ACTIVITY_LAUNCHES_MSG = 21;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -0700837 static final int KILL_APPLICATION_MSG = 22;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800838 static final int FINALIZE_PENDING_INTENT_MSG = 23;
Dianne Hackborn860755f2010-06-03 18:47:52 -0700839 static final int POST_HEAVY_NOTIFICATION_MSG = 24;
840 static final int CANCEL_HEAVY_NOTIFICATION_MSG = 25;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700841 static final int SHOW_STRICT_MODE_VIOLATION_MSG = 26;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700842 static final int CHECK_EXCESSIVE_WAKE_LOCKS_MSG = 27;
Robert Greenwalt03595d02010-11-02 14:08:23 -0700843 static final int CLEAR_DNS_CACHE = 28;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700844 static final int UPDATE_HTTP_PROXY = 29;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700845 static final int SHOW_COMPAT_MODE_DIALOG_MSG = 30;
Dianne Hackborn36f80f32011-05-31 18:26:45 -0700846 static final int DISPATCH_FOREGROUND_ACTIVITIES_CHANGED = 31;
847 static final int DISPATCH_PROCESS_DIED = 32;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700848 static final int REPORT_MEM_USAGE = 33;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800849
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800850 static final int FIRST_ACTIVITY_STACK_MSG = 100;
851 static final int FIRST_BROADCAST_QUEUE_MSG = 200;
852 static final int FIRST_COMPAT_MODE_MSG = 300;
853
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800854 AlertDialog mUidAlert;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700855 CompatModeDialog mCompatModeDialog;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700856 long mLastMemUsageReportTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800857
858 final Handler mHandler = new Handler() {
859 //public Handler() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800860 // if (localLOGV) Slog.v(TAG, "Handler started!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800861 //}
862
863 public void handleMessage(Message msg) {
864 switch (msg.what) {
865 case SHOW_ERROR_MSG: {
866 HashMap data = (HashMap) msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800867 synchronized (ActivityManagerService.this) {
868 ProcessRecord proc = (ProcessRecord)data.get("app");
869 if (proc != null && proc.crashDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800870 Slog.e(TAG, "App already has crash dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800871 return;
872 }
873 AppErrorResult res = (AppErrorResult) data.get("result");
Joe Onorato54a4a412011-11-02 20:50:08 -0700874 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Dan Egnorb7f03672009-12-09 16:22:32 -0800875 Dialog d = new AppErrorDialog(mContext, res, proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800876 d.show();
877 proc.crashDialog = d;
878 } else {
879 // The device is asleep, so just pretend that the user
880 // saw a crash dialog and hit "force quit".
881 res.set(0);
882 }
883 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700884
885 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800886 } break;
887 case SHOW_NOT_RESPONDING_MSG: {
888 synchronized (ActivityManagerService.this) {
889 HashMap data = (HashMap) msg.obj;
890 ProcessRecord proc = (ProcessRecord)data.get("app");
891 if (proc != null && proc.anrDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800892 Slog.e(TAG, "App already has anr dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800893 return;
894 }
The Android Open Source Project4df24232009-03-05 14:34:35 -0800895
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700896 Intent intent = new Intent("android.intent.action.ANR");
897 if (!mProcessesReady) {
Christopher Tatef46723b2012-01-26 14:19:24 -0800898 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
899 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700900 }
901 broadcastIntentLocked(null, null, intent,
The Android Open Source Project4df24232009-03-05 14:34:35 -0800902 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -0700903 false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
The Android Open Source Project4df24232009-03-05 14:34:35 -0800904
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800905 Dialog d = new AppNotRespondingDialog(ActivityManagerService.this,
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700906 mContext, proc, (ActivityRecord)data.get("activity"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800907 d.show();
908 proc.anrDialog = d;
909 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700910
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700911 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800912 } break;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700913 case SHOW_STRICT_MODE_VIOLATION_MSG: {
914 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj;
915 synchronized (ActivityManagerService.this) {
916 ProcessRecord proc = (ProcessRecord) data.get("app");
917 if (proc == null) {
918 Slog.e(TAG, "App not found when showing strict mode dialog.");
919 break;
920 }
921 if (proc.crashDialog != null) {
922 Slog.e(TAG, "App already has strict mode dialog: " + proc);
923 return;
924 }
925 AppErrorResult res = (AppErrorResult) data.get("result");
Joe Onorato54a4a412011-11-02 20:50:08 -0700926 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700927 Dialog d = new StrictModeViolationDialog(mContext, res, proc);
928 d.show();
929 proc.crashDialog = d;
930 } else {
931 // The device is asleep, so just pretend that the user
932 // saw a crash dialog and hit "force quit".
933 res.set(0);
934 }
935 }
936 ensureBootCompleted();
937 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800938 case SHOW_FACTORY_ERROR_MSG: {
939 Dialog d = new FactoryErrorDialog(
940 mContext, msg.getData().getCharSequence("msg"));
941 d.show();
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700942 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800943 } break;
944 case UPDATE_CONFIGURATION_MSG: {
945 final ContentResolver resolver = mContext.getContentResolver();
946 Settings.System.putConfiguration(resolver, (Configuration)msg.obj);
947 } break;
948 case GC_BACKGROUND_PROCESSES_MSG: {
949 synchronized (ActivityManagerService.this) {
950 performAppGcsIfAppropriateLocked();
951 }
952 } break;
953 case WAIT_FOR_DEBUGGER_MSG: {
954 synchronized (ActivityManagerService.this) {
955 ProcessRecord app = (ProcessRecord)msg.obj;
956 if (msg.arg1 != 0) {
957 if (!app.waitedForDebugger) {
958 Dialog d = new AppWaitingForDebuggerDialog(
959 ActivityManagerService.this,
960 mContext, app);
961 app.waitDialog = d;
962 app.waitedForDebugger = true;
963 d.show();
964 }
965 } else {
966 if (app.waitDialog != null) {
967 app.waitDialog.dismiss();
968 app.waitDialog = null;
969 }
970 }
971 }
972 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800973 case SERVICE_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700974 if (mDidDexOpt) {
975 mDidDexOpt = false;
976 Message nmsg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
977 nmsg.obj = msg.obj;
978 mHandler.sendMessageDelayed(nmsg, SERVICE_TIMEOUT);
979 return;
980 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800981 serviceTimeout((ProcessRecord)msg.obj);
982 } break;
983 case UPDATE_TIME_ZONE: {
984 synchronized (ActivityManagerService.this) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800985 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
986 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800987 if (r.thread != null) {
988 try {
989 r.thread.updateTimeZone();
990 } catch (RemoteException ex) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800991 Slog.w(TAG, "Failed to update time zone for: " + r.info.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800992 }
993 }
994 }
995 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700996 } break;
Robert Greenwalt03595d02010-11-02 14:08:23 -0700997 case CLEAR_DNS_CACHE: {
998 synchronized (ActivityManagerService.this) {
999 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1000 ProcessRecord r = mLruProcesses.get(i);
1001 if (r.thread != null) {
1002 try {
1003 r.thread.clearDnsCache();
1004 } catch (RemoteException ex) {
1005 Slog.w(TAG, "Failed to clear dns cache for: " + r.info.processName);
1006 }
1007 }
1008 }
1009 }
1010 } break;
Robert Greenwalt434203a2010-10-11 16:00:27 -07001011 case UPDATE_HTTP_PROXY: {
1012 ProxyProperties proxy = (ProxyProperties)msg.obj;
1013 String host = "";
1014 String port = "";
1015 String exclList = "";
1016 if (proxy != null) {
1017 host = proxy.getHost();
1018 port = Integer.toString(proxy.getPort());
1019 exclList = proxy.getExclusionList();
1020 }
1021 synchronized (ActivityManagerService.this) {
1022 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1023 ProcessRecord r = mLruProcesses.get(i);
1024 if (r.thread != null) {
1025 try {
1026 r.thread.setHttpProxy(host, port, exclList);
1027 } catch (RemoteException ex) {
1028 Slog.w(TAG, "Failed to update http proxy for: " +
1029 r.info.processName);
1030 }
1031 }
1032 }
1033 }
1034 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001035 case SHOW_UID_ERROR_MSG: {
Joe Onorato54a4a412011-11-02 20:50:08 -07001036 String title = "System UIDs Inconsistent";
1037 String text = "UIDs on the system are inconsistent, you need to wipe your"
1038 + " data partition or your device will be unstable.";
1039 Log.e(TAG, title + ": " + text);
1040 if (mShowDialogs) {
1041 // XXX This is a temporary dialog, no need to localize.
1042 AlertDialog d = new BaseErrorDialog(mContext);
1043 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
1044 d.setCancelable(false);
1045 d.setTitle(title);
1046 d.setMessage(text);
1047 d.setButton(DialogInterface.BUTTON_POSITIVE, "I'm Feeling Lucky",
1048 mHandler.obtainMessage(IM_FEELING_LUCKY_MSG));
1049 mUidAlert = d;
1050 d.show();
1051 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001052 } break;
1053 case IM_FEELING_LUCKY_MSG: {
1054 if (mUidAlert != null) {
1055 mUidAlert.dismiss();
1056 mUidAlert = null;
1057 }
1058 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001059 case PROC_START_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001060 if (mDidDexOpt) {
1061 mDidDexOpt = false;
1062 Message nmsg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
1063 nmsg.obj = msg.obj;
1064 mHandler.sendMessageDelayed(nmsg, PROC_START_TIMEOUT);
1065 return;
1066 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001067 ProcessRecord app = (ProcessRecord)msg.obj;
1068 synchronized (ActivityManagerService.this) {
1069 processStartTimedOutLocked(app);
1070 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001071 } break;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07001072 case DO_PENDING_ACTIVITY_LAUNCHES_MSG: {
1073 synchronized (ActivityManagerService.this) {
1074 doPendingActivityLaunchesLocked(true);
1075 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001076 } break;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001077 case KILL_APPLICATION_MSG: {
1078 synchronized (ActivityManagerService.this) {
1079 int uid = msg.arg1;
1080 boolean restart = (msg.arg2 == 1);
1081 String pkg = (String) msg.obj;
Christopher Tate3dacd842011-08-19 14:56:15 -07001082 forceStopPackageLocked(pkg, uid, restart, false, true, false);
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001083 }
1084 } break;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001085 case FINALIZE_PENDING_INTENT_MSG: {
1086 ((PendingIntentRecord)msg.obj).completeFinalize();
1087 } break;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001088 case POST_HEAVY_NOTIFICATION_MSG: {
1089 INotificationManager inm = NotificationManager.getService();
1090 if (inm == null) {
1091 return;
1092 }
1093
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001094 ActivityRecord root = (ActivityRecord)msg.obj;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001095 ProcessRecord process = root.app;
1096 if (process == null) {
1097 return;
1098 }
1099
1100 try {
1101 Context context = mContext.createPackageContext(process.info.packageName, 0);
1102 String text = mContext.getString(R.string.heavy_weight_notification,
1103 context.getApplicationInfo().loadLabel(context.getPackageManager()));
1104 Notification notification = new Notification();
1105 notification.icon = com.android.internal.R.drawable.stat_sys_adb; //context.getApplicationInfo().icon;
1106 notification.when = 0;
1107 notification.flags = Notification.FLAG_ONGOING_EVENT;
1108 notification.tickerText = text;
1109 notification.defaults = 0; // please be quiet
1110 notification.sound = null;
1111 notification.vibrate = null;
1112 notification.setLatestEventInfo(context, text,
1113 mContext.getText(R.string.heavy_weight_notification_detail),
1114 PendingIntent.getActivity(mContext, 0, root.intent,
1115 PendingIntent.FLAG_CANCEL_CURRENT));
1116
1117 try {
1118 int[] outId = new int[1];
1119 inm.enqueueNotification("android", R.string.heavy_weight_notification,
1120 notification, outId);
1121 } catch (RuntimeException e) {
1122 Slog.w(ActivityManagerService.TAG,
1123 "Error showing notification for heavy-weight app", e);
1124 } catch (RemoteException e) {
1125 }
1126 } catch (NameNotFoundException e) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07001127 Slog.w(TAG, "Unable to create context for heavy notification", e);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001128 }
1129 } break;
1130 case CANCEL_HEAVY_NOTIFICATION_MSG: {
1131 INotificationManager inm = NotificationManager.getService();
1132 if (inm == null) {
1133 return;
1134 }
1135 try {
1136 inm.cancelNotification("android",
1137 R.string.heavy_weight_notification);
1138 } catch (RuntimeException e) {
1139 Slog.w(ActivityManagerService.TAG,
1140 "Error canceling notification for service", e);
1141 } catch (RemoteException e) {
1142 }
1143 } break;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001144 case CHECK_EXCESSIVE_WAKE_LOCKS_MSG: {
1145 synchronized (ActivityManagerService.this) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001146 checkExcessivePowerUsageLocked(true);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07001147 removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001148 Message nmsg = obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
1149 sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001150 }
1151 } break;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001152 case SHOW_COMPAT_MODE_DIALOG_MSG: {
1153 synchronized (ActivityManagerService.this) {
1154 ActivityRecord ar = (ActivityRecord)msg.obj;
1155 if (mCompatModeDialog != null) {
1156 if (mCompatModeDialog.mAppInfo.packageName.equals(
1157 ar.info.applicationInfo.packageName)) {
1158 return;
1159 }
1160 mCompatModeDialog.dismiss();
1161 mCompatModeDialog = null;
1162 }
Dianne Hackborn29478262011-06-07 15:44:22 -07001163 if (ar != null && false) {
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001164 if (mCompatModePackages.getPackageAskCompatModeLocked(
1165 ar.packageName)) {
1166 int mode = mCompatModePackages.computeCompatModeLocked(
1167 ar.info.applicationInfo);
1168 if (mode == ActivityManager.COMPAT_MODE_DISABLED
1169 || mode == ActivityManager.COMPAT_MODE_ENABLED) {
1170 mCompatModeDialog = new CompatModeDialog(
1171 ActivityManagerService.this, mContext,
1172 ar.info.applicationInfo);
1173 mCompatModeDialog.show();
1174 }
1175 }
1176 }
1177 }
Dianne Hackborn36f80f32011-05-31 18:26:45 -07001178 break;
1179 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001180 case DISPATCH_FOREGROUND_ACTIVITIES_CHANGED: {
Jeff Sharkey287bd832011-05-28 19:36:26 -07001181 final int pid = msg.arg1;
1182 final int uid = msg.arg2;
1183 final boolean foregroundActivities = (Boolean) msg.obj;
1184 dispatchForegroundActivitiesChanged(pid, uid, foregroundActivities);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001185 break;
1186 }
1187 case DISPATCH_PROCESS_DIED: {
Jeff Sharkey287bd832011-05-28 19:36:26 -07001188 final int pid = msg.arg1;
1189 final int uid = msg.arg2;
1190 dispatchProcessDied(pid, uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001191 break;
1192 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001193 case REPORT_MEM_USAGE: {
1194 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
1195 if (!isDebuggable) {
1196 return;
1197 }
1198 synchronized (ActivityManagerService.this) {
1199 long now = SystemClock.uptimeMillis();
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001200 if (now < (mLastMemUsageReportTime+5*60*1000)) {
1201 // Don't report more than every 5 minutes to somewhat
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001202 // avoid spamming.
1203 return;
1204 }
1205 mLastMemUsageReportTime = now;
1206 }
1207 Thread thread = new Thread() {
1208 @Override public void run() {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001209 StringBuilder dropBuilder = new StringBuilder(1024);
1210 StringBuilder logBuilder = new StringBuilder(1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -08001211 StringWriter oomSw = new StringWriter();
1212 PrintWriter oomPw = new PrintWriter(oomSw);
1213 StringWriter catSw = new StringWriter();
1214 PrintWriter catPw = new PrintWriter(catSw);
1215 String[] emptyArgs = new String[] { };
1216 StringBuilder tag = new StringBuilder(128);
1217 StringBuilder stack = new StringBuilder(128);
1218 tag.append("Low on memory -- ");
1219 dumpApplicationMemoryUsage(null, oomPw, " ", emptyArgs, true, catPw,
1220 tag, stack);
1221 dropBuilder.append(stack);
1222 dropBuilder.append('\n');
1223 dropBuilder.append('\n');
1224 String oomString = oomSw.toString();
1225 dropBuilder.append(oomString);
1226 dropBuilder.append('\n');
1227 logBuilder.append(oomString);
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001228 try {
1229 java.lang.Process proc = Runtime.getRuntime().exec(new String[] {
1230 "procrank", });
1231 final InputStreamReader converter = new InputStreamReader(
1232 proc.getInputStream());
1233 BufferedReader in = new BufferedReader(converter);
1234 String line;
1235 while (true) {
1236 line = in.readLine();
1237 if (line == null) {
1238 break;
1239 }
1240 if (line.length() > 0) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001241 logBuilder.append(line);
1242 logBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001243 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001244 dropBuilder.append(line);
1245 dropBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001246 }
1247 converter.close();
1248 } catch (IOException e) {
1249 }
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001250 synchronized (ActivityManagerService.this) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08001251 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001252 dumpProcessesLocked(null, catPw, emptyArgs, 0, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001253 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001254 dumpServicesLocked(null, catPw, emptyArgs, 0, false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001255 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001256 dumpActivitiesLocked(null, catPw, emptyArgs, 0, false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001257 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001258 dropBuilder.append(catSw.toString());
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001259 addErrorToDropBox("lowmem", null, "system_server", null,
1260 null, tag.toString(), dropBuilder.toString(), null, null);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001261 Slog.i(TAG, logBuilder.toString());
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001262 synchronized (ActivityManagerService.this) {
1263 long now = SystemClock.uptimeMillis();
1264 if (mLastMemUsageReportTime < now) {
1265 mLastMemUsageReportTime = now;
1266 }
1267 }
1268 }
1269 };
1270 thread.start();
1271 break;
1272 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001273 }
1274 }
1275 };
1276
1277 public static void setSystemProcess() {
1278 try {
1279 ActivityManagerService m = mSelf;
1280
Dianne Hackborna573f6a2012-02-09 16:12:18 -08001281 ServiceManager.addService("activity", m, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001282 ServiceManager.addService("meminfo", new MemBinder(m));
Chet Haase9c1e23b2011-03-24 10:51:31 -07001283 ServiceManager.addService("gfxinfo", new GraphicsBinder(m));
Jeff Brown6754ba22011-12-14 20:20:01 -08001284 ServiceManager.addService("dbinfo", new DbBinder(m));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001285 if (MONITOR_CPU_USAGE) {
1286 ServiceManager.addService("cpuinfo", new CpuBinder(m));
1287 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001288 ServiceManager.addService("permission", new PermissionController(m));
1289
1290 ApplicationInfo info =
1291 mSelf.mContext.getPackageManager().getApplicationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -07001292 "android", STOCK_PM_FLAGS);
Mike Cleron432b7132009-09-24 15:28:29 -07001293 mSystemThread.installSystemApplicationInfo(info);
1294
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001295 synchronized (mSelf) {
1296 ProcessRecord app = mSelf.newProcessRecordLocked(
1297 mSystemThread.getApplicationThread(), info,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001298 info.processName, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001299 app.persistent = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08001300 app.pid = MY_PID;
Dianne Hackborn7d608422011-08-07 16:24:18 -07001301 app.maxAdj = ProcessList.SYSTEM_ADJ;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001302 mSelf.mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001303 synchronized (mSelf.mPidsSelfLocked) {
1304 mSelf.mPidsSelfLocked.put(app.pid, app);
1305 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001306 mSelf.updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001307 }
1308 } catch (PackageManager.NameNotFoundException e) {
1309 throw new RuntimeException(
1310 "Unable to find android system package", e);
1311 }
1312 }
1313
1314 public void setWindowManager(WindowManagerService wm) {
1315 mWindowManager = wm;
1316 }
1317
1318 public static final Context main(int factoryTest) {
1319 AThread thr = new AThread();
1320 thr.start();
1321
1322 synchronized (thr) {
1323 while (thr.mService == null) {
1324 try {
1325 thr.wait();
1326 } catch (InterruptedException e) {
1327 }
1328 }
1329 }
1330
1331 ActivityManagerService m = thr.mService;
1332 mSelf = m;
1333 ActivityThread at = ActivityThread.systemMain();
1334 mSystemThread = at;
1335 Context context = at.getSystemContext();
Dianne Hackborn247fe742011-01-08 17:25:57 -08001336 context.setTheme(android.R.style.Theme_Holo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001337 m.mContext = context;
1338 m.mFactoryTest = factoryTest;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001339 m.mMainStack = new ActivityStack(m, context, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001340
1341 m.mBatteryStatsService.publish(context);
1342 m.mUsageStatsService.publish(context);
1343
1344 synchronized (thr) {
1345 thr.mReady = true;
1346 thr.notifyAll();
1347 }
1348
1349 m.startRunning(null, null, null, null);
1350
1351 return context;
1352 }
1353
1354 public static ActivityManagerService self() {
1355 return mSelf;
1356 }
1357
1358 static class AThread extends Thread {
1359 ActivityManagerService mService;
1360 boolean mReady = false;
1361
1362 public AThread() {
1363 super("ActivityManager");
1364 }
1365
1366 public void run() {
1367 Looper.prepare();
1368
1369 android.os.Process.setThreadPriority(
1370 android.os.Process.THREAD_PRIORITY_FOREGROUND);
Christopher Tate160edb32010-06-30 17:46:30 -07001371 android.os.Process.setCanSelfBackground(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001372
1373 ActivityManagerService m = new ActivityManagerService();
1374
1375 synchronized (this) {
1376 mService = m;
1377 notifyAll();
1378 }
1379
1380 synchronized (this) {
1381 while (!mReady) {
1382 try {
1383 wait();
1384 } catch (InterruptedException e) {
1385 }
1386 }
1387 }
1388
Brad Fitzpatrickec062f62010-11-03 09:56:54 -07001389 // For debug builds, log event loop stalls to dropbox for analysis.
1390 if (StrictMode.conditionallyEnableDebugLogging()) {
1391 Slog.i(TAG, "Enabled StrictMode logging for AThread's Looper");
1392 }
1393
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001394 Looper.loop();
1395 }
1396 }
1397
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001398 static class MemBinder extends Binder {
1399 ActivityManagerService mActivityManagerService;
1400 MemBinder(ActivityManagerService activityManagerService) {
1401 mActivityManagerService = activityManagerService;
1402 }
1403
1404 @Override
1405 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001406 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1407 != PackageManager.PERMISSION_GRANTED) {
1408 pw.println("Permission Denial: can't dump meminfo from from pid="
1409 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1410 + " without permission " + android.Manifest.permission.DUMP);
1411 return;
1412 }
1413
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001414 mActivityManagerService.dumpApplicationMemoryUsage(fd, pw, " ", args,
Dianne Hackborn672342c2011-11-29 11:29:02 -08001415 false, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001416 }
1417 }
1418
Chet Haase9c1e23b2011-03-24 10:51:31 -07001419 static class GraphicsBinder extends Binder {
1420 ActivityManagerService mActivityManagerService;
1421 GraphicsBinder(ActivityManagerService activityManagerService) {
1422 mActivityManagerService = activityManagerService;
1423 }
1424
1425 @Override
1426 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001427 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1428 != PackageManager.PERMISSION_GRANTED) {
1429 pw.println("Permission Denial: can't dump gfxinfo from from pid="
1430 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1431 + " without permission " + android.Manifest.permission.DUMP);
1432 return;
1433 }
1434
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001435 mActivityManagerService.dumpGraphicsHardwareUsage(fd, pw, args);
Chet Haase9c1e23b2011-03-24 10:51:31 -07001436 }
1437 }
1438
Jeff Brown6754ba22011-12-14 20:20:01 -08001439 static class DbBinder extends Binder {
1440 ActivityManagerService mActivityManagerService;
1441 DbBinder(ActivityManagerService activityManagerService) {
1442 mActivityManagerService = activityManagerService;
1443 }
1444
1445 @Override
1446 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1447 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1448 != PackageManager.PERMISSION_GRANTED) {
1449 pw.println("Permission Denial: can't dump dbinfo from from pid="
1450 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1451 + " without permission " + android.Manifest.permission.DUMP);
1452 return;
1453 }
1454
1455 mActivityManagerService.dumpDbInfo(fd, pw, args);
1456 }
1457 }
1458
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001459 static class CpuBinder extends Binder {
1460 ActivityManagerService mActivityManagerService;
1461 CpuBinder(ActivityManagerService activityManagerService) {
1462 mActivityManagerService = activityManagerService;
1463 }
1464
1465 @Override
1466 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001467 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1468 != PackageManager.PERMISSION_GRANTED) {
1469 pw.println("Permission Denial: can't dump cpuinfo from from pid="
1470 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1471 + " without permission " + android.Manifest.permission.DUMP);
1472 return;
1473 }
1474
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001475 synchronized (mActivityManagerService.mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07001476 pw.print(mActivityManagerService.mProcessStats.printCurrentLoad());
1477 pw.print(mActivityManagerService.mProcessStats.printCurrentState(
1478 SystemClock.uptimeMillis()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001479 }
1480 }
1481 }
1482
1483 private ActivityManagerService() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001484 Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
Dianne Hackborn2c6c5e62009-10-08 17:55:49 -07001485
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001486 mFgBroadcastQueue = new BroadcastQueue(this, "foreground", BROADCAST_FG_TIMEOUT);
1487 mBgBroadcastQueue = new BroadcastQueue(this, "background", BROADCAST_BG_TIMEOUT);
1488 mBroadcastQueues[0] = mFgBroadcastQueue;
1489 mBroadcastQueues[1] = mBgBroadcastQueue;
1490
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001491 File dataDir = Environment.getDataDirectory();
1492 File systemDir = new File(dataDir, "system");
1493 systemDir.mkdirs();
1494 mBatteryStatsService = new BatteryStatsService(new File(
1495 systemDir, "batterystats.bin").toString());
1496 mBatteryStatsService.getActiveStatistics().readLocked();
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001497 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
Dianne Hackborn287952c2010-09-22 22:34:31 -07001498 mOnBattery = DEBUG_POWER ? true
1499 : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001500 mBatteryStatsService.getActiveStatistics().setCallback(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001501
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001502 mUsageStatsService = new UsageStatsService(new File(
Dianne Hackborn6447ca32009-04-07 19:50:08 -07001503 systemDir, "usagestats").toString());
Mike Lockwood3a74bd32011-08-12 13:55:22 -07001504 mHeadless = "1".equals(SystemProperties.get("ro.config.headless", "0"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001505
Jack Palevichb90d28c2009-07-22 15:35:24 -07001506 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",
1507 ConfigurationInfo.GL_ES_VERSION_UNDEFINED);
1508
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001509 mConfiguration.setToDefaults();
1510 mConfiguration.locale = Locale.getDefault();
Dianne Hackborn813075a62011-11-14 17:45:19 -08001511 mConfigurationSeq = mConfiguration.seq = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001512 mProcessStats.init();
1513
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07001514 mCompatModePackages = new CompatModePackages(this, systemDir);
1515
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001516 // Add ourself to the Watchdog monitors.
1517 Watchdog.getInstance().addMonitor(this);
1518
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001519 mProcessStatsThread = new Thread("ProcessStats") {
1520 public void run() {
1521 while (true) {
1522 try {
1523 try {
1524 synchronized(this) {
1525 final long now = SystemClock.uptimeMillis();
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001526 long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001527 long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001528 //Slog.i(TAG, "Cpu delay=" + nextCpuDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001529 // + ", write delay=" + nextWriteDelay);
1530 if (nextWriteDelay < nextCpuDelay) {
1531 nextCpuDelay = nextWriteDelay;
1532 }
1533 if (nextCpuDelay > 0) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001534 mProcessStatsMutexFree.set(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001535 this.wait(nextCpuDelay);
1536 }
1537 }
1538 } catch (InterruptedException e) {
1539 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001540 updateCpuStatsNow();
1541 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001542 Slog.e(TAG, "Unexpected exception collecting process stats", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001543 }
1544 }
1545 }
1546 };
1547 mProcessStatsThread.start();
1548 }
1549
1550 @Override
1551 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1552 throws RemoteException {
1553 try {
1554 return super.onTransact(code, data, reply, flags);
1555 } catch (RuntimeException e) {
1556 // The activity manager only throws security exceptions, so let's
1557 // log all others.
1558 if (!(e instanceof SecurityException)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001559 Slog.e(TAG, "Activity Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001560 }
1561 throw e;
1562 }
1563 }
1564
1565 void updateCpuStats() {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001566 final long now = SystemClock.uptimeMillis();
1567 if (mLastCpuTime.get() >= now - MONITOR_CPU_MIN_TIME) {
1568 return;
1569 }
1570 if (mProcessStatsMutexFree.compareAndSet(true, false)) {
1571 synchronized (mProcessStatsThread) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001572 mProcessStatsThread.notify();
1573 }
1574 }
1575 }
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001576
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001577 void updateCpuStatsNow() {
1578 synchronized (mProcessStatsThread) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001579 mProcessStatsMutexFree.set(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001580 final long now = SystemClock.uptimeMillis();
1581 boolean haveNewCpuStats = false;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07001582
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001583 if (MONITOR_CPU_USAGE &&
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001584 mLastCpuTime.get() < (now-MONITOR_CPU_MIN_TIME)) {
1585 mLastCpuTime.set(now);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001586 haveNewCpuStats = true;
1587 mProcessStats.update();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001588 //Slog.i(TAG, mProcessStats.printCurrentState());
1589 //Slog.i(TAG, "Total CPU usage: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001590 // + mProcessStats.getTotalCpuPercent() + "%");
1591
Joe Onorato8a9b2202010-02-26 18:56:32 -08001592 // Slog the cpu usage if the property is set.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001593 if ("true".equals(SystemProperties.get("events.cpu"))) {
1594 int user = mProcessStats.getLastUserTime();
1595 int system = mProcessStats.getLastSystemTime();
1596 int iowait = mProcessStats.getLastIoWaitTime();
1597 int irq = mProcessStats.getLastIrqTime();
1598 int softIrq = mProcessStats.getLastSoftIrqTime();
1599 int idle = mProcessStats.getLastIdleTime();
1600
1601 int total = user + system + iowait + irq + softIrq + idle;
1602 if (total == 0) total = 1;
1603
Doug Zongker2bec3d42009-12-04 12:52:44 -08001604 EventLog.writeEvent(EventLogTags.CPU,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001605 ((user+system+iowait+irq+softIrq) * 100) / total,
1606 (user * 100) / total,
1607 (system * 100) / total,
1608 (iowait * 100) / total,
1609 (irq * 100) / total,
1610 (softIrq * 100) / total);
1611 }
1612 }
1613
Amith Yamasanie43530a2009-08-21 13:11:37 -07001614 long[] cpuSpeedTimes = mProcessStats.getLastCpuSpeedTimes();
Amith Yamasani819f9282009-06-24 23:18:15 -07001615 final BatteryStatsImpl bstats = mBatteryStatsService.getActiveStatistics();
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001616 synchronized(bstats) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001617 synchronized(mPidsSelfLocked) {
1618 if (haveNewCpuStats) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001619 if (mOnBattery) {
1620 int perc = bstats.startAddingCpuLocked();
1621 int totalUTime = 0;
1622 int totalSTime = 0;
Dianne Hackborn287952c2010-09-22 22:34:31 -07001623 final int N = mProcessStats.countStats();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001624 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001625 ProcessStats.Stats st = mProcessStats.getStats(i);
1626 if (!st.working) {
1627 continue;
1628 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001629 ProcessRecord pr = mPidsSelfLocked.get(st.pid);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001630 int otherUTime = (st.rel_utime*perc)/100;
1631 int otherSTime = (st.rel_stime*perc)/100;
1632 totalUTime += otherUTime;
1633 totalSTime += otherSTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001634 if (pr != null) {
1635 BatteryStatsImpl.Uid.Proc ps = pr.batteryStats;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001636 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1637 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001638 ps.addSpeedStepTimes(cpuSpeedTimes);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001639 pr.curCpuTime += (st.rel_utime+st.rel_stime) * 10;
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001640 } else {
1641 BatteryStatsImpl.Uid.Proc ps =
Amith Yamasani819f9282009-06-24 23:18:15 -07001642 bstats.getProcessStatsLocked(st.name, st.pid);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001643 if (ps != null) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001644 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1645 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001646 ps.addSpeedStepTimes(cpuSpeedTimes);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001647 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001648 }
1649 }
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001650 bstats.finishAddingCpuLocked(perc, totalUTime,
1651 totalSTime, cpuSpeedTimes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001652 }
1653 }
1654 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001655
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001656 if (mLastWriteTime < (now-BATTERY_STATS_TIME)) {
1657 mLastWriteTime = now;
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001658 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001659 }
1660 }
1661 }
1662 }
1663
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001664 @Override
1665 public void batteryNeedsCpuUpdate() {
1666 updateCpuStatsNow();
1667 }
1668
1669 @Override
1670 public void batteryPowerChanged(boolean onBattery) {
1671 // When plugging in, update the CPU stats first before changing
1672 // the plug state.
1673 updateCpuStatsNow();
1674 synchronized (this) {
1675 synchronized(mPidsSelfLocked) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001676 mOnBattery = DEBUG_POWER ? true : onBattery;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001677 }
1678 }
1679 }
1680
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001681 /**
1682 * Initialize the application bind args. These are passed to each
1683 * process when the bindApplication() IPC is sent to the process. They're
1684 * lazily setup to make sure the services are running when they're asked for.
1685 */
1686 private HashMap<String, IBinder> getCommonServicesLocked() {
1687 if (mAppBindArgs == null) {
1688 mAppBindArgs = new HashMap<String, IBinder>();
1689
1690 // Setup the application init args
1691 mAppBindArgs.put("package", ServiceManager.getService("package"));
1692 mAppBindArgs.put("window", ServiceManager.getService("window"));
1693 mAppBindArgs.put(Context.ALARM_SERVICE,
1694 ServiceManager.getService(Context.ALARM_SERVICE));
1695 }
1696 return mAppBindArgs;
1697 }
1698
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001699 final void setFocusedActivityLocked(ActivityRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001700 if (mFocusedActivity != r) {
1701 mFocusedActivity = r;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001702 if (r != null) {
1703 mWindowManager.setFocusedApp(r.appToken, true);
1704 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001705 }
1706 }
1707
Dianne Hackborn906497c2010-05-10 15:57:38 -07001708 private final void updateLruProcessInternalLocked(ProcessRecord app,
1709 boolean oomAdj, boolean updateActivityTime, int bestPos) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001710 // put it on the LRU to keep track of when it should be exited.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001711 int lrui = mLruProcesses.indexOf(app);
1712 if (lrui >= 0) mLruProcesses.remove(lrui);
1713
1714 int i = mLruProcesses.size()-1;
1715 int skipTop = 0;
1716
Dianne Hackborn906497c2010-05-10 15:57:38 -07001717 app.lruSeq = mLruSeq;
1718
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001719 // compute the new weight for this process.
1720 if (updateActivityTime) {
1721 app.lastActivityTime = SystemClock.uptimeMillis();
1722 }
1723 if (app.activities.size() > 0) {
1724 // If this process has activities, we more strongly want to keep
1725 // it around.
1726 app.lruWeight = app.lastActivityTime;
1727 } else if (app.pubProviders.size() > 0) {
1728 // If this process contains content providers, we want to keep
1729 // it a little more strongly.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001730 app.lruWeight = app.lastActivityTime - ProcessList.CONTENT_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001731 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001732 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001733 } else {
1734 // If this process doesn't have activities, we less strongly
1735 // want to keep it around, and generally want to avoid getting
1736 // in front of any very recently used activities.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001737 app.lruWeight = app.lastActivityTime - ProcessList.EMPTY_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001738 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001739 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001740 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001741
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001742 while (i >= 0) {
1743 ProcessRecord p = mLruProcesses.get(i);
1744 // If this app shouldn't be in front of the first N background
1745 // apps, then skip over that many that are currently hidden.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001746 if (skipTop > 0 && p.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001747 skipTop--;
1748 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001749 if (p.lruWeight <= app.lruWeight || i < bestPos) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001750 mLruProcesses.add(i+1, app);
1751 break;
1752 }
1753 i--;
1754 }
1755 if (i < 0) {
1756 mLruProcesses.add(0, app);
1757 }
1758
Dianne Hackborn906497c2010-05-10 15:57:38 -07001759 // If the app is currently using a content provider or service,
1760 // bump those processes as well.
1761 if (app.connections.size() > 0) {
1762 for (ConnectionRecord cr : app.connections) {
1763 if (cr.binding != null && cr.binding.service != null
1764 && cr.binding.service.app != null
1765 && cr.binding.service.app.lruSeq != mLruSeq) {
1766 updateLruProcessInternalLocked(cr.binding.service.app, oomAdj,
1767 updateActivityTime, i+1);
1768 }
1769 }
1770 }
1771 if (app.conProviders.size() > 0) {
1772 for (ContentProviderRecord cpr : app.conProviders.keySet()) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07001773 if (cpr.proc != null && cpr.proc.lruSeq != mLruSeq) {
1774 updateLruProcessInternalLocked(cpr.proc, oomAdj,
Dianne Hackborn906497c2010-05-10 15:57:38 -07001775 updateActivityTime, i+1);
1776 }
1777 }
1778 }
1779
Joe Onorato8a9b2202010-02-26 18:56:32 -08001780 //Slog.i(TAG, "Putting proc to front: " + app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001781 if (oomAdj) {
1782 updateOomAdjLocked();
1783 }
1784 }
1785
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001786 final void updateLruProcessLocked(ProcessRecord app,
Dianne Hackborn906497c2010-05-10 15:57:38 -07001787 boolean oomAdj, boolean updateActivityTime) {
1788 mLruSeq++;
1789 updateLruProcessInternalLocked(app, oomAdj, updateActivityTime, 0);
1790 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001791
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001792 final ProcessRecord getProcessRecordLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001793 String processName, int uid) {
1794 if (uid == Process.SYSTEM_UID) {
1795 // The system gets to run in any process. If there are multiple
1796 // processes with the same uid, just pick the first (this
1797 // should never happen).
1798 SparseArray<ProcessRecord> procs = mProcessNames.getMap().get(
1799 processName);
1800 return procs != null ? procs.valueAt(0) : null;
1801 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001802 // uid = applyUserId(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001803 ProcessRecord proc = mProcessNames.get(processName, uid);
1804 return proc;
1805 }
1806
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001807 void ensurePackageDexOpt(String packageName) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001808 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001809 try {
1810 if (pm.performDexOpt(packageName)) {
1811 mDidDexOpt = true;
1812 }
1813 } catch (RemoteException e) {
1814 }
1815 }
1816
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001817 boolean isNextTransitionForward() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001818 int transit = mWindowManager.getPendingAppTransition();
1819 return transit == WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
1820 || transit == WindowManagerPolicy.TRANSIT_TASK_OPEN
1821 || transit == WindowManagerPolicy.TRANSIT_TASK_TO_FRONT;
1822 }
1823
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001824 final ProcessRecord startProcessLocked(String processName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001825 ApplicationInfo info, boolean knownToBeDead, int intentFlags,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001826 String hostingType, ComponentName hostingName, boolean allowWhileBooting,
1827 boolean isolated) {
1828 ProcessRecord app;
1829 if (!isolated) {
1830 app = getProcessRecordLocked(processName, info.uid);
1831 } else {
1832 // If this is an isolated process, it can't re-use an existing process.
1833 app = null;
1834 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001835 // We don't have to do anything more if:
1836 // (1) There is an existing application record; and
1837 // (2) The caller doesn't think it is dead, OR there is no thread
1838 // object attached to it so we know it couldn't have crashed; and
1839 // (3) There is a pid assigned to it, so it is either starting or
1840 // already running.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001841 if (DEBUG_PROCESSES) Slog.v(TAG, "startProcess: name=" + processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001842 + " app=" + app + " knownToBeDead=" + knownToBeDead
1843 + " thread=" + (app != null ? app.thread : null)
1844 + " pid=" + (app != null ? app.pid : -1));
Magnus Edlund7bb25812010-02-24 15:45:06 +01001845 if (app != null && app.pid > 0) {
1846 if (!knownToBeDead || app.thread == null) {
Dianne Hackborn20cb56e2010-03-04 00:58:29 -08001847 // We already have the app running, or are waiting for it to
1848 // come up (we have a pid but not yet its thread), so keep it.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001849 if (DEBUG_PROCESSES) Slog.v(TAG, "App already running: " + app);
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001850 // If this is a new package in the process, add the package to the list
1851 app.addPackage(info.packageName);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001852 return app;
1853 } else {
1854 // An application record is attached to a previous process,
1855 // clean it up now.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001856 if (DEBUG_PROCESSES) Slog.v(TAG, "App died: " + app);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07001857 handleAppDiedLocked(app, true, true);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001858 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001859 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01001860
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001861 String hostingNameStr = hostingName != null
1862 ? hostingName.flattenToShortString() : null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001863
1864 if (!isolated) {
1865 if ((intentFlags&Intent.FLAG_FROM_BACKGROUND) != 0) {
1866 // If we are in the background, then check to see if this process
1867 // is bad. If so, we will just silently fail.
1868 if (mBadProcesses.get(info.processName, info.uid) != null) {
1869 if (DEBUG_PROCESSES) Slog.v(TAG, "Bad process: " + info.uid
1870 + "/" + info.processName);
1871 return null;
1872 }
1873 } else {
1874 // When the user is explicitly starting a process, then clear its
1875 // crash count so that we won't make it bad until they see at
1876 // least one crash dialog again, and make the process good again
1877 // if it had been bad.
1878 if (DEBUG_PROCESSES) Slog.v(TAG, "Clearing bad process: " + info.uid
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001879 + "/" + info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001880 mProcessCrashTimes.remove(info.processName, info.uid);
1881 if (mBadProcesses.get(info.processName, info.uid) != null) {
1882 EventLog.writeEvent(EventLogTags.AM_PROC_GOOD, info.uid,
1883 info.processName);
1884 mBadProcesses.remove(info.processName, info.uid);
1885 if (app != null) {
1886 app.bad = false;
1887 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001888 }
1889 }
1890 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001891
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001892 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001893 app = newProcessRecordLocked(null, info, processName, isolated);
1894 if (app == null) {
1895 Slog.w(TAG, "Failed making new process record for "
1896 + processName + "/" + info.uid + " isolated=" + isolated);
1897 return null;
1898 }
1899 mProcessNames.put(processName, app.uid, app);
1900 if (isolated) {
1901 mIsolatedProcesses.put(app.uid, app);
1902 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001903 } else {
1904 // If this is a new package in the process, add the package to the list
1905 app.addPackage(info.packageName);
1906 }
1907
1908 // If the system is not ready yet, then hold off on starting this
1909 // process until it is.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001910 if (!mProcessesReady
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001911 && !isAllowedWhileBooting(info)
1912 && !allowWhileBooting) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001913 if (!mProcessesOnHold.contains(app)) {
1914 mProcessesOnHold.add(app);
1915 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001916 if (DEBUG_PROCESSES) Slog.v(TAG, "System not ready, putting on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001917 return app;
1918 }
1919
1920 startProcessLocked(app, hostingType, hostingNameStr);
1921 return (app.pid != 0) ? app : null;
1922 }
1923
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001924 boolean isAllowedWhileBooting(ApplicationInfo ai) {
1925 return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0;
1926 }
1927
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001928 private final void startProcessLocked(ProcessRecord app,
1929 String hostingType, String hostingNameStr) {
1930 if (app.pid > 0 && app.pid != MY_PID) {
1931 synchronized (mPidsSelfLocked) {
1932 mPidsSelfLocked.remove(app.pid);
1933 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
1934 }
1935 app.pid = 0;
1936 }
1937
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001938 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
1939 "startProcessLocked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001940 mProcessesOnHold.remove(app);
1941
1942 updateCpuStats();
1943
1944 System.arraycopy(mProcDeaths, 0, mProcDeaths, 1, mProcDeaths.length-1);
1945 mProcDeaths[0] = 0;
1946
1947 try {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001948 int uid = app.uid;
Amith Yamasani742a6712011-05-04 14:49:28 -07001949
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001950 int[] gids = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001951 if (!app.isolated) {
1952 try {
1953 gids = mContext.getPackageManager().getPackageGids(
1954 app.info.packageName);
1955 } catch (PackageManager.NameNotFoundException e) {
1956 Slog.w(TAG, "Unable to retrieve gids", e);
1957 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001958 }
1959 if (mFactoryTest != SystemServer.FACTORY_TEST_OFF) {
1960 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
1961 && mTopComponent != null
1962 && app.processName.equals(mTopComponent.getPackageName())) {
1963 uid = 0;
1964 }
1965 if (mFactoryTest == SystemServer.FACTORY_TEST_HIGH_LEVEL
1966 && (app.info.flags&ApplicationInfo.FLAG_FACTORY_TEST) != 0) {
1967 uid = 0;
1968 }
1969 }
1970 int debugFlags = 0;
1971 if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
1972 debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;
Elliott Hughesfa36aee2011-06-17 14:39:41 -07001973 // Also turn on CheckJNI for debuggable apps. It's quite
1974 // awkward to turn on otherwise.
1975 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001976 }
Ben Cheng6c0afff2010-02-14 16:18:56 -08001977 // Run the app in safe mode if its manifest requests so or the
1978 // system is booted in safe mode.
1979 if ((app.info.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0 ||
1980 Zygote.systemInSafeMode == true) {
Ben Cheng23085b72010-02-08 16:06:32 -08001981 debugFlags |= Zygote.DEBUG_ENABLE_SAFEMODE;
1982 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001983 if ("1".equals(SystemProperties.get("debug.checkjni"))) {
1984 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
1985 }
Elliott Hughesae07ecf2011-07-06 17:33:27 -07001986 if ("1".equals(SystemProperties.get("debug.jni.logging"))) {
1987 debugFlags |= Zygote.DEBUG_ENABLE_JNI_LOGGING;
1988 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001989 if ("1".equals(SystemProperties.get("debug.assert"))) {
1990 debugFlags |= Zygote.DEBUG_ENABLE_ASSERT;
1991 }
Jeff Brown3f9dd282011-07-08 20:02:19 -07001992
1993 // Start the process. It will either succeed and return a result containing
1994 // the PID of the new process, or else throw a RuntimeException.
1995 Process.ProcessStartResult startResult = Process.start("android.app.ActivityThread",
Elliott Hughese1dfcb72011-07-08 11:08:07 -07001996 app.processName, uid, uid, gids, debugFlags,
1997 app.info.targetSdkVersion, null);
Jeff Brown3f9dd282011-07-08 20:02:19 -07001998
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001999 BatteryStatsImpl bs = app.batteryStats.getBatteryStats();
2000 synchronized (bs) {
2001 if (bs.isOnBattery()) {
2002 app.batteryStats.incStartsLocked();
2003 }
2004 }
2005
Jeff Brown3f9dd282011-07-08 20:02:19 -07002006 EventLog.writeEvent(EventLogTags.AM_PROC_START, startResult.pid, uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002007 app.processName, hostingType,
2008 hostingNameStr != null ? hostingNameStr : "");
2009
2010 if (app.persistent) {
Jeff Brown3f9dd282011-07-08 20:02:19 -07002011 Watchdog.getInstance().processStarted(app.processName, startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002012 }
2013
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07002014 StringBuilder buf = mStringBuilder;
2015 buf.setLength(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002016 buf.append("Start proc ");
2017 buf.append(app.processName);
2018 buf.append(" for ");
2019 buf.append(hostingType);
2020 if (hostingNameStr != null) {
2021 buf.append(" ");
2022 buf.append(hostingNameStr);
2023 }
2024 buf.append(": pid=");
Jeff Brown3f9dd282011-07-08 20:02:19 -07002025 buf.append(startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002026 buf.append(" uid=");
2027 buf.append(uid);
2028 buf.append(" gids={");
2029 if (gids != null) {
2030 for (int gi=0; gi<gids.length; gi++) {
2031 if (gi != 0) buf.append(", ");
2032 buf.append(gids[gi]);
2033
2034 }
2035 }
2036 buf.append("}");
Joe Onorato8a9b2202010-02-26 18:56:32 -08002037 Slog.i(TAG, buf.toString());
Jeff Brown3f9dd282011-07-08 20:02:19 -07002038 app.pid = startResult.pid;
2039 app.usingWrapper = startResult.usingWrapper;
2040 app.removed = false;
2041 synchronized (mPidsSelfLocked) {
2042 this.mPidsSelfLocked.put(startResult.pid, app);
2043 Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
2044 msg.obj = app;
2045 mHandler.sendMessageDelayed(msg, startResult.usingWrapper
2046 ? PROC_START_TIMEOUT_WITH_WRAPPER : PROC_START_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002047 }
2048 } catch (RuntimeException e) {
2049 // XXX do better error recovery.
2050 app.pid = 0;
Joe Onorato8a9b2202010-02-26 18:56:32 -08002051 Slog.e(TAG, "Failure starting process " + app.processName, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002052 }
2053 }
2054
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002055 void updateUsageStats(ActivityRecord resumedComponent, boolean resumed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002056 if (resumed) {
2057 mUsageStatsService.noteResumeComponent(resumedComponent.realActivity);
2058 } else {
2059 mUsageStatsService.notePauseComponent(resumedComponent.realActivity);
2060 }
2061 }
2062
Amith Yamasani742a6712011-05-04 14:49:28 -07002063 boolean startHomeActivityLocked(int userId) {
Mike Lockwooda8f767a2011-08-31 14:32:37 -04002064 if (mHeadless) {
2065 // Added because none of the other calls to ensureBootCompleted seem to fire
2066 // when running headless.
2067 ensureBootCompleted();
2068 return false;
2069 }
2070
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002071 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2072 && mTopAction == null) {
2073 // We are running in factory test mode, but unable to find
2074 // the factory test app, so just sit around displaying the
2075 // error message and don't try to start anything.
2076 return false;
2077 }
2078 Intent intent = new Intent(
2079 mTopAction,
2080 mTopData != null ? Uri.parse(mTopData) : null);
2081 intent.setComponent(mTopComponent);
2082 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
2083 intent.addCategory(Intent.CATEGORY_HOME);
2084 }
2085 ActivityInfo aInfo =
2086 intent.resolveActivityInfo(mContext.getPackageManager(),
2087 STOCK_PM_FLAGS);
2088 if (aInfo != null) {
2089 intent.setComponent(new ComponentName(
2090 aInfo.applicationInfo.packageName, aInfo.name));
2091 // Don't do this if the home app is currently being
2092 // instrumented.
Amith Yamasani742a6712011-05-04 14:49:28 -07002093 aInfo = new ActivityInfo(aInfo);
2094 aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002095 ProcessRecord app = getProcessRecordLocked(aInfo.processName,
2096 aInfo.applicationInfo.uid);
2097 if (app == null || app.instrumentationClass == null) {
2098 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002099 mMainStack.startActivityLocked(null, intent, null, aInfo,
2100 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002101 }
2102 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002103
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002104 return true;
2105 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002106
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002107 /**
2108 * Starts the "new version setup screen" if appropriate.
2109 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002110 void startSetupActivityLocked() {
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002111 // Only do this once per boot.
2112 if (mCheckedForSetup) {
2113 return;
2114 }
2115
2116 // We will show this screen if the current one is a different
2117 // version than the last one shown, and we are not running in
2118 // low-level factory test mode.
2119 final ContentResolver resolver = mContext.getContentResolver();
2120 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL &&
2121 Settings.Secure.getInt(resolver,
2122 Settings.Secure.DEVICE_PROVISIONED, 0) != 0) {
2123 mCheckedForSetup = true;
2124
2125 // See if we should be showing the platform update setup UI.
2126 Intent intent = new Intent(Intent.ACTION_UPGRADE_SETUP);
2127 List<ResolveInfo> ris = mSelf.mContext.getPackageManager()
2128 .queryIntentActivities(intent, PackageManager.GET_META_DATA);
2129
2130 // We don't allow third party apps to replace this.
2131 ResolveInfo ri = null;
2132 for (int i=0; ris != null && i<ris.size(); i++) {
2133 if ((ris.get(i).activityInfo.applicationInfo.flags
2134 & ApplicationInfo.FLAG_SYSTEM) != 0) {
2135 ri = ris.get(i);
2136 break;
2137 }
2138 }
2139
2140 if (ri != null) {
2141 String vers = ri.activityInfo.metaData != null
2142 ? ri.activityInfo.metaData.getString(Intent.METADATA_SETUP_VERSION)
2143 : null;
2144 if (vers == null && ri.activityInfo.applicationInfo.metaData != null) {
2145 vers = ri.activityInfo.applicationInfo.metaData.getString(
2146 Intent.METADATA_SETUP_VERSION);
2147 }
2148 String lastVers = Settings.Secure.getString(
2149 resolver, Settings.Secure.LAST_SETUP_SHOWN);
2150 if (vers != null && !vers.equals(lastVers)) {
2151 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2152 intent.setComponent(new ComponentName(
2153 ri.activityInfo.packageName, ri.activityInfo.name));
Dianne Hackborna4972e92012-03-14 10:38:05 -07002154 mMainStack.startActivityLocked(null, intent, null, ri.activityInfo,
2155 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002156 }
2157 }
2158 }
2159 }
2160
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002161 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002162 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002163 }
2164
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002165 void enforceNotIsolatedCaller(String caller) {
2166 if (UserId.isIsolated(Binder.getCallingUid())) {
2167 throw new SecurityException("Isolated process not allowed to call " + caller);
2168 }
2169 }
2170
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002171 public int getFrontActivityScreenCompatMode() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002172 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002173 synchronized (this) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002174 return mCompatModePackages.getFrontActivityScreenCompatModeLocked();
2175 }
2176 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002177
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002178 public void setFrontActivityScreenCompatMode(int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002179 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2180 "setFrontActivityScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002181 synchronized (this) {
2182 mCompatModePackages.setFrontActivityScreenCompatModeLocked(mode);
2183 }
2184 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002185
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002186 public int getPackageScreenCompatMode(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002187 enforceNotIsolatedCaller("getPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002188 synchronized (this) {
2189 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
2190 }
2191 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002192
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002193 public void setPackageScreenCompatMode(String packageName, int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002194 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2195 "setPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002196 synchronized (this) {
2197 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002198 }
2199 }
2200
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002201 public boolean getPackageAskScreenCompat(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002202 enforceNotIsolatedCaller("getPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002203 synchronized (this) {
2204 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
2205 }
2206 }
2207
2208 public void setPackageAskScreenCompat(String packageName, boolean ask) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002209 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2210 "setPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002211 synchronized (this) {
2212 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
2213 }
2214 }
2215
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002216 void reportResumedActivityLocked(ActivityRecord r) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002217 //Slog.i(TAG, "**** REPORT RESUME: " + r);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002218
2219 final int identHash = System.identityHashCode(r);
2220 updateUsageStats(r, true);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002221 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002222
Jeff Sharkeya4620792011-05-20 15:29:23 -07002223 private void dispatchForegroundActivitiesChanged(int pid, int uid, boolean foregroundActivities) {
2224 int i = mProcessObservers.beginBroadcast();
2225 while (i > 0) {
2226 i--;
2227 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2228 if (observer != null) {
2229 try {
2230 observer.onForegroundActivitiesChanged(pid, uid, foregroundActivities);
2231 } catch (RemoteException e) {
2232 }
2233 }
2234 }
2235 mProcessObservers.finishBroadcast();
2236 }
2237
2238 private void dispatchProcessDied(int pid, int uid) {
2239 int i = mProcessObservers.beginBroadcast();
2240 while (i > 0) {
2241 i--;
2242 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2243 if (observer != null) {
2244 try {
2245 observer.onProcessDied(pid, uid);
2246 } catch (RemoteException e) {
2247 }
2248 }
2249 }
2250 mProcessObservers.finishBroadcast();
2251 }
2252
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002253 final void doPendingActivityLaunchesLocked(boolean doResume) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002254 final int N = mPendingActivityLaunches.size();
2255 if (N <= 0) {
2256 return;
2257 }
2258 for (int i=0; i<N; i++) {
2259 PendingActivityLaunch pal = mPendingActivityLaunches.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002260 mMainStack.startActivityUncheckedLocked(pal.r, pal.sourceRecord,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002261 pal.startFlags, doResume && i == (N-1), null);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002262 }
2263 mPendingActivityLaunches.clear();
2264 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002265
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002266 public final int startActivity(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002267 Intent intent, String resolvedType, IBinder resultTo,
2268 String resultWho, int requestCode, int startFlags,
2269 String profileFile, ParcelFileDescriptor profileFd, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002270 enforceNotIsolatedCaller("startActivity");
Amith Yamasani742a6712011-05-04 14:49:28 -07002271 int userId = 0;
2272 if (intent.getCategories() != null && intent.getCategories().contains(Intent.CATEGORY_HOME)) {
2273 // Requesting home, set the identity to the current user
2274 // HACK!
2275 userId = mCurrentUserId;
2276 } else {
2277 // TODO: Fix this in a better way - calls coming from SystemUI should probably carry
2278 // the current user's userId
2279 if (Binder.getCallingUid() < Process.FIRST_APPLICATION_UID) {
2280 userId = 0;
2281 } else {
2282 userId = Binder.getOrigCallingUser();
2283 }
2284 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002285 return mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002286 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
2287 null, null, options, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002288 }
2289
2290 public final WaitResult startActivityAndWait(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002291 Intent intent, String resolvedType, IBinder resultTo,
2292 String resultWho, int requestCode, int startFlags, String profileFile,
2293 ParcelFileDescriptor profileFd, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002294 enforceNotIsolatedCaller("startActivityAndWait");
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002295 WaitResult res = new WaitResult();
Amith Yamasani742a6712011-05-04 14:49:28 -07002296 int userId = Binder.getOrigCallingUser();
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002297 mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002298 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
2299 res, null, options, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002300 return res;
2301 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08002302
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002303 public final int startActivityWithConfig(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002304 Intent intent, String resolvedType, IBinder resultTo,
2305 String resultWho, int requestCode, int startFlags, Configuration config,
2306 Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002307 enforceNotIsolatedCaller("startActivityWithConfig");
Amith Yamasani742a6712011-05-04 14:49:28 -07002308 int ret = mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002309 resultTo, resultWho, requestCode, startFlags,
2310 null, null, null, config, options, Binder.getOrigCallingUser());
Amith Yamasani742a6712011-05-04 14:49:28 -07002311 return ret;
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002312 }
2313
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002314 public int startActivityIntentSender(IApplicationThread caller,
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002315 IntentSender intent, Intent fillInIntent, String resolvedType,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002316 IBinder resultTo, String resultWho, int requestCode,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002317 int flagsMask, int flagsValues, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002318 enforceNotIsolatedCaller("startActivityIntentSender");
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002319 // Refuse possible leaked file descriptors
2320 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
2321 throw new IllegalArgumentException("File descriptors passed in Intent");
2322 }
2323
2324 IIntentSender sender = intent.getTarget();
2325 if (!(sender instanceof PendingIntentRecord)) {
2326 throw new IllegalArgumentException("Bad PendingIntent object");
2327 }
2328
2329 PendingIntentRecord pir = (PendingIntentRecord)sender;
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002330
2331 synchronized (this) {
2332 // If this is coming from the currently resumed activity, it is
2333 // effectively saying that app switches are allowed at this point.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002334 if (mMainStack.mResumedActivity != null
2335 && mMainStack.mResumedActivity.info.applicationInfo.uid ==
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002336 Binder.getCallingUid()) {
2337 mAppSwitchesAllowedTime = 0;
2338 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002339 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002340 int ret = pir.sendInner(0, fillInIntent, resolvedType, null, null,
2341 resultTo, resultWho, requestCode, flagsMask, flagsValues, options);
Amith Yamasani742a6712011-05-04 14:49:28 -07002342 return ret;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002343 }
2344
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002345 public boolean startNextMatchingActivity(IBinder callingActivity,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002346 Intent intent, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002347 // Refuse possible leaked file descriptors
2348 if (intent != null && intent.hasFileDescriptors() == true) {
2349 throw new IllegalArgumentException("File descriptors passed in Intent");
2350 }
2351
2352 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002353 ActivityRecord r = mMainStack.isInStackLocked(callingActivity);
2354 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002355 return false;
2356 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002357 if (r.app == null || r.app.thread == null) {
2358 // The caller is not running... d'oh!
2359 return false;
2360 }
2361 intent = new Intent(intent);
2362 // The caller is not allowed to change the data.
2363 intent.setDataAndType(r.intent.getData(), r.intent.getType());
2364 // And we are resetting to find the next component...
2365 intent.setComponent(null);
2366
2367 ActivityInfo aInfo = null;
2368 try {
2369 List<ResolveInfo> resolves =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002370 AppGlobals.getPackageManager().queryIntentActivities(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002371 intent, r.resolvedType,
Dianne Hackborn1655be42009-05-08 14:29:01 -07002372 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002373
2374 // Look for the original activity in the list...
2375 final int N = resolves != null ? resolves.size() : 0;
2376 for (int i=0; i<N; i++) {
2377 ResolveInfo rInfo = resolves.get(i);
2378 if (rInfo.activityInfo.packageName.equals(r.packageName)
2379 && rInfo.activityInfo.name.equals(r.info.name)) {
2380 // We found the current one... the next matching is
2381 // after it.
2382 i++;
2383 if (i<N) {
2384 aInfo = resolves.get(i).activityInfo;
2385 }
2386 break;
2387 }
2388 }
2389 } catch (RemoteException e) {
2390 }
2391
2392 if (aInfo == null) {
2393 // Nobody who is next!
2394 return false;
2395 }
2396
2397 intent.setComponent(new ComponentName(
2398 aInfo.applicationInfo.packageName, aInfo.name));
2399 intent.setFlags(intent.getFlags()&~(
2400 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
2401 Intent.FLAG_ACTIVITY_CLEAR_TOP|
2402 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
2403 Intent.FLAG_ACTIVITY_NEW_TASK));
2404
2405 // Okay now we need to start the new activity, replacing the
2406 // currently running activity. This is a little tricky because
2407 // we want to start the new one as if the current one is finished,
2408 // but not finish the current one first so that there is no flicker.
2409 // And thus...
2410 final boolean wasFinishing = r.finishing;
2411 r.finishing = true;
2412
2413 // Propagate reply information over to the new activity.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002414 final ActivityRecord resultTo = r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002415 final String resultWho = r.resultWho;
2416 final int requestCode = r.requestCode;
2417 r.resultTo = null;
2418 if (resultTo != null) {
2419 resultTo.removeResultsLocked(r, resultWho, requestCode);
2420 }
2421
2422 final long origId = Binder.clearCallingIdentity();
2423 // XXX we are not dealing with propagating grantedUriPermissions...
2424 // those are not yet exposed to user code, so there is no need.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002425 int res = mMainStack.startActivityLocked(r.app.thread, intent,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002426 r.resolvedType, aInfo, resultTo != null ? resultTo.appToken : null,
2427 resultWho, requestCode, -1, r.launchedFromUid, 0,
2428 options, false, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002429 Binder.restoreCallingIdentity(origId);
2430
2431 r.finishing = wasFinishing;
Dianne Hackborna4972e92012-03-14 10:38:05 -07002432 if (res != ActivityManager.START_SUCCESS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002433 return false;
2434 }
2435 return true;
2436 }
2437 }
2438
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002439 public final int startActivityInPackage(int uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002440 Intent intent, String resolvedType, IBinder resultTo,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002441 String resultWho, int requestCode, int startFlags, Bundle options) {
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002442
2443 // This is so super not safe, that only the system (or okay root)
2444 // can do it.
Amith Yamasani742a6712011-05-04 14:49:28 -07002445 int userId = Binder.getOrigCallingUser();
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002446 final int callingUid = Binder.getCallingUid();
2447 if (callingUid != 0 && callingUid != Process.myUid()) {
2448 throw new SecurityException(
2449 "startActivityInPackage only available to the system");
2450 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002451
Amith Yamasani742a6712011-05-04 14:49:28 -07002452 int ret = mMainStack.startActivityMayWait(null, uid, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002453 resultTo, resultWho, requestCode, startFlags,
2454 null, null, null, null, options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002455 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002456 }
2457
2458 public final int startActivities(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002459 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002460 enforceNotIsolatedCaller("startActivities");
Amith Yamasani742a6712011-05-04 14:49:28 -07002461 int ret = mMainStack.startActivities(caller, -1, intents, resolvedTypes, resultTo,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002462 options, Binder.getOrigCallingUser());
Amith Yamasani742a6712011-05-04 14:49:28 -07002463 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002464 }
2465
2466 public final int startActivitiesInPackage(int uid,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002467 Intent[] intents, String[] resolvedTypes, IBinder resultTo,
2468 Bundle options) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002469
2470 // This is so super not safe, that only the system (or okay root)
2471 // can do it.
2472 final int callingUid = Binder.getCallingUid();
2473 if (callingUid != 0 && callingUid != Process.myUid()) {
2474 throw new SecurityException(
2475 "startActivityInPackage only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002476 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002477 int ret = mMainStack.startActivities(null, uid, intents, resolvedTypes, resultTo,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002478 options, UserId.getUserId(uid));
Amith Yamasani742a6712011-05-04 14:49:28 -07002479 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002480 }
2481
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002482 final void addRecentTaskLocked(TaskRecord task) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002483 int N = mRecentTasks.size();
Dianne Hackborn7c0e75e2010-12-21 19:15:40 -08002484 // Quick case: check if the top-most recent task is the same.
2485 if (N > 0 && mRecentTasks.get(0) == task) {
2486 return;
2487 }
2488 // Remove any existing entries that are the same kind of task.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002489 for (int i=0; i<N; i++) {
2490 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07002491 if (task.userId == tr.userId
2492 && ((task.affinity != null && task.affinity.equals(tr.affinity))
2493 || (task.intent != null && task.intent.filterEquals(tr.intent)))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002494 mRecentTasks.remove(i);
2495 i--;
2496 N--;
2497 if (task.intent == null) {
2498 // If the new recent task we are adding is not fully
2499 // specified, then replace it with the existing recent task.
2500 task = tr;
2501 }
2502 }
2503 }
2504 if (N >= MAX_RECENT_TASKS) {
2505 mRecentTasks.remove(N-1);
2506 }
2507 mRecentTasks.add(0, task);
2508 }
2509
2510 public void setRequestedOrientation(IBinder token,
2511 int requestedOrientation) {
2512 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002513 ActivityRecord r = mMainStack.isInStackLocked(token);
2514 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002515 return;
2516 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002517 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornbe707852011-11-11 14:32:10 -08002518 mWindowManager.setAppOrientation(r.appToken, requestedOrientation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002519 Configuration config = mWindowManager.updateOrientationFromAppTokens(
The Android Open Source Project10592532009-03-18 17:39:46 -07002520 mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -08002521 r.mayFreezeScreenLocked(r.app) ? r.appToken : null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002522 if (config != null) {
2523 r.frozenBeforeDestroy = true;
Dianne Hackborn813075a62011-11-14 17:45:19 -08002524 if (!updateConfigurationLocked(config, r, false, false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002525 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002526 }
2527 }
2528 Binder.restoreCallingIdentity(origId);
2529 }
2530 }
2531
2532 public int getRequestedOrientation(IBinder token) {
2533 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002534 ActivityRecord r = mMainStack.isInStackLocked(token);
2535 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002536 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
2537 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08002538 return mWindowManager.getAppOrientation(r.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002539 }
2540 }
2541
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002542 /**
2543 * This is the internal entry point for handling Activity.finish().
2544 *
2545 * @param token The Binder token referencing the Activity we want to finish.
2546 * @param resultCode Result code, if any, from this Activity.
2547 * @param resultData Result data (Intent), if any, from this Activity.
2548 *
Alexey Tarasov83bad3d2009-08-12 15:05:43 +11002549 * @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 -08002550 */
2551 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData) {
2552 // Refuse possible leaked file descriptors
2553 if (resultData != null && resultData.hasFileDescriptors() == true) {
2554 throw new IllegalArgumentException("File descriptors passed in Intent");
2555 }
2556
2557 synchronized(this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002558 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002559 // Find the first activity that is not finishing.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002560 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002561 if (next != null) {
2562 // ask watcher if this is allowed
2563 boolean resumeOK = true;
2564 try {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002565 resumeOK = mController.activityResuming(next.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002566 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002567 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002568 }
2569
2570 if (!resumeOK) {
2571 return false;
2572 }
2573 }
2574 }
2575 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002576 boolean res = mMainStack.requestFinishActivityLocked(token, resultCode,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002577 resultData, "app-request");
2578 Binder.restoreCallingIdentity(origId);
2579 return res;
2580 }
2581 }
2582
Dianne Hackborn860755f2010-06-03 18:47:52 -07002583 public final void finishHeavyWeightApp() {
2584 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2585 != PackageManager.PERMISSION_GRANTED) {
2586 String msg = "Permission Denial: finishHeavyWeightApp() from pid="
2587 + Binder.getCallingPid()
2588 + ", uid=" + Binder.getCallingUid()
2589 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2590 Slog.w(TAG, msg);
2591 throw new SecurityException(msg);
2592 }
2593
2594 synchronized(this) {
2595 if (mHeavyWeightProcess == null) {
2596 return;
2597 }
2598
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002599 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>(
Dianne Hackborn860755f2010-06-03 18:47:52 -07002600 mHeavyWeightProcess.activities);
2601 for (int i=0; i<activities.size(); i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002602 ActivityRecord r = activities.get(i);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002603 if (!r.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002604 int index = mMainStack.indexOfTokenLocked(r.appToken);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002605 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002606 mMainStack.finishActivityLocked(r, index, Activity.RESULT_CANCELED,
Dianne Hackborn860755f2010-06-03 18:47:52 -07002607 null, "finish-heavy");
2608 }
2609 }
2610 }
2611
2612 mHeavyWeightProcess = null;
2613 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
2614 }
2615 }
2616
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002617 public void crashApplication(int uid, int initialPid, String packageName,
2618 String message) {
2619 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2620 != PackageManager.PERMISSION_GRANTED) {
2621 String msg = "Permission Denial: crashApplication() from pid="
2622 + Binder.getCallingPid()
2623 + ", uid=" + Binder.getCallingUid()
2624 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2625 Slog.w(TAG, msg);
2626 throw new SecurityException(msg);
2627 }
2628
2629 synchronized(this) {
2630 ProcessRecord proc = null;
2631
2632 // Figure out which process to kill. We don't trust that initialPid
2633 // still has any relation to current pids, so must scan through the
2634 // list.
2635 synchronized (mPidsSelfLocked) {
2636 for (int i=0; i<mPidsSelfLocked.size(); i++) {
2637 ProcessRecord p = mPidsSelfLocked.valueAt(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002638 if (p.uid != uid) {
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002639 continue;
2640 }
2641 if (p.pid == initialPid) {
2642 proc = p;
2643 break;
2644 }
2645 for (String str : p.pkgList) {
2646 if (str.equals(packageName)) {
2647 proc = p;
2648 }
2649 }
2650 }
2651 }
2652
2653 if (proc == null) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07002654 Slog.w(TAG, "crashApplication: nothing for uid=" + uid
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002655 + " initialPid=" + initialPid
2656 + " packageName=" + packageName);
2657 return;
2658 }
2659
2660 if (proc.thread != null) {
Dianne Hackborn9f531192010-08-04 17:48:03 -07002661 if (proc.pid == Process.myPid()) {
2662 Log.w(TAG, "crashApplication: trying to crash self!");
2663 return;
2664 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002665 long ident = Binder.clearCallingIdentity();
2666 try {
2667 proc.thread.scheduleCrash(message);
2668 } catch (RemoteException e) {
2669 }
2670 Binder.restoreCallingIdentity(ident);
2671 }
2672 }
2673 }
2674
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002675 public final void finishSubActivity(IBinder token, String resultWho,
2676 int requestCode) {
2677 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002678 ActivityRecord self = mMainStack.isInStackLocked(token);
2679 if (self == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002680 return;
2681 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002682
2683 final long origId = Binder.clearCallingIdentity();
2684
2685 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002686 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2687 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002688 if (r.resultTo == self && r.requestCode == requestCode) {
2689 if ((r.resultWho == null && resultWho == null) ||
2690 (r.resultWho != null && r.resultWho.equals(resultWho))) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002691 mMainStack.finishActivityLocked(r, i,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002692 Activity.RESULT_CANCELED, null, "request-sub");
2693 }
2694 }
2695 }
2696
2697 Binder.restoreCallingIdentity(origId);
2698 }
2699 }
2700
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002701 public boolean willActivityBeVisible(IBinder token) {
2702 synchronized(this) {
2703 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002704 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2705 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08002706 if (r.appToken == token) {
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002707 return true;
2708 }
2709 if (r.fullscreen && !r.finishing) {
2710 return false;
2711 }
2712 }
2713 return true;
2714 }
2715 }
2716
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002717 public void overridePendingTransition(IBinder token, String packageName,
2718 int enterAnim, int exitAnim) {
2719 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002720 ActivityRecord self = mMainStack.isInStackLocked(token);
2721 if (self == null) {
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002722 return;
2723 }
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002724
2725 final long origId = Binder.clearCallingIdentity();
2726
2727 if (self.state == ActivityState.RESUMED
2728 || self.state == ActivityState.PAUSING) {
2729 mWindowManager.overridePendingAppTransition(packageName,
2730 enterAnim, exitAnim);
2731 }
2732
2733 Binder.restoreCallingIdentity(origId);
2734 }
2735 }
2736
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002737 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002738 * Main function for removing an existing process from the activity manager
2739 * as a result of that process going away. Clears out all connections
2740 * to the process.
2741 */
2742 private final void handleAppDiedLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002743 boolean restarting, boolean allowRestart) {
2744 cleanUpApplicationRecordLocked(app, restarting, allowRestart, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002745 if (!restarting) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002746 mLruProcesses.remove(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002747 }
2748
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002749 if (mProfileProc == app) {
2750 clearProfilerLocked();
2751 }
2752
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002753 // Just in case...
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002754 if (mMainStack.mPausingActivity != null && mMainStack.mPausingActivity.app == app) {
2755 if (DEBUG_PAUSE) Slog.v(TAG, "App died while pausing: " +mMainStack.mPausingActivity);
2756 mMainStack.mPausingActivity = null;
2757 }
2758 if (mMainStack.mLastPausedActivity != null && mMainStack.mLastPausedActivity.app == app) {
2759 mMainStack.mLastPausedActivity = null;
2760 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002761
2762 // Remove this application's activities from active lists.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002763 mMainStack.removeHistoryRecordsForAppLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002764
2765 boolean atTop = true;
2766 boolean hasVisibleActivities = false;
2767
2768 // Clean out the history list.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002769 int i = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08002770 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002771 TAG, "Removing app " + app + " from history with " + i + " entries");
2772 while (i > 0) {
2773 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002774 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002775 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002776 TAG, "Record #" + i + " " + r + ": app=" + r.app);
2777 if (r.app == app) {
2778 if ((!r.haveState && !r.stateNotNeeded) || r.finishing) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002779 if (ActivityStack.DEBUG_ADD_REMOVE) {
2780 RuntimeException here = new RuntimeException("here");
2781 here.fillInStackTrace();
2782 Slog.i(TAG, "Removing activity " + r + " from stack at " + i
2783 + ": haveState=" + r.haveState
2784 + " stateNotNeeded=" + r.stateNotNeeded
2785 + " finishing=" + r.finishing
2786 + " state=" + r.state, here);
2787 }
2788 if (!r.finishing) {
2789 Slog.w(TAG, "Force removing " + r + ": app died, no saved state");
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -08002790 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
2791 System.identityHashCode(r),
2792 r.task.taskId, r.shortComponentName,
2793 "proc died without state saved");
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002794 }
Dianne Hackborn5c607432012-02-28 14:44:19 -08002795 mMainStack.removeActivityFromHistoryLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002796
2797 } else {
2798 // We have the current state for this activity, so
2799 // it can be restarted later when needed.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002800 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002801 TAG, "Keeping entry, setting app to null");
2802 if (r.visible) {
2803 hasVisibleActivities = true;
2804 }
2805 r.app = null;
2806 r.nowVisible = false;
2807 if (!r.haveState) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002808 if (ActivityStack.DEBUG_SAVED_STATE) Slog.i(TAG,
2809 "App died, clearing saved state of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002810 r.icicle = null;
2811 }
2812 }
2813
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002814 r.stack.cleanUpActivityLocked(r, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002815 }
2816 atTop = false;
2817 }
2818
2819 app.activities.clear();
2820
2821 if (app.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002822 Slog.w(TAG, "Crash of app " + app.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002823 + " running instrumentation " + app.instrumentationClass);
2824 Bundle info = new Bundle();
2825 info.putString("shortMsg", "Process crashed.");
2826 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
2827 }
2828
2829 if (!restarting) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002830 if (!mMainStack.resumeTopActivityLocked(null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002831 // If there was nothing to resume, and we are not already
2832 // restarting this process, but there is a visible activity that
2833 // is hosted by the process... then make sure all visible
2834 // activities are running, taking care of restarting this
2835 // process.
2836 if (hasVisibleActivities) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002837 mMainStack.ensureActivitiesVisibleLocked(null, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002838 }
2839 }
2840 }
2841 }
2842
2843 private final int getLRURecordIndexForAppLocked(IApplicationThread thread) {
2844 IBinder threadBinder = thread.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002845 // Find the application record.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002846 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2847 ProcessRecord rec = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002848 if (rec.thread != null && rec.thread.asBinder() == threadBinder) {
2849 return i;
2850 }
2851 }
2852 return -1;
2853 }
2854
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002855 final ProcessRecord getRecordForAppLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002856 IApplicationThread thread) {
2857 if (thread == null) {
2858 return null;
2859 }
2860
2861 int appIndex = getLRURecordIndexForAppLocked(thread);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002862 return appIndex >= 0 ? mLruProcesses.get(appIndex) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002863 }
2864
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002865 final void appDiedLocked(ProcessRecord app, int pid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002866 IApplicationThread thread) {
2867
2868 mProcDeaths[0]++;
2869
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002870 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
2871 synchronized (stats) {
2872 stats.noteProcessDiedLocked(app.info.uid, pid);
2873 }
2874
Magnus Edlund7bb25812010-02-24 15:45:06 +01002875 // Clean up already done if the process has been re-started.
2876 if (app.pid == pid && app.thread != null &&
2877 app.thread.asBinder() == thread.asBinder()) {
Dianne Hackborn906497c2010-05-10 15:57:38 -07002878 if (!app.killedBackground) {
2879 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
2880 + ") has died.");
2881 }
Doug Zongker2bec3d42009-12-04 12:52:44 -08002882 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002883 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002884 TAG, "Dying app: " + app + ", pid: " + pid
2885 + ", thread: " + thread.asBinder());
2886 boolean doLowMem = app.instrumentationClass == null;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002887 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002888
2889 if (doLowMem) {
2890 // If there are no longer any background processes running,
2891 // and the app that died was not running instrumentation,
2892 // then tell everyone we are now low on memory.
2893 boolean haveBg = false;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002894 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2895 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -07002896 if (rec.thread != null && rec.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002897 haveBg = true;
2898 break;
2899 }
2900 }
2901
2902 if (!haveBg) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002903 EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mLruProcesses.size());
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002904 long now = SystemClock.uptimeMillis();
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002905 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2906 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn36124872009-10-08 16:22:03 -07002907 if (rec != app && rec.thread != null &&
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002908 (rec.lastLowMemory+GC_MIN_INTERVAL) <= now) {
2909 // The low memory report is overriding any current
2910 // state for a GC request. Make sure to do
Dianne Hackborn32907cf2010-06-10 17:50:20 -07002911 // heavy/important/visible/foreground processes first.
Dianne Hackborn7d608422011-08-07 16:24:18 -07002912 if (rec.setAdj <= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002913 rec.lastRequestedGc = 0;
2914 } else {
2915 rec.lastRequestedGc = rec.lastLowMemory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002916 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002917 rec.reportLowMemory = true;
2918 rec.lastLowMemory = now;
2919 mProcessesToGc.remove(rec);
2920 addProcessToGcListLocked(rec);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002921 }
2922 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07002923 mHandler.sendEmptyMessage(REPORT_MEM_USAGE);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002924 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002925 }
2926 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01002927 } else if (app.pid != pid) {
2928 // A new process has already been started.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002929 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
Magnus Edlund7bb25812010-02-24 15:45:06 +01002930 + ") has died and restarted (pid " + app.pid + ").");
Dianne Hackborn28a8c2b2010-03-01 11:30:02 -08002931 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08002932 } else if (DEBUG_PROCESSES) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002933 Slog.d(TAG, "Received spurious death notification for thread "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002934 + thread.asBinder());
2935 }
2936 }
2937
Dan Egnor42471dd2010-01-07 17:25:22 -08002938 /**
2939 * If a stack trace dump file is configured, dump process stack traces.
Christopher Tate6ee412d2010-05-28 12:01:56 -07002940 * @param clearTraces causes the dump file to be erased prior to the new
2941 * traces being written, if true; when false, the new traces will be
2942 * appended to any existing file content.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002943 * @param firstPids of dalvik VM processes to dump stack traces for first
2944 * @param lastPids of dalvik VM processes to dump stack traces for last
Dan Egnor42471dd2010-01-07 17:25:22 -08002945 * @return file containing stack traces, or null if no dump file is configured
2946 */
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002947 public static File dumpStackTraces(boolean clearTraces, ArrayList<Integer> firstPids,
2948 ProcessStats processStats, SparseArray<Boolean> lastPids) {
Dan Egnor42471dd2010-01-07 17:25:22 -08002949 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
2950 if (tracesPath == null || tracesPath.length() == 0) {
2951 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002952 }
Dan Egnor42471dd2010-01-07 17:25:22 -08002953
2954 File tracesFile = new File(tracesPath);
2955 try {
2956 File tracesDir = tracesFile.getParentFile();
2957 if (!tracesDir.exists()) tracesFile.mkdirs();
2958 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
2959
Christopher Tate6ee412d2010-05-28 12:01:56 -07002960 if (clearTraces && tracesFile.exists()) tracesFile.delete();
Dan Egnor42471dd2010-01-07 17:25:22 -08002961 tracesFile.createNewFile();
2962 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
2963 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002964 Slog.w(TAG, "Unable to prepare ANR traces file: " + tracesPath, e);
Dan Egnor42471dd2010-01-07 17:25:22 -08002965 return null;
2966 }
2967
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07002968 dumpStackTraces(tracesPath, firstPids, processStats, lastPids);
2969 return tracesFile;
2970 }
2971
2972 private static void dumpStackTraces(String tracesPath, ArrayList<Integer> firstPids,
2973 ProcessStats processStats, SparseArray<Boolean> lastPids) {
Dan Egnor42471dd2010-01-07 17:25:22 -08002974 // Use a FileObserver to detect when traces finish writing.
2975 // The order of traces is considered important to maintain for legibility.
2976 FileObserver observer = new FileObserver(tracesPath, FileObserver.CLOSE_WRITE) {
2977 public synchronized void onEvent(int event, String path) { notify(); }
2978 };
2979
2980 try {
2981 observer.startWatching();
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002982
2983 // First collect all of the stacks of the most important pids.
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07002984 if (firstPids != null) {
2985 try {
2986 int num = firstPids.size();
2987 for (int i = 0; i < num; i++) {
2988 synchronized (observer) {
2989 Process.sendSignal(firstPids.get(i), Process.SIGNAL_QUIT);
2990 observer.wait(200); // Wait for write-close, give up after 200msec
2991 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002992 }
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07002993 } catch (InterruptedException e) {
2994 Log.wtf(TAG, e);
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002995 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002996 }
2997
2998 // Next measure CPU usage.
2999 if (processStats != null) {
3000 processStats.init();
3001 System.gc();
3002 processStats.update();
3003 try {
3004 synchronized (processStats) {
3005 processStats.wait(500); // measure over 1/2 second.
3006 }
3007 } catch (InterruptedException e) {
3008 }
3009 processStats.update();
3010
3011 // We'll take the stack crawls of just the top apps using CPU.
3012 final int N = processStats.countWorkingStats();
3013 int numProcs = 0;
3014 for (int i=0; i<N && numProcs<5; i++) {
3015 ProcessStats.Stats stats = processStats.getWorkingStats(i);
3016 if (lastPids.indexOfKey(stats.pid) >= 0) {
3017 numProcs++;
3018 try {
3019 synchronized (observer) {
3020 Process.sendSignal(stats.pid, Process.SIGNAL_QUIT);
3021 observer.wait(200); // Wait for write-close, give up after 200msec
3022 }
3023 } catch (InterruptedException e) {
3024 Log.wtf(TAG, e);
3025 }
3026
3027 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003028 }
3029 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003030
Dan Egnor42471dd2010-01-07 17:25:22 -08003031 } finally {
3032 observer.stopWatching();
3033 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003034 }
3035
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003036 final void logAppTooSlow(ProcessRecord app, long startTime, String msg) {
3037 if (IS_USER_BUILD) {
3038 return;
3039 }
3040 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
3041 if (tracesPath == null || tracesPath.length() == 0) {
3042 return;
3043 }
3044
3045 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
3046 StrictMode.allowThreadDiskWrites();
3047 try {
3048 final File tracesFile = new File(tracesPath);
3049 final File tracesDir = tracesFile.getParentFile();
3050 final File tracesTmp = new File(tracesDir, "__tmp__");
3051 try {
3052 if (!tracesDir.exists()) tracesFile.mkdirs();
3053 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
3054
3055 if (tracesFile.exists()) {
3056 tracesTmp.delete();
3057 tracesFile.renameTo(tracesTmp);
3058 }
3059 StringBuilder sb = new StringBuilder();
3060 Time tobj = new Time();
3061 tobj.set(System.currentTimeMillis());
3062 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
3063 sb.append(": ");
3064 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
3065 sb.append(" since ");
3066 sb.append(msg);
3067 FileOutputStream fos = new FileOutputStream(tracesFile);
3068 fos.write(sb.toString().getBytes());
3069 if (app == null) {
3070 fos.write("\n*** No application process!".getBytes());
3071 }
3072 fos.close();
3073 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
3074 } catch (IOException e) {
3075 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesPath, e);
3076 return;
3077 }
3078
3079 if (app != null) {
3080 ArrayList<Integer> firstPids = new ArrayList<Integer>();
3081 firstPids.add(app.pid);
3082 dumpStackTraces(tracesPath, firstPids, null, null);
3083 }
3084
3085 File lastTracesFile = null;
3086 File curTracesFile = null;
3087 for (int i=9; i>=0; i--) {
3088 String name = String.format("slow%02d.txt", i);
3089 curTracesFile = new File(tracesDir, name);
3090 if (curTracesFile.exists()) {
3091 if (lastTracesFile != null) {
3092 curTracesFile.renameTo(lastTracesFile);
3093 } else {
3094 curTracesFile.delete();
3095 }
3096 }
3097 lastTracesFile = curTracesFile;
3098 }
3099 tracesFile.renameTo(curTracesFile);
3100 if (tracesTmp.exists()) {
3101 tracesTmp.renameTo(tracesFile);
3102 }
3103 } finally {
3104 StrictMode.setThreadPolicy(oldPolicy);
3105 }
3106 }
3107
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003108 final void appNotResponding(ProcessRecord app, ActivityRecord activity,
3109 ActivityRecord parent, final String annotation) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003110 ArrayList<Integer> firstPids = new ArrayList<Integer>(5);
3111 SparseArray<Boolean> lastPids = new SparseArray<Boolean>(20);
3112
Dianne Hackborn287952c2010-09-22 22:34:31 -07003113 if (mController != null) {
3114 try {
3115 // 0 == continue, -1 = kill process immediately
3116 int res = mController.appEarlyNotResponding(app.processName, app.pid, annotation);
3117 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3118 } catch (RemoteException e) {
3119 mController = null;
3120 }
3121 }
3122
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003123 long anrTime = SystemClock.uptimeMillis();
3124 if (MONITOR_CPU_USAGE) {
3125 updateCpuStatsNow();
3126 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003127
3128 synchronized (this) {
3129 // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down.
3130 if (mShuttingDown) {
3131 Slog.i(TAG, "During shutdown skipping ANR: " + app + " " + annotation);
3132 return;
3133 } else if (app.notResponding) {
3134 Slog.i(TAG, "Skipping duplicate ANR: " + app + " " + annotation);
3135 return;
3136 } else if (app.crashing) {
3137 Slog.i(TAG, "Crashing app skipping ANR: " + app + " " + annotation);
3138 return;
3139 }
3140
3141 // In case we come through here for the same app before completing
3142 // this one, mark as anring now so we will bail out.
3143 app.notResponding = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08003144
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003145 // Log the ANR to the event log.
3146 EventLog.writeEvent(EventLogTags.AM_ANR, app.pid, app.processName, app.info.flags,
3147 annotation);
Dan Egnor42471dd2010-01-07 17:25:22 -08003148
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003149 // Dump thread traces as quickly as we can, starting with "interesting" processes.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003150 firstPids.add(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003151
3152 int parentPid = app.pid;
3153 if (parent != null && parent.app != null && parent.app.pid > 0) parentPid = parent.app.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003154 if (parentPid != app.pid) firstPids.add(parentPid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003155
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003156 if (MY_PID != app.pid && MY_PID != parentPid) firstPids.add(MY_PID);
Dan Egnor42471dd2010-01-07 17:25:22 -08003157
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003158 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
3159 ProcessRecord r = mLruProcesses.get(i);
3160 if (r != null && r.thread != null) {
3161 int pid = r.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003162 if (pid > 0 && pid != app.pid && pid != parentPid && pid != MY_PID) {
3163 if (r.persistent) {
3164 firstPids.add(pid);
3165 } else {
3166 lastPids.put(pid, Boolean.TRUE);
3167 }
3168 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003169 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003170 }
3171 }
3172
Dan Egnor42471dd2010-01-07 17:25:22 -08003173 // Log the ANR to the main log.
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07003174 StringBuilder info = mStringBuilder;
3175 info.setLength(0);
Dan Egnor42471dd2010-01-07 17:25:22 -08003176 info.append("ANR in ").append(app.processName);
3177 if (activity != null && activity.shortComponentName != null) {
3178 info.append(" (").append(activity.shortComponentName).append(")");
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07003179 }
Eric Rowe6f4f6192010-02-17 18:29:04 -08003180 info.append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003181 if (annotation != null) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003182 info.append("Reason: ").append(annotation).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003183 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003184 if (parent != null && parent != activity) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003185 info.append("Parent: ").append(parent.shortComponentName).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003186 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003187
Dianne Hackborn287952c2010-09-22 22:34:31 -07003188 final ProcessStats processStats = new ProcessStats(true);
3189
3190 File tracesFile = dumpStackTraces(true, firstPids, processStats, lastPids);
3191
Dan Egnor42471dd2010-01-07 17:25:22 -08003192 String cpuInfo = null;
3193 if (MONITOR_CPU_USAGE) {
3194 updateCpuStatsNow();
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003195 synchronized (mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003196 cpuInfo = mProcessStats.printCurrentState(anrTime);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003197 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003198 info.append(processStats.printCurrentLoad());
Dan Egnor42471dd2010-01-07 17:25:22 -08003199 info.append(cpuInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003200 }
3201
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003202 info.append(processStats.printCurrentState(anrTime));
3203
Joe Onorato8a9b2202010-02-26 18:56:32 -08003204 Slog.e(TAG, info.toString());
Dan Egnor42471dd2010-01-07 17:25:22 -08003205 if (tracesFile == null) {
3206 // There is no trace file, so dump (only) the alleged culprit's threads to the log
3207 Process.sendSignal(app.pid, Process.SIGNAL_QUIT);
3208 }
3209
Jeff Sharkeya353d262011-10-28 11:12:06 -07003210 addErrorToDropBox("anr", app, app.processName, activity, parent, annotation,
3211 cpuInfo, tracesFile, null);
Dan Egnor42471dd2010-01-07 17:25:22 -08003212
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003213 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003214 try {
Dan Egnor42471dd2010-01-07 17:25:22 -08003215 // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately
3216 int res = mController.appNotResponding(app.processName, app.pid, info.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003217 if (res != 0) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003218 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3219 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003220 }
3221 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003222 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003223 }
3224 }
3225
Dan Egnor42471dd2010-01-07 17:25:22 -08003226 // Unless configured otherwise, swallow ANRs in background processes & kill the process.
3227 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
3228 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003229
3230 synchronized (this) {
3231 if (!showBackground && !app.isInterestingToUserLocked() && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003232 Slog.w(TAG, "Killing " + app + ": background ANR");
3233 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
3234 app.processName, app.setAdj, "background ANR");
3235 Process.killProcessQuiet(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003236 return;
3237 }
3238
3239 // Set the app's notResponding state, and look up the errorReportReceiver
3240 makeAppNotRespondingLocked(app,
3241 activity != null ? activity.shortComponentName : null,
3242 annotation != null ? "ANR " + annotation : "ANR",
3243 info.toString());
3244
3245 // Bring up the infamous App Not Responding dialog
3246 Message msg = Message.obtain();
3247 HashMap map = new HashMap();
3248 msg.what = SHOW_NOT_RESPONDING_MSG;
3249 msg.obj = map;
3250 map.put("app", app);
3251 if (activity != null) {
3252 map.put("activity", activity);
3253 }
3254
3255 mHandler.sendMessage(msg);
Dan Egnor42471dd2010-01-07 17:25:22 -08003256 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003257 }
3258
Dianne Hackborn0dad3642010-09-09 21:25:35 -07003259 final void showLaunchWarningLocked(final ActivityRecord cur, final ActivityRecord next) {
3260 if (!mLaunchWarningShown) {
3261 mLaunchWarningShown = true;
3262 mHandler.post(new Runnable() {
3263 @Override
3264 public void run() {
3265 synchronized (ActivityManagerService.this) {
3266 final Dialog d = new LaunchWarningWindow(mContext, cur, next);
3267 d.show();
3268 mHandler.postDelayed(new Runnable() {
3269 @Override
3270 public void run() {
3271 synchronized (ActivityManagerService.this) {
3272 d.dismiss();
3273 mLaunchWarningShown = false;
3274 }
3275 }
3276 }, 4000);
3277 }
3278 }
3279 });
3280 }
3281 }
3282
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003283 public boolean clearApplicationUserData(final String packageName,
Amith Yamasani742a6712011-05-04 14:49:28 -07003284 final IPackageDataObserver observer, final int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003285 enforceNotIsolatedCaller("clearApplicationUserData");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003286 int uid = Binder.getCallingUid();
3287 int pid = Binder.getCallingPid();
3288 long callingId = Binder.clearCallingIdentity();
3289 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003290 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003291 int pkgUid = -1;
3292 synchronized(this) {
3293 try {
3294 pkgUid = pm.getPackageUid(packageName);
3295 } catch (RemoteException e) {
3296 }
3297 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003298 Slog.w(TAG, "Invalid packageName:" + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003299 return false;
3300 }
3301 if (uid == pkgUid || checkComponentPermission(
3302 android.Manifest.permission.CLEAR_APP_USER_DATA,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08003303 pid, uid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003304 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003305 forceStopPackageLocked(packageName, pkgUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003306 } else {
3307 throw new SecurityException(pid+" does not have permission:"+
3308 android.Manifest.permission.CLEAR_APP_USER_DATA+" to clear data" +
3309 "for process:"+packageName);
3310 }
3311 }
3312
3313 try {
3314 //clear application user data
3315 pm.clearApplicationUserData(packageName, observer);
3316 Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED,
3317 Uri.fromParts("package", packageName, null));
3318 intent.putExtra(Intent.EXTRA_UID, pkgUid);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003319 broadcastIntentInPackage("android", Process.SYSTEM_UID, intent,
Amith Yamasani742a6712011-05-04 14:49:28 -07003320 null, null, 0, null, null, null, false, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003321 } catch (RemoteException e) {
3322 }
3323 } finally {
3324 Binder.restoreCallingIdentity(callingId);
3325 }
3326 return true;
3327 }
3328
Dianne Hackborn03abb812010-01-04 18:43:19 -08003329 public void killBackgroundProcesses(final String packageName) {
3330 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3331 != PackageManager.PERMISSION_GRANTED &&
3332 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES)
3333 != PackageManager.PERMISSION_GRANTED) {
3334 String msg = "Permission Denial: killBackgroundProcesses() from pid="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003335 + Binder.getCallingPid()
3336 + ", uid=" + Binder.getCallingUid()
Dianne Hackborn03abb812010-01-04 18:43:19 -08003337 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003338 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003339 throw new SecurityException(msg);
3340 }
3341
3342 long callingId = Binder.clearCallingIdentity();
3343 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003344 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003345 int pkgUid = -1;
3346 synchronized(this) {
3347 try {
3348 pkgUid = pm.getPackageUid(packageName);
3349 } catch (RemoteException e) {
3350 }
3351 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003352 Slog.w(TAG, "Invalid packageName: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003353 return;
3354 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003355 killPackageProcessesLocked(packageName, pkgUid,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003356 ProcessList.SERVICE_ADJ, false, true, true, false, "kill background");
3357 }
3358 } finally {
3359 Binder.restoreCallingIdentity(callingId);
3360 }
3361 }
3362
3363 public void killAllBackgroundProcesses() {
3364 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3365 != PackageManager.PERMISSION_GRANTED) {
3366 String msg = "Permission Denial: killAllBackgroundProcesses() from pid="
3367 + Binder.getCallingPid()
3368 + ", uid=" + Binder.getCallingUid()
3369 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
3370 Slog.w(TAG, msg);
3371 throw new SecurityException(msg);
3372 }
3373
3374 long callingId = Binder.clearCallingIdentity();
3375 try {
3376 synchronized(this) {
3377 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
3378 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3379 final int NA = apps.size();
3380 for (int ia=0; ia<NA; ia++) {
3381 ProcessRecord app = apps.valueAt(ia);
3382 if (app.persistent) {
3383 // we don't kill persistent processes
3384 continue;
3385 }
3386 if (app.removed) {
3387 procs.add(app);
3388 } else if (app.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
3389 app.removed = true;
3390 procs.add(app);
3391 }
3392 }
3393 }
3394
3395 int N = procs.size();
3396 for (int i=0; i<N; i++) {
3397 removeProcessLocked(procs.get(i), false, true, "kill all background");
3398 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003399 }
3400 } finally {
3401 Binder.restoreCallingIdentity(callingId);
3402 }
3403 }
3404
3405 public void forceStopPackage(final String packageName) {
3406 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3407 != PackageManager.PERMISSION_GRANTED) {
3408 String msg = "Permission Denial: forceStopPackage() from pid="
3409 + Binder.getCallingPid()
3410 + ", uid=" + Binder.getCallingUid()
3411 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003412 Slog.w(TAG, msg);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003413 throw new SecurityException(msg);
3414 }
Amith Yamasani742a6712011-05-04 14:49:28 -07003415 final int userId = Binder.getOrigCallingUser();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003416 long callingId = Binder.clearCallingIdentity();
3417 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003418 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003419 int pkgUid = -1;
3420 synchronized(this) {
3421 try {
3422 pkgUid = pm.getPackageUid(packageName);
Amith Yamasani742a6712011-05-04 14:49:28 -07003423 // Convert the uid to the one for the calling user
3424 pkgUid = UserId.getUid(userId, pkgUid);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003425 } catch (RemoteException e) {
3426 }
3427 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003428 Slog.w(TAG, "Invalid packageName: " + packageName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003429 return;
3430 }
3431 forceStopPackageLocked(packageName, pkgUid);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003432 try {
3433 pm.setPackageStoppedState(packageName, true);
3434 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08003435 } catch (IllegalArgumentException e) {
3436 Slog.w(TAG, "Failed trying to unstop package "
3437 + packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003438 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003439 }
3440 } finally {
3441 Binder.restoreCallingIdentity(callingId);
3442 }
3443 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003444
3445 /*
3446 * The pkg name and uid have to be specified.
3447 * @see android.app.IActivityManager#killApplicationWithUid(java.lang.String, int)
3448 */
3449 public void killApplicationWithUid(String pkg, int uid) {
3450 if (pkg == null) {
3451 return;
3452 }
3453 // Make sure the uid is valid.
3454 if (uid < 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003455 Slog.w(TAG, "Invalid uid specified for pkg : " + pkg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003456 return;
3457 }
3458 int callerUid = Binder.getCallingUid();
3459 // Only the system server can kill an application
3460 if (callerUid == Process.SYSTEM_UID) {
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07003461 // Post an aysnc message to kill the application
3462 Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG);
3463 msg.arg1 = uid;
3464 msg.arg2 = 0;
3465 msg.obj = pkg;
Suchi Amalapurapud50066f2009-08-18 16:57:41 -07003466 mHandler.sendMessage(msg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003467 } else {
3468 throw new SecurityException(callerUid + " cannot kill pkg: " +
3469 pkg);
3470 }
3471 }
3472
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003473 public void closeSystemDialogs(String reason) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003474 enforceNotIsolatedCaller("closeSystemDialogs");
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003475 Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003476 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003477 if (reason != null) {
3478 intent.putExtra("reason", reason);
3479 }
3480
3481 final int uid = Binder.getCallingUid();
3482 final long origId = Binder.clearCallingIdentity();
3483 synchronized (this) {
Dianne Hackbornffa42482009-09-23 22:20:11 -07003484 mWindowManager.closeSystemDialogs(reason);
3485
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08003486 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003487 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornffa42482009-09-23 22:20:11 -07003488 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003489 r.stack.finishActivityLocked(r, i,
Dianne Hackbornffa42482009-09-23 22:20:11 -07003490 Activity.RESULT_CANCELED, null, "close-sys");
3491 }
3492 }
3493
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003494 broadcastIntentLocked(null, null, intent, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07003495 null, 0, null, null, null, false, false, -1, uid, 0 /* TODO: Verify */);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003496 }
3497 Binder.restoreCallingIdentity(origId);
3498 }
3499
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003500 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids)
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003501 throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003502 enforceNotIsolatedCaller("getProcessMemoryInfo");
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003503 Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length];
3504 for (int i=pids.length-1; i>=0; i--) {
3505 infos[i] = new Debug.MemoryInfo();
3506 Debug.getMemoryInfo(pids[i], infos[i]);
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003507 }
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003508 return infos;
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003509 }
Christopher Tate5e1ab332009-09-01 20:32:49 -07003510
Dianne Hackbornb437e092011-08-05 17:50:29 -07003511 public long[] getProcessPss(int[] pids) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003512 enforceNotIsolatedCaller("getProcessPss");
Dianne Hackbornb437e092011-08-05 17:50:29 -07003513 long[] pss = new long[pids.length];
3514 for (int i=pids.length-1; i>=0; i--) {
3515 pss[i] = Debug.getPss(pids[i]);
3516 }
3517 return pss;
3518 }
3519
Christopher Tate5e1ab332009-09-01 20:32:49 -07003520 public void killApplicationProcess(String processName, int uid) {
3521 if (processName == null) {
3522 return;
3523 }
3524
3525 int callerUid = Binder.getCallingUid();
3526 // Only the system server can kill an application
3527 if (callerUid == Process.SYSTEM_UID) {
3528 synchronized (this) {
3529 ProcessRecord app = getProcessRecordLocked(processName, uid);
Christopher Tate4a627c72011-04-01 14:43:32 -07003530 if (app != null && app.thread != null) {
Christopher Tate5e1ab332009-09-01 20:32:49 -07003531 try {
3532 app.thread.scheduleSuicide();
3533 } catch (RemoteException e) {
3534 // If the other end already died, then our work here is done.
3535 }
3536 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003537 Slog.w(TAG, "Process/uid not found attempting kill of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07003538 + processName + " / " + uid);
3539 }
3540 }
3541 } else {
3542 throw new SecurityException(callerUid + " cannot kill app process: " +
3543 processName);
3544 }
3545 }
3546
Dianne Hackborn03abb812010-01-04 18:43:19 -08003547 private void forceStopPackageLocked(final String packageName, int uid) {
Christopher Tate3dacd842011-08-19 14:56:15 -07003548 forceStopPackageLocked(packageName, uid, false, false, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003549 Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED,
3550 Uri.fromParts("package", packageName, null));
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003551 if (!mProcessesReady) {
3552 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3553 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003554 intent.putExtra(Intent.EXTRA_UID, uid);
3555 broadcastIntentLocked(null, null, intent,
3556 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07003557 false, false,
3558 MY_PID, Process.SYSTEM_UID, UserId.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003559 }
3560
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003561 private final boolean killPackageProcessesLocked(String packageName, int uid,
Christopher Tate3dacd842011-08-19 14:56:15 -07003562 int minOomAdj, boolean callerWillRestart, boolean allowRestart, boolean doit,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003563 boolean evenPersistent, String reason) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003564 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003565
Dianne Hackborn03abb812010-01-04 18:43:19 -08003566 // Remove all processes this package may have touched: all with the
3567 // same UID (except for the system or root user), and all whose name
3568 // matches the package name.
3569 final String procNamePrefix = packageName + ":";
3570 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3571 final int NA = apps.size();
3572 for (int ia=0; ia<NA; ia++) {
3573 ProcessRecord app = apps.valueAt(ia);
Christopher Tate3dacd842011-08-19 14:56:15 -07003574 if (app.persistent && !evenPersistent) {
Christopher Tate064d8422011-07-26 15:38:07 -07003575 // we don't kill persistent processes
3576 continue;
3577 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003578 if (app.removed) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003579 if (doit) {
3580 procs.add(app);
3581 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003582 } else if ((uid > 0 && uid != Process.SYSTEM_UID && app.info.uid == uid)
3583 || app.processName.equals(packageName)
3584 || app.processName.startsWith(procNamePrefix)) {
3585 if (app.setAdj >= minOomAdj) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003586 if (!doit) {
3587 return true;
3588 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003589 app.removed = true;
3590 procs.add(app);
3591 }
3592 }
3593 }
3594 }
3595
3596 int N = procs.size();
3597 for (int i=0; i<N; i++) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003598 removeProcessLocked(procs.get(i), callerWillRestart, allowRestart, reason);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003599 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003600 return N > 0;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003601 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003602
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003603 private final boolean forceStopPackageLocked(String name, int uid,
Christopher Tate3dacd842011-08-19 14:56:15 -07003604 boolean callerWillRestart, boolean purgeCache, boolean doit,
3605 boolean evenPersistent) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003606 int i;
3607 int N;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003608
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003609 if (uid < 0) {
3610 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003611 uid = AppGlobals.getPackageManager().getPackageUid(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003612 } catch (RemoteException e) {
3613 }
3614 }
3615
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003616 if (doit) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003617 Slog.i(TAG, "Force stopping package " + name + " uid=" + uid);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003618
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003619 Iterator<SparseArray<Long>> badApps = mProcessCrashTimes.getMap().values().iterator();
3620 while (badApps.hasNext()) {
3621 SparseArray<Long> ba = badApps.next();
3622 if (ba.get(uid) != null) {
3623 badApps.remove();
3624 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003625 }
3626 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003627
3628 boolean didSomething = killPackageProcessesLocked(name, uid, -100,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003629 callerWillRestart, false, doit, evenPersistent, "force stop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003630
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003631 TaskRecord lastTask = null;
3632 for (i=0; i<mMainStack.mHistory.size(); i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003633 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003634 final boolean samePackage = r.packageName.equals(name);
3635 if ((samePackage || r.task == lastTask)
Christopher Tate3dacd842011-08-19 14:56:15 -07003636 && (r.app == null || evenPersistent || !r.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003637 if (!doit) {
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003638 if (r.finishing) {
3639 // If this activity is just finishing, then it is not
3640 // interesting as far as something to stop.
3641 continue;
3642 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003643 return true;
3644 }
3645 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003646 Slog.i(TAG, " Force finishing activity " + r);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003647 if (samePackage) {
3648 if (r.app != null) {
3649 r.app.removed = true;
3650 }
3651 r.app = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003652 }
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003653 lastTask = r.task;
3654 if (r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
3655 null, "force-stop")) {
3656 i--;
3657 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003658 }
3659 }
3660
3661 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
Amith Yamasani742a6712011-05-04 14:49:28 -07003662 int userId = UserId.getUserId(uid);
3663 for (ServiceRecord service : mServiceMap.getAllServices(userId)) {
Christopher Tate064d8422011-07-26 15:38:07 -07003664 if (service.packageName.equals(name)
Christopher Tate3dacd842011-08-19 14:56:15 -07003665 && (service.app == null || evenPersistent || !service.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003666 if (!doit) {
3667 return true;
3668 }
3669 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003670 Slog.i(TAG, " Force stopping service " + service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003671 if (service.app != null) {
3672 service.app.removed = true;
3673 }
3674 service.app = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003675 service.isolatedProc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003676 services.add(service);
3677 }
3678 }
3679
3680 N = services.size();
3681 for (i=0; i<N; i++) {
3682 bringDownServiceLocked(services.get(i), true);
3683 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003684
3685 ArrayList<ContentProviderRecord> providers = new ArrayList<ContentProviderRecord>();
Amith Yamasani37ce3a82012-02-06 12:04:42 -08003686 for (ContentProviderRecord provider : mProviderMap.getProvidersByClass(-1).values()) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003687 if (provider.info.packageName.equals(name)
3688 && (provider.proc == null || evenPersistent || !provider.proc.persistent)) {
3689 if (!doit) {
3690 return true;
3691 }
3692 didSomething = true;
3693 providers.add(provider);
3694 }
3695 }
3696
3697 N = providers.size();
3698 for (i=0; i<N; i++) {
3699 removeDyingProviderLocked(null, providers.get(i));
3700 }
3701
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003702 if (doit) {
3703 if (purgeCache) {
3704 AttributeCache ac = AttributeCache.instance();
3705 if (ac != null) {
3706 ac.removePackage(name);
3707 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003708 }
Dianne Hackborn38cc8962011-10-13 11:33:55 -07003709 if (mBooted) {
3710 mMainStack.resumeTopActivityLocked(null);
3711 mMainStack.scheduleIdleLocked();
3712 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003713 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003714
3715 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003716 }
3717
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003718 private final boolean removeProcessLocked(ProcessRecord app,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003719 boolean callerWillRestart, boolean allowRestart, String reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003720 final String name = app.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003721 final int uid = app.uid;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003722 if (DEBUG_PROCESSES) Slog.d(
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003723 TAG, "Force removing proc " + app.toShortString() + " (" + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003724 + "/" + uid + ")");
3725
3726 mProcessNames.remove(name, uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003727 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003728 if (mHeavyWeightProcess == app) {
3729 mHeavyWeightProcess = null;
3730 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3731 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003732 boolean needRestart = false;
3733 if (app.pid > 0 && app.pid != MY_PID) {
3734 int pid = app.pid;
3735 synchronized (mPidsSelfLocked) {
3736 mPidsSelfLocked.remove(pid);
3737 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3738 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003739 Slog.i(TAG, "Killing proc " + app.toShortString() + ": " + reason);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003740 handleAppDiedLocked(app, true, allowRestart);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003741 mLruProcesses.remove(app);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003742 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003743
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003744 if (app.persistent && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003745 if (!callerWillRestart) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003746 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003747 } else {
3748 needRestart = true;
3749 }
3750 }
3751 } else {
3752 mRemovedProcesses.add(app);
3753 }
3754
3755 return needRestart;
3756 }
3757
3758 private final void processStartTimedOutLocked(ProcessRecord app) {
3759 final int pid = app.pid;
3760 boolean gone = false;
3761 synchronized (mPidsSelfLocked) {
3762 ProcessRecord knownApp = mPidsSelfLocked.get(pid);
3763 if (knownApp != null && knownApp.thread == null) {
3764 mPidsSelfLocked.remove(pid);
3765 gone = true;
3766 }
3767 }
3768
3769 if (gone) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003770 Slog.w(TAG, "Process " + app + " failed to attach");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003771 EventLog.writeEvent(EventLogTags.AM_PROCESS_START_TIMEOUT, pid, app.uid,
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003772 app.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003773 mProcessNames.remove(app.processName, app.uid);
3774 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003775 if (mHeavyWeightProcess == app) {
3776 mHeavyWeightProcess = null;
3777 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3778 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003779 // Take care of any launching providers waiting for this process.
3780 checkAppInLaunchingProvidersLocked(app, true);
3781 // Take care of any services that are waiting for the process.
3782 for (int i=0; i<mPendingServices.size(); i++) {
3783 ServiceRecord sr = mPendingServices.get(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003784 if ((app.uid == sr.appInfo.uid
3785 && app.processName.equals(sr.processName))
3786 || sr.isolatedProc == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003787 Slog.w(TAG, "Forcing bringing down service: " + sr);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003788 sr.isolatedProc = null;
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003789 mPendingServices.remove(i);
3790 i--;
3791 bringDownServiceLocked(sr, true);
3792 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003793 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003794 EventLog.writeEvent(EventLogTags.AM_KILL, pid,
3795 app.processName, app.setAdj, "start timeout");
3796 Process.killProcessQuiet(pid);
Christopher Tate181fafa2009-05-14 11:12:14 -07003797 if (mBackupTarget != null && mBackupTarget.app.pid == pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003798 Slog.w(TAG, "Unattached app died before backup, skipping");
Christopher Tate181fafa2009-05-14 11:12:14 -07003799 try {
3800 IBackupManager bm = IBackupManager.Stub.asInterface(
3801 ServiceManager.getService(Context.BACKUP_SERVICE));
3802 bm.agentDisconnected(app.info.packageName);
3803 } catch (RemoteException e) {
3804 // Can't happen; the backup manager is local
3805 }
3806 }
Christopher Tatef46723b2012-01-26 14:19:24 -08003807 if (isPendingBroadcastProcessLocked(pid)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003808 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
Christopher Tatef46723b2012-01-26 14:19:24 -08003809 skipPendingBroadcastLocked(pid);
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003810 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003811 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003812 Slog.w(TAG, "Spurious process start timeout - pid not known for " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003813 }
3814 }
3815
3816 private final boolean attachApplicationLocked(IApplicationThread thread,
3817 int pid) {
3818
3819 // Find the application record that is being attached... either via
3820 // the pid if we are running in multiple processes, or just pull the
3821 // next app record if we are emulating process with anonymous threads.
3822 ProcessRecord app;
3823 if (pid != MY_PID && pid >= 0) {
3824 synchronized (mPidsSelfLocked) {
3825 app = mPidsSelfLocked.get(pid);
3826 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003827 } else {
3828 app = null;
3829 }
3830
3831 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003832 Slog.w(TAG, "No pending application record for pid " + pid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003833 + " (IApplicationThread " + thread + "); dropping process");
Doug Zongker2bec3d42009-12-04 12:52:44 -08003834 EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003835 if (pid > 0 && pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003836 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003837 } else {
3838 try {
3839 thread.scheduleExit();
3840 } catch (Exception e) {
3841 // Ignore exceptions.
3842 }
3843 }
3844 return false;
3845 }
3846
3847 // If this application record is still attached to a previous
3848 // process, clean it up now.
3849 if (app.thread != null) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003850 handleAppDiedLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003851 }
3852
3853 // Tell the process all about itself.
3854
Joe Onorato8a9b2202010-02-26 18:56:32 -08003855 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003856 TAG, "Binding process pid " + pid + " to record " + app);
3857
3858 String processName = app.processName;
3859 try {
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07003860 AppDeathRecipient adr = new AppDeathRecipient(
3861 app, pid, thread);
3862 thread.asBinder().linkToDeath(adr, 0);
3863 app.deathRecipient = adr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003864 } catch (RemoteException e) {
3865 app.resetPackageList();
3866 startProcessLocked(app, "link fail", processName);
3867 return false;
3868 }
3869
Doug Zongker2bec3d42009-12-04 12:52:44 -08003870 EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.pid, app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003871
3872 app.thread = thread;
3873 app.curAdj = app.setAdj = -100;
Dianne Hackborn09c916b2009-12-08 14:50:51 -08003874 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
3875 app.setSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003876 app.forcingToForeground = null;
3877 app.foregroundServices = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07003878 app.hasShownUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003879 app.debugging = false;
3880
3881 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3882
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003883 boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003884 List providers = normalMode ? generateApplicationProvidersLocked(app) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003885
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003886 if (!normalMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003887 Slog.i(TAG, "Launching preboot mode app: " + app);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003888 }
3889
Joe Onorato8a9b2202010-02-26 18:56:32 -08003890 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003891 TAG, "New app record " + app
3892 + " thread=" + thread.asBinder() + " pid=" + pid);
3893 try {
3894 int testMode = IApplicationThread.DEBUG_OFF;
3895 if (mDebugApp != null && mDebugApp.equals(processName)) {
3896 testMode = mWaitForDebugger
3897 ? IApplicationThread.DEBUG_WAIT
3898 : IApplicationThread.DEBUG_ON;
3899 app.debugging = true;
3900 if (mDebugTransient) {
3901 mDebugApp = mOrigDebugApp;
3902 mWaitForDebugger = mOrigWaitForDebugger;
3903 }
3904 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003905 String profileFile = app.instrumentationProfileFile;
3906 ParcelFileDescriptor profileFd = null;
3907 boolean profileAutoStop = false;
3908 if (mProfileApp != null && mProfileApp.equals(processName)) {
3909 mProfileProc = app;
3910 profileFile = mProfileFile;
3911 profileFd = mProfileFd;
3912 profileAutoStop = mAutoStopProfiler;
3913 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08003914 boolean enableOpenGlTrace = false;
3915 if (mOpenGlTraceApp != null && mOpenGlTraceApp.equals(processName)) {
3916 enableOpenGlTrace = true;
3917 mOpenGlTraceApp = null;
3918 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003919
Christopher Tate181fafa2009-05-14 11:12:14 -07003920 // If the app is being launched for restore or full backup, set it up specially
3921 boolean isRestrictedBackupMode = false;
3922 if (mBackupTarget != null && mBackupAppName.equals(processName)) {
3923 isRestrictedBackupMode = (mBackupTarget.backupMode == BackupRecord.RESTORE)
Christopher Tate75a99702011-05-18 16:28:19 -07003924 || (mBackupTarget.backupMode == BackupRecord.RESTORE_FULL)
Christopher Tate181fafa2009-05-14 11:12:14 -07003925 || (mBackupTarget.backupMode == BackupRecord.BACKUP_FULL);
3926 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003927
Dianne Hackbornd7f6daa2009-06-22 17:06:35 -07003928 ensurePackageDexOpt(app.instrumentationInfo != null
3929 ? app.instrumentationInfo.packageName
3930 : app.info.packageName);
3931 if (app.instrumentationClass != null) {
3932 ensurePackageDexOpt(app.instrumentationClass.getPackageName());
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003933 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08003934 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Binding proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003935 + processName + " with config " + mConfiguration);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003936 ApplicationInfo appInfo = app.instrumentationInfo != null
3937 ? app.instrumentationInfo : app.info;
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -07003938 app.compat = compatibilityInfoForPackageLocked(appInfo);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003939 if (profileFd != null) {
3940 profileFd = profileFd.dup();
3941 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003942 thread.bindApplication(processName, appInfo, providers,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003943 app.instrumentationClass, profileFile, profileFd, profileAutoStop,
Siva Velusamy92a8b222012-03-09 16:24:04 -08003944 app.instrumentationArguments, app.instrumentationWatcher, testMode,
3945 enableOpenGlTrace, isRestrictedBackupMode || !normalMode, app.persistent,
Dianne Hackborn813075a62011-11-14 17:45:19 -08003946 new Configuration(mConfiguration), app.compat, getCommonServicesLocked(),
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08003947 mCoreSettingsObserver.getCoreSettingsLocked());
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003948 updateLruProcessLocked(app, false, true);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003949 app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003950 } catch (Exception e) {
3951 // todo: Yikes! What should we do? For now we will try to
3952 // start another process, but that could easily get us in
3953 // an infinite loop of restarting processes...
Joe Onorato8a9b2202010-02-26 18:56:32 -08003954 Slog.w(TAG, "Exception thrown during bind!", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003955
3956 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07003957 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003958 startProcessLocked(app, "bind fail", processName);
3959 return false;
3960 }
3961
3962 // Remove this record from the list of starting applications.
3963 mPersistentStartingProcesses.remove(app);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003964 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
3965 "Attach application locked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003966 mProcessesOnHold.remove(app);
3967
3968 boolean badApp = false;
3969 boolean didSomething = false;
3970
3971 // See if the top visible activity is waiting to run in this process...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003972 ActivityRecord hr = mMainStack.topRunningActivityLocked(null);
Christopher Tate04c0af82010-06-07 18:35:20 -07003973 if (hr != null && normalMode) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003974 if (hr.app == null && app.uid == hr.info.applicationInfo.uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003975 && processName.equals(hr.processName)) {
3976 try {
Mike Lockwood3a74bd32011-08-12 13:55:22 -07003977 if (mHeadless) {
3978 Slog.e(TAG, "Starting activities not supported on headless device: " + hr);
3979 } else if (mMainStack.realStartActivityLocked(hr, app, true, true)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003980 didSomething = true;
3981 }
3982 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003983 Slog.w(TAG, "Exception in new application when starting activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003984 + hr.intent.getComponent().flattenToShortString(), e);
3985 badApp = true;
3986 }
3987 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003988 mMainStack.ensureActivitiesVisibleLocked(hr, null, processName, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003989 }
3990 }
3991
3992 // Find any services that should be running in this process...
3993 if (!badApp && mPendingServices.size() > 0) {
3994 ServiceRecord sr = null;
3995 try {
3996 for (int i=0; i<mPendingServices.size(); i++) {
3997 sr = mPendingServices.get(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003998 if (app != sr.isolatedProc && (app.uid != sr.appInfo.uid
3999 || !processName.equals(sr.processName))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004000 continue;
4001 }
4002
4003 mPendingServices.remove(i);
4004 i--;
4005 realStartServiceLocked(sr, app);
4006 didSomething = true;
4007 }
4008 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004009 Slog.w(TAG, "Exception in new application when starting service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004010 + sr.shortName, e);
4011 badApp = true;
4012 }
4013 }
4014
Christopher Tatef46723b2012-01-26 14:19:24 -08004015 // Check if a next-broadcast receiver is in this process...
4016 if (!badApp && isPendingBroadcastProcessLocked(pid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004017 try {
Christopher Tatef46723b2012-01-26 14:19:24 -08004018 didSomething = sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004019 } catch (Exception e) {
Christopher Tatef46723b2012-01-26 14:19:24 -08004020 // If the app died trying to launch the receiver we declare it 'bad'
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004021 badApp = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004022 }
4023 }
4024
Christopher Tate181fafa2009-05-14 11:12:14 -07004025 // Check whether the next backup agent is in this process...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004026 if (!badApp && mBackupTarget != null && mBackupTarget.appInfo.uid == app.uid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004027 if (DEBUG_BACKUP) Slog.v(TAG, "New app is backup target, launching agent for " + app);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004028 ensurePackageDexOpt(mBackupTarget.appInfo.packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07004029 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004030 thread.scheduleCreateBackupAgent(mBackupTarget.appInfo,
4031 compatibilityInfoForPackageLocked(mBackupTarget.appInfo),
4032 mBackupTarget.backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -07004033 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004034 Slog.w(TAG, "Exception scheduling backup agent creation: ");
Christopher Tate181fafa2009-05-14 11:12:14 -07004035 e.printStackTrace();
4036 }
4037 }
4038
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004039 if (badApp) {
4040 // todo: Also need to kill application to deal with all
4041 // kinds of exceptions.
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004042 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004043 return false;
4044 }
4045
4046 if (!didSomething) {
4047 updateOomAdjLocked();
4048 }
4049
4050 return true;
4051 }
4052
4053 public final void attachApplication(IApplicationThread thread) {
4054 synchronized (this) {
4055 int callingPid = Binder.getCallingPid();
4056 final long origId = Binder.clearCallingIdentity();
4057 attachApplicationLocked(thread, callingPid);
4058 Binder.restoreCallingIdentity(origId);
4059 }
4060 }
4061
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004062 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004063 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004064 ActivityRecord r = mMainStack.activityIdleInternal(token, false, config);
4065 if (stopProfiling) {
4066 synchronized (this) {
4067 if (mProfileProc == r.app) {
4068 if (mProfileFd != null) {
4069 try {
4070 mProfileFd.close();
4071 } catch (IOException e) {
4072 }
4073 clearProfilerLocked();
4074 }
4075 }
4076 }
4077 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004078 Binder.restoreCallingIdentity(origId);
4079 }
4080
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004081 void enableScreenAfterBoot() {
Doug Zongker2bec3d42009-12-04 12:52:44 -08004082 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004083 SystemClock.uptimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004084 mWindowManager.enableScreenAfterBoot();
4085 }
4086
Dianne Hackborn661cd522011-08-22 00:26:20 -07004087 public void showBootMessage(final CharSequence msg, final boolean always) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004088 enforceNotIsolatedCaller("showBootMessage");
Dianne Hackborn661cd522011-08-22 00:26:20 -07004089 mWindowManager.showBootMessage(msg, always);
4090 }
4091
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004092 public void dismissKeyguardOnNextActivity() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004093 enforceNotIsolatedCaller("dismissKeyguardOnNextActivity");
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004094 synchronized (this) {
4095 mMainStack.dismissKeyguardOnNextActivityLocked();
4096 }
4097 }
4098
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004099 final void finishBooting() {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004100 IntentFilter pkgFilter = new IntentFilter();
4101 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
4102 pkgFilter.addDataScheme("package");
4103 mContext.registerReceiver(new BroadcastReceiver() {
4104 @Override
4105 public void onReceive(Context context, Intent intent) {
4106 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
4107 if (pkgs != null) {
4108 for (String pkg : pkgs) {
Vairavan Srinivasan61f07652010-07-22 13:36:40 -07004109 synchronized (ActivityManagerService.this) {
Christopher Tate3dacd842011-08-19 14:56:15 -07004110 if (forceStopPackageLocked(pkg, -1, false, false, false, false)) {
Vairavan Srinivasan61f07652010-07-22 13:36:40 -07004111 setResultCode(Activity.RESULT_OK);
4112 return;
4113 }
4114 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004115 }
4116 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004117 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004118 }, pkgFilter);
4119
4120 synchronized (this) {
4121 // Ensure that any processes we had put on hold are now started
4122 // up.
4123 final int NP = mProcessesOnHold.size();
4124 if (NP > 0) {
4125 ArrayList<ProcessRecord> procs =
4126 new ArrayList<ProcessRecord>(mProcessesOnHold);
4127 for (int ip=0; ip<NP; ip++) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004128 if (DEBUG_PROCESSES) Slog.v(TAG, "Starting process on hold: "
4129 + procs.get(ip));
4130 startProcessLocked(procs.get(ip), "on-hold", null);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004131 }
4132 }
4133
4134 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004135 // Start looking for apps that are abusing wake locks.
4136 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07004137 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004138 // Tell anyone interested that we are done booting!
Dianne Hackbornf4c454b2010-08-11 12:47:41 -07004139 SystemProperties.set("sys.boot_completed", "1");
Guang Zhu191713a2012-01-12 12:02:22 -08004140 SystemProperties.set("dev.bootcomplete", "1");
Amith Yamasani742a6712011-05-04 14:49:28 -07004141 /* TODO: Send this to all users that are to be logged in on startup */
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004142 broadcastIntentLocked(null, null,
4143 new Intent(Intent.ACTION_BOOT_COMPLETED, null),
4144 null, null, 0, null, null,
4145 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
Amith Yamasani742a6712011-05-04 14:49:28 -07004146 false, false, MY_PID, Process.SYSTEM_UID, Binder.getOrigCallingUser());
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004147 }
4148 }
4149 }
4150
4151 final void ensureBootCompleted() {
4152 boolean booting;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004153 boolean enableScreen;
4154 synchronized (this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004155 booting = mBooting;
4156 mBooting = false;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004157 enableScreen = !mBooted;
4158 mBooted = true;
4159 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004160
4161 if (booting) {
4162 finishBooting();
4163 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004164
4165 if (enableScreen) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004166 enableScreenAfterBoot();
4167 }
4168 }
4169
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004170 public final void activityPaused(IBinder token) {
4171 final long origId = Binder.clearCallingIdentity();
4172 mMainStack.activityPaused(token, false);
4173 Binder.restoreCallingIdentity(origId);
4174 }
4175
4176 public final void activityStopped(IBinder token, Bundle icicle, Bitmap thumbnail,
4177 CharSequence description) {
4178 if (localLOGV) Slog.v(
4179 TAG, "Activity stopped: token=" + token);
4180
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004181 // Refuse possible leaked file descriptors
4182 if (icicle != null && icicle.hasFileDescriptors()) {
4183 throw new IllegalArgumentException("File descriptors passed in Bundle");
4184 }
4185
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004186 ActivityRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004187
4188 final long origId = Binder.clearCallingIdentity();
4189
4190 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004191 r = mMainStack.isInStackLocked(token);
4192 if (r != null) {
4193 r.stack.activityStoppedLocked(r, icicle, thumbnail, description);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004194 }
4195 }
4196
4197 if (r != null) {
4198 sendPendingThumbnail(r, null, null, null, false);
4199 }
4200
4201 trimApplications();
4202
4203 Binder.restoreCallingIdentity(origId);
4204 }
4205
4206 public final void activityDestroyed(IBinder token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004207 if (DEBUG_SWITCH) Slog.v(TAG, "ACTIVITY DESTROYED: " + token);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004208 mMainStack.activityDestroyed(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004209 }
4210
4211 public String getCallingPackage(IBinder token) {
4212 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004213 ActivityRecord r = getCallingRecordLocked(token);
Dianne Hackborn9bbcb912009-10-20 15:42:38 -07004214 return r != null && r.app != null ? r.info.packageName : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004215 }
4216 }
4217
4218 public ComponentName getCallingActivity(IBinder token) {
4219 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004220 ActivityRecord r = getCallingRecordLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004221 return r != null ? r.intent.getComponent() : null;
4222 }
4223 }
4224
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004225 private ActivityRecord getCallingRecordLocked(IBinder token) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004226 ActivityRecord r = mMainStack.isInStackLocked(token);
4227 if (r == null) {
4228 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004229 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004230 return r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004231 }
4232
4233 public ComponentName getActivityClassForToken(IBinder token) {
4234 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004235 ActivityRecord r = mMainStack.isInStackLocked(token);
4236 if (r == null) {
4237 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004238 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004239 return r.intent.getComponent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004240 }
4241 }
4242
4243 public String getPackageForToken(IBinder token) {
4244 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004245 ActivityRecord r = mMainStack.isInStackLocked(token);
4246 if (r == null) {
4247 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004248 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004249 return r.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004250 }
4251 }
4252
4253 public IIntentSender getIntentSender(int type,
4254 String packageName, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004255 int requestCode, Intent[] intents, String[] resolvedTypes,
4256 int flags, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004257 enforceNotIsolatedCaller("getIntentSender");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004258 // Refuse possible leaked file descriptors
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004259 if (intents != null) {
4260 if (intents.length < 1) {
4261 throw new IllegalArgumentException("Intents array length must be >= 1");
4262 }
4263 for (int i=0; i<intents.length; i++) {
4264 Intent intent = intents[i];
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004265 if (intent != null) {
4266 if (intent.hasFileDescriptors()) {
4267 throw new IllegalArgumentException("File descriptors passed in Intent");
4268 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07004269 if (type == ActivityManager.INTENT_SENDER_BROADCAST &&
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004270 (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
4271 throw new IllegalArgumentException(
4272 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
4273 }
4274 intents[i] = new Intent(intent);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004275 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004276 }
4277 if (resolvedTypes != null && resolvedTypes.length != intents.length) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004278 throw new IllegalArgumentException(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004279 "Intent array length does not match resolvedTypes length");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004280 }
4281 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004282 if (options != null) {
4283 if (options.hasFileDescriptors()) {
4284 throw new IllegalArgumentException("File descriptors passed in options");
4285 }
4286 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004287
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004288 synchronized(this) {
4289 int callingUid = Binder.getCallingUid();
4290 try {
Jeff Brown10e89712011-07-08 18:52:57 -07004291 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004292 int uid = AppGlobals.getPackageManager()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004293 .getPackageUid(packageName);
Amith Yamasani742a6712011-05-04 14:49:28 -07004294 if (UserId.getAppId(callingUid) != uid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004295 String msg = "Permission Denial: getIntentSender() from pid="
4296 + Binder.getCallingPid()
4297 + ", uid=" + Binder.getCallingUid()
4298 + ", (need uid=" + uid + ")"
4299 + " is not allowed to send as package " + packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004300 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004301 throw new SecurityException(msg);
4302 }
4303 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004304
Amith Yamasani742a6712011-05-04 14:49:28 -07004305 if (DEBUG_MU)
4306 Slog.i(TAG_MU, "Getting intent sender for origCallingUid="
4307 + Binder.getOrigCallingUid());
4308 return getIntentSenderLocked(type, packageName, Binder.getOrigCallingUid(),
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004309 token, resultWho, requestCode, intents, resolvedTypes, flags, options);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004310
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004311 } catch (RemoteException e) {
4312 throw new SecurityException(e);
4313 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004314 }
4315 }
4316
4317 IIntentSender getIntentSenderLocked(int type,
4318 String packageName, int callingUid, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004319 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
4320 Bundle options) {
Amith Yamasani742a6712011-05-04 14:49:28 -07004321 if (DEBUG_MU)
4322 Slog.v(TAG_MU, "getIntentSenderLocked(): uid=" + callingUid);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004323 ActivityRecord activity = null;
Dianne Hackborna4972e92012-03-14 10:38:05 -07004324 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004325 activity = mMainStack.isInStackLocked(token);
4326 if (activity == null) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004327 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004328 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004329 if (activity.finishing) {
4330 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004331 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004332 }
4333
4334 final boolean noCreate = (flags&PendingIntent.FLAG_NO_CREATE) != 0;
4335 final boolean cancelCurrent = (flags&PendingIntent.FLAG_CANCEL_CURRENT) != 0;
4336 final boolean updateCurrent = (flags&PendingIntent.FLAG_UPDATE_CURRENT) != 0;
4337 flags &= ~(PendingIntent.FLAG_NO_CREATE|PendingIntent.FLAG_CANCEL_CURRENT
4338 |PendingIntent.FLAG_UPDATE_CURRENT);
4339
4340 PendingIntentRecord.Key key = new PendingIntentRecord.Key(
4341 type, packageName, activity, resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004342 requestCode, intents, resolvedTypes, flags, options);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004343 WeakReference<PendingIntentRecord> ref;
4344 ref = mIntentSenderRecords.get(key);
4345 PendingIntentRecord rec = ref != null ? ref.get() : null;
4346 if (rec != null) {
4347 if (!cancelCurrent) {
4348 if (updateCurrent) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004349 if (rec.key.requestIntent != null) {
4350 rec.key.requestIntent.replaceExtras(intents != null ? intents[0] : null);
4351 }
4352 if (intents != null) {
4353 intents[intents.length-1] = rec.key.requestIntent;
4354 rec.key.allIntents = intents;
4355 rec.key.allResolvedTypes = resolvedTypes;
4356 } else {
4357 rec.key.allIntents = null;
4358 rec.key.allResolvedTypes = null;
4359 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004360 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004361 return rec;
4362 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004363 rec.canceled = true;
4364 mIntentSenderRecords.remove(key);
4365 }
4366 if (noCreate) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004367 return rec;
4368 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004369 rec = new PendingIntentRecord(this, key, callingUid);
4370 mIntentSenderRecords.put(key, rec.ref);
Dianne Hackborna4972e92012-03-14 10:38:05 -07004371 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004372 if (activity.pendingResults == null) {
4373 activity.pendingResults
4374 = new HashSet<WeakReference<PendingIntentRecord>>();
4375 }
4376 activity.pendingResults.add(rec.ref);
4377 }
4378 return rec;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004379 }
4380
4381 public void cancelIntentSender(IIntentSender sender) {
4382 if (!(sender instanceof PendingIntentRecord)) {
4383 return;
4384 }
4385 synchronized(this) {
4386 PendingIntentRecord rec = (PendingIntentRecord)sender;
4387 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004388 int uid = AppGlobals.getPackageManager()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004389 .getPackageUid(rec.key.packageName);
Amith Yamasani04e0d262012-02-14 11:50:53 -08004390 if (!UserId.isSameApp(uid, Binder.getCallingUid())) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004391 String msg = "Permission Denial: cancelIntentSender() from pid="
4392 + Binder.getCallingPid()
4393 + ", uid=" + Binder.getCallingUid()
4394 + " is not allowed to cancel packges "
4395 + rec.key.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004396 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004397 throw new SecurityException(msg);
4398 }
4399 } catch (RemoteException e) {
4400 throw new SecurityException(e);
4401 }
4402 cancelIntentSenderLocked(rec, true);
4403 }
4404 }
4405
4406 void cancelIntentSenderLocked(PendingIntentRecord rec, boolean cleanActivity) {
4407 rec.canceled = true;
4408 mIntentSenderRecords.remove(rec.key);
4409 if (cleanActivity && rec.key.activity != null) {
4410 rec.key.activity.pendingResults.remove(rec.ref);
4411 }
4412 }
4413
4414 public String getPackageForIntentSender(IIntentSender pendingResult) {
4415 if (!(pendingResult instanceof PendingIntentRecord)) {
4416 return null;
4417 }
Brad Fitzpatrickb213d102010-04-19 11:58:52 -07004418 try {
4419 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4420 return res.key.packageName;
4421 } catch (ClassCastException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004422 }
4423 return null;
4424 }
4425
Dianne Hackborn6c418d52011-06-29 14:05:33 -07004426 public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) {
4427 if (!(pendingResult instanceof PendingIntentRecord)) {
4428 return false;
4429 }
4430 try {
4431 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4432 if (res.key.allIntents == null) {
4433 return false;
4434 }
4435 for (int i=0; i<res.key.allIntents.length; i++) {
4436 Intent intent = res.key.allIntents[i];
4437 if (intent.getPackage() != null && intent.getComponent() != null) {
4438 return false;
4439 }
4440 }
4441 return true;
4442 } catch (ClassCastException e) {
4443 }
4444 return false;
4445 }
4446
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004447 public void setProcessLimit(int max) {
4448 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4449 "setProcessLimit()");
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004450 synchronized (this) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07004451 mProcessLimit = max < 0 ? ProcessList.MAX_HIDDEN_APPS : max;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004452 mProcessLimitOverride = max;
4453 }
4454 trimApplications();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004455 }
4456
4457 public int getProcessLimit() {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004458 synchronized (this) {
4459 return mProcessLimitOverride;
4460 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004461 }
4462
4463 void foregroundTokenDied(ForegroundToken token) {
4464 synchronized (ActivityManagerService.this) {
4465 synchronized (mPidsSelfLocked) {
4466 ForegroundToken cur
4467 = mForegroundProcesses.get(token.pid);
4468 if (cur != token) {
4469 return;
4470 }
4471 mForegroundProcesses.remove(token.pid);
4472 ProcessRecord pr = mPidsSelfLocked.get(token.pid);
4473 if (pr == null) {
4474 return;
4475 }
4476 pr.forcingToForeground = null;
4477 pr.foregroundServices = false;
4478 }
4479 updateOomAdjLocked();
4480 }
4481 }
4482
4483 public void setProcessForeground(IBinder token, int pid, boolean isForeground) {
4484 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4485 "setProcessForeground()");
4486 synchronized(this) {
4487 boolean changed = false;
4488
4489 synchronized (mPidsSelfLocked) {
4490 ProcessRecord pr = mPidsSelfLocked.get(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004491 if (pr == null && isForeground) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004492 Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004493 return;
4494 }
4495 ForegroundToken oldToken = mForegroundProcesses.get(pid);
4496 if (oldToken != null) {
4497 oldToken.token.unlinkToDeath(oldToken, 0);
4498 mForegroundProcesses.remove(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004499 if (pr != null) {
4500 pr.forcingToForeground = null;
4501 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004502 changed = true;
4503 }
4504 if (isForeground && token != null) {
4505 ForegroundToken newToken = new ForegroundToken() {
4506 public void binderDied() {
4507 foregroundTokenDied(this);
4508 }
4509 };
4510 newToken.pid = pid;
4511 newToken.token = token;
4512 try {
4513 token.linkToDeath(newToken, 0);
4514 mForegroundProcesses.put(pid, newToken);
4515 pr.forcingToForeground = token;
4516 changed = true;
4517 } catch (RemoteException e) {
4518 // If the process died while doing this, we will later
4519 // do the cleanup with the process death link.
4520 }
4521 }
4522 }
4523
4524 if (changed) {
4525 updateOomAdjLocked();
4526 }
4527 }
4528 }
4529
4530 // =========================================================
4531 // PERMISSIONS
4532 // =========================================================
4533
4534 static class PermissionController extends IPermissionController.Stub {
4535 ActivityManagerService mActivityManagerService;
4536 PermissionController(ActivityManagerService activityManagerService) {
4537 mActivityManagerService = activityManagerService;
4538 }
4539
4540 public boolean checkPermission(String permission, int pid, int uid) {
4541 return mActivityManagerService.checkPermission(permission, pid,
4542 uid) == PackageManager.PERMISSION_GRANTED;
4543 }
4544 }
4545
4546 /**
4547 * This can be called with or without the global lock held.
4548 */
4549 int checkComponentPermission(String permission, int pid, int uid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004550 int owningUid, boolean exported) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004551 // We might be performing an operation on behalf of an indirect binder
4552 // invocation, e.g. via {@link #openContentUri}. Check and adjust the
4553 // client identity accordingly before proceeding.
4554 Identity tlsIdentity = sCallerIdentity.get();
4555 if (tlsIdentity != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004556 Slog.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004557 + tlsIdentity.pid + "," + tlsIdentity.uid + "}");
4558 uid = tlsIdentity.uid;
4559 pid = tlsIdentity.pid;
4560 }
4561
4562 // Root, system server and our own process get to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07004563 if (uid == 0 || uid == Process.SYSTEM_UID || pid == MY_PID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004564 return PackageManager.PERMISSION_GRANTED;
4565 }
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004566 // Isolated processes don't get any permissions.
4567 if (UserId.isIsolated(uid)) {
4568 return PackageManager.PERMISSION_DENIED;
4569 }
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004570 // If there is a uid that owns whatever is being accessed, it has
4571 // blanket access to it regardless of the permissions it requires.
Amith Yamasani742a6712011-05-04 14:49:28 -07004572 if (owningUid >= 0 && UserId.isSameApp(uid, owningUid)) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004573 return PackageManager.PERMISSION_GRANTED;
4574 }
4575 // If the target is not exported, then nobody else can get to it.
4576 if (!exported) {
4577 Slog.w(TAG, "Permission denied: checkComponentPermission() owningUid=" + owningUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004578 return PackageManager.PERMISSION_DENIED;
4579 }
4580 if (permission == null) {
4581 return PackageManager.PERMISSION_GRANTED;
4582 }
4583 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004584 return AppGlobals.getPackageManager()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004585 .checkUidPermission(permission, uid);
4586 } catch (RemoteException e) {
4587 // Should never happen, but if it does... deny!
Joe Onorato8a9b2202010-02-26 18:56:32 -08004588 Slog.e(TAG, "PackageManager is dead?!?", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004589 }
4590 return PackageManager.PERMISSION_DENIED;
4591 }
4592
4593 /**
4594 * As the only public entry point for permissions checking, this method
4595 * can enforce the semantic that requesting a check on a null global
4596 * permission is automatically denied. (Internally a null permission
4597 * string is used when calling {@link #checkComponentPermission} in cases
4598 * when only uid-based security is needed.)
4599 *
4600 * This can be called with or without the global lock held.
4601 */
4602 public int checkPermission(String permission, int pid, int uid) {
4603 if (permission == null) {
4604 return PackageManager.PERMISSION_DENIED;
4605 }
Amith Yamasani742a6712011-05-04 14:49:28 -07004606 return checkComponentPermission(permission, pid, UserId.getAppId(uid), -1, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004607 }
4608
4609 /**
4610 * Binder IPC calls go through the public entry point.
4611 * This can be called with or without the global lock held.
4612 */
4613 int checkCallingPermission(String permission) {
4614 return checkPermission(permission,
4615 Binder.getCallingPid(),
Amith Yamasani742a6712011-05-04 14:49:28 -07004616 UserId.getAppId(Binder.getCallingUid()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004617 }
4618
4619 /**
4620 * This can be called with or without the global lock held.
4621 */
4622 void enforceCallingPermission(String permission, String func) {
4623 if (checkCallingPermission(permission)
4624 == PackageManager.PERMISSION_GRANTED) {
4625 return;
4626 }
4627
4628 String msg = "Permission Denial: " + func + " from pid="
4629 + Binder.getCallingPid()
4630 + ", uid=" + Binder.getCallingUid()
4631 + " requires " + permission;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004632 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004633 throw new SecurityException(msg);
4634 }
4635
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004636 /**
4637 * Determine if UID is holding permissions required to access {@link Uri} in
4638 * the given {@link ProviderInfo}. Final permission checking is always done
4639 * in {@link ContentProvider}.
4640 */
4641 private final boolean checkHoldingPermissionsLocked(
4642 IPackageManager pm, ProviderInfo pi, Uri uri, int uid, int modeFlags) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004643 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4644 "checkHoldingPermissionsLocked: uri=" + uri + " uid=" + uid);
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004645
4646 if (pi.applicationInfo.uid == uid) {
4647 return true;
4648 } else if (!pi.exported) {
4649 return false;
4650 }
4651
4652 boolean readMet = (modeFlags & Intent.FLAG_GRANT_READ_URI_PERMISSION) == 0;
4653 boolean writeMet = (modeFlags & Intent.FLAG_GRANT_WRITE_URI_PERMISSION) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004654 try {
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004655 // check if target holds top-level <provider> permissions
4656 if (!readMet && pi.readPermission != null
4657 && (pm.checkUidPermission(pi.readPermission, uid) == PERMISSION_GRANTED)) {
4658 readMet = true;
4659 }
4660 if (!writeMet && pi.writePermission != null
4661 && (pm.checkUidPermission(pi.writePermission, uid) == PERMISSION_GRANTED)) {
4662 writeMet = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004663 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004664
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004665 // track if unprotected read/write is allowed; any denied
4666 // <path-permission> below removes this ability
4667 boolean allowDefaultRead = pi.readPermission == null;
4668 boolean allowDefaultWrite = pi.writePermission == null;
Dianne Hackborn48058e82010-09-27 16:53:23 -07004669
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004670 // check if target holds any <path-permission> that match uri
4671 final PathPermission[] pps = pi.pathPermissions;
4672 if (pps != null) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004673 final String path = uri.getPath();
4674 int i = pps.length;
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004675 while (i > 0 && (!readMet || !writeMet)) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004676 i--;
4677 PathPermission pp = pps[i];
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004678 if (pp.match(path)) {
4679 if (!readMet) {
4680 final String pprperm = pp.getReadPermission();
4681 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking read perm for "
4682 + pprperm + " for " + pp.getPath()
4683 + ": match=" + pp.match(path)
4684 + " check=" + pm.checkUidPermission(pprperm, uid));
4685 if (pprperm != null) {
4686 if (pm.checkUidPermission(pprperm, uid) == PERMISSION_GRANTED) {
4687 readMet = true;
4688 } else {
4689 allowDefaultRead = false;
4690 }
4691 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004692 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004693 if (!writeMet) {
4694 final String ppwperm = pp.getWritePermission();
4695 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking write perm "
4696 + ppwperm + " for " + pp.getPath()
4697 + ": match=" + pp.match(path)
4698 + " check=" + pm.checkUidPermission(ppwperm, uid));
4699 if (ppwperm != null) {
4700 if (pm.checkUidPermission(ppwperm, uid) == PERMISSION_GRANTED) {
4701 writeMet = true;
4702 } else {
4703 allowDefaultWrite = false;
4704 }
4705 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004706 }
4707 }
4708 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07004709 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004710
4711 // grant unprotected <provider> read/write, if not blocked by
4712 // <path-permission> above
4713 if (allowDefaultRead) readMet = true;
4714 if (allowDefaultWrite) writeMet = true;
4715
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004716 } catch (RemoteException e) {
4717 return false;
4718 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004719
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004720 return readMet && writeMet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004721 }
4722
4723 private final boolean checkUriPermissionLocked(Uri uri, int uid,
4724 int modeFlags) {
4725 // Root gets to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07004726 if (uid == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004727 return true;
4728 }
4729 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(uid);
4730 if (perms == null) return false;
4731 UriPermission perm = perms.get(uri);
4732 if (perm == null) return false;
4733 return (modeFlags&perm.modeFlags) == modeFlags;
4734 }
4735
4736 public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004737 enforceNotIsolatedCaller("checkUriPermission");
4738
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004739 // Another redirected-binder-call permissions check as in
4740 // {@link checkComponentPermission}.
4741 Identity tlsIdentity = sCallerIdentity.get();
4742 if (tlsIdentity != null) {
4743 uid = tlsIdentity.uid;
4744 pid = tlsIdentity.pid;
4745 }
4746
Amith Yamasani742a6712011-05-04 14:49:28 -07004747 uid = UserId.getAppId(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004748 // Our own process gets to do everything.
4749 if (pid == MY_PID) {
4750 return PackageManager.PERMISSION_GRANTED;
4751 }
4752 synchronized(this) {
4753 return checkUriPermissionLocked(uri, uid, modeFlags)
4754 ? PackageManager.PERMISSION_GRANTED
4755 : PackageManager.PERMISSION_DENIED;
4756 }
4757 }
4758
Dianne Hackborn39792d22010-08-19 18:01:52 -07004759 /**
4760 * Check if the targetPkg can be granted permission to access uri by
4761 * the callingUid using the given modeFlags. Throws a security exception
4762 * if callingUid is not allowed to do this. Returns the uid of the target
4763 * if the URI permission grant should be performed; returns -1 if it is not
4764 * needed (for example targetPkg already has permission to access the URI).
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004765 * If you already know the uid of the target, you can supply it in
4766 * lastTargetUid else set that to -1.
Dianne Hackborn39792d22010-08-19 18:01:52 -07004767 */
4768 int checkGrantUriPermissionLocked(int callingUid, String targetPkg,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004769 Uri uri, int modeFlags, int lastTargetUid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004770 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4771 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4772 if (modeFlags == 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004773 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004774 }
4775
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004776 if (targetPkg != null) {
4777 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4778 "Checking grant " + targetPkg + " permission to " + uri);
4779 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004780
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004781 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004782
4783 // If this is not a content: uri, we can't do anything with it.
4784 if (!ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004785 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004786 "Can't grant URI permission for non-content URI: " + uri);
Dianne Hackborn39792d22010-08-19 18:01:52 -07004787 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004788 }
4789
4790 String name = uri.getAuthority();
4791 ProviderInfo pi = null;
Amith Yamasani742a6712011-05-04 14:49:28 -07004792 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
4793 UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004794 if (cpr != null) {
4795 pi = cpr.info;
4796 } else {
4797 try {
4798 pi = pm.resolveContentProvider(name,
4799 PackageManager.GET_URI_PERMISSION_PATTERNS);
4800 } catch (RemoteException ex) {
4801 }
4802 }
4803 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07004804 Slog.w(TAG, "No content provider found for permission check: " + uri.toSafeString());
Dianne Hackborn39792d22010-08-19 18:01:52 -07004805 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004806 }
4807
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004808 int targetUid = lastTargetUid;
4809 if (targetUid < 0 && targetPkg != null) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004810 try {
4811 targetUid = pm.getPackageUid(targetPkg);
4812 if (targetUid < 0) {
4813 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4814 "Can't grant URI permission no uid for: " + targetPkg);
4815 return -1;
4816 }
4817 } catch (RemoteException ex) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004818 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004819 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004820 }
4821
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004822 if (targetUid >= 0) {
4823 // First... does the target actually need this permission?
4824 if (checkHoldingPermissionsLocked(pm, pi, uri, targetUid, modeFlags)) {
4825 // No need to grant the target this permission.
4826 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4827 "Target " + targetPkg + " already has full permission to " + uri);
4828 return -1;
4829 }
4830 } else {
4831 // First... there is no target package, so can anyone access it?
4832 boolean allowed = pi.exported;
4833 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
4834 if (pi.readPermission != null) {
4835 allowed = false;
4836 }
4837 }
4838 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
4839 if (pi.writePermission != null) {
4840 allowed = false;
4841 }
4842 }
4843 if (allowed) {
4844 return -1;
4845 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004846 }
4847
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004848 // Second... is the provider allowing granting of URI permissions?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004849 if (!pi.grantUriPermissions) {
4850 throw new SecurityException("Provider " + pi.packageName
4851 + "/" + pi.name
4852 + " does not allow granting of Uri permissions (uri "
4853 + uri + ")");
4854 }
4855 if (pi.uriPermissionPatterns != null) {
4856 final int N = pi.uriPermissionPatterns.length;
4857 boolean allowed = false;
4858 for (int i=0; i<N; i++) {
4859 if (pi.uriPermissionPatterns[i] != null
4860 && pi.uriPermissionPatterns[i].match(uri.getPath())) {
4861 allowed = true;
4862 break;
4863 }
4864 }
4865 if (!allowed) {
4866 throw new SecurityException("Provider " + pi.packageName
4867 + "/" + pi.name
4868 + " does not allow granting of permission to path of Uri "
4869 + uri);
4870 }
4871 }
4872
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004873 // Third... does the caller itself have permission to access
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004874 // this uri?
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004875 if (callingUid != Process.myUid()) {
4876 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
4877 if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
4878 throw new SecurityException("Uid " + callingUid
4879 + " does not have permission to uri " + uri);
4880 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004881 }
4882 }
4883
Dianne Hackborn39792d22010-08-19 18:01:52 -07004884 return targetUid;
4885 }
4886
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004887 public int checkGrantUriPermission(int callingUid, String targetPkg,
4888 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004889 enforceNotIsolatedCaller("checkGrantUriPermission");
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004890 synchronized(this) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004891 return checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004892 }
4893 }
4894
Dianne Hackborn39792d22010-08-19 18:01:52 -07004895 void grantUriPermissionUncheckedLocked(int targetUid, String targetPkg,
4896 Uri uri, int modeFlags, UriPermissionOwner owner) {
4897 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4898 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4899 if (modeFlags == 0) {
4900 return;
4901 }
4902
4903 // So here we are: the caller has the assumed permission
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004904 // to the uri, and the target doesn't. Let's now give this to
4905 // the target.
4906
Joe Onorato8a9b2202010-02-26 18:56:32 -08004907 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn39792d22010-08-19 18:01:52 -07004908 "Granting " + targetPkg + "/" + targetUid + " permission to " + uri);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004909
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004910 HashMap<Uri, UriPermission> targetUris
4911 = mGrantedUriPermissions.get(targetUid);
4912 if (targetUris == null) {
4913 targetUris = new HashMap<Uri, UriPermission>();
4914 mGrantedUriPermissions.put(targetUid, targetUris);
4915 }
4916
4917 UriPermission perm = targetUris.get(uri);
4918 if (perm == null) {
4919 perm = new UriPermission(targetUid, uri);
4920 targetUris.put(uri, perm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004921 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07004922
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004923 perm.modeFlags |= modeFlags;
Dianne Hackborn39792d22010-08-19 18:01:52 -07004924 if (owner == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004925 perm.globalModeFlags |= modeFlags;
Vairavan Srinivasan91c12c22011-01-21 18:26:06 -08004926 } else {
4927 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
4928 perm.readOwners.add(owner);
4929 owner.addReadPermission(perm);
4930 }
4931 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
4932 perm.writeOwners.add(owner);
4933 owner.addWritePermission(perm);
4934 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004935 }
4936 }
4937
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004938 void grantUriPermissionLocked(int callingUid, String targetPkg, Uri uri,
4939 int modeFlags, UriPermissionOwner owner) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004940 if (targetPkg == null) {
4941 throw new NullPointerException("targetPkg");
4942 }
4943
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004944 int targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn39792d22010-08-19 18:01:52 -07004945 if (targetUid < 0) {
4946 return;
4947 }
4948
4949 grantUriPermissionUncheckedLocked(targetUid, targetPkg, uri, modeFlags, owner);
4950 }
4951
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004952 static class NeededUriGrants extends ArrayList<Uri> {
4953 final String targetPkg;
4954 final int targetUid;
4955 final int flags;
4956
4957 NeededUriGrants(String _targetPkg, int _targetUid, int _flags) {
4958 targetPkg = _targetPkg;
4959 targetUid = _targetUid;
4960 flags = _flags;
4961 }
4962 }
4963
Dianne Hackborn39792d22010-08-19 18:01:52 -07004964 /**
4965 * Like checkGrantUriPermissionLocked, but takes an Intent.
4966 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004967 NeededUriGrants checkGrantUriPermissionFromIntentLocked(int callingUid,
4968 String targetPkg, Intent intent, int mode, NeededUriGrants needed) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07004969 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004970 "Checking URI perm to data=" + (intent != null ? intent.getData() : null)
4971 + " clip=" + (intent != null ? intent.getClipData() : null)
Dianne Hackbornb424b632010-08-18 15:59:05 -07004972 + " from " + intent + "; flags=0x"
4973 + Integer.toHexString(intent != null ? intent.getFlags() : 0));
4974
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004975 if (targetPkg == null) {
4976 throw new NullPointerException("targetPkg");
4977 }
4978
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004979 if (intent == null) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004980 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004981 }
4982 Uri data = intent.getData();
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004983 ClipData clip = intent.getClipData();
4984 if (data == null && clip == null) {
4985 return null;
Dianne Hackborn39792d22010-08-19 18:01:52 -07004986 }
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004987 if (data != null) {
4988 int target = checkGrantUriPermissionLocked(callingUid, targetPkg, data,
4989 mode, needed != null ? needed.targetUid : -1);
4990 if (target > 0) {
4991 if (needed == null) {
4992 needed = new NeededUriGrants(targetPkg, target, mode);
4993 }
4994 needed.add(data);
4995 }
4996 }
4997 if (clip != null) {
4998 for (int i=0; i<clip.getItemCount(); i++) {
4999 Uri uri = clip.getItemAt(i).getUri();
5000 if (uri != null) {
5001 int target = -1;
5002 target = checkGrantUriPermissionLocked(callingUid, targetPkg, uri,
5003 mode, needed != null ? needed.targetUid : -1);
5004 if (target > 0) {
5005 if (needed == null) {
5006 needed = new NeededUriGrants(targetPkg, target, mode);
5007 }
5008 needed.add(uri);
5009 }
5010 } else {
5011 Intent clipIntent = clip.getItemAt(i).getIntent();
5012 if (clipIntent != null) {
5013 NeededUriGrants newNeeded = checkGrantUriPermissionFromIntentLocked(
5014 callingUid, targetPkg, clipIntent, mode, needed);
5015 if (newNeeded != null) {
5016 needed = newNeeded;
5017 }
5018 }
5019 }
5020 }
5021 }
5022
5023 return needed;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005024 }
5025
5026 /**
5027 * Like grantUriPermissionUncheckedLocked, but takes an Intent.
5028 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005029 void grantUriPermissionUncheckedFromIntentLocked(NeededUriGrants needed,
5030 UriPermissionOwner owner) {
5031 if (needed != null) {
5032 for (int i=0; i<needed.size(); i++) {
5033 grantUriPermissionUncheckedLocked(needed.targetUid, needed.targetPkg,
5034 needed.get(i), needed.flags, owner);
5035 }
5036 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005037 }
5038
5039 void grantUriPermissionFromIntentLocked(int callingUid,
5040 String targetPkg, Intent intent, UriPermissionOwner owner) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005041 NeededUriGrants needed = checkGrantUriPermissionFromIntentLocked(callingUid, targetPkg,
Dianne Hackbornd9781fe2012-03-08 18:04:18 -08005042 intent, intent != null ? intent.getFlags() : 0, null);
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005043 if (needed == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005044 return;
5045 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005046
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005047 grantUriPermissionUncheckedFromIntentLocked(needed, owner);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005048 }
5049
5050 public void grantUriPermission(IApplicationThread caller, String targetPkg,
5051 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005052 enforceNotIsolatedCaller("grantUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005053 synchronized(this) {
5054 final ProcessRecord r = getRecordForAppLocked(caller);
5055 if (r == null) {
5056 throw new SecurityException("Unable to find app for caller "
5057 + caller
5058 + " when granting permission to uri " + uri);
5059 }
5060 if (targetPkg == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005061 throw new IllegalArgumentException("null target");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005062 }
5063 if (uri == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005064 throw new IllegalArgumentException("null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005065 }
5066
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005067 grantUriPermissionLocked(r.uid, targetPkg, uri, modeFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005068 null);
5069 }
5070 }
5071
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005072 void removeUriPermissionIfNeededLocked(UriPermission perm) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005073 if ((perm.modeFlags&(Intent.FLAG_GRANT_READ_URI_PERMISSION
5074 |Intent.FLAG_GRANT_WRITE_URI_PERMISSION)) == 0) {
5075 HashMap<Uri, UriPermission> perms
5076 = mGrantedUriPermissions.get(perm.uid);
5077 if (perms != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005078 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005079 "Removing " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005080 perms.remove(perm.uri);
5081 if (perms.size() == 0) {
5082 mGrantedUriPermissions.remove(perm.uid);
5083 }
5084 }
5085 }
5086 }
5087
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005088 private void revokeUriPermissionLocked(int callingUid, Uri uri,
5089 int modeFlags) {
5090 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5091 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5092 if (modeFlags == 0) {
5093 return;
5094 }
5095
Joe Onorato8a9b2202010-02-26 18:56:32 -08005096 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005097 "Revoking all granted permissions to " + uri);
5098
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005099 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005100
5101 final String authority = uri.getAuthority();
5102 ProviderInfo pi = null;
Amith Yamasani742a6712011-05-04 14:49:28 -07005103 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority,
5104 UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005105 if (cpr != null) {
5106 pi = cpr.info;
5107 } else {
5108 try {
5109 pi = pm.resolveContentProvider(authority,
5110 PackageManager.GET_URI_PERMISSION_PATTERNS);
5111 } catch (RemoteException ex) {
5112 }
5113 }
5114 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005115 Slog.w(TAG, "No content provider found for permission revoke: " + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005116 return;
5117 }
5118
5119 // Does the caller have this permission on the URI?
Dianne Hackborn48058e82010-09-27 16:53:23 -07005120 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005121 // Right now, if you are not the original owner of the permission,
5122 // you are not allowed to revoke it.
5123 //if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5124 throw new SecurityException("Uid " + callingUid
5125 + " does not have permission to uri " + uri);
5126 //}
5127 }
5128
5129 // Go through all of the permissions and remove any that match.
5130 final List<String> SEGMENTS = uri.getPathSegments();
5131 if (SEGMENTS != null) {
5132 final int NS = SEGMENTS.size();
5133 int N = mGrantedUriPermissions.size();
5134 for (int i=0; i<N; i++) {
5135 HashMap<Uri, UriPermission> perms
5136 = mGrantedUriPermissions.valueAt(i);
5137 Iterator<UriPermission> it = perms.values().iterator();
5138 toploop:
5139 while (it.hasNext()) {
5140 UriPermission perm = it.next();
5141 Uri targetUri = perm.uri;
5142 if (!authority.equals(targetUri.getAuthority())) {
5143 continue;
5144 }
5145 List<String> targetSegments = targetUri.getPathSegments();
5146 if (targetSegments == null) {
5147 continue;
5148 }
5149 if (targetSegments.size() < NS) {
5150 continue;
5151 }
5152 for (int j=0; j<NS; j++) {
5153 if (!SEGMENTS.get(j).equals(targetSegments.get(j))) {
5154 continue toploop;
5155 }
5156 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08005157 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005158 "Revoking " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005159 perm.clearModes(modeFlags);
5160 if (perm.modeFlags == 0) {
5161 it.remove();
5162 }
5163 }
5164 if (perms.size() == 0) {
5165 mGrantedUriPermissions.remove(
5166 mGrantedUriPermissions.keyAt(i));
5167 N--;
5168 i--;
5169 }
5170 }
5171 }
5172 }
5173
5174 public void revokeUriPermission(IApplicationThread caller, Uri uri,
5175 int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005176 enforceNotIsolatedCaller("revokeUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005177 synchronized(this) {
5178 final ProcessRecord r = getRecordForAppLocked(caller);
5179 if (r == null) {
5180 throw new SecurityException("Unable to find app for caller "
5181 + caller
5182 + " when revoking permission to uri " + uri);
5183 }
5184 if (uri == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005185 Slog.w(TAG, "revokeUriPermission: null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005186 return;
5187 }
5188
5189 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5190 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5191 if (modeFlags == 0) {
5192 return;
5193 }
5194
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005195 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005196
5197 final String authority = uri.getAuthority();
5198 ProviderInfo pi = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005199 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005200 if (cpr != null) {
5201 pi = cpr.info;
5202 } else {
5203 try {
5204 pi = pm.resolveContentProvider(authority,
5205 PackageManager.GET_URI_PERMISSION_PATTERNS);
5206 } catch (RemoteException ex) {
5207 }
5208 }
5209 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005210 Slog.w(TAG, "No content provider found for permission revoke: "
5211 + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005212 return;
5213 }
5214
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005215 revokeUriPermissionLocked(r.uid, uri, modeFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005216 }
5217 }
5218
Dianne Hackborn7e269642010-08-25 19:50:20 -07005219 @Override
5220 public IBinder newUriPermissionOwner(String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005221 enforceNotIsolatedCaller("newUriPermissionOwner");
Dianne Hackborn7e269642010-08-25 19:50:20 -07005222 synchronized(this) {
5223 UriPermissionOwner owner = new UriPermissionOwner(this, name);
5224 return owner.getExternalTokenLocked();
5225 }
5226 }
5227
5228 @Override
5229 public void grantUriPermissionFromOwner(IBinder token, int fromUid, String targetPkg,
5230 Uri uri, int modeFlags) {
5231 synchronized(this) {
5232 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5233 if (owner == null) {
5234 throw new IllegalArgumentException("Unknown owner: " + token);
5235 }
5236 if (fromUid != Binder.getCallingUid()) {
5237 if (Binder.getCallingUid() != Process.myUid()) {
5238 // Only system code can grant URI permissions on behalf
5239 // of other users.
5240 throw new SecurityException("nice try");
5241 }
5242 }
5243 if (targetPkg == null) {
5244 throw new IllegalArgumentException("null target");
5245 }
5246 if (uri == null) {
5247 throw new IllegalArgumentException("null uri");
5248 }
5249
5250 grantUriPermissionLocked(fromUid, targetPkg, uri, modeFlags, owner);
5251 }
5252 }
5253
5254 @Override
5255 public void revokeUriPermissionFromOwner(IBinder token, Uri uri, int mode) {
5256 synchronized(this) {
5257 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5258 if (owner == null) {
5259 throw new IllegalArgumentException("Unknown owner: " + token);
5260 }
5261
5262 if (uri == null) {
5263 owner.removeUriPermissionsLocked(mode);
5264 } else {
5265 owner.removeUriPermissionLocked(uri, mode);
5266 }
5267 }
5268 }
5269
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005270 public void showWaitingForDebugger(IApplicationThread who, boolean waiting) {
5271 synchronized (this) {
5272 ProcessRecord app =
5273 who != null ? getRecordForAppLocked(who) : null;
5274 if (app == null) return;
5275
5276 Message msg = Message.obtain();
5277 msg.what = WAIT_FOR_DEBUGGER_MSG;
5278 msg.obj = app;
5279 msg.arg1 = waiting ? 1 : 0;
5280 mHandler.sendMessage(msg);
5281 }
5282 }
5283
5284 public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07005285 final long homeAppMem = mProcessList.getMemLevel(ProcessList.HOME_APP_ADJ);
5286 final long hiddenAppMem = mProcessList.getMemLevel(ProcessList.HIDDEN_APP_MIN_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005287 outInfo.availMem = Process.getFreeMemory();
Dianne Hackborn7d608422011-08-07 16:24:18 -07005288 outInfo.threshold = homeAppMem;
5289 outInfo.lowMemory = outInfo.availMem < (homeAppMem + ((hiddenAppMem-homeAppMem)/2));
5290 outInfo.hiddenAppThreshold = hiddenAppMem;
5291 outInfo.secondaryServerThreshold = mProcessList.getMemLevel(
Dianne Hackborne02c88a2011-10-28 13:58:15 -07005292 ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07005293 outInfo.visibleAppThreshold = mProcessList.getMemLevel(
5294 ProcessList.VISIBLE_APP_ADJ);
5295 outInfo.foregroundAppThreshold = mProcessList.getMemLevel(
5296 ProcessList.FOREGROUND_APP_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005297 }
5298
5299 // =========================================================
5300 // TASK MANAGEMENT
5301 // =========================================================
5302
5303 public List getTasks(int maxNum, int flags,
5304 IThumbnailReceiver receiver) {
5305 ArrayList list = new ArrayList();
5306
5307 PendingThumbnailsRecord pending = null;
5308 IApplicationThread topThumbnail = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005309 ActivityRecord topRecord = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005310
5311 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005312 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005313 TAG, "getTasks: max=" + maxNum + ", flags=" + flags
5314 + ", receiver=" + receiver);
5315
5316 if (checkCallingPermission(android.Manifest.permission.GET_TASKS)
5317 != PackageManager.PERMISSION_GRANTED) {
5318 if (receiver != null) {
5319 // If the caller wants to wait for pending thumbnails,
5320 // it ain't gonna get them.
5321 try {
5322 receiver.finished();
5323 } catch (RemoteException ex) {
5324 }
5325 }
5326 String msg = "Permission Denial: getTasks() from pid="
5327 + Binder.getCallingPid()
5328 + ", uid=" + Binder.getCallingUid()
5329 + " requires " + android.Manifest.permission.GET_TASKS;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005330 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005331 throw new SecurityException(msg);
5332 }
5333
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005334 int pos = mMainStack.mHistory.size()-1;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005335 ActivityRecord next =
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005336 pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005337 ActivityRecord top = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005338 TaskRecord curTask = null;
5339 int numActivities = 0;
5340 int numRunning = 0;
5341 while (pos >= 0 && maxNum > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005342 final ActivityRecord r = next;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005343 pos--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005344 next = pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005345
5346 // Initialize state for next task if needed.
5347 if (top == null ||
5348 (top.state == ActivityState.INITIALIZING
5349 && top.task == r.task)) {
5350 top = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005351 curTask = r.task;
5352 numActivities = numRunning = 0;
5353 }
5354
5355 // Add 'r' into the current task.
5356 numActivities++;
5357 if (r.app != null && r.app.thread != null) {
5358 numRunning++;
5359 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005360
Joe Onorato8a9b2202010-02-26 18:56:32 -08005361 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005362 TAG, r.intent.getComponent().flattenToShortString()
5363 + ": task=" + r.task);
5364
5365 // If the next one is a different task, generate a new
5366 // TaskInfo entry for what we have.
5367 if (next == null || next.task != curTask) {
5368 ActivityManager.RunningTaskInfo ci
5369 = new ActivityManager.RunningTaskInfo();
5370 ci.id = curTask.taskId;
5371 ci.baseActivity = r.intent.getComponent();
5372 ci.topActivity = top.intent.getComponent();
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005373 if (top.thumbHolder != null) {
5374 ci.description = top.thumbHolder.lastDescription;
5375 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005376 ci.numActivities = numActivities;
5377 ci.numRunning = numRunning;
5378 //System.out.println(
5379 // "#" + maxNum + ": " + " descr=" + ci.description);
5380 if (ci.thumbnail == null && receiver != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005381 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005382 TAG, "State=" + top.state + "Idle=" + top.idle
5383 + " app=" + top.app
5384 + " thr=" + (top.app != null ? top.app.thread : null));
5385 if (top.state == ActivityState.RESUMED
5386 || top.state == ActivityState.PAUSING) {
5387 if (top.idle && top.app != null
5388 && top.app.thread != null) {
5389 topRecord = top;
5390 topThumbnail = top.app.thread;
5391 } else {
5392 top.thumbnailNeeded = true;
5393 }
5394 }
5395 if (pending == null) {
5396 pending = new PendingThumbnailsRecord(receiver);
5397 }
5398 pending.pendingRecords.add(top);
5399 }
5400 list.add(ci);
5401 maxNum--;
5402 top = null;
5403 }
5404 }
5405
5406 if (pending != null) {
5407 mPendingThumbnails.add(pending);
5408 }
5409 }
5410
Joe Onorato8a9b2202010-02-26 18:56:32 -08005411 if (localLOGV) Slog.v(TAG, "We have pending thumbnails: " + pending);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005412
5413 if (topThumbnail != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005414 if (localLOGV) Slog.v(TAG, "Requesting top thumbnail");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005415 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08005416 topThumbnail.requestThumbnail(topRecord.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005417 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005418 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005419 sendPendingThumbnail(null, topRecord.appToken, null, null, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005420 }
5421 }
5422
5423 if (pending == null && receiver != null) {
5424 // In this case all thumbnails were available and the client
5425 // is being asked to be told when the remaining ones come in...
5426 // which is unusually, since the top-most currently running
5427 // activity should never have a canned thumbnail! Oh well.
5428 try {
5429 receiver.finished();
5430 } catch (RemoteException ex) {
5431 }
5432 }
5433
5434 return list;
5435 }
5436
5437 public List<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum,
5438 int flags) {
Amith Yamasani742a6712011-05-04 14:49:28 -07005439 final int callingUid = Binder.getCallingUid();
5440 // If it's the system uid asking, then use the current user id.
5441 // TODO: Make sure that there aren't any other legitimate calls from the system uid that
5442 // require the entire list.
5443 final int callingUserId = callingUid == Process.SYSTEM_UID
5444 ? mCurrentUserId : UserId.getUserId(callingUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005445 synchronized (this) {
5446 enforceCallingPermission(android.Manifest.permission.GET_TASKS,
5447 "getRecentTasks()");
5448
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005449 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005450
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005451 final int N = mRecentTasks.size();
5452 ArrayList<ActivityManager.RecentTaskInfo> res
5453 = new ArrayList<ActivityManager.RecentTaskInfo>(
5454 maxNum < N ? maxNum : N);
5455 for (int i=0; i<N && maxNum > 0; i++) {
5456 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005457 // Only add calling user's recent tasks
5458 if (tr.userId != callingUserId) continue;
Dianne Hackborn905577f2011-09-07 18:31:28 -07005459 // Return the entry if desired by the caller. We always return
5460 // the first entry, because callers always expect this to be the
Amith Yamasani742a6712011-05-04 14:49:28 -07005461 // foreground app. We may filter others if the caller has
Dianne Hackborn905577f2011-09-07 18:31:28 -07005462 // not supplied RECENT_WITH_EXCLUDED and there is some reason
5463 // we should exclude the entry.
Amith Yamasani742a6712011-05-04 14:49:28 -07005464
Dianne Hackborn905577f2011-09-07 18:31:28 -07005465 if (i == 0
5466 || ((flags&ActivityManager.RECENT_WITH_EXCLUDED) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005467 || (tr.intent == null)
5468 || ((tr.intent.getFlags()
5469 &Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) == 0)) {
5470 ActivityManager.RecentTaskInfo rti
5471 = new ActivityManager.RecentTaskInfo();
5472 rti.id = tr.numActivities > 0 ? tr.taskId : -1;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005473 rti.persistentId = tr.taskId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005474 rti.baseIntent = new Intent(
5475 tr.intent != null ? tr.intent : tr.affinityIntent);
5476 rti.origActivity = tr.origActivity;
Dianne Hackbornd2835932010-12-13 16:28:46 -08005477 rti.description = tr.lastDescription;
5478
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005479 if ((flags&ActivityManager.RECENT_IGNORE_UNAVAILABLE) != 0) {
5480 // Check whether this activity is currently available.
5481 try {
5482 if (rti.origActivity != null) {
5483 if (pm.getActivityInfo(rti.origActivity, 0) == null) {
5484 continue;
5485 }
5486 } else if (rti.baseIntent != null) {
5487 if (pm.queryIntentActivities(rti.baseIntent,
5488 null, 0) == null) {
5489 continue;
5490 }
5491 }
5492 } catch (RemoteException e) {
5493 // Will never happen.
5494 }
5495 }
5496
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005497 res.add(rti);
5498 maxNum--;
5499 }
5500 }
5501 return res;
5502 }
5503 }
5504
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005505 private TaskRecord taskForIdLocked(int id) {
5506 final int N = mRecentTasks.size();
5507 for (int i=0; i<N; i++) {
5508 TaskRecord tr = mRecentTasks.get(i);
5509 if (tr.taskId == id) {
5510 return tr;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005511 }
5512 }
5513 return null;
5514 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005515
5516 public ActivityManager.TaskThumbnails getTaskThumbnails(int id) {
5517 synchronized (this) {
5518 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
5519 "getTaskThumbnails()");
5520 TaskRecord tr = taskForIdLocked(id);
5521 if (tr != null) {
5522 return mMainStack.getTaskThumbnailsLocked(tr);
5523 }
5524 }
5525 return null;
5526 }
5527
5528 public boolean removeSubTask(int taskId, int subTaskIndex) {
5529 synchronized (this) {
5530 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5531 "removeSubTask()");
5532 long ident = Binder.clearCallingIdentity();
5533 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005534 return mMainStack.removeTaskActivitiesLocked(taskId, subTaskIndex,
5535 true) != null;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005536 } finally {
5537 Binder.restoreCallingIdentity(ident);
5538 }
5539 }
5540 }
5541
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005542 private void cleanUpRemovedTaskLocked(TaskRecord tr, int flags) {
5543 final boolean killProcesses = (flags&ActivityManager.REMOVE_TASK_KILL_PROCESS) != 0;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005544 Intent baseIntent = new Intent(
5545 tr.intent != null ? tr.intent : tr.affinityIntent);
5546 ComponentName component = baseIntent.getComponent();
5547 if (component == null) {
5548 Slog.w(TAG, "Now component for base intent of task: " + tr);
5549 return;
5550 }
5551
5552 // Find any running services associated with this app.
5553 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005554 for (ServiceRecord sr : mServiceMap.getAllServices(tr.userId)) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005555 if (sr.packageName.equals(component.getPackageName())) {
5556 services.add(sr);
5557 }
5558 }
5559
5560 // Take care of any running services associated with the app.
5561 for (int i=0; i<services.size(); i++) {
5562 ServiceRecord sr = services.get(i);
5563 if (sr.startRequested) {
5564 if ((sr.serviceInfo.flags&ServiceInfo.FLAG_STOP_WITH_TASK) != 0) {
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005565 Slog.i(TAG, "Stopping service " + sr.shortName + ": remove task");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005566 stopServiceLocked(sr);
5567 } else {
5568 sr.pendingStarts.add(new ServiceRecord.StartItem(sr, true,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005569 sr.makeNextStartId(), baseIntent, null));
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005570 if (sr.app != null && sr.app.thread != null) {
5571 sendServiceArgsLocked(sr, false);
5572 }
5573 }
5574 }
5575 }
5576
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005577 if (killProcesses) {
5578 // Find any running processes associated with this app.
5579 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
5580 SparseArray<ProcessRecord> appProcs
5581 = mProcessNames.getMap().get(component.getPackageName());
5582 if (appProcs != null) {
5583 for (int i=0; i<appProcs.size(); i++) {
5584 procs.add(appProcs.valueAt(i));
5585 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005586 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005587
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005588 // Kill the running processes.
5589 for (int i=0; i<procs.size(); i++) {
5590 ProcessRecord pr = procs.get(i);
5591 if (pr.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
5592 Slog.i(TAG, "Killing " + pr.toShortString() + ": remove task");
5593 EventLog.writeEvent(EventLogTags.AM_KILL, pr.pid,
5594 pr.processName, pr.setAdj, "remove task");
5595 Process.killProcessQuiet(pr.pid);
5596 } else {
5597 pr.waitingToKill = "remove task";
5598 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005599 }
5600 }
5601 }
5602
5603 public boolean removeTask(int taskId, int flags) {
5604 synchronized (this) {
5605 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5606 "removeTask()");
5607 long ident = Binder.clearCallingIdentity();
5608 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005609 ActivityRecord r = mMainStack.removeTaskActivitiesLocked(taskId, -1,
5610 false);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005611 if (r != null) {
5612 mRecentTasks.remove(r.task);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005613 cleanUpRemovedTaskLocked(r.task, flags);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005614 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005615 } else {
5616 TaskRecord tr = null;
5617 int i=0;
5618 while (i < mRecentTasks.size()) {
5619 TaskRecord t = mRecentTasks.get(i);
5620 if (t.taskId == taskId) {
5621 tr = t;
5622 break;
5623 }
5624 i++;
5625 }
5626 if (tr != null) {
5627 if (tr.numActivities <= 0) {
5628 // Caller is just removing a recent task that is
5629 // not actively running. That is easy!
5630 mRecentTasks.remove(i);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005631 cleanUpRemovedTaskLocked(tr, flags);
5632 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005633 } else {
5634 Slog.w(TAG, "removeTask: task " + taskId
5635 + " does not have activities to remove, "
5636 + " but numActivities=" + tr.numActivities
5637 + ": " + tr);
5638 }
5639 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005640 }
5641 } finally {
5642 Binder.restoreCallingIdentity(ident);
5643 }
5644 }
5645 return false;
5646 }
Dianne Hackbornd94df452011-02-16 18:53:31 -08005647
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005648 private final int findAffinityTaskTopLocked(int startIndex, String affinity) {
5649 int j;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005650 TaskRecord startTask = ((ActivityRecord)mMainStack.mHistory.get(startIndex)).task;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005651 TaskRecord jt = startTask;
5652
5653 // First look backwards
5654 for (j=startIndex-1; j>=0; j--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005655 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005656 if (r.task != jt) {
5657 jt = r.task;
5658 if (affinity.equals(jt.affinity)) {
5659 return j;
5660 }
5661 }
5662 }
5663
5664 // Now look forwards
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005665 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005666 jt = startTask;
5667 for (j=startIndex+1; j<N; j++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005668 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005669 if (r.task != jt) {
5670 if (affinity.equals(jt.affinity)) {
5671 return j;
5672 }
5673 jt = r.task;
5674 }
5675 }
5676
5677 // Might it be at the top?
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005678 if (affinity.equals(((ActivityRecord)mMainStack.mHistory.get(N-1)).task.affinity)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005679 return N-1;
5680 }
5681
5682 return -1;
5683 }
5684
5685 /**
Dianne Hackbornb06ea702009-07-13 13:07:51 -07005686 * TODO: Add mController hook
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005687 */
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005688 public void moveTaskToFront(int task, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005689 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5690 "moveTaskToFront()");
5691
5692 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005693 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5694 Binder.getCallingUid(), "Task to front")) {
5695 return;
5696 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005697 final long origId = Binder.clearCallingIdentity();
5698 try {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005699 TaskRecord tr = taskForIdLocked(task);
5700 if (tr != null) {
5701 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5702 mMainStack.mUserLeaving = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005703 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005704 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5705 // Caller wants the home activity moved with it. To accomplish this,
5706 // we'll just move the home task to the top first.
5707 mMainStack.moveHomeToFrontLocked();
5708 }
5709 mMainStack.moveTaskToFrontLocked(tr, null);
5710 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005711 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005712 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
5713 ActivityRecord hr = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005714 if (hr.task.taskId == task) {
Dianne Hackbornd94df452011-02-16 18:53:31 -08005715 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5716 mMainStack.mUserLeaving = true;
5717 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005718 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5719 // Caller wants the home activity moved with it. To accomplish this,
5720 // we'll just move the home task to the top first.
5721 mMainStack.moveHomeToFrontLocked();
5722 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005723 mMainStack.moveTaskToFrontLocked(hr.task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005724 return;
5725 }
5726 }
5727 } finally {
5728 Binder.restoreCallingIdentity(origId);
5729 }
5730 }
5731 }
5732
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005733 public void moveTaskToBack(int task) {
5734 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5735 "moveTaskToBack()");
5736
5737 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005738 if (mMainStack.mResumedActivity != null
5739 && mMainStack.mResumedActivity.task.taskId == task) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005740 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5741 Binder.getCallingUid(), "Task to back")) {
5742 return;
5743 }
5744 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005745 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005746 mMainStack.moveTaskToBackLocked(task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005747 Binder.restoreCallingIdentity(origId);
5748 }
5749 }
5750
5751 /**
5752 * Moves an activity, and all of the other activities within the same task, to the bottom
5753 * of the history stack. The activity's order within the task is unchanged.
5754 *
5755 * @param token A reference to the activity we wish to move
5756 * @param nonRoot If false then this only works if the activity is the root
5757 * of a task; if true it will work for any activity in a task.
5758 * @return Returns true if the move completed, false if not.
5759 */
5760 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005761 enforceNotIsolatedCaller("moveActivityTaskToBack");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005762 synchronized(this) {
5763 final long origId = Binder.clearCallingIdentity();
5764 int taskId = getTaskForActivityLocked(token, !nonRoot);
5765 if (taskId >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005766 return mMainStack.moveTaskToBackLocked(taskId, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005767 }
5768 Binder.restoreCallingIdentity(origId);
5769 }
5770 return false;
5771 }
5772
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005773 public void moveTaskBackwards(int task) {
5774 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5775 "moveTaskBackwards()");
5776
5777 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005778 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5779 Binder.getCallingUid(), "Task backwards")) {
5780 return;
5781 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005782 final long origId = Binder.clearCallingIdentity();
5783 moveTaskBackwardsLocked(task);
5784 Binder.restoreCallingIdentity(origId);
5785 }
5786 }
5787
5788 private final void moveTaskBackwardsLocked(int task) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005789 Slog.e(TAG, "moveTaskBackwards not yet implemented!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005790 }
5791
5792 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
5793 synchronized(this) {
5794 return getTaskForActivityLocked(token, onlyRoot);
5795 }
5796 }
5797
5798 int getTaskForActivityLocked(IBinder token, boolean onlyRoot) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005799 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005800 TaskRecord lastTask = null;
5801 for (int i=0; i<N; i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005802 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005803 if (r.appToken == token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005804 if (!onlyRoot || lastTask != r.task) {
5805 return r.task.taskId;
5806 }
5807 return -1;
5808 }
5809 lastTask = r.task;
5810 }
5811
5812 return -1;
5813 }
5814
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005815 // =========================================================
5816 // THUMBNAILS
5817 // =========================================================
5818
5819 public void reportThumbnail(IBinder token,
5820 Bitmap thumbnail, CharSequence description) {
5821 //System.out.println("Report thumbnail for " + token + ": " + thumbnail);
5822 final long origId = Binder.clearCallingIdentity();
5823 sendPendingThumbnail(null, token, thumbnail, description, true);
5824 Binder.restoreCallingIdentity(origId);
5825 }
5826
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005827 final void sendPendingThumbnail(ActivityRecord r, IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005828 Bitmap thumbnail, CharSequence description, boolean always) {
5829 TaskRecord task = null;
5830 ArrayList receivers = null;
5831
5832 //System.out.println("Send pending thumbnail: " + r);
5833
5834 synchronized(this) {
5835 if (r == null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07005836 r = mMainStack.isInStackLocked(token);
5837 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005838 return;
5839 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005840 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005841 if (thumbnail == null && r.thumbHolder != null) {
5842 thumbnail = r.thumbHolder.lastThumbnail;
5843 description = r.thumbHolder.lastDescription;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005844 }
5845 if (thumbnail == null && !always) {
5846 // If there is no thumbnail, and this entry is not actually
5847 // going away, then abort for now and pick up the next
5848 // thumbnail we get.
5849 return;
5850 }
5851 task = r.task;
5852
5853 int N = mPendingThumbnails.size();
5854 int i=0;
5855 while (i<N) {
5856 PendingThumbnailsRecord pr =
5857 (PendingThumbnailsRecord)mPendingThumbnails.get(i);
5858 //System.out.println("Looking in " + pr.pendingRecords);
5859 if (pr.pendingRecords.remove(r)) {
5860 if (receivers == null) {
5861 receivers = new ArrayList();
5862 }
5863 receivers.add(pr);
5864 if (pr.pendingRecords.size() == 0) {
5865 pr.finished = true;
5866 mPendingThumbnails.remove(i);
5867 N--;
5868 continue;
5869 }
5870 }
5871 i++;
5872 }
5873 }
5874
5875 if (receivers != null) {
5876 final int N = receivers.size();
5877 for (int i=0; i<N; i++) {
5878 try {
5879 PendingThumbnailsRecord pr =
5880 (PendingThumbnailsRecord)receivers.get(i);
5881 pr.receiver.newThumbnail(
5882 task != null ? task.taskId : -1, thumbnail, description);
5883 if (pr.finished) {
5884 pr.receiver.finished();
5885 }
5886 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005887 Slog.w(TAG, "Exception thrown when sending thumbnail", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005888 }
5889 }
5890 }
5891 }
5892
5893 // =========================================================
5894 // CONTENT PROVIDERS
5895 // =========================================================
5896
Jeff Brown10e89712011-07-08 18:52:57 -07005897 private final List<ProviderInfo> generateApplicationProvidersLocked(ProcessRecord app) {
5898 List<ProviderInfo> providers = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005899 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005900 providers = AppGlobals.getPackageManager().
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005901 queryContentProviders(app.processName, app.uid,
Dianne Hackborn1655be42009-05-08 14:29:01 -07005902 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005903 } catch (RemoteException ex) {
5904 }
Amith Yamasani742a6712011-05-04 14:49:28 -07005905 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005906 Slog.v(TAG_MU, "generateApplicationProvidersLocked, app.info.uid = " + app.uid);
5907 int userId = app.userId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005908 if (providers != null) {
5909 final int N = providers.size();
5910 for (int i=0; i<N; i++) {
5911 ProviderInfo cpi =
5912 (ProviderInfo)providers.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005913
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07005914 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07005915 ContentProviderRecord cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005916 if (cpr == null) {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08005917 cpr = new ContentProviderRecord(this, cpi, app.info, comp);
Amith Yamasani742a6712011-05-04 14:49:28 -07005918 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005919 }
Amith Yamasani742a6712011-05-04 14:49:28 -07005920 if (DEBUG_MU)
5921 Slog.v(TAG_MU, "generateApplicationProvidersLocked, cpi.uid = " + cpr.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005922 app.pubProviders.put(cpi.name, cpr);
5923 app.addPackage(cpi.applicationInfo.packageName);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07005924 ensurePackageDexOpt(cpi.applicationInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005925 }
5926 }
5927 return providers;
5928 }
5929
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005930 /**
5931 * Check if {@link ProcessRecord} has a possible chance at accessing the
5932 * given {@link ProviderInfo}. Final permission checking is always done
5933 * in {@link ContentProvider}.
5934 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005935 private final String checkContentProviderPermissionLocked(
Dianne Hackbornb424b632010-08-18 15:59:05 -07005936 ProviderInfo cpi, ProcessRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005937 final int callingPid = (r != null) ? r.pid : Binder.getCallingPid();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005938 final int callingUid = (r != null) ? r.uid : Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005939 if (checkComponentPermission(cpi.readPermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005940 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005941 == PackageManager.PERMISSION_GRANTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005942 return null;
5943 }
5944 if (checkComponentPermission(cpi.writePermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005945 cpi.applicationInfo.uid, cpi.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005946 == PackageManager.PERMISSION_GRANTED) {
5947 return null;
5948 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07005949
5950 PathPermission[] pps = cpi.pathPermissions;
5951 if (pps != null) {
5952 int i = pps.length;
5953 while (i > 0) {
5954 i--;
5955 PathPermission pp = pps[i];
5956 if (checkComponentPermission(pp.getReadPermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005957 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005958 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07005959 return null;
5960 }
5961 if (checkComponentPermission(pp.getWritePermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005962 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackborn2af632f2009-07-08 14:56:37 -07005963 == PackageManager.PERMISSION_GRANTED) {
5964 return null;
5965 }
5966 }
5967 }
5968
Dianne Hackbornb424b632010-08-18 15:59:05 -07005969 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(callingUid);
5970 if (perms != null) {
5971 for (Map.Entry<Uri, UriPermission> uri : perms.entrySet()) {
5972 if (uri.getKey().getAuthority().equals(cpi.authority)) {
5973 return null;
5974 }
5975 }
5976 }
5977
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005978 String msg;
5979 if (!cpi.exported) {
5980 msg = "Permission Denial: opening provider " + cpi.name
5981 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
5982 + ", uid=" + callingUid + ") that is not exported from uid "
5983 + cpi.applicationInfo.uid;
5984 } else {
5985 msg = "Permission Denial: opening provider " + cpi.name
5986 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
5987 + ", uid=" + callingUid + ") requires "
5988 + cpi.readPermission + " or " + cpi.writePermission;
5989 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08005990 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005991 return msg;
5992 }
5993
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08005994 boolean incProviderCount(ProcessRecord r, final ContentProviderRecord cpr,
5995 IBinder externalProcessToken) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005996 if (r != null) {
5997 Integer cnt = r.conProviders.get(cpr);
5998 if (DEBUG_PROVIDER) Slog.v(TAG,
5999 "Adding provider requested by "
6000 + r.processName + " from process "
6001 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
6002 + " cnt=" + (cnt == null ? 1 : cnt));
6003 if (cnt == null) {
6004 cpr.clients.add(r);
6005 r.conProviders.put(cpr, new Integer(1));
6006 return true;
6007 } else {
6008 r.conProviders.put(cpr, new Integer(cnt.intValue()+1));
6009 }
6010 } else {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006011 cpr.addExternalProcessHandleLocked(externalProcessToken);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006012 }
6013 return false;
6014 }
6015
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006016 boolean decProviderCount(ProcessRecord r, final ContentProviderRecord cpr,
6017 IBinder externalProcessToken) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006018 if (r != null) {
6019 Integer cnt = r.conProviders.get(cpr);
6020 if (DEBUG_PROVIDER) Slog.v(TAG,
6021 "Removing provider requested by "
6022 + r.processName + " from process "
6023 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
6024 + " cnt=" + cnt);
6025 if (cnt == null || cnt.intValue() <= 1) {
6026 cpr.clients.remove(r);
6027 r.conProviders.remove(cpr);
6028 return true;
6029 } else {
6030 r.conProviders.put(cpr, new Integer(cnt.intValue()-1));
6031 }
6032 } else {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006033 cpr.removeExternalProcessHandleLocked(externalProcessToken);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006034 }
6035 return false;
6036 }
6037
Amith Yamasani742a6712011-05-04 14:49:28 -07006038 private final ContentProviderHolder getContentProviderImpl(IApplicationThread caller,
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006039 String name, IBinder token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006040 ContentProviderRecord cpr;
6041 ProviderInfo cpi = null;
6042
6043 synchronized(this) {
6044 ProcessRecord r = null;
6045 if (caller != null) {
6046 r = getRecordForAppLocked(caller);
6047 if (r == null) {
6048 throw new SecurityException(
6049 "Unable to find app for caller " + caller
6050 + " (pid=" + Binder.getCallingPid()
6051 + ") when getting content provider " + name);
6052 }
6053 }
6054
6055 // First check if this content provider has been published...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006056 int userId = UserId.getUserId(r != null ? r.uid : Binder.getCallingUid());
Amith Yamasani742a6712011-05-04 14:49:28 -07006057 cpr = mProviderMap.getProviderByName(name, userId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006058 boolean providerRunning = cpr != null;
6059 if (providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006060 cpi = cpr.info;
Dianne Hackbornb424b632010-08-18 15:59:05 -07006061 String msg;
6062 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6063 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006064 }
6065
6066 if (r != null && cpr.canRunHere(r)) {
6067 // This provider has been published or is in the process
6068 // of being published... but it is also allowed to run
6069 // in the caller's process, so don't make a connection
6070 // and just let the caller instantiate its own instance.
6071 if (cpr.provider != null) {
6072 // don't give caller the provider object, it needs
6073 // to make its own.
6074 cpr = new ContentProviderRecord(cpr);
6075 }
6076 return cpr;
6077 }
6078
6079 final long origId = Binder.clearCallingIdentity();
6080
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006081 // In this case the provider instance already exists, so we can
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006082 // return it right away.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006083 final boolean countChanged = incProviderCount(r, cpr, token);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006084 if (countChanged) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006085 if (cpr.proc != null && r.setAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006086 // If this is a perceptible app accessing the provider,
Dianne Hackborn906497c2010-05-10 15:57:38 -07006087 // make sure to count it as being accessed and thus
6088 // back up on the LRU list. This is good because
6089 // content providers are often expensive to start.
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006090 updateLruProcessLocked(cpr.proc, false, true);
Dianne Hackborn906497c2010-05-10 15:57:38 -07006091 }
Dianne Hackborn6f86c0e2010-05-11 14:20:52 -07006092 }
6093
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006094 if (cpr.proc != null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006095 if (false) {
6096 if (cpr.name.flattenToShortString().equals(
6097 "com.android.providers.calendar/.CalendarProvider2")) {
6098 Slog.v(TAG, "****************** KILLING "
6099 + cpr.name.flattenToShortString());
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006100 Process.killProcess(cpr.proc.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006101 }
6102 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006103 boolean success = updateOomAdjLocked(cpr.proc);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006104 if (DEBUG_PROVIDER) Slog.i(TAG, "Adjust success: " + success);
6105 // NOTE: there is still a race here where a signal could be
6106 // pending on the process even though we managed to update its
6107 // adj level. Not sure what to do about this, but at least
6108 // the race is now smaller.
6109 if (!success) {
6110 // Uh oh... it looks like the provider's process
6111 // has been killed on us. We need to wait for a new
6112 // process to be started, and make sure its death
6113 // doesn't kill our process.
6114 Slog.i(TAG,
6115 "Existing provider " + cpr.name.flattenToShortString()
6116 + " is crashing; detaching " + r);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006117 boolean lastRef = decProviderCount(r, cpr, token);
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006118 appDiedLocked(cpr.proc, cpr.proc.pid, cpr.proc.thread);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006119 if (!lastRef) {
6120 // This wasn't the last ref our process had on
6121 // the provider... we have now been killed, bail.
6122 return null;
6123 }
6124 providerRunning = false;
6125 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006126 }
6127
6128 Binder.restoreCallingIdentity(origId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006129 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006130
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006131 if (!providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006132 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006133 cpi = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07006134 resolveContentProvider(name,
6135 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006136 } catch (RemoteException ex) {
6137 }
6138 if (cpi == null) {
6139 return null;
6140 }
6141
Amith Yamasani742a6712011-05-04 14:49:28 -07006142 cpi.applicationInfo = getAppInfoForUser(cpi.applicationInfo,
6143 Binder.getOrigCallingUser());
6144
Dianne Hackbornb424b632010-08-18 15:59:05 -07006145 String msg;
6146 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6147 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006148 }
6149
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07006150 if (!mProcessesReady && !mDidUpdate && !mWaitingUpdate
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006151 && !cpi.processName.equals("system")) {
6152 // If this content provider does not run in the system
6153 // process, and the system is not yet ready to run other
6154 // processes, then fail fast instead of hanging.
6155 throw new IllegalArgumentException(
6156 "Attempt to launch content provider before system ready");
6157 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006158
6159 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006160 cpr = mProviderMap.getProviderByClass(comp, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006161 final boolean firstClass = cpr == null;
6162 if (firstClass) {
6163 try {
6164 ApplicationInfo ai =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006165 AppGlobals.getPackageManager().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006166 getApplicationInfo(
6167 cpi.applicationInfo.packageName,
Dianne Hackborn1655be42009-05-08 14:29:01 -07006168 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006169 if (ai == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006170 Slog.w(TAG, "No package info for content provider "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006171 + cpi.name);
6172 return null;
6173 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006174 ai = getAppInfoForUser(ai, Binder.getOrigCallingUser());
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006175 cpr = new ContentProviderRecord(this, cpi, ai, comp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006176 } catch (RemoteException ex) {
6177 // pm is in same process, this will never happen.
6178 }
6179 }
6180
6181 if (r != null && cpr.canRunHere(r)) {
6182 // If this is a multiprocess provider, then just return its
6183 // info and allow the caller to instantiate it. Only do
6184 // this if the provider is the same user as the caller's
6185 // process, or can run as root (so can be in any process).
6186 return cpr;
6187 }
6188
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006189 if (DEBUG_PROVIDER) {
6190 RuntimeException e = new RuntimeException("here");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006191 Slog.w(TAG, "LAUNCHING REMOTE PROVIDER (myuid " + r.uid
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006192 + " pruid " + cpr.appInfo.uid + "): " + cpr.info.name, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006193 }
6194
6195 // This is single process, and our app is now connecting to it.
6196 // See if we are already in the process of launching this
6197 // provider.
6198 final int N = mLaunchingProviders.size();
6199 int i;
6200 for (i=0; i<N; i++) {
6201 if (mLaunchingProviders.get(i) == cpr) {
6202 break;
6203 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006204 }
6205
6206 // If the provider is not already being launched, then get it
6207 // started.
6208 if (i >= N) {
6209 final long origId = Binder.clearCallingIdentity();
Dianne Hackborne7f97212011-02-24 14:40:20 -08006210
6211 try {
6212 // Content provider is now in use, its package can't be stopped.
6213 try {
6214 AppGlobals.getPackageManager().setPackageStoppedState(
6215 cpr.appInfo.packageName, false);
6216 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006217 } catch (IllegalArgumentException e) {
6218 Slog.w(TAG, "Failed trying to unstop package "
6219 + cpr.appInfo.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006220 }
6221
6222 ProcessRecord proc = startProcessLocked(cpi.processName,
6223 cpr.appInfo, false, 0, "content provider",
6224 new ComponentName(cpi.applicationInfo.packageName,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006225 cpi.name), false, false);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006226 if (proc == null) {
6227 Slog.w(TAG, "Unable to launch app "
6228 + cpi.applicationInfo.packageName + "/"
6229 + cpi.applicationInfo.uid + " for provider "
6230 + name + ": process is bad");
6231 return null;
6232 }
6233 cpr.launchingApp = proc;
6234 mLaunchingProviders.add(cpr);
6235 } finally {
6236 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006237 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006238 }
6239
6240 // Make sure the provider is published (the same provider class
6241 // may be published under multiple names).
6242 if (firstClass) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006243 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006244 }
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006245
Amith Yamasani742a6712011-05-04 14:49:28 -07006246 mProviderMap.putProviderByName(name, cpr);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006247 incProviderCount(r, cpr, token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006248 }
6249 }
6250
6251 // Wait for the provider to be published...
6252 synchronized (cpr) {
6253 while (cpr.provider == null) {
6254 if (cpr.launchingApp == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006255 Slog.w(TAG, "Unable to launch app "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006256 + cpi.applicationInfo.packageName + "/"
6257 + cpi.applicationInfo.uid + " for provider "
6258 + name + ": launching app became null");
Doug Zongker2bec3d42009-12-04 12:52:44 -08006259 EventLog.writeEvent(EventLogTags.AM_PROVIDER_LOST_PROCESS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006260 cpi.applicationInfo.packageName,
6261 cpi.applicationInfo.uid, name);
6262 return null;
6263 }
6264 try {
Amith Yamasani742a6712011-05-04 14:49:28 -07006265 if (DEBUG_MU) {
6266 Slog.v(TAG_MU, "Waiting to start provider " + cpr + " launchingApp="
6267 + cpr.launchingApp);
6268 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006269 cpr.wait();
6270 } catch (InterruptedException ex) {
6271 }
6272 }
6273 }
6274 return cpr;
6275 }
6276
6277 public final ContentProviderHolder getContentProvider(
6278 IApplicationThread caller, String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006279 enforceNotIsolatedCaller("getContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006280 if (caller == null) {
6281 String msg = "null IApplicationThread when getting content provider "
6282 + name;
Joe Onorato8a9b2202010-02-26 18:56:32 -08006283 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006284 throw new SecurityException(msg);
6285 }
6286
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006287 return getContentProviderImpl(caller, name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006288 }
6289
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006290 public ContentProviderHolder getContentProviderExternal(String name, IBinder token) {
6291 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6292 "Do not have permission in call getContentProviderExternal()");
6293 return getContentProviderExternalUnchecked(name, token);
6294 }
6295
6296 private ContentProviderHolder getContentProviderExternalUnchecked(String name,IBinder token) {
6297 return getContentProviderImpl(null, name, token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006298 }
6299
6300 /**
6301 * Drop a content provider from a ProcessRecord's bookkeeping
6302 * @param cpr
6303 */
6304 public void removeContentProvider(IApplicationThread caller, String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006305 enforceNotIsolatedCaller("removeContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006306 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006307 int userId = UserId.getUserId(Binder.getCallingUid());
6308 ContentProviderRecord cpr = mProviderMap.getProviderByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006309 if(cpr == null) {
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006310 // remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006311 if (DEBUG_PROVIDER) Slog.v(TAG, name +
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006312 " provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006313 return;
6314 }
6315 final ProcessRecord r = getRecordForAppLocked(caller);
6316 if (r == null) {
6317 throw new SecurityException(
6318 "Unable to find app for caller " + caller +
6319 " when removing content provider " + name);
6320 }
6321 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006322 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006323 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp, userId);
6324 if (DEBUG_PROVIDER) Slog.v(TAG, "Removing provider requested by "
6325 + r.info.processName + " from process "
6326 + localCpr.appInfo.processName);
6327 if (localCpr.launchingApp == r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006328 //should not happen. taken care of as a local provider
Joe Onorato8a9b2202010-02-26 18:56:32 -08006329 Slog.w(TAG, "removeContentProvider called on local provider: "
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006330 + cpr.info.name + " in process " + r.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006331 return;
6332 } else {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006333 if (decProviderCount(r, localCpr, null)) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006334 updateOomAdjLocked();
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07006335 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006336 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006337 }
6338 }
6339
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006340 public void removeContentProviderExternal(String name, IBinder token) {
6341 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6342 "Do not have permission in call removeContentProviderExternal()");
6343 removeContentProviderExternalUnchecked(name, token);
6344 }
6345
6346 private void removeContentProviderExternalUnchecked(String name, IBinder token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006347 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006348 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
6349 Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006350 if(cpr == null) {
6351 //remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006352 if(localLOGV) Slog.v(TAG, name+" content provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006353 return;
6354 }
6355
6356 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006357 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006358 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp,
6359 Binder.getOrigCallingUser());
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006360 if (localCpr.hasExternalProcessHandles()) {
6361 if (localCpr.removeExternalProcessHandleLocked(token)) {
6362 updateOomAdjLocked();
6363 } else {
6364 Slog.e(TAG, "Attmpt to remove content provider " + localCpr
6365 + " with no external reference for token: "
6366 + token + ".");
6367 }
6368 } else {
6369 Slog.e(TAG, "Attmpt to remove content provider: " + localCpr
6370 + " with no external references.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006371 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006372 }
6373 }
6374
6375 public final void publishContentProviders(IApplicationThread caller,
6376 List<ContentProviderHolder> providers) {
6377 if (providers == null) {
6378 return;
6379 }
6380
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006381 enforceNotIsolatedCaller("publishContentProviders");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006382 synchronized(this) {
6383 final ProcessRecord r = getRecordForAppLocked(caller);
Amith Yamasani742a6712011-05-04 14:49:28 -07006384 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006385 Slog.v(TAG_MU, "ProcessRecord uid = " + r.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006386 if (r == null) {
6387 throw new SecurityException(
6388 "Unable to find app for caller " + caller
6389 + " (pid=" + Binder.getCallingPid()
6390 + ") when publishing content providers");
6391 }
6392
6393 final long origId = Binder.clearCallingIdentity();
6394
6395 final int N = providers.size();
6396 for (int i=0; i<N; i++) {
6397 ContentProviderHolder src = providers.get(i);
6398 if (src == null || src.info == null || src.provider == null) {
6399 continue;
6400 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07006401 ContentProviderRecord dst = r.pubProviders.get(src.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006402 if (DEBUG_MU)
6403 Slog.v(TAG_MU, "ContentProviderRecord uid = " + dst.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006404 if (dst != null) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006405 ComponentName comp = new ComponentName(dst.info.packageName, dst.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006406 mProviderMap.putProviderByClass(comp, dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006407 String names[] = dst.info.authority.split(";");
6408 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006409 mProviderMap.putProviderByName(names[j], dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006410 }
6411
6412 int NL = mLaunchingProviders.size();
6413 int j;
6414 for (j=0; j<NL; j++) {
6415 if (mLaunchingProviders.get(j) == dst) {
6416 mLaunchingProviders.remove(j);
6417 j--;
6418 NL--;
6419 }
6420 }
6421 synchronized (dst) {
6422 dst.provider = src.provider;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006423 dst.proc = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006424 dst.notifyAll();
6425 }
6426 updateOomAdjLocked(r);
6427 }
6428 }
6429
6430 Binder.restoreCallingIdentity(origId);
6431 }
6432 }
6433
6434 public static final void installSystemProviders() {
Jeff Brown10e89712011-07-08 18:52:57 -07006435 List<ProviderInfo> providers;
Josh Bartel2ecce342010-02-25 10:55:48 -06006436 synchronized (mSelf) {
6437 ProcessRecord app = mSelf.mProcessNames.get("system", Process.SYSTEM_UID);
6438 providers = mSelf.generateApplicationProvidersLocked(app);
Dianne Hackborn5c83a5f2010-03-12 16:46:46 -08006439 if (providers != null) {
6440 for (int i=providers.size()-1; i>=0; i--) {
6441 ProviderInfo pi = (ProviderInfo)providers.get(i);
6442 if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6443 Slog.w(TAG, "Not installing system proc provider " + pi.name
6444 + ": not system .apk");
6445 providers.remove(i);
6446 }
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006447 }
6448 }
6449 }
Josh Bartel2ecce342010-02-25 10:55:48 -06006450 if (providers != null) {
6451 mSystemThread.installSystemProviders(providers);
6452 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08006453
6454 mSelf.mCoreSettingsObserver = new CoreSettingsObserver(mSelf);
Mark Brophyc6350272011-08-05 16:16:39 +01006455
6456 mSelf.mUsageStatsService.monitorPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006457 }
6458
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006459 /**
6460 * Allows app to retrieve the MIME type of a URI without having permission
6461 * to access its content provider.
6462 *
6463 * CTS tests for this functionality can be run with "runtest cts-appsecurity".
6464 *
6465 * Test cases are at cts/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/
6466 * src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java
6467 */
6468 public String getProviderMimeType(Uri uri) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006469 enforceNotIsolatedCaller("getProviderMimeType");
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006470 final String name = uri.getAuthority();
6471 final long ident = Binder.clearCallingIdentity();
6472 ContentProviderHolder holder = null;
6473
6474 try {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006475 holder = getContentProviderExternalUnchecked(name, null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006476 if (holder != null) {
6477 return holder.provider.getType(uri);
6478 }
6479 } catch (RemoteException e) {
6480 Log.w(TAG, "Content provider dead retrieving " + uri, e);
6481 return null;
6482 } finally {
6483 if (holder != null) {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006484 removeContentProviderExternalUnchecked(name, null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006485 }
6486 Binder.restoreCallingIdentity(ident);
6487 }
6488
6489 return null;
6490 }
6491
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006492 // =========================================================
6493 // GLOBAL MANAGEMENT
6494 // =========================================================
6495
6496 final ProcessRecord newProcessRecordLocked(IApplicationThread thread,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006497 ApplicationInfo info, String customProcess, boolean isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006498 String proc = customProcess != null ? customProcess : info.processName;
6499 BatteryStatsImpl.Uid.Proc ps = null;
6500 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006501 int uid = info.uid;
6502 if (isolated) {
6503 int userId = UserId.getUserId(uid);
6504 int stepsLeft = Process.LAST_ISOLATED_UID - Process.FIRST_ISOLATED_UID + 1;
6505 uid = 0;
6506 while (true) {
6507 if (mNextIsolatedProcessUid < Process.FIRST_ISOLATED_UID
6508 || mNextIsolatedProcessUid > Process.LAST_ISOLATED_UID) {
6509 mNextIsolatedProcessUid = Process.FIRST_ISOLATED_UID;
6510 }
6511 uid = UserId.getUid(userId, mNextIsolatedProcessUid);
6512 mNextIsolatedProcessUid++;
6513 if (mIsolatedProcesses.indexOfKey(uid) < 0) {
6514 // No process for this uid, use it.
6515 break;
6516 }
6517 stepsLeft--;
6518 if (stepsLeft <= 0) {
6519 return null;
6520 }
6521 }
6522 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006523 synchronized (stats) {
6524 ps = stats.getProcessStatsLocked(info.uid, proc);
6525 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006526 return new ProcessRecord(ps, thread, info, proc, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006527 }
6528
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006529 final ProcessRecord addAppLocked(ApplicationInfo info, boolean isolated) {
6530 ProcessRecord app;
6531 if (!isolated) {
6532 app = getProcessRecordLocked(info.processName, info.uid);
6533 } else {
6534 app = null;
6535 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006536
6537 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006538 app = newProcessRecordLocked(null, info, null, isolated);
6539 mProcessNames.put(info.processName, app.uid, app);
6540 if (isolated) {
6541 mIsolatedProcesses.put(app.uid, app);
6542 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08006543 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006544 }
6545
Dianne Hackborne7f97212011-02-24 14:40:20 -08006546 // This package really, really can not be stopped.
6547 try {
6548 AppGlobals.getPackageManager().setPackageStoppedState(
6549 info.packageName, false);
6550 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006551 } catch (IllegalArgumentException e) {
6552 Slog.w(TAG, "Failed trying to unstop package "
6553 + info.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006554 }
6555
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006556 if ((info.flags&(ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT))
6557 == (ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT)) {
6558 app.persistent = true;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07006559 app.maxAdj = ProcessList.PERSISTENT_PROC_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006560 }
6561 if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) {
6562 mPersistentStartingProcesses.add(app);
6563 startProcessLocked(app, "added application", app.processName);
6564 }
6565
6566 return app;
6567 }
6568
6569 public void unhandledBack() {
6570 enforceCallingPermission(android.Manifest.permission.FORCE_BACK,
6571 "unhandledBack()");
6572
6573 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006574 int count = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08006575 if (DEBUG_SWITCH) Slog.d(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006576 TAG, "Performing unhandledBack(): stack size = " + count);
6577 if (count > 1) {
6578 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006579 mMainStack.finishActivityLocked((ActivityRecord)mMainStack.mHistory.get(count-1),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006580 count-1, Activity.RESULT_CANCELED, null, "unhandled-back");
6581 Binder.restoreCallingIdentity(origId);
6582 }
6583 }
6584 }
6585
6586 public ParcelFileDescriptor openContentUri(Uri uri) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006587 enforceNotIsolatedCaller("openContentUri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006588 String name = uri.getAuthority();
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006589 ContentProviderHolder cph = getContentProviderExternalUnchecked(name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006590 ParcelFileDescriptor pfd = null;
6591 if (cph != null) {
6592 // We record the binder invoker's uid in thread-local storage before
6593 // going to the content provider to open the file. Later, in the code
6594 // that handles all permissions checks, we look for this uid and use
6595 // that rather than the Activity Manager's own uid. The effect is that
6596 // we do the check against the caller's permissions even though it looks
6597 // to the content provider like the Activity Manager itself is making
6598 // the request.
6599 sCallerIdentity.set(new Identity(
6600 Binder.getCallingPid(), Binder.getCallingUid()));
6601 try {
6602 pfd = cph.provider.openFile(uri, "r");
6603 } catch (FileNotFoundException e) {
6604 // do nothing; pfd will be returned null
6605 } finally {
6606 // Ensure that whatever happens, we clean up the identity state
6607 sCallerIdentity.remove();
6608 }
6609
6610 // We've got the fd now, so we're done with the provider.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006611 removeContentProviderExternalUnchecked(name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006612 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006613 Slog.d(TAG, "Failed to get provider for authority '" + name + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006614 }
6615 return pfd;
6616 }
6617
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006618 // Actually is sleeping or shutting down or whatever else in the future
6619 // is an inactive state.
6620 public boolean isSleeping() {
6621 return mSleeping || mShuttingDown;
6622 }
6623
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006624 public void goingToSleep() {
6625 synchronized(this) {
6626 mSleeping = true;
6627 mWindowManager.setEventDispatching(false);
6628
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006629 mMainStack.stopIfSleepingLocked();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006630
6631 // Initialize the wake times of all processes.
Dianne Hackborn287952c2010-09-22 22:34:31 -07006632 checkExcessivePowerUsageLocked(false);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006633 mHandler.removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
6634 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07006635 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006636 }
6637 }
6638
Dianne Hackborn55280a92009-05-07 15:53:46 -07006639 public boolean shutdown(int timeout) {
6640 if (checkCallingPermission(android.Manifest.permission.SHUTDOWN)
6641 != PackageManager.PERMISSION_GRANTED) {
6642 throw new SecurityException("Requires permission "
6643 + android.Manifest.permission.SHUTDOWN);
6644 }
6645
6646 boolean timedout = false;
6647
6648 synchronized(this) {
6649 mShuttingDown = true;
6650 mWindowManager.setEventDispatching(false);
6651
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006652 if (mMainStack.mResumedActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006653 mMainStack.stopIfSleepingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07006654 final long endTime = System.currentTimeMillis() + timeout;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006655 while (mMainStack.mResumedActivity != null
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08006656 || mMainStack.mPausingActivity != null) {
Dianne Hackborn55280a92009-05-07 15:53:46 -07006657 long delay = endTime - System.currentTimeMillis();
6658 if (delay <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006659 Slog.w(TAG, "Activity manager shutdown timed out");
Dianne Hackborn55280a92009-05-07 15:53:46 -07006660 timedout = true;
6661 break;
6662 }
6663 try {
6664 this.wait();
6665 } catch (InterruptedException e) {
6666 }
6667 }
6668 }
6669 }
6670
6671 mUsageStatsService.shutdown();
6672 mBatteryStatsService.shutdown();
6673
6674 return timedout;
6675 }
6676
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006677 public final void activitySlept(IBinder token) {
6678 if (localLOGV) Slog.v(
6679 TAG, "Activity slept: token=" + token);
6680
6681 ActivityRecord r = null;
6682
6683 final long origId = Binder.clearCallingIdentity();
6684
6685 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006686 r = mMainStack.isInStackLocked(token);
6687 if (r != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006688 mMainStack.activitySleptLocked(r);
6689 }
6690 }
6691
6692 Binder.restoreCallingIdentity(origId);
6693 }
6694
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006695 public void wakingUp() {
6696 synchronized(this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006697 mWindowManager.setEventDispatching(true);
6698 mSleeping = false;
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006699 mMainStack.awakeFromSleepingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006700 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006701 }
6702 }
6703
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006704 public void stopAppSwitches() {
6705 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
6706 != PackageManager.PERMISSION_GRANTED) {
6707 throw new SecurityException("Requires permission "
6708 + android.Manifest.permission.STOP_APP_SWITCHES);
6709 }
6710
6711 synchronized(this) {
6712 mAppSwitchesAllowedTime = SystemClock.uptimeMillis()
6713 + APP_SWITCH_DELAY_TIME;
6714 mDidAppSwitch = false;
6715 mHandler.removeMessages(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
6716 Message msg = mHandler.obtainMessage(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
6717 mHandler.sendMessageDelayed(msg, APP_SWITCH_DELAY_TIME);
6718 }
6719 }
6720
6721 public void resumeAppSwitches() {
6722 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
6723 != PackageManager.PERMISSION_GRANTED) {
6724 throw new SecurityException("Requires permission "
6725 + android.Manifest.permission.STOP_APP_SWITCHES);
6726 }
6727
6728 synchronized(this) {
6729 // Note that we don't execute any pending app switches... we will
6730 // let those wait until either the timeout, or the next start
6731 // activity request.
6732 mAppSwitchesAllowedTime = 0;
6733 }
6734 }
6735
6736 boolean checkAppSwitchAllowedLocked(int callingPid, int callingUid,
6737 String name) {
6738 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
6739 return true;
6740 }
6741
6742 final int perm = checkComponentPermission(
6743 android.Manifest.permission.STOP_APP_SWITCHES, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006744 callingUid, -1, true);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006745 if (perm == PackageManager.PERMISSION_GRANTED) {
6746 return true;
6747 }
6748
Joe Onorato8a9b2202010-02-26 18:56:32 -08006749 Slog.w(TAG, name + " request from " + callingUid + " stopped");
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006750 return false;
6751 }
6752
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006753 public void setDebugApp(String packageName, boolean waitForDebugger,
6754 boolean persistent) {
6755 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
6756 "setDebugApp()");
6757
6758 // Note that this is not really thread safe if there are multiple
6759 // callers into it at the same time, but that's not a situation we
6760 // care about.
6761 if (persistent) {
6762 final ContentResolver resolver = mContext.getContentResolver();
6763 Settings.System.putString(
6764 resolver, Settings.System.DEBUG_APP,
6765 packageName);
6766 Settings.System.putInt(
6767 resolver, Settings.System.WAIT_FOR_DEBUGGER,
6768 waitForDebugger ? 1 : 0);
6769 }
6770
6771 synchronized (this) {
6772 if (!persistent) {
6773 mOrigDebugApp = mDebugApp;
6774 mOrigWaitForDebugger = mWaitForDebugger;
6775 }
6776 mDebugApp = packageName;
6777 mWaitForDebugger = waitForDebugger;
6778 mDebugTransient = !persistent;
6779 if (packageName != null) {
6780 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -07006781 forceStopPackageLocked(packageName, -1, false, false, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006782 Binder.restoreCallingIdentity(origId);
6783 }
6784 }
6785 }
6786
Siva Velusamy92a8b222012-03-09 16:24:04 -08006787 void setOpenGlTraceApp(ApplicationInfo app, String processName) {
6788 synchronized (this) {
6789 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
6790 if (!isDebuggable) {
6791 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
6792 throw new SecurityException("Process not debuggable: " + app.packageName);
6793 }
6794 }
6795
6796 mOpenGlTraceApp = processName;
6797 }
6798 }
6799
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07006800 void setProfileApp(ApplicationInfo app, String processName, String profileFile,
6801 ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
6802 synchronized (this) {
6803 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
6804 if (!isDebuggable) {
6805 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
6806 throw new SecurityException("Process not debuggable: " + app.packageName);
6807 }
6808 }
6809 mProfileApp = processName;
6810 mProfileFile = profileFile;
6811 if (mProfileFd != null) {
6812 try {
6813 mProfileFd.close();
6814 } catch (IOException e) {
6815 }
6816 mProfileFd = null;
6817 }
6818 mProfileFd = profileFd;
6819 mProfileType = 0;
6820 mAutoStopProfiler = autoStopProfiler;
6821 }
6822 }
6823
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006824 public void setAlwaysFinish(boolean enabled) {
6825 enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH,
6826 "setAlwaysFinish()");
6827
6828 Settings.System.putInt(
6829 mContext.getContentResolver(),
6830 Settings.System.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0);
6831
6832 synchronized (this) {
6833 mAlwaysFinishActivities = enabled;
6834 }
6835 }
6836
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006837 public void setActivityController(IActivityController controller) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006838 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006839 "setActivityController()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006840 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006841 mController = controller;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006842 }
6843 }
6844
Dianne Hackborn9327f4f2010-01-29 10:38:29 -08006845 public boolean isUserAMonkey() {
6846 // For now the fact that there is a controller implies
6847 // we have a monkey.
6848 synchronized (this) {
6849 return mController != null;
6850 }
6851 }
6852
Jeff Sharkeya4620792011-05-20 15:29:23 -07006853 public void registerProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08006854 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
6855 "registerProcessObserver()");
6856 synchronized (this) {
6857 mProcessObservers.register(observer);
6858 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07006859 }
6860
6861 public void unregisterProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08006862 synchronized (this) {
6863 mProcessObservers.unregister(observer);
6864 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07006865 }
6866
Daniel Sandler69a48172010-06-23 16:29:36 -04006867 public void setImmersive(IBinder token, boolean immersive) {
6868 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006869 ActivityRecord r = mMainStack.isInStackLocked(token);
6870 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04006871 throw new IllegalArgumentException();
6872 }
Daniel Sandler69a48172010-06-23 16:29:36 -04006873 r.immersive = immersive;
6874 }
6875 }
6876
6877 public boolean isImmersive(IBinder token) {
6878 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006879 ActivityRecord r = mMainStack.isInStackLocked(token);
6880 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04006881 throw new IllegalArgumentException();
6882 }
Daniel Sandler69a48172010-06-23 16:29:36 -04006883 return r.immersive;
6884 }
6885 }
6886
6887 public boolean isTopActivityImmersive() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006888 enforceNotIsolatedCaller("startActivity");
Daniel Sandler69a48172010-06-23 16:29:36 -04006889 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006890 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Daniel Sandler69a48172010-06-23 16:29:36 -04006891 return (r != null) ? r.immersive : false;
6892 }
6893 }
6894
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006895 public final void enterSafeMode() {
6896 synchronized(this) {
6897 // It only makes sense to do this before the system is ready
6898 // and started launching other packages.
6899 if (!mSystemReady) {
6900 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006901 AppGlobals.getPackageManager().enterSafeMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006902 } catch (RemoteException e) {
6903 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006904 }
6905 }
6906 }
6907
Jeff Brownb09abc12011-01-13 21:08:27 -08006908 public final void showSafeModeOverlay() {
6909 View v = LayoutInflater.from(mContext).inflate(
6910 com.android.internal.R.layout.safe_mode, null);
6911 WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
6912 lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
6913 lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
6914 lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
6915 lp.gravity = Gravity.BOTTOM | Gravity.LEFT;
6916 lp.format = v.getBackground().getOpacity();
6917 lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
6918 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
6919 ((WindowManager)mContext.getSystemService(
6920 Context.WINDOW_SERVICE)).addView(v, lp);
6921 }
6922
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006923 public void noteWakeupAlarm(IIntentSender sender) {
6924 if (!(sender instanceof PendingIntentRecord)) {
6925 return;
6926 }
6927 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
6928 synchronized (stats) {
6929 if (mBatteryStatsService.isOnBattery()) {
6930 mBatteryStatsService.enforceCallingPermission();
6931 PendingIntentRecord rec = (PendingIntentRecord)sender;
6932 int MY_UID = Binder.getCallingUid();
6933 int uid = rec.uid == MY_UID ? Process.SYSTEM_UID : rec.uid;
6934 BatteryStatsImpl.Uid.Pkg pkg =
6935 stats.getPackageStatsLocked(uid, rec.key.packageName);
6936 pkg.incWakeupsLocked();
6937 }
6938 }
6939 }
6940
Dianne Hackborn64825172011-03-02 21:32:58 -08006941 public boolean killPids(int[] pids, String pReason, boolean secure) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006942 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006943 throw new SecurityException("killPids only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006944 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006945 String reason = (pReason == null) ? "Unknown" : pReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006946 // XXX Note: don't acquire main activity lock here, because the window
6947 // manager calls in with its locks held.
6948
6949 boolean killed = false;
6950 synchronized (mPidsSelfLocked) {
6951 int[] types = new int[pids.length];
6952 int worstType = 0;
6953 for (int i=0; i<pids.length; i++) {
6954 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
6955 if (proc != null) {
6956 int type = proc.setAdj;
6957 types[i] = type;
6958 if (type > worstType) {
6959 worstType = type;
6960 }
6961 }
6962 }
6963
Dianne Hackborn64825172011-03-02 21:32:58 -08006964 // If the worst oom_adj is somewhere in the hidden proc LRU range,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006965 // then constrain it so we will kill all hidden procs.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07006966 if (worstType < ProcessList.HIDDEN_APP_MAX_ADJ
6967 && worstType > ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07006968 worstType = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006969 }
Dianne Hackborn64825172011-03-02 21:32:58 -08006970
6971 // If this is not a secure call, don't let it kill processes that
6972 // are important.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07006973 if (!secure && worstType < ProcessList.SERVICE_ADJ) {
6974 worstType = ProcessList.SERVICE_ADJ;
Dianne Hackborn64825172011-03-02 21:32:58 -08006975 }
6976
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006977 Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006978 for (int i=0; i<pids.length; i++) {
6979 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
6980 if (proc == null) {
6981 continue;
6982 }
6983 int adj = proc.setAdj;
Dianne Hackborn906497c2010-05-10 15:57:38 -07006984 if (adj >= worstType && !proc.killedBackground) {
Dianne Hackborn8633e682010-04-22 16:03:41 -07006985 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006986 EventLog.writeEvent(EventLogTags.AM_KILL, proc.pid,
6987 proc.processName, adj, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006988 killed = true;
Dianne Hackborn906497c2010-05-10 15:57:38 -07006989 proc.killedBackground = true;
6990 Process.killProcessQuiet(pids[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006991 }
6992 }
6993 }
6994 return killed;
6995 }
6996
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006997 public final void startRunning(String pkg, String cls, String action,
6998 String data) {
6999 synchronized(this) {
7000 if (mStartRunning) {
7001 return;
7002 }
7003 mStartRunning = true;
7004 mTopComponent = pkg != null && cls != null
7005 ? new ComponentName(pkg, cls) : null;
7006 mTopAction = action != null ? action : Intent.ACTION_MAIN;
7007 mTopData = data;
7008 if (!mSystemReady) {
7009 return;
7010 }
7011 }
7012
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007013 systemReady(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007014 }
7015
7016 private void retrieveSettings() {
7017 final ContentResolver resolver = mContext.getContentResolver();
7018 String debugApp = Settings.System.getString(
7019 resolver, Settings.System.DEBUG_APP);
7020 boolean waitForDebugger = Settings.System.getInt(
7021 resolver, Settings.System.WAIT_FOR_DEBUGGER, 0) != 0;
7022 boolean alwaysFinishActivities = Settings.System.getInt(
7023 resolver, Settings.System.ALWAYS_FINISH_ACTIVITIES, 0) != 0;
7024
7025 Configuration configuration = new Configuration();
7026 Settings.System.getConfiguration(resolver, configuration);
7027
7028 synchronized (this) {
7029 mDebugApp = mOrigDebugApp = debugApp;
7030 mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger;
7031 mAlwaysFinishActivities = alwaysFinishActivities;
7032 // This happens before any activities are started, so we can
7033 // change mConfiguration in-place.
Dianne Hackborn813075a62011-11-14 17:45:19 -08007034 updateConfigurationLocked(configuration, null, false, true);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007035 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Initial config: " + mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007036 }
7037 }
7038
7039 public boolean testIsSystemReady() {
7040 // no need to synchronize(this) just to read & return the value
7041 return mSystemReady;
7042 }
7043
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007044 private static File getCalledPreBootReceiversFile() {
7045 File dataDir = Environment.getDataDirectory();
7046 File systemDir = new File(dataDir, "system");
7047 File fname = new File(systemDir, "called_pre_boots.dat");
7048 return fname;
7049 }
Dianne Hackborn661cd522011-08-22 00:26:20 -07007050
7051 static final int LAST_DONE_VERSION = 10000;
7052
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007053 private static ArrayList<ComponentName> readLastDonePreBootReceivers() {
7054 ArrayList<ComponentName> lastDoneReceivers = new ArrayList<ComponentName>();
7055 File file = getCalledPreBootReceiversFile();
7056 FileInputStream fis = null;
7057 try {
7058 fis = new FileInputStream(file);
7059 DataInputStream dis = new DataInputStream(new BufferedInputStream(fis, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007060 int fvers = dis.readInt();
7061 if (fvers == LAST_DONE_VERSION) {
7062 String vers = dis.readUTF();
7063 String codename = dis.readUTF();
7064 String build = dis.readUTF();
7065 if (android.os.Build.VERSION.RELEASE.equals(vers)
7066 && android.os.Build.VERSION.CODENAME.equals(codename)
7067 && android.os.Build.VERSION.INCREMENTAL.equals(build)) {
7068 int num = dis.readInt();
7069 while (num > 0) {
7070 num--;
7071 String pkg = dis.readUTF();
7072 String cls = dis.readUTF();
7073 lastDoneReceivers.add(new ComponentName(pkg, cls));
7074 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007075 }
7076 }
7077 } catch (FileNotFoundException e) {
7078 } catch (IOException e) {
7079 Slog.w(TAG, "Failure reading last done pre-boot receivers", e);
7080 } finally {
7081 if (fis != null) {
7082 try {
7083 fis.close();
7084 } catch (IOException e) {
7085 }
7086 }
7087 }
7088 return lastDoneReceivers;
7089 }
7090
7091 private static void writeLastDonePreBootReceivers(ArrayList<ComponentName> list) {
7092 File file = getCalledPreBootReceiversFile();
7093 FileOutputStream fos = null;
7094 DataOutputStream dos = null;
7095 try {
7096 Slog.i(TAG, "Writing new set of last done pre-boot receivers...");
7097 fos = new FileOutputStream(file);
7098 dos = new DataOutputStream(new BufferedOutputStream(fos, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007099 dos.writeInt(LAST_DONE_VERSION);
7100 dos.writeUTF(android.os.Build.VERSION.RELEASE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007101 dos.writeUTF(android.os.Build.VERSION.CODENAME);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007102 dos.writeUTF(android.os.Build.VERSION.INCREMENTAL);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007103 dos.writeInt(list.size());
7104 for (int i=0; i<list.size(); i++) {
7105 dos.writeUTF(list.get(i).getPackageName());
7106 dos.writeUTF(list.get(i).getClassName());
7107 }
7108 } catch (IOException e) {
7109 Slog.w(TAG, "Failure writing last done pre-boot receivers", e);
7110 file.delete();
7111 } finally {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07007112 FileUtils.sync(fos);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007113 if (dos != null) {
7114 try {
7115 dos.close();
7116 } catch (IOException e) {
7117 // TODO Auto-generated catch block
7118 e.printStackTrace();
7119 }
7120 }
7121 }
7122 }
7123
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007124 public void systemReady(final Runnable goingCallback) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007125 synchronized(this) {
7126 if (mSystemReady) {
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007127 if (goingCallback != null) goingCallback.run();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007128 return;
7129 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007130
7131 // Check to see if there are any update receivers to run.
7132 if (!mDidUpdate) {
7133 if (mWaitingUpdate) {
7134 return;
7135 }
7136 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
7137 List<ResolveInfo> ris = null;
7138 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007139 ris = AppGlobals.getPackageManager().queryIntentReceivers(
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007140 intent, null, 0);
7141 } catch (RemoteException e) {
7142 }
7143 if (ris != null) {
7144 for (int i=ris.size()-1; i>=0; i--) {
7145 if ((ris.get(i).activityInfo.applicationInfo.flags
7146 &ApplicationInfo.FLAG_SYSTEM) == 0) {
7147 ris.remove(i);
7148 }
7149 }
7150 intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007151
7152 ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers();
7153
7154 final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007155 for (int i=0; i<ris.size(); i++) {
7156 ActivityInfo ai = ris.get(i).activityInfo;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007157 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7158 if (lastDoneReceivers.contains(comp)) {
7159 ris.remove(i);
7160 i--;
7161 }
7162 }
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07007163
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007164 for (int i=0; i<ris.size(); i++) {
7165 ActivityInfo ai = ris.get(i).activityInfo;
7166 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7167 doneReceivers.add(comp);
7168 intent.setComponent(comp);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007169 IIntentReceiver finisher = null;
Dianne Hackbornd6847842010-01-12 18:14:19 -08007170 if (i == ris.size()-1) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007171 finisher = new IIntentReceiver.Stub() {
7172 public void performReceive(Intent intent, int resultCode,
Dianne Hackborn68d881c2009-10-05 13:58:17 -07007173 String data, Bundle extras, boolean ordered,
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007174 boolean sticky) {
7175 // The raw IIntentReceiver interface is called
7176 // with the AM lock held, so redispatch to
7177 // execute our code without the lock.
7178 mHandler.post(new Runnable() {
7179 public void run() {
7180 synchronized (ActivityManagerService.this) {
7181 mDidUpdate = true;
7182 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007183 writeLastDonePreBootReceivers(doneReceivers);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007184 showBootMessage(mContext.getText(
7185 R.string.android_upgrading_complete),
7186 false);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007187 systemReady(goingCallback);
7188 }
7189 });
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007190 }
7191 };
7192 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08007193 Slog.i(TAG, "Sending system update to: " + intent.getComponent());
Amith Yamasani742a6712011-05-04 14:49:28 -07007194 /* TODO: Send this to all users */
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007195 broadcastIntentLocked(null, null, intent, null, finisher,
Amith Yamasani742a6712011-05-04 14:49:28 -07007196 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID,
Amith Yamasanic600e21f2012-02-14 16:08:07 -08007197 0 /* UserId zero */);
Dianne Hackbornd6847842010-01-12 18:14:19 -08007198 if (finisher != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007199 mWaitingUpdate = true;
7200 }
7201 }
7202 }
7203 if (mWaitingUpdate) {
7204 return;
7205 }
7206 mDidUpdate = true;
7207 }
7208
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007209 mSystemReady = true;
7210 if (!mStartRunning) {
7211 return;
7212 }
7213 }
7214
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007215 ArrayList<ProcessRecord> procsToKill = null;
7216 synchronized(mPidsSelfLocked) {
7217 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
7218 ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7219 if (!isAllowedWhileBooting(proc.info)){
7220 if (procsToKill == null) {
7221 procsToKill = new ArrayList<ProcessRecord>();
7222 }
7223 procsToKill.add(proc);
7224 }
7225 }
7226 }
7227
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007228 synchronized(this) {
7229 if (procsToKill != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007230 for (int i=procsToKill.size()-1; i>=0; i--) {
7231 ProcessRecord proc = procsToKill.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007232 Slog.i(TAG, "Removing system update proc: " + proc);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007233 removeProcessLocked(proc, true, false, "system update done");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007234 }
7235 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007236
7237 // Now that we have cleaned up any update processes, we
7238 // are ready to start launching real processes and know that
7239 // we won't trample on them any more.
7240 mProcessesReady = true;
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007241 }
7242
Joe Onorato8a9b2202010-02-26 18:56:32 -08007243 Slog.i(TAG, "System now ready");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007244 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007245 SystemClock.uptimeMillis());
7246
7247 synchronized(this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007248 // Make sure we have no pre-ready processes sitting around.
7249
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007250 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
7251 ResolveInfo ri = mContext.getPackageManager()
7252 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST),
Dianne Hackborn1655be42009-05-08 14:29:01 -07007253 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007254 CharSequence errorMsg = null;
7255 if (ri != null) {
7256 ActivityInfo ai = ri.activityInfo;
7257 ApplicationInfo app = ai.applicationInfo;
7258 if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7259 mTopAction = Intent.ACTION_FACTORY_TEST;
7260 mTopData = null;
7261 mTopComponent = new ComponentName(app.packageName,
7262 ai.name);
7263 } else {
7264 errorMsg = mContext.getResources().getText(
7265 com.android.internal.R.string.factorytest_not_system);
7266 }
7267 } else {
7268 errorMsg = mContext.getResources().getText(
7269 com.android.internal.R.string.factorytest_no_action);
7270 }
7271 if (errorMsg != null) {
7272 mTopAction = null;
7273 mTopData = null;
7274 mTopComponent = null;
7275 Message msg = Message.obtain();
7276 msg.what = SHOW_FACTORY_ERROR_MSG;
7277 msg.getData().putCharSequence("msg", errorMsg);
7278 mHandler.sendMessage(msg);
7279 }
7280 }
7281 }
7282
7283 retrieveSettings();
7284
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007285 if (goingCallback != null) goingCallback.run();
7286
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007287 synchronized (this) {
7288 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
7289 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007290 List apps = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07007291 getPersistentApplications(STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007292 if (apps != null) {
7293 int N = apps.size();
7294 int i;
7295 for (i=0; i<N; i++) {
7296 ApplicationInfo info
7297 = (ApplicationInfo)apps.get(i);
7298 if (info != null &&
7299 !info.packageName.equals("android")) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007300 addAppLocked(info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007301 }
7302 }
7303 }
7304 } catch (RemoteException ex) {
7305 // pm is in same process, this will never happen.
7306 }
7307 }
7308
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007309 // Start up initial activity.
7310 mBooting = true;
7311
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007312 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007313 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007314 Message msg = Message.obtain();
7315 msg.what = SHOW_UID_ERROR_MSG;
7316 mHandler.sendMessage(msg);
7317 }
7318 } catch (RemoteException e) {
7319 }
7320
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007321 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007322 }
7323 }
7324
Dan Egnorb7f03672009-12-09 16:22:32 -08007325 private boolean makeAppCrashingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007326 String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007327 app.crashing = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007328 app.crashingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007329 ActivityManager.ProcessErrorStateInfo.CRASHED, null, shortMsg, longMsg, stackTrace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007330 startAppProblemLocked(app);
7331 app.stopFreezingAllLocked();
7332 return handleAppCrashLocked(app);
7333 }
7334
Dan Egnorb7f03672009-12-09 16:22:32 -08007335 private void makeAppNotRespondingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007336 String activity, String shortMsg, String longMsg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007337 app.notResponding = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007338 app.notRespondingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007339 ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING,
7340 activity, shortMsg, longMsg, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007341 startAppProblemLocked(app);
7342 app.stopFreezingAllLocked();
7343 }
7344
7345 /**
7346 * Generate a process error record, suitable for attachment to a ProcessRecord.
7347 *
7348 * @param app The ProcessRecord in which the error occurred.
7349 * @param condition Crashing, Application Not Responding, etc. Values are defined in
7350 * ActivityManager.AppErrorStateInfo
Dan Egnor60d87622009-12-16 16:32:58 -08007351 * @param activity The activity associated with the crash, if known.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007352 * @param shortMsg Short message describing the crash.
7353 * @param longMsg Long message describing the crash.
Dan Egnorb7f03672009-12-09 16:22:32 -08007354 * @param stackTrace Full crash stack trace, may be null.
7355 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007356 * @return Returns a fully-formed AppErrorStateInfo record.
7357 */
7358 private ActivityManager.ProcessErrorStateInfo generateProcessError(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007359 int condition, String activity, String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007360 ActivityManager.ProcessErrorStateInfo report = new ActivityManager.ProcessErrorStateInfo();
Dan Egnorb7f03672009-12-09 16:22:32 -08007361
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007362 report.condition = condition;
7363 report.processName = app.processName;
7364 report.pid = app.pid;
7365 report.uid = app.info.uid;
Dan Egnor60d87622009-12-16 16:32:58 -08007366 report.tag = activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007367 report.shortMsg = shortMsg;
7368 report.longMsg = longMsg;
Dan Egnorb7f03672009-12-09 16:22:32 -08007369 report.stackTrace = stackTrace;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007370
7371 return report;
7372 }
7373
Dan Egnor42471dd2010-01-07 17:25:22 -08007374 void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007375 synchronized (this) {
7376 app.crashing = false;
7377 app.crashingReport = null;
7378 app.notResponding = false;
7379 app.notRespondingReport = null;
7380 if (app.anrDialog == fromDialog) {
7381 app.anrDialog = null;
7382 }
7383 if (app.waitDialog == fromDialog) {
7384 app.waitDialog = null;
7385 }
7386 if (app.pid > 0 && app.pid != MY_PID) {
Dan Egnor42471dd2010-01-07 17:25:22 -08007387 handleAppCrashLocked(app);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007388 Slog.i(ActivityManagerService.TAG, "Killing " + app + ": user's request");
Dianne Hackborn8633e682010-04-22 16:03:41 -07007389 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
7390 app.processName, app.setAdj, "user's request after error");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007391 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007392 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007393 }
7394 }
Dan Egnor42471dd2010-01-07 17:25:22 -08007395
Dan Egnorb7f03672009-12-09 16:22:32 -08007396 private boolean handleAppCrashLocked(ProcessRecord app) {
Mike Lockwood86548c42011-09-13 17:21:46 -04007397 if (mHeadless) {
7398 Log.e(TAG, "handleAppCrashLocked: " + app.processName);
7399 return false;
7400 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007401 long now = SystemClock.uptimeMillis();
7402
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007403 Long crashTime;
7404 if (!app.isolated) {
7405 crashTime = mProcessCrashTimes.get(app.info.processName, app.uid);
7406 } else {
7407 crashTime = null;
7408 }
Dianne Hackborn7d608422011-08-07 16:24:18 -07007409 if (crashTime != null && now < crashTime+ProcessList.MIN_CRASH_INTERVAL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007410 // This process loses!
Joe Onorato8a9b2202010-02-26 18:56:32 -08007411 Slog.w(TAG, "Process " + app.info.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007412 + " has crashed too many times: killing!");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007413 EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007414 app.info.processName, app.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007415 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
7416 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007417 if (r.app == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007418 Slog.w(TAG, " Force finishing activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007419 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007420 r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED, null, "crashed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007421 }
7422 }
7423 if (!app.persistent) {
7424 // We don't want to start this process again until the user
7425 // explicitly does so... but for persistent process, we really
7426 // need to keep it running. If a persistent process is actually
7427 // repeatedly crashing, then badness for everyone.
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007428 EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007429 app.info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007430 if (!app.isolated) {
7431 // XXX We don't have a way to mark isolated processes
7432 // as bad, since they don't have a peristent identity.
7433 mBadProcesses.put(app.info.processName, app.uid, now);
7434 mProcessCrashTimes.remove(app.info.processName, app.uid);
7435 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007436 app.bad = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007437 app.removed = true;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07007438 // Don't let services in this process be restarted and potentially
7439 // annoy the user repeatedly. Unless it is persistent, since those
7440 // processes run critical code.
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007441 removeProcessLocked(app, false, false, "crash");
Dianne Hackborncb44d962011-03-10 17:02:27 -08007442 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007443 return false;
7444 }
Dianne Hackborncb44d962011-03-10 17:02:27 -08007445 mMainStack.resumeTopActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007446 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007447 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007448 if (r.app == app) {
7449 // If the top running activity is from this crashing
7450 // process, then terminate it to avoid getting in a loop.
7451 Slog.w(TAG, " Force finishing activity "
7452 + r.intent.getComponent().flattenToShortString());
Dianne Hackbornbe707852011-11-11 14:32:10 -08007453 int index = mMainStack.indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007454 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007455 Activity.RESULT_CANCELED, null, "crashed");
Dianne Hackborn070783f2010-12-29 16:46:28 -08007456 // Also terminate any activities below it that aren't yet
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007457 // stopped, to avoid a situation where one will get
7458 // re-start our crashing activity once it gets resumed again.
7459 index--;
7460 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007461 r = (ActivityRecord)mMainStack.mHistory.get(index);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007462 if (r.state == ActivityState.RESUMED
7463 || r.state == ActivityState.PAUSING
7464 || r.state == ActivityState.PAUSED) {
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08007465 if (!r.isHomeActivity || mHomeProcess != r.app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007466 Slog.w(TAG, " Force finishing activity "
7467 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007468 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007469 Activity.RESULT_CANCELED, null, "crashed");
7470 }
7471 }
7472 }
7473 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007474 }
7475
7476 // Bump up the crash count of any services currently running in the proc.
7477 if (app.services.size() != 0) {
7478 // Any services running in the application need to be placed
7479 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -07007480 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007481 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07007482 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007483 sr.crashCount++;
7484 }
7485 }
Mattias Larssona4fd0072010-06-22 22:37:03 +02007486
7487 // If the crashing process is what we consider to be the "home process" and it has been
7488 // replaced by a third-party app, clear the package preferred activities from packages
7489 // with a home activity running in the process to prevent a repeatedly crashing app
7490 // from blocking the user to manually clear the list.
7491 if (app == mHomeProcess && mHomeProcess.activities.size() > 0
7492 && (mHomeProcess.info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
7493 Iterator it = mHomeProcess.activities.iterator();
7494 while (it.hasNext()) {
Jean-Baptiste Queru5ea89f72010-07-30 09:30:31 -07007495 ActivityRecord r = (ActivityRecord)it.next();
Mattias Larssona4fd0072010-06-22 22:37:03 +02007496 if (r.isHomeActivity) {
7497 Log.i(TAG, "Clearing package preferred activities from " + r.packageName);
7498 try {
7499 ActivityThread.getPackageManager()
7500 .clearPackagePreferredActivities(r.packageName);
7501 } catch (RemoteException c) {
7502 // pm is in same process, this will never happen.
7503 }
7504 }
7505 }
7506 }
7507
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007508 if (!app.isolated) {
7509 // XXX Can't keep track of crash times for isolated processes,
7510 // because they don't have a perisistent identity.
7511 mProcessCrashTimes.put(app.info.processName, app.uid, now);
7512 }
7513
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007514 return true;
7515 }
7516
7517 void startAppProblemLocked(ProcessRecord app) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08007518 app.errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver(
7519 mContext, app.info.packageName, app.info.flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007520 skipCurrentReceiverLocked(app);
7521 }
7522
7523 void skipCurrentReceiverLocked(ProcessRecord app) {
Christopher Tatef46723b2012-01-26 14:19:24 -08007524 for (BroadcastQueue queue : mBroadcastQueues) {
7525 queue.skipCurrentReceiverLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007526 }
7527 }
7528
Dan Egnor60d87622009-12-16 16:32:58 -08007529 /**
7530 * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes.
7531 * The application process will exit immediately after this call returns.
7532 * @param app object of the crashing app, null for the system server
7533 * @param crashInfo describing the exception
7534 */
7535 public void handleApplicationCrash(IBinder app, ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007536 ProcessRecord r = findAppProcess(app, "Crash");
Jeff Sharkeya353d262011-10-28 11:12:06 -07007537 final String processName = app == null ? "system_server"
7538 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08007539
7540 EventLog.writeEvent(EventLogTags.AM_CRASH, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07007541 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08007542 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08007543 crashInfo.exceptionClassName,
7544 crashInfo.exceptionMessage,
7545 crashInfo.throwFileName,
7546 crashInfo.throwLineNumber);
7547
Jeff Sharkeya353d262011-10-28 11:12:06 -07007548 addErrorToDropBox("crash", r, processName, null, null, null, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08007549
7550 crashApplication(r, crashInfo);
7551 }
7552
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007553 public void handleApplicationStrictModeViolation(
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007554 IBinder app,
7555 int violationMask,
7556 StrictMode.ViolationInfo info) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007557 ProcessRecord r = findAppProcess(app, "StrictMode");
7558 if (r == null) {
7559 return;
7560 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007561
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007562 if ((violationMask & StrictMode.PENALTY_DROPBOX) != 0) {
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08007563 Integer stackFingerprint = info.hashCode();
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007564 boolean logIt = true;
7565 synchronized (mAlreadyLoggedViolatedStacks) {
7566 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) {
7567 logIt = false;
7568 // TODO: sub-sample into EventLog for these, with
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007569 // the info.durationMillis? Then we'd get
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007570 // the relative pain numbers, without logging all
7571 // the stack traces repeatedly. We'd want to do
7572 // likewise in the client code, which also does
7573 // dup suppression, before the Binder call.
7574 } else {
7575 if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) {
7576 mAlreadyLoggedViolatedStacks.clear();
7577 }
7578 mAlreadyLoggedViolatedStacks.add(stackFingerprint);
7579 }
7580 }
7581 if (logIt) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007582 logStrictModeViolationToDropBox(r, info);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007583 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007584 }
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007585
7586 if ((violationMask & StrictMode.PENALTY_DIALOG) != 0) {
7587 AppErrorResult result = new AppErrorResult();
7588 synchronized (this) {
7589 final long origId = Binder.clearCallingIdentity();
7590
7591 Message msg = Message.obtain();
7592 msg.what = SHOW_STRICT_MODE_VIOLATION_MSG;
7593 HashMap<String, Object> data = new HashMap<String, Object>();
7594 data.put("result", result);
7595 data.put("app", r);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007596 data.put("violationMask", violationMask);
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007597 data.put("info", info);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007598 msg.obj = data;
7599 mHandler.sendMessage(msg);
7600
7601 Binder.restoreCallingIdentity(origId);
7602 }
7603 int res = result.get();
Dianne Hackbornb424b632010-08-18 15:59:05 -07007604 Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007605 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007606 }
7607
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007608 // Depending on the policy in effect, there could be a bunch of
7609 // these in quick succession so we try to batch these together to
7610 // minimize disk writes, number of dropbox entries, and maximize
7611 // compression, by having more fewer, larger records.
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007612 private void logStrictModeViolationToDropBox(
7613 ProcessRecord process,
7614 StrictMode.ViolationInfo info) {
7615 if (info == null) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007616 return;
7617 }
7618 final boolean isSystemApp = process == null ||
7619 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM |
7620 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07007621 final String processName = process == null ? "unknown" : process.processName;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007622 final String dropboxTag = isSystemApp ? "system_app_strictmode" : "data_app_strictmode";
7623 final DropBoxManager dbox = (DropBoxManager)
7624 mContext.getSystemService(Context.DROPBOX_SERVICE);
7625
7626 // Exit early if the dropbox isn't configured to accept this report type.
7627 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
7628
7629 boolean bufferWasEmpty;
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007630 boolean needsFlush;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007631 final StringBuilder sb = isSystemApp ? mStrictModeBuffer : new StringBuilder(1024);
7632 synchronized (sb) {
7633 bufferWasEmpty = sb.length() == 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07007634 appendDropBoxProcessHeaders(process, processName, sb);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007635 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
7636 sb.append("System-App: ").append(isSystemApp).append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007637 sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n");
7638 if (info.violationNumThisLoop != 0) {
7639 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n");
7640 }
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07007641 if (info.numAnimationsRunning != 0) {
7642 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n");
7643 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07007644 if (info.broadcastIntentAction != null) {
7645 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n");
7646 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08007647 if (info.durationMillis != -1) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007648 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n");
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007649 }
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08007650 if (info.numInstances != -1) {
7651 sb.append("Instance-Count: ").append(info.numInstances).append("\n");
7652 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08007653 if (info.tags != null) {
7654 for (String tag : info.tags) {
7655 sb.append("Span-Tag: ").append(tag).append("\n");
7656 }
7657 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007658 sb.append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007659 if (info.crashInfo != null && info.crashInfo.stackTrace != null) {
7660 sb.append(info.crashInfo.stackTrace);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007661 }
7662 sb.append("\n");
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007663
7664 // Only buffer up to ~64k. Various logging bits truncate
7665 // things at 128k.
7666 needsFlush = (sb.length() > 64 * 1024);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007667 }
7668
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007669 // Flush immediately if the buffer's grown too large, or this
7670 // is a non-system app. Non-system apps are isolated with a
7671 // different tag & policy and not batched.
7672 //
7673 // Batching is useful during internal testing with
7674 // StrictMode settings turned up high. Without batching,
7675 // thousands of separate files could be created on boot.
7676 if (!isSystemApp || needsFlush) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007677 new Thread("Error dump: " + dropboxTag) {
7678 @Override
7679 public void run() {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007680 String report;
7681 synchronized (sb) {
7682 report = sb.toString();
7683 sb.delete(0, sb.length());
7684 sb.trimToSize();
7685 }
7686 if (report.length() != 0) {
7687 dbox.addText(dropboxTag, report);
7688 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007689 }
7690 }.start();
7691 return;
7692 }
7693
7694 // System app batching:
7695 if (!bufferWasEmpty) {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007696 // An existing dropbox-writing thread is outstanding, so
7697 // we don't need to start it up. The existing thread will
7698 // catch the buffer appends we just did.
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007699 return;
7700 }
7701
7702 // Worker thread to both batch writes and to avoid blocking the caller on I/O.
7703 // (After this point, we shouldn't access AMS internal data structures.)
7704 new Thread("Error dump: " + dropboxTag) {
7705 @Override
7706 public void run() {
7707 // 5 second sleep to let stacks arrive and be batched together
7708 try {
7709 Thread.sleep(5000); // 5 seconds
7710 } catch (InterruptedException e) {}
7711
7712 String errorReport;
7713 synchronized (mStrictModeBuffer) {
7714 errorReport = mStrictModeBuffer.toString();
7715 if (errorReport.length() == 0) {
7716 return;
7717 }
7718 mStrictModeBuffer.delete(0, mStrictModeBuffer.length());
7719 mStrictModeBuffer.trimToSize();
7720 }
7721 dbox.addText(dropboxTag, errorReport);
7722 }
7723 }.start();
7724 }
7725
Dan Egnor60d87622009-12-16 16:32:58 -08007726 /**
7727 * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors.
7728 * @param app object of the crashing app, null for the system server
7729 * @param tag reported by the caller
7730 * @param crashInfo describing the context of the error
7731 * @return true if the process should exit immediately (WTF is fatal)
7732 */
7733 public boolean handleApplicationWtf(IBinder app, String tag,
Dan Egnorb7f03672009-12-09 16:22:32 -08007734 ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007735 ProcessRecord r = findAppProcess(app, "WTF");
Jeff Sharkeya353d262011-10-28 11:12:06 -07007736 final String processName = app == null ? "system_server"
7737 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08007738
7739 EventLog.writeEvent(EventLogTags.AM_WTF, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07007740 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08007741 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08007742 tag, crashInfo.exceptionMessage);
7743
Jeff Sharkeya353d262011-10-28 11:12:06 -07007744 addErrorToDropBox("wtf", r, processName, null, null, tag, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08007745
Dianne Hackborn1ab43772011-03-15 14:38:02 -07007746 if (r != null && r.pid != Process.myPid() &&
7747 Settings.Secure.getInt(mContext.getContentResolver(),
7748 Settings.Secure.WTF_IS_FATAL, 0) != 0) {
Dan Egnor60d87622009-12-16 16:32:58 -08007749 crashApplication(r, crashInfo);
7750 return true;
7751 } else {
7752 return false;
7753 }
7754 }
7755
7756 /**
7757 * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit})
7758 * @return the corresponding {@link ProcessRecord} object, or null if none could be found
7759 */
Dianne Hackborncb44d962011-03-10 17:02:27 -08007760 private ProcessRecord findAppProcess(IBinder app, String reason) {
Dan Egnor60d87622009-12-16 16:32:58 -08007761 if (app == null) {
7762 return null;
7763 }
7764
7765 synchronized (this) {
7766 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
7767 final int NA = apps.size();
7768 for (int ia=0; ia<NA; ia++) {
7769 ProcessRecord p = apps.valueAt(ia);
7770 if (p.thread != null && p.thread.asBinder() == app) {
7771 return p;
7772 }
7773 }
7774 }
7775
Dianne Hackborncb44d962011-03-10 17:02:27 -08007776 Slog.w(TAG, "Can't find mystery application for " + reason
7777 + " from pid=" + Binder.getCallingPid()
7778 + " uid=" + Binder.getCallingUid() + ": " + app);
Dan Egnor60d87622009-12-16 16:32:58 -08007779 return null;
7780 }
7781 }
7782
7783 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007784 * Utility function for addErrorToDropBox and handleStrictModeViolation's logging
7785 * to append various headers to the dropbox log text.
Dan Egnor60d87622009-12-16 16:32:58 -08007786 */
Jeff Sharkeya353d262011-10-28 11:12:06 -07007787 private void appendDropBoxProcessHeaders(ProcessRecord process, String processName,
7788 StringBuilder sb) {
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08007789 // Watchdog thread ends up invoking this function (with
7790 // a null ProcessRecord) to add the stack file to dropbox.
7791 // Do not acquire a lock on this (am) in such cases, as it
7792 // could cause a potential deadlock, if and when watchdog
7793 // is invoked due to unavailability of lock on am and it
7794 // would prevent watchdog from killing system_server.
7795 if (process == null) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07007796 sb.append("Process: ").append(processName).append("\n");
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08007797 return;
7798 }
Brad Fitzpatrick1e02d362010-09-10 09:19:50 -07007799 // Note: ProcessRecord 'process' is guarded by the service
7800 // instance. (notably process.pkgList, which could otherwise change
7801 // concurrently during execution of this method)
7802 synchronized (this) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07007803 sb.append("Process: ").append(processName).append("\n");
Dan Egnora455d192010-03-12 08:52:28 -08007804 int flags = process.info.flags;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007805 IPackageManager pm = AppGlobals.getPackageManager();
Dan Egnora455d192010-03-12 08:52:28 -08007806 sb.append("Flags: 0x").append(Integer.toString(flags, 16)).append("\n");
7807 for (String pkg : process.pkgList) {
7808 sb.append("Package: ").append(pkg);
Dan Egnor42471dd2010-01-07 17:25:22 -08007809 try {
Dan Egnora455d192010-03-12 08:52:28 -08007810 PackageInfo pi = pm.getPackageInfo(pkg, 0);
7811 if (pi != null) {
7812 sb.append(" v").append(pi.versionCode);
7813 if (pi.versionName != null) {
7814 sb.append(" (").append(pi.versionName).append(")");
7815 }
7816 }
7817 } catch (RemoteException e) {
7818 Slog.e(TAG, "Error getting package info: " + pkg, e);
Dan Egnor60d87622009-12-16 16:32:58 -08007819 }
Dan Egnora455d192010-03-12 08:52:28 -08007820 sb.append("\n");
Dan Egnor60d87622009-12-16 16:32:58 -08007821 }
Dan Egnora455d192010-03-12 08:52:28 -08007822 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007823 }
7824
7825 private static String processClass(ProcessRecord process) {
7826 if (process == null || process.pid == MY_PID) {
7827 return "system_server";
7828 } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
7829 return "system_app";
7830 } else {
7831 return "data_app";
7832 }
7833 }
7834
7835 /**
7836 * Write a description of an error (crash, WTF, ANR) to the drop box.
7837 * @param eventType to include in the drop box tag ("crash", "wtf", etc.)
7838 * @param process which caused the error, null means the system server
7839 * @param activity which triggered the error, null if unknown
7840 * @param parent activity related to the error, null if unknown
7841 * @param subject line related to the error, null if absent
7842 * @param report in long form describing the error, null if absent
7843 * @param logFile to include in the report, null if none
7844 * @param crashInfo giving an application stack trace, null if absent
7845 */
7846 public void addErrorToDropBox(String eventType,
Jeff Sharkeya353d262011-10-28 11:12:06 -07007847 ProcessRecord process, String processName, ActivityRecord activity,
7848 ActivityRecord parent, String subject,
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007849 final String report, final File logFile,
7850 final ApplicationErrorReport.CrashInfo crashInfo) {
7851 // NOTE -- this must never acquire the ActivityManagerService lock,
7852 // otherwise the watchdog may be prevented from resetting the system.
7853
7854 final String dropboxTag = processClass(process) + "_" + eventType;
7855 final DropBoxManager dbox = (DropBoxManager)
7856 mContext.getSystemService(Context.DROPBOX_SERVICE);
7857
7858 // Exit early if the dropbox isn't configured to accept this report type.
7859 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
7860
7861 final StringBuilder sb = new StringBuilder(1024);
Jeff Sharkeya353d262011-10-28 11:12:06 -07007862 appendDropBoxProcessHeaders(process, processName, sb);
Dan Egnora455d192010-03-12 08:52:28 -08007863 if (activity != null) {
7864 sb.append("Activity: ").append(activity.shortComponentName).append("\n");
7865 }
7866 if (parent != null && parent.app != null && parent.app.pid != process.pid) {
7867 sb.append("Parent-Process: ").append(parent.app.processName).append("\n");
7868 }
7869 if (parent != null && parent != activity) {
7870 sb.append("Parent-Activity: ").append(parent.shortComponentName).append("\n");
7871 }
7872 if (subject != null) {
7873 sb.append("Subject: ").append(subject).append("\n");
7874 }
7875 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
Christian Lindeberg03d2ca62010-09-28 14:52:20 +02007876 if (Debug.isDebuggerConnected()) {
7877 sb.append("Debugger: Connected\n");
7878 }
Dan Egnora455d192010-03-12 08:52:28 -08007879 sb.append("\n");
7880
7881 // Do the rest in a worker thread to avoid blocking the caller on I/O
7882 // (After this point, we shouldn't access AMS internal data structures.)
7883 Thread worker = new Thread("Error dump: " + dropboxTag) {
7884 @Override
7885 public void run() {
7886 if (report != null) {
7887 sb.append(report);
7888 }
7889 if (logFile != null) {
7890 try {
7891 sb.append(FileUtils.readTextFile(logFile, 128 * 1024, "\n\n[[TRUNCATED]]"));
7892 } catch (IOException e) {
7893 Slog.e(TAG, "Error reading " + logFile, e);
7894 }
7895 }
7896 if (crashInfo != null && crashInfo.stackTrace != null) {
7897 sb.append(crashInfo.stackTrace);
7898 }
7899
7900 String setting = Settings.Secure.ERROR_LOGCAT_PREFIX + dropboxTag;
7901 int lines = Settings.Secure.getInt(mContext.getContentResolver(), setting, 0);
7902 if (lines > 0) {
7903 sb.append("\n");
7904
7905 // Merge several logcat streams, and take the last N lines
7906 InputStreamReader input = null;
7907 try {
7908 java.lang.Process logcat = new ProcessBuilder("/system/bin/logcat",
7909 "-v", "time", "-b", "events", "-b", "system", "-b", "main",
7910 "-t", String.valueOf(lines)).redirectErrorStream(true).start();
7911
7912 try { logcat.getOutputStream().close(); } catch (IOException e) {}
7913 try { logcat.getErrorStream().close(); } catch (IOException e) {}
7914 input = new InputStreamReader(logcat.getInputStream());
7915
7916 int num;
7917 char[] buf = new char[8192];
7918 while ((num = input.read(buf)) > 0) sb.append(buf, 0, num);
7919 } catch (IOException e) {
7920 Slog.e(TAG, "Error running logcat", e);
7921 } finally {
7922 if (input != null) try { input.close(); } catch (IOException e) {}
7923 }
7924 }
7925
7926 dbox.addText(dropboxTag, sb.toString());
Dan Egnor60d87622009-12-16 16:32:58 -08007927 }
Dan Egnora455d192010-03-12 08:52:28 -08007928 };
7929
7930 if (process == null || process.pid == MY_PID) {
7931 worker.run(); // We may be about to die -- need to run this synchronously
7932 } else {
7933 worker.start();
Dan Egnor60d87622009-12-16 16:32:58 -08007934 }
7935 }
7936
7937 /**
7938 * Bring up the "unexpected error" dialog box for a crashing app.
7939 * Deal with edge cases (intercepts from instrumented applications,
7940 * ActivityController, error intent receivers, that sort of thing).
7941 * @param r the application crashing
7942 * @param crashInfo describing the failure
7943 */
7944 private void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) {
Dan Egnorb7f03672009-12-09 16:22:32 -08007945 long timeMillis = System.currentTimeMillis();
7946 String shortMsg = crashInfo.exceptionClassName;
7947 String longMsg = crashInfo.exceptionMessage;
7948 String stackTrace = crashInfo.stackTrace;
7949 if (shortMsg != null && longMsg != null) {
7950 longMsg = shortMsg + ": " + longMsg;
7951 } else if (shortMsg != null) {
7952 longMsg = shortMsg;
7953 }
7954
Dan Egnor60d87622009-12-16 16:32:58 -08007955 AppErrorResult result = new AppErrorResult();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007956 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007957 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007958 try {
7959 String name = r != null ? r.processName : null;
7960 int pid = r != null ? r.pid : Binder.getCallingPid();
Dan Egnor60d87622009-12-16 16:32:58 -08007961 if (!mController.appCrashed(name, pid,
Dan Egnorb7f03672009-12-09 16:22:32 -08007962 shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007963 Slog.w(TAG, "Force-killing crashed app " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007964 + " at watcher's request");
7965 Process.killProcess(pid);
Dan Egnorb7f03672009-12-09 16:22:32 -08007966 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007967 }
7968 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007969 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007970 }
7971 }
7972
7973 final long origId = Binder.clearCallingIdentity();
7974
7975 // If this process is running instrumentation, finish it.
7976 if (r != null && r.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007977 Slog.w(TAG, "Error in app " + r.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007978 + " running instrumentation " + r.instrumentationClass + ":");
Joe Onorato8a9b2202010-02-26 18:56:32 -08007979 if (shortMsg != null) Slog.w(TAG, " " + shortMsg);
7980 if (longMsg != null) Slog.w(TAG, " " + longMsg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007981 Bundle info = new Bundle();
7982 info.putString("shortMsg", shortMsg);
7983 info.putString("longMsg", longMsg);
7984 finishInstrumentationLocked(r, Activity.RESULT_CANCELED, info);
7985 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08007986 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007987 }
7988
Dan Egnor60d87622009-12-16 16:32:58 -08007989 // If we can't identify the process or it's already exceeded its crash quota,
7990 // quit right away without showing a crash dialog.
7991 if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007992 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08007993 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007994 }
7995
7996 Message msg = Message.obtain();
7997 msg.what = SHOW_ERROR_MSG;
7998 HashMap data = new HashMap();
7999 data.put("result", result);
8000 data.put("app", r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008001 msg.obj = data;
8002 mHandler.sendMessage(msg);
8003
8004 Binder.restoreCallingIdentity(origId);
8005 }
8006
8007 int res = result.get();
8008
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008009 Intent appErrorIntent = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008010 synchronized (this) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008011 if (r != null && !r.isolated) {
8012 // XXX Can't keep track of crash time for isolated processes,
8013 // since they don't have a persistent identity.
8014 mProcessCrashTimes.put(r.info.processName, r.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008015 SystemClock.uptimeMillis());
8016 }
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008017 if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008018 appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008019 }
8020 }
8021
8022 if (appErrorIntent != null) {
8023 try {
8024 mContext.startActivity(appErrorIntent);
8025 } catch (ActivityNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008026 Slog.w(TAG, "bug report receiver dissappeared", e);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008027 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008028 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008029 }
Dan Egnorb7f03672009-12-09 16:22:32 -08008030
8031 Intent createAppErrorIntentLocked(ProcessRecord r,
8032 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
8033 ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008034 if (report == null) {
8035 return null;
8036 }
8037 Intent result = new Intent(Intent.ACTION_APP_ERROR);
8038 result.setComponent(r.errorReportReceiver);
8039 result.putExtra(Intent.EXTRA_BUG_REPORT, report);
8040 result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
8041 return result;
8042 }
8043
Dan Egnorb7f03672009-12-09 16:22:32 -08008044 private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r,
8045 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008046 if (r.errorReportReceiver == null) {
8047 return null;
8048 }
8049
8050 if (!r.crashing && !r.notResponding) {
8051 return null;
8052 }
8053
Dan Egnorb7f03672009-12-09 16:22:32 -08008054 ApplicationErrorReport report = new ApplicationErrorReport();
8055 report.packageName = r.info.packageName;
8056 report.installerPackageName = r.errorReportReceiver.getPackageName();
8057 report.processName = r.processName;
8058 report.time = timeMillis;
Jacek Surazskie0ee6ef2010-01-07 16:23:03 +01008059 report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008060
Dan Egnorb7f03672009-12-09 16:22:32 -08008061 if (r.crashing) {
8062 report.type = ApplicationErrorReport.TYPE_CRASH;
8063 report.crashInfo = crashInfo;
8064 } else if (r.notResponding) {
8065 report.type = ApplicationErrorReport.TYPE_ANR;
8066 report.anrInfo = new ApplicationErrorReport.AnrInfo();
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008067
Dan Egnorb7f03672009-12-09 16:22:32 -08008068 report.anrInfo.activity = r.notRespondingReport.tag;
8069 report.anrInfo.cause = r.notRespondingReport.shortMsg;
8070 report.anrInfo.info = r.notRespondingReport.longMsg;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008071 }
8072
Dan Egnorb7f03672009-12-09 16:22:32 -08008073 return report;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008074 }
8075
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008076 public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008077 enforceNotIsolatedCaller("getProcessesInErrorState");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008078 // assume our apps are happy - lazy create the list
8079 List<ActivityManager.ProcessErrorStateInfo> errList = null;
8080
8081 synchronized (this) {
8082
8083 // iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008084 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8085 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008086 if ((app.thread != null) && (app.crashing || app.notResponding)) {
8087 // This one's in trouble, so we'll generate a report for it
8088 // crashes are higher priority (in case there's a crash *and* an anr)
8089 ActivityManager.ProcessErrorStateInfo report = null;
8090 if (app.crashing) {
8091 report = app.crashingReport;
8092 } else if (app.notResponding) {
8093 report = app.notRespondingReport;
8094 }
8095
8096 if (report != null) {
8097 if (errList == null) {
8098 errList = new ArrayList<ActivityManager.ProcessErrorStateInfo>(1);
8099 }
8100 errList.add(report);
8101 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008102 Slog.w(TAG, "Missing app error report, app = " + app.processName +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008103 " crashing = " + app.crashing +
8104 " notResponding = " + app.notResponding);
8105 }
8106 }
8107 }
8108 }
8109
8110 return errList;
8111 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07008112
8113 static int oomAdjToImportance(int adj, ActivityManager.RunningAppProcessInfo currApp) {
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008114 if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008115 if (currApp != null) {
8116 currApp.lru = adj - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
8117 }
8118 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008119 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
8120 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008121 } else if (adj >= ProcessList.HOME_APP_ADJ) {
8122 if (currApp != null) {
8123 currApp.lru = 0;
8124 }
8125 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008126 } else if (adj >= ProcessList.SERVICE_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008127 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
8128 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
8129 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
8130 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
8131 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
8132 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
8133 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
8134 } else {
8135 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
8136 }
8137 }
8138
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008139 private void fillInProcMemInfo(ProcessRecord app,
8140 ActivityManager.RunningAppProcessInfo outInfo) {
8141 outInfo.pid = app.pid;
8142 outInfo.uid = app.info.uid;
8143 if (mHeavyWeightProcess == app) {
8144 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_CANT_SAVE_STATE;
8145 }
8146 if (app.persistent) {
8147 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_PERSISTENT;
8148 }
8149 outInfo.lastTrimLevel = app.trimMemoryLevel;
8150 int adj = app.curAdj;
8151 outInfo.importance = oomAdjToImportance(adj, outInfo);
8152 outInfo.importanceReasonCode = app.adjTypeCode;
8153 }
8154
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008155 public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008156 enforceNotIsolatedCaller("getRunningAppProcesses");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008157 // Lazy instantiation of list
8158 List<ActivityManager.RunningAppProcessInfo> runList = null;
8159 synchronized (this) {
8160 // Iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008161 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8162 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008163 if ((app.thread != null) && (!app.crashing && !app.notResponding)) {
8164 // Generate process state info for running application
8165 ActivityManager.RunningAppProcessInfo currApp =
8166 new ActivityManager.RunningAppProcessInfo(app.processName,
8167 app.pid, app.getPackageList());
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008168 fillInProcMemInfo(app, currApp);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008169 if (app.adjSource instanceof ProcessRecord) {
8170 currApp.importanceReasonPid = ((ProcessRecord)app.adjSource).pid;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008171 currApp.importanceReasonImportance = oomAdjToImportance(
8172 app.adjSourceOom, null);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008173 } else if (app.adjSource instanceof ActivityRecord) {
8174 ActivityRecord r = (ActivityRecord)app.adjSource;
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008175 if (r.app != null) currApp.importanceReasonPid = r.app.pid;
8176 }
8177 if (app.adjTarget instanceof ComponentName) {
8178 currApp.importanceReasonComponent = (ComponentName)app.adjTarget;
8179 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08008180 //Slog.v(TAG, "Proc " + app.processName + ": imp=" + currApp.importance
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008181 // + " lru=" + currApp.lru);
8182 if (runList == null) {
8183 runList = new ArrayList<ActivityManager.RunningAppProcessInfo>();
8184 }
8185 runList.add(currApp);
8186 }
8187 }
8188 }
8189 return runList;
8190 }
8191
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008192 public List<ApplicationInfo> getRunningExternalApplications() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008193 enforceNotIsolatedCaller("getRunningExternalApplications");
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008194 List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses();
8195 List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>();
8196 if (runningApps != null && runningApps.size() > 0) {
8197 Set<String> extList = new HashSet<String>();
8198 for (ActivityManager.RunningAppProcessInfo app : runningApps) {
8199 if (app.pkgList != null) {
8200 for (String pkg : app.pkgList) {
8201 extList.add(pkg);
8202 }
8203 }
8204 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008205 IPackageManager pm = AppGlobals.getPackageManager();
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008206 for (String pkg : extList) {
8207 try {
8208 ApplicationInfo info = pm.getApplicationInfo(pkg, 0);
8209 if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
8210 retList.add(info);
8211 }
8212 } catch (RemoteException e) {
8213 }
8214 }
8215 }
8216 return retList;
8217 }
8218
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008219 @Override
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008220 public void getMyMemoryState(ActivityManager.RunningAppProcessInfo outInfo) {
8221 enforceNotIsolatedCaller("getMyMemoryState");
8222 synchronized (this) {
8223 ProcessRecord proc;
8224 synchronized (mPidsSelfLocked) {
8225 proc = mPidsSelfLocked.get(Binder.getCallingPid());
8226 }
8227 fillInProcMemInfo(proc, outInfo);
8228 }
8229 }
8230
8231 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008232 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008233 if (checkCallingPermission(android.Manifest.permission.DUMP)
8234 != PackageManager.PERMISSION_GRANTED) {
8235 pw.println("Permission Denial: can't dump ActivityManager from from pid="
8236 + Binder.getCallingPid()
8237 + ", uid=" + Binder.getCallingUid()
8238 + " without permission "
8239 + android.Manifest.permission.DUMP);
8240 return;
8241 }
8242
8243 boolean dumpAll = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008244 boolean dumpClient = false;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008245 String dumpPackage = null;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008246
8247 int opti = 0;
8248 while (opti < args.length) {
8249 String opt = args[opti];
8250 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
8251 break;
8252 }
8253 opti++;
8254 if ("-a".equals(opt)) {
8255 dumpAll = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008256 } else if ("-c".equals(opt)) {
8257 dumpClient = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008258 } else if ("-h".equals(opt)) {
8259 pw.println("Activity manager dump options:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008260 pw.println(" [-a] [-c] [-h] [cmd] ...");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008261 pw.println(" cmd may be one of:");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008262 pw.println(" a[ctivities]: activity stack state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008263 pw.println(" b[roadcasts] [PACKAGE_NAME]: broadcast state");
8264 pw.println(" i[ntents] [PACKAGE_NAME]: pending intent state");
8265 pw.println(" p[rocesses] [PACKAGE_NAME]: process state");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008266 pw.println(" o[om]: out of memory management");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008267 pw.println(" prov[iders] [COMP_SPEC ...]: content provider state");
Marco Nelissen18cb2872011-11-15 11:19:53 -08008268 pw.println(" provider [COMP_SPEC]: provider client-side state");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008269 pw.println(" s[ervices] [COMP_SPEC ...]: service state");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008270 pw.println(" service [COMP_SPEC]: service client-side state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008271 pw.println(" package [PACKAGE_NAME]: all state related to given package");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008272 pw.println(" all: dump all activities");
8273 pw.println(" top: dump the top activity");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008274 pw.println(" cmd may also be a COMP_SPEC to dump activities.");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008275 pw.println(" COMP_SPEC may be a component name (com.foo/.myApp),");
8276 pw.println(" a partial substring in a component name, a");
8277 pw.println(" hex object identifier.");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008278 pw.println(" -a: include all available server state.");
8279 pw.println(" -c: include client state.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008280 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008281 } else {
8282 pw.println("Unknown argument: " + opt + "; use -h for help");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008283 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008284 }
8285
8286 // Is the caller requesting to dump a particular piece of data?
8287 if (opti < args.length) {
8288 String cmd = args[opti];
8289 opti++;
8290 if ("activities".equals(cmd) || "a".equals(cmd)) {
8291 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008292 dumpActivitiesLocked(fd, pw, args, opti, true, dumpClient, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008293 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008294 return;
8295 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008296 String[] newArgs;
8297 String name;
8298 if (opti >= args.length) {
8299 name = null;
8300 newArgs = EMPTY_STRING_ARRAY;
8301 } else {
8302 name = args[opti];
8303 opti++;
8304 newArgs = new String[args.length - opti];
8305 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8306 args.length - opti);
8307 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008308 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008309 dumpBroadcastsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008310 }
8311 return;
8312 } else if ("intents".equals(cmd) || "i".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008313 String[] newArgs;
8314 String name;
8315 if (opti >= args.length) {
8316 name = null;
8317 newArgs = EMPTY_STRING_ARRAY;
8318 } else {
8319 name = args[opti];
8320 opti++;
8321 newArgs = new String[args.length - opti];
8322 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8323 args.length - opti);
8324 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008325 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008326 dumpPendingIntentsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008327 }
8328 return;
8329 } else if ("processes".equals(cmd) || "p".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008330 String[] newArgs;
8331 String name;
8332 if (opti >= args.length) {
8333 name = null;
8334 newArgs = EMPTY_STRING_ARRAY;
8335 } else {
8336 name = args[opti];
8337 opti++;
8338 newArgs = new String[args.length - opti];
8339 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8340 args.length - opti);
8341 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008342 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008343 dumpProcessesLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008344 }
8345 return;
Dianne Hackborn287952c2010-09-22 22:34:31 -07008346 } else if ("oom".equals(cmd) || "o".equals(cmd)) {
8347 synchronized (this) {
8348 dumpOomLocked(fd, pw, args, opti, true);
8349 }
8350 return;
Marco Nelissen18cb2872011-11-15 11:19:53 -08008351 } else if ("provider".equals(cmd)) {
8352 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, args.length - opti);
8362 }
8363 if (!dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) {
8364 pw.println("No providers match: " + name);
8365 pw.println("Use -h for help.");
8366 }
8367 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008368 } else if ("providers".equals(cmd) || "prov".equals(cmd)) {
8369 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008370 dumpProvidersLocked(fd, pw, args, opti, true, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008371 }
8372 return;
8373 } else if ("service".equals(cmd)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008374 String[] newArgs;
8375 String name;
8376 if (opti >= args.length) {
8377 name = null;
8378 newArgs = EMPTY_STRING_ARRAY;
8379 } else {
8380 name = args[opti];
8381 opti++;
8382 newArgs = new String[args.length - opti];
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008383 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8384 args.length - opti);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008385 }
8386 if (!dumpService(fd, pw, name, newArgs, 0, dumpAll)) {
8387 pw.println("No services match: " + name);
8388 pw.println("Use -h for help.");
8389 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008390 return;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008391 } else if ("package".equals(cmd)) {
8392 String[] newArgs;
8393 if (opti >= args.length) {
8394 pw.println("package: no package name specified");
8395 pw.println("Use -h for help.");
8396 return;
8397 } else {
8398 dumpPackage = args[opti];
8399 opti++;
8400 newArgs = new String[args.length - opti];
8401 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8402 args.length - opti);
8403 args = newArgs;
8404 opti = 0;
8405 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008406 } else if ("services".equals(cmd) || "s".equals(cmd)) {
8407 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008408 dumpServicesLocked(fd, pw, args, opti, true, dumpClient, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008409 }
8410 return;
Dianne Hackborn625ac272010-09-17 18:29:22 -07008411 } else {
8412 // Dumping a single activity?
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008413 if (!dumpActivity(fd, pw, cmd, args, opti, dumpAll)) {
8414 pw.println("Bad activity command, or no activities match: " + cmd);
8415 pw.println("Use -h for help.");
Dianne Hackborn625ac272010-09-17 18:29:22 -07008416 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08008417 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008418 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008419 }
8420
8421 // No piece of data specified, dump everything.
8422 synchronized (this) {
8423 boolean needSep;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008424 needSep = dumpPendingIntentsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008425 if (needSep) {
8426 pw.println(" ");
8427 }
8428 if (dumpAll) {
8429 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008430 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008431 needSep = dumpBroadcastsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008432 if (needSep) {
8433 pw.println(" ");
8434 }
8435 if (dumpAll) {
8436 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008437 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008438 needSep = dumpProvidersLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008439 if (needSep) {
8440 pw.println(" ");
8441 }
8442 if (dumpAll) {
8443 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008444 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008445 needSep = dumpServicesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008446 if (needSep) {
8447 pw.println(" ");
8448 }
8449 if (dumpAll) {
8450 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008451 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008452 needSep = dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008453 if (needSep) {
8454 pw.println(" ");
8455 }
8456 if (dumpAll) {
8457 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008458 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008459 dumpProcessesLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008460 }
8461 }
8462
8463 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008464 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008465 pw.println("ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
8466 pw.println(" Main stack:");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008467 dumpHistoryList(fd, pw, mMainStack.mHistory, " ", "Hist", true, !dumpAll, dumpClient,
8468 dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008469 pw.println(" ");
8470 pw.println(" Running activities (most recent first):");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008471 dumpHistoryList(fd, pw, mMainStack.mLRUActivities, " ", "Run", false, !dumpAll, false,
8472 dumpPackage);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008473 if (mMainStack.mWaitingVisibleActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008474 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008475 pw.println(" Activities waiting for another to become visible:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008476 dumpHistoryList(fd, pw, mMainStack.mWaitingVisibleActivities, " ", "Wait", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008477 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008478 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008479 if (mMainStack.mStoppingActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008480 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008481 pw.println(" Activities waiting to stop:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008482 dumpHistoryList(fd, pw, mMainStack.mStoppingActivities, " ", "Stop", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008483 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008484 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008485 if (mMainStack.mGoingToSleepActivities.size() > 0) {
8486 pw.println(" ");
8487 pw.println(" Activities waiting to sleep:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008488 dumpHistoryList(fd, pw, mMainStack.mGoingToSleepActivities, " ", "Sleep", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008489 !dumpAll, false, dumpPackage);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008490 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008491 if (mMainStack.mFinishingActivities.size() > 0) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008492 pw.println(" ");
8493 pw.println(" Activities waiting to finish:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008494 dumpHistoryList(fd, pw, mMainStack.mFinishingActivities, " ", "Fin", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008495 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008496 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008497
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008498 pw.println(" ");
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08008499 if (mMainStack.mPausingActivity != null) {
8500 pw.println(" mPausingActivity: " + mMainStack.mPausingActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008501 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008502 pw.println(" mResumedActivity: " + mMainStack.mResumedActivity);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008503 pw.println(" mFocusedActivity: " + mFocusedActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008504 if (dumpAll) {
8505 pw.println(" mLastPausedActivity: " + mMainStack.mLastPausedActivity);
8506 pw.println(" mSleepTimeout: " + mMainStack.mSleepTimeout);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07008507 pw.println(" mDismissKeyguardOnNextActivity: "
8508 + mMainStack.mDismissKeyguardOnNextActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008509 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008510
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008511 if (mRecentTasks.size() > 0) {
8512 pw.println();
8513 pw.println(" Recent tasks:");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008514
8515 final int N = mRecentTasks.size();
8516 for (int i=0; i<N; i++) {
8517 TaskRecord tr = mRecentTasks.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008518 if (dumpPackage != null) {
8519 if (tr.realActivity == null ||
8520 !dumpPackage.equals(tr.realActivity)) {
8521 continue;
8522 }
8523 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008524 pw.print(" * Recent #"); pw.print(i); pw.print(": ");
8525 pw.println(tr);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008526 if (dumpAll) {
8527 mRecentTasks.get(i).dump(pw, " ");
8528 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008529 }
8530 }
8531
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008532 if (dumpAll) {
8533 pw.println(" ");
8534 pw.println(" mCurTask: " + mCurTask);
8535 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008536
8537 return true;
8538 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008539
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008540 boolean dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008541 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008542 boolean needSep = false;
8543 int numPers = 0;
8544
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008545 pw.println("ACTIVITY MANAGER RUNNING PROCESSES (dumpsys activity processes)");
8546
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008547 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008548 for (SparseArray<ProcessRecord> procs : mProcessNames.getMap().values()) {
8549 final int NA = procs.size();
8550 for (int ia=0; ia<NA; ia++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008551 ProcessRecord r = procs.valueAt(ia);
8552 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8553 continue;
8554 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008555 if (!needSep) {
8556 pw.println(" All known processes:");
8557 needSep = true;
8558 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008559 pw.print(r.persistent ? " *PERS*" : " *APP*");
8560 pw.print(" UID "); pw.print(procs.keyAt(ia));
8561 pw.print(" "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008562 r.dump(pw, " ");
8563 if (r.persistent) {
8564 numPers++;
8565 }
8566 }
8567 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008568 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008569
8570 if (mIsolatedProcesses.size() > 0) {
8571 if (needSep) pw.println(" ");
8572 needSep = true;
8573 pw.println(" Isolated process list (sorted by uid):");
8574 for (int i=0; i<mIsolatedProcesses.size(); i++) {
8575 ProcessRecord r = mIsolatedProcesses.valueAt(i);
8576 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8577 continue;
8578 }
8579 pw.println(String.format("%sIsolated #%2d: %s",
8580 " ", i, r.toString()));
8581 }
8582 }
8583
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008584 if (mLruProcesses.size() > 0) {
8585 if (needSep) pw.println(" ");
8586 needSep = true;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008587 pw.println(" Process LRU list (sorted by oom_adj):");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008588 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008589 "Proc", "PERS", false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008590 needSep = true;
8591 }
8592
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008593 if (dumpAll) {
8594 synchronized (mPidsSelfLocked) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008595 boolean printed = false;
8596 for (int i=0; i<mPidsSelfLocked.size(); i++) {
8597 ProcessRecord r = mPidsSelfLocked.valueAt(i);
8598 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8599 continue;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008600 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008601 if (!printed) {
8602 if (needSep) pw.println(" ");
8603 needSep = true;
8604 pw.println(" PID mappings:");
8605 printed = true;
8606 }
8607 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i));
8608 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008609 }
8610 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008611 }
8612
8613 if (mForegroundProcesses.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008614 synchronized (mPidsSelfLocked) {
8615 boolean printed = false;
8616 for (int i=0; i<mForegroundProcesses.size(); i++) {
8617 ProcessRecord r = mPidsSelfLocked.get(
8618 mForegroundProcesses.valueAt(i).pid);
8619 if (dumpPackage != null && (r == null
8620 || !dumpPackage.equals(r.info.packageName))) {
8621 continue;
8622 }
8623 if (!printed) {
8624 if (needSep) pw.println(" ");
8625 needSep = true;
8626 pw.println(" Foreground Processes:");
8627 printed = true;
8628 }
8629 pw.print(" PID #"); pw.print(mForegroundProcesses.keyAt(i));
8630 pw.print(": "); pw.println(mForegroundProcesses.valueAt(i));
8631 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008632 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008633 }
8634
8635 if (mPersistentStartingProcesses.size() > 0) {
8636 if (needSep) pw.println(" ");
8637 needSep = true;
8638 pw.println(" Persisent processes that are starting:");
8639 dumpProcessList(pw, this, mPersistentStartingProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008640 "Starting Norm", "Restarting PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008641 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008642
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008643 if (mRemovedProcesses.size() > 0) {
8644 if (needSep) pw.println(" ");
8645 needSep = true;
8646 pw.println(" Processes that are being removed:");
8647 dumpProcessList(pw, this, mRemovedProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008648 "Removed Norm", "Removed PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008649 }
8650
8651 if (mProcessesOnHold.size() > 0) {
8652 if (needSep) pw.println(" ");
8653 needSep = true;
8654 pw.println(" Processes that are on old until the system is ready:");
8655 dumpProcessList(pw, this, mProcessesOnHold, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008656 "OnHold Norm", "OnHold PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008657 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008658
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008659 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008660
8661 if (mProcessCrashTimes.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008662 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008663 long now = SystemClock.uptimeMillis();
8664 for (Map.Entry<String, SparseArray<Long>> procs
8665 : mProcessCrashTimes.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008666 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008667 SparseArray<Long> uids = procs.getValue();
8668 final int N = uids.size();
8669 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008670 int puid = uids.keyAt(i);
8671 ProcessRecord r = mProcessNames.get(pname, puid);
8672 if (dumpPackage != null && (r == null
8673 || !dumpPackage.equals(r.info.packageName))) {
8674 continue;
8675 }
8676 if (!printed) {
8677 if (needSep) pw.println(" ");
8678 needSep = true;
8679 pw.println(" Time since processes crashed:");
8680 printed = true;
8681 }
8682 pw.print(" Process "); pw.print(pname);
8683 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008684 pw.print(": last crashed ");
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008685 TimeUtils.formatDuration(now-uids.valueAt(i), pw);
8686 pw.println(" ago");
Dianne Hackbornfd12af42009-08-27 00:44:33 -07008687 }
8688 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008689 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008690
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008691 if (mBadProcesses.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008692 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008693 for (Map.Entry<String, SparseArray<Long>> procs
8694 : mBadProcesses.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008695 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008696 SparseArray<Long> uids = procs.getValue();
8697 final int N = uids.size();
8698 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008699 int puid = uids.keyAt(i);
8700 ProcessRecord r = mProcessNames.get(pname, puid);
8701 if (dumpPackage != null && (r == null
8702 || !dumpPackage.equals(r.info.packageName))) {
8703 continue;
8704 }
8705 if (!printed) {
8706 if (needSep) pw.println(" ");
8707 needSep = true;
8708 pw.println(" Bad processes:");
8709 }
8710 pw.print(" Bad process "); pw.print(pname);
8711 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008712 pw.print(": crashed at time ");
8713 pw.println(uids.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008714 }
8715 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008716 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008717
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008718 pw.println();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008719 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07008720 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn50685602011-12-01 12:23:37 -08008721 if (dumpAll) {
8722 StringBuilder sb = new StringBuilder(128);
8723 sb.append(" mPreviousProcessVisibleTime: ");
8724 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
8725 pw.println(sb);
8726 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07008727 if (mHeavyWeightProcess != null) {
8728 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
8729 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008730 pw.println(" mConfiguration: " + mConfiguration);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008731 if (dumpAll) {
8732 pw.println(" mConfigWillChange: " + mMainStack.mConfigWillChange);
Dianne Hackborn3d0724d2011-05-12 15:39:41 -07008733 if (mCompatModePackages.getPackages().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008734 boolean printed = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07008735 for (Map.Entry<String, Integer> entry
8736 : mCompatModePackages.getPackages().entrySet()) {
8737 String pkg = entry.getKey();
8738 int mode = entry.getValue();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008739 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
8740 continue;
8741 }
8742 if (!printed) {
8743 pw.println(" mScreenCompatPackages:");
8744 printed = true;
8745 }
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07008746 pw.print(" "); pw.print(pkg); pw.print(": ");
8747 pw.print(mode); pw.println();
8748 }
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07008749 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008750 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008751 pw.println(" mSleeping=" + mSleeping + " mShuttingDown=" + mShuttingDown);
8752 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
8753 || mOrigWaitForDebugger) {
8754 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp
8755 + " mDebugTransient=" + mDebugTransient
8756 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger);
8757 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08008758 if (mOpenGlTraceApp != null) {
8759 pw.println(" mOpenGlTraceApp=" + mOpenGlTraceApp);
8760 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07008761 if (mProfileApp != null || mProfileProc != null || mProfileFile != null
8762 || mProfileFd != null) {
8763 pw.println(" mProfileApp=" + mProfileApp + " mProfileProc=" + mProfileProc);
8764 pw.println(" mProfileFile=" + mProfileFile + " mProfileFd=" + mProfileFd);
8765 pw.println(" mProfileType=" + mProfileType + " mAutoStopProfiler="
8766 + mAutoStopProfiler);
8767 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008768 if (mAlwaysFinishActivities || mController != null) {
8769 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities
8770 + " mController=" + mController);
8771 }
8772 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008773 pw.println(" Total persistent processes: " + numPers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008774 pw.println(" mStartRunning=" + mStartRunning
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07008775 + " mProcessesReady=" + mProcessesReady
8776 + " mSystemReady=" + mSystemReady);
8777 pw.println(" mBooting=" + mBooting
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008778 + " mBooted=" + mBooted
8779 + " mFactoryTest=" + mFactoryTest);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008780 pw.print(" mLastPowerCheckRealtime=");
8781 TimeUtils.formatDuration(mLastPowerCheckRealtime, pw);
8782 pw.println("");
8783 pw.print(" mLastPowerCheckUptime=");
8784 TimeUtils.formatDuration(mLastPowerCheckUptime, pw);
8785 pw.println("");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008786 pw.println(" mGoingToSleep=" + mMainStack.mGoingToSleep);
8787 pw.println(" mLaunchingActivity=" + mMainStack.mLaunchingActivity);
Dianne Hackborn906497c2010-05-10 15:57:38 -07008788 pw.println(" mAdjSeq=" + mAdjSeq + " mLruSeq=" + mLruSeq);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008789 pw.println(" mNumServiceProcs=" + mNumServiceProcs
8790 + " mNewNumServiceProcs=" + mNewNumServiceProcs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008791 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008792
8793 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008794 }
8795
Dianne Hackborn287952c2010-09-22 22:34:31 -07008796 boolean dumpProcessesToGc(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008797 int opti, boolean needSep, boolean dumpAll, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07008798 if (mProcessesToGc.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008799 boolean printed = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -07008800 long now = SystemClock.uptimeMillis();
8801 for (int i=0; i<mProcessesToGc.size(); i++) {
8802 ProcessRecord proc = mProcessesToGc.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008803 if (dumpPackage != null && !dumpPackage.equals(proc.info.packageName)) {
8804 continue;
8805 }
8806 if (!printed) {
8807 if (needSep) pw.println(" ");
8808 needSep = true;
8809 pw.println(" Processes that are waiting to GC:");
8810 printed = true;
8811 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008812 pw.print(" Process "); pw.println(proc);
8813 pw.print(" lowMem="); pw.print(proc.reportLowMemory);
8814 pw.print(", last gced=");
8815 pw.print(now-proc.lastRequestedGc);
8816 pw.print(" ms ago, last lowMem=");
8817 pw.print(now-proc.lastLowMemory);
8818 pw.println(" ms ago");
8819
8820 }
8821 }
8822 return needSep;
8823 }
8824
8825 boolean dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args,
8826 int opti, boolean dumpAll) {
8827 boolean needSep = false;
8828
8829 if (mLruProcesses.size() > 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07008830 if (needSep) pw.println(" ");
8831 needSep = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -07008832 pw.println(" OOM levels:");
Dianne Hackborn7d608422011-08-07 16:24:18 -07008833 pw.print(" SYSTEM_ADJ: "); pw.println(ProcessList.SYSTEM_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008834 pw.print(" PERSISTENT_PROC_ADJ: "); pw.println(ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07008835 pw.print(" FOREGROUND_APP_ADJ: "); pw.println(ProcessList.FOREGROUND_APP_ADJ);
8836 pw.print(" VISIBLE_APP_ADJ: "); pw.println(ProcessList.VISIBLE_APP_ADJ);
8837 pw.print(" PERCEPTIBLE_APP_ADJ: "); pw.println(ProcessList.PERCEPTIBLE_APP_ADJ);
8838 pw.print(" HEAVY_WEIGHT_APP_ADJ: "); pw.println(ProcessList.HEAVY_WEIGHT_APP_ADJ);
8839 pw.print(" BACKUP_APP_ADJ: "); pw.println(ProcessList.BACKUP_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008840 pw.print(" SERVICE_ADJ: "); pw.println(ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07008841 pw.print(" HOME_APP_ADJ: "); pw.println(ProcessList.HOME_APP_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07008842 pw.print(" PREVIOUS_APP_ADJ: "); pw.println(ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008843 pw.print(" SERVICE_B_ADJ: "); pw.println(ProcessList.SERVICE_B_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07008844 pw.print(" HIDDEN_APP_MIN_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008845 pw.print(" HIDDEN_APP_MAX_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MAX_ADJ);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07008846
8847 if (needSep) pw.println(" ");
8848 needSep = true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07008849 pw.println(" Process OOM control:");
Dianne Hackborn905577f2011-09-07 18:31:28 -07008850 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008851 "Proc", "PERS", true, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008852 needSep = true;
8853 }
8854
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008855 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008856
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008857 pw.println();
Dianne Hackborn287952c2010-09-22 22:34:31 -07008858 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07008859 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008860 if (mHeavyWeightProcess != null) {
8861 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
8862 }
8863
8864 return true;
8865 }
8866
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008867 /**
8868 * There are three ways to call this:
8869 * - no service specified: dump all the services
8870 * - a flattened component name that matched an existing service was specified as the
8871 * first arg: dump that one service
8872 * - the first arg isn't the flattened component name of an existing service:
8873 * dump all services whose component contains the first arg as a substring
8874 */
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008875 protected boolean dumpService(FileDescriptor fd, PrintWriter pw, String name, String[] args,
8876 int opti, boolean dumpAll) {
8877 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008878
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008879 if ("all".equals(name)) {
Dianne Hackborn14bfa392010-07-24 19:58:06 -07008880 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07008881 try {
8882 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
8883 for (UserInfo user : users) {
8884 for (ServiceRecord r1 : mServiceMap.getAllServices(user.id)) {
8885 services.add(r1);
8886 }
8887 }
8888 } catch (RemoteException re) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008889 }
8890 }
8891 } else {
8892 ComponentName componentName = name != null
8893 ? ComponentName.unflattenFromString(name) : null;
8894 int objectId = 0;
8895 if (componentName == null) {
8896 // Not a '/' separated full component name; maybe an object ID?
8897 try {
8898 objectId = Integer.parseInt(name, 16);
8899 name = null;
8900 componentName = null;
8901 } catch (RuntimeException e) {
8902 }
8903 }
8904
8905 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07008906 try {
8907 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
8908 for (UserInfo user : users) {
8909 for (ServiceRecord r1 : mServiceMap.getAllServices(user.id)) {
8910 if (componentName != null) {
8911 if (r1.name.equals(componentName)) {
8912 services.add(r1);
8913 }
8914 } else if (name != null) {
8915 if (r1.name.flattenToString().contains(name)) {
8916 services.add(r1);
8917 }
8918 } else if (System.identityHashCode(r1) == objectId) {
8919 services.add(r1);
8920 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008921 }
Dianne Hackborn14bfa392010-07-24 19:58:06 -07008922 }
Amith Yamasani742a6712011-05-04 14:49:28 -07008923 } catch (RemoteException re) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008924 }
8925 }
8926 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008927
8928 if (services.size() <= 0) {
8929 return false;
8930 }
8931
8932 boolean needSep = false;
8933 for (int i=0; i<services.size(); i++) {
8934 if (needSep) {
8935 pw.println();
8936 }
8937 needSep = true;
8938 dumpService("", fd, pw, services.get(i), args, dumpAll);
8939 }
8940 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008941 }
8942
8943 /**
8944 * Invokes IApplicationThread.dumpService() on the thread of the specified service if
8945 * there is a thread associated with the service.
8946 */
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008947 private void dumpService(String prefix, FileDescriptor fd, PrintWriter pw,
8948 final ServiceRecord r, String[] args, boolean dumpAll) {
8949 String innerPrefix = prefix + " ";
8950 synchronized (this) {
8951 pw.print(prefix); pw.print("SERVICE ");
8952 pw.print(r.shortName); pw.print(" ");
8953 pw.print(Integer.toHexString(System.identityHashCode(r)));
8954 pw.print(" pid=");
8955 if (r.app != null) pw.println(r.app.pid);
8956 else pw.println("(not running)");
8957 if (dumpAll) {
8958 r.dump(pw, innerPrefix);
8959 }
8960 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008961 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008962 pw.print(prefix); pw.println(" Client:");
8963 pw.flush();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008964 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008965 TransferPipe tp = new TransferPipe();
8966 try {
8967 r.app.thread.dumpService(tp.getWriteFd().getFileDescriptor(), r, args);
8968 tp.setBufferPrefix(prefix + " ");
8969 tp.go(fd);
8970 } finally {
8971 tp.kill();
8972 }
8973 } catch (IOException e) {
8974 pw.println(prefix + " Failure while dumping the service: " + e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008975 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008976 pw.println(prefix + " Got a RemoteException while dumping the service");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008977 }
8978 }
8979 }
8980
Marco Nelissen18cb2872011-11-15 11:19:53 -08008981 /**
8982 * There are three ways to call this:
8983 * - no provider specified: dump all the providers
8984 * - a flattened component name that matched an existing provider was specified as the
8985 * first arg: dump that one provider
8986 * - the first arg isn't the flattened component name of an existing provider:
8987 * dump all providers whose component contains the first arg as a substring
8988 */
8989 protected boolean dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args,
8990 int opti, boolean dumpAll) {
Marco Nelissende7408c2012-02-08 14:57:38 -08008991 return mProviderMap.dumpProvider(fd, pw, name, args, opti, dumpAll);
Marco Nelissen18cb2872011-11-15 11:19:53 -08008992 }
8993
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008994 static class ItemMatcher {
8995 ArrayList<ComponentName> components;
8996 ArrayList<String> strings;
8997 ArrayList<Integer> objects;
8998 boolean all;
8999
9000 ItemMatcher() {
9001 all = true;
9002 }
9003
9004 void build(String name) {
9005 ComponentName componentName = ComponentName.unflattenFromString(name);
9006 if (componentName != null) {
9007 if (components == null) {
9008 components = new ArrayList<ComponentName>();
9009 }
9010 components.add(componentName);
9011 all = false;
9012 } else {
9013 int objectId = 0;
9014 // Not a '/' separated full component name; maybe an object ID?
9015 try {
9016 objectId = Integer.parseInt(name, 16);
9017 if (objects == null) {
9018 objects = new ArrayList<Integer>();
9019 }
9020 objects.add(objectId);
9021 all = false;
9022 } catch (RuntimeException e) {
9023 // Not an integer; just do string match.
9024 if (strings == null) {
9025 strings = new ArrayList<String>();
9026 }
9027 strings.add(name);
9028 all = false;
9029 }
9030 }
9031 }
9032
9033 int build(String[] args, int opti) {
9034 for (; opti<args.length; opti++) {
9035 String name = args[opti];
9036 if ("--".equals(name)) {
9037 return opti+1;
9038 }
9039 build(name);
9040 }
9041 return opti;
9042 }
9043
9044 boolean match(Object object, ComponentName comp) {
9045 if (all) {
9046 return true;
9047 }
9048 if (components != null) {
9049 for (int i=0; i<components.size(); i++) {
9050 if (components.get(i).equals(comp)) {
9051 return true;
9052 }
9053 }
9054 }
9055 if (objects != null) {
9056 for (int i=0; i<objects.size(); i++) {
9057 if (System.identityHashCode(object) == objects.get(i)) {
9058 return true;
9059 }
9060 }
9061 }
9062 if (strings != null) {
9063 String flat = comp.flattenToString();
9064 for (int i=0; i<strings.size(); i++) {
9065 if (flat.contains(strings.get(i))) {
9066 return true;
9067 }
9068 }
9069 }
9070 return false;
9071 }
9072 }
9073
Dianne Hackborn625ac272010-09-17 18:29:22 -07009074 /**
9075 * There are three things that cmd can be:
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009076 * - a flattened component name that matches an existing activity
Dianne Hackborn625ac272010-09-17 18:29:22 -07009077 * - the cmd arg isn't the flattened component name of an existing activity:
9078 * dump all activity whose component contains the cmd as a substring
9079 * - A hex number of the ActivityRecord object instance.
9080 */
9081 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9082 int opti, boolean dumpAll) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009083 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009084
9085 if ("all".equals(name)) {
9086 synchronized (this) {
9087 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009088 activities.add(r1);
9089 }
9090 }
Dianne Hackbornf9302322011-06-14 18:36:14 -07009091 } else if ("top".equals(name)) {
9092 synchronized (this) {
9093 final int N = mMainStack.mHistory.size();
9094 if (N > 0) {
9095 activities.add((ActivityRecord)mMainStack.mHistory.get(N-1));
9096 }
9097 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009098 } else {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009099 ItemMatcher matcher = new ItemMatcher();
9100 matcher.build(name);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009101
9102 synchronized (this) {
9103 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009104 if (matcher.match(r1, r1.intent.getComponent())) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009105 activities.add(r1);
9106 }
9107 }
9108 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009109 }
9110
9111 if (activities.size() <= 0) {
9112 return false;
9113 }
9114
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009115 String[] newArgs = new String[args.length - opti];
9116 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
9117
Dianne Hackborn30d71892010-12-11 10:37:55 -08009118 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009119 boolean needSep = false;
Dianne Hackborn30d71892010-12-11 10:37:55 -08009120 for (int i=activities.size()-1; i>=0; i--) {
9121 ActivityRecord r = (ActivityRecord)activities.get(i);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009122 if (needSep) {
9123 pw.println();
9124 }
9125 needSep = true;
9126 synchronized (this) {
9127 if (lastTask != r.task) {
9128 lastTask = r.task;
9129 pw.print("TASK "); pw.print(lastTask.affinity);
9130 pw.print(" id="); pw.println(lastTask.taskId);
9131 if (dumpAll) {
9132 lastTask.dump(pw, " ");
9133 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08009134 }
9135 }
9136 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009137 }
9138 return true;
9139 }
9140
9141 /**
9142 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
9143 * there is a thread associated with the activity.
9144 */
Dianne Hackborn30d71892010-12-11 10:37:55 -08009145 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009146 final ActivityRecord r, String[] args, boolean dumpAll) {
9147 String innerPrefix = prefix + " ";
Dianne Hackborn30d71892010-12-11 10:37:55 -08009148 synchronized (this) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009149 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
9150 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
9151 pw.print(" pid=");
Dianne Hackborn30d71892010-12-11 10:37:55 -08009152 if (r.app != null) pw.println(r.app.pid);
9153 else pw.println("(not running)");
9154 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009155 r.dump(pw, innerPrefix);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009156 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009157 }
9158 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009159 // flush anything that is already in the PrintWriter since the thread is going
9160 // to write to the file descriptor directly
9161 pw.flush();
Dianne Hackborn625ac272010-09-17 18:29:22 -07009162 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009163 TransferPipe tp = new TransferPipe();
9164 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009165 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9166 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009167 tp.go(fd);
9168 } finally {
9169 tp.kill();
9170 }
9171 } catch (IOException e) {
9172 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009173 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009174 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
Dianne Hackborn625ac272010-09-17 18:29:22 -07009175 }
9176 }
9177 }
9178
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009179 boolean dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009180 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009181 boolean needSep = false;
9182
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009183 pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009184 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009185 if (mRegisteredReceivers.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009186 boolean printed = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009187 Iterator it = mRegisteredReceivers.values().iterator();
9188 while (it.hasNext()) {
9189 ReceiverList r = (ReceiverList)it.next();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009190 if (dumpPackage != null && (r.app == null ||
9191 !dumpPackage.equals(r.app.info.packageName))) {
9192 continue;
9193 }
9194 if (!printed) {
9195 pw.println(" Registered Receivers:");
9196 needSep = true;
9197 printed = true;
9198 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009199 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009200 r.dump(pw, " ");
9201 }
9202 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009203
9204 if (mReceiverResolver.dump(pw, needSep ?
9205 "\n Receiver Resolver Table:" : " Receiver Resolver Table:",
9206 " ", dumpPackage, false)) {
9207 needSep = true;
9208 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009209 }
Christopher Tatef46723b2012-01-26 14:19:24 -08009210
9211 for (BroadcastQueue q : mBroadcastQueues) {
9212 needSep = q.dumpLocked(fd, pw, args, opti, dumpAll, dumpPackage, needSep);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009213 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009214
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009215 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009216
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009217 if (mStickyBroadcasts != null && dumpPackage == null) {
9218 if (needSep) {
9219 pw.println();
9220 }
9221 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009222 pw.println(" Sticky broadcasts:");
9223 StringBuilder sb = new StringBuilder(128);
9224 for (Map.Entry<String, ArrayList<Intent>> ent
9225 : mStickyBroadcasts.entrySet()) {
9226 pw.print(" * Sticky action "); pw.print(ent.getKey());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009227 if (dumpAll) {
9228 pw.println(":");
9229 ArrayList<Intent> intents = ent.getValue();
9230 final int N = intents.size();
9231 for (int i=0; i<N; i++) {
9232 sb.setLength(0);
9233 sb.append(" Intent: ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009234 intents.get(i).toShortString(sb, false, true, false, false);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009235 pw.println(sb.toString());
9236 Bundle bundle = intents.get(i).getExtras();
9237 if (bundle != null) {
9238 pw.print(" ");
9239 pw.println(bundle.toString());
9240 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009241 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009242 } else {
9243 pw.println("");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009244 }
9245 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009246 needSep = true;
9247 }
9248
9249 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009250 pw.println();
Christopher Tatef46723b2012-01-26 14:19:24 -08009251 for (BroadcastQueue queue : mBroadcastQueues) {
9252 pw.println(" mBroadcastsScheduled [" + queue.mQueueName + "]="
9253 + queue.mBroadcastsScheduled);
9254 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009255 pw.println(" mHandler:");
9256 mHandler.dump(new PrintWriterPrinter(pw), " ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009257 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009258 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009259
9260 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009261 }
9262
Marco Nelissen18cb2872011-11-15 11:19:53 -08009263 /**
9264 * Prints a list of ServiceRecords (dumpsys activity services)
9265 */
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009266 boolean dumpServicesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009267 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009268 boolean needSep = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009269
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009270 ItemMatcher matcher = new ItemMatcher();
9271 matcher.build(args, opti);
9272
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009273 pw.println("ACTIVITY MANAGER SERVICES (dumpsys activity services)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009274 try {
9275 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
9276 for (UserInfo user : users) {
9277 if (mServiceMap.getAllServices(user.id).size() > 0) {
9278 boolean printed = false;
9279 long nowReal = SystemClock.elapsedRealtime();
9280 Iterator<ServiceRecord> it = mServiceMap.getAllServices(
9281 user.id).iterator();
9282 needSep = false;
9283 while (it.hasNext()) {
9284 ServiceRecord r = it.next();
9285 if (!matcher.match(r, r.name)) {
9286 continue;
9287 }
9288 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9289 continue;
9290 }
9291 if (!printed) {
9292 pw.println(" Active services:");
9293 printed = true;
9294 }
9295 if (needSep) {
9296 pw.println();
9297 }
9298 pw.print(" * ");
9299 pw.println(r);
9300 if (dumpAll) {
9301 r.dump(pw, " ");
9302 needSep = true;
9303 } else {
9304 pw.print(" app=");
9305 pw.println(r.app);
9306 pw.print(" created=");
9307 TimeUtils.formatDuration(r.createTime, nowReal, pw);
9308 pw.print(" started=");
9309 pw.print(r.startRequested);
9310 pw.print(" connections=");
9311 pw.println(r.connections.size());
9312 if (r.connections.size() > 0) {
9313 pw.println(" Connections:");
9314 for (ArrayList<ConnectionRecord> clist : r.connections.values()) {
9315 for (int i = 0; i < clist.size(); i++) {
9316 ConnectionRecord conn = clist.get(i);
9317 pw.print(" ");
9318 pw.print(conn.binding.intent.intent.getIntent()
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009319 .toShortString(false, false, false, false));
Amith Yamasani742a6712011-05-04 14:49:28 -07009320 pw.print(" -> ");
9321 ProcessRecord proc = conn.binding.client;
9322 pw.println(proc != null ? proc.toShortString() : "null");
9323 }
9324 }
Dianne Hackborn8ec8d412011-11-14 18:27:24 -08009325 }
9326 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009327 if (dumpClient && r.app != null && r.app.thread != null) {
9328 pw.println(" Client:");
9329 pw.flush();
9330 try {
9331 TransferPipe tp = new TransferPipe();
9332 try {
9333 r.app.thread.dumpService(tp.getWriteFd().getFileDescriptor(),
9334 r, args);
9335 tp.setBufferPrefix(" ");
9336 // Short timeout, since blocking here can
9337 // deadlock with the application.
9338 tp.go(fd, 2000);
9339 } finally {
9340 tp.kill();
9341 }
9342 } catch (IOException e) {
9343 pw.println(" Failure while dumping the service: " + e);
9344 } catch (RemoteException e) {
9345 pw.println(" Got a RemoteException while dumping the service");
9346 }
9347 needSep = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009348 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009349 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009350 needSep = printed;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009351 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009352 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009353 } catch (RemoteException re) {
9354
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009355 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009356
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009357 if (mPendingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009358 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009359 for (int i=0; i<mPendingServices.size(); i++) {
9360 ServiceRecord r = mPendingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009361 if (!matcher.match(r, r.name)) {
9362 continue;
9363 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009364 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9365 continue;
9366 }
9367 if (!printed) {
9368 if (needSep) pw.println(" ");
9369 needSep = true;
9370 pw.println(" Pending services:");
9371 printed = true;
9372 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009373 pw.print(" * Pending "); pw.println(r);
9374 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009375 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009376 needSep = true;
9377 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009378
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009379 if (mRestartingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009380 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009381 for (int i=0; i<mRestartingServices.size(); i++) {
9382 ServiceRecord r = mRestartingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009383 if (!matcher.match(r, r.name)) {
9384 continue;
9385 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009386 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9387 continue;
9388 }
9389 if (!printed) {
9390 if (needSep) pw.println(" ");
9391 needSep = true;
9392 pw.println(" Restarting services:");
9393 printed = true;
9394 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009395 pw.print(" * Restarting "); pw.println(r);
9396 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009397 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009398 needSep = true;
9399 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009400
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009401 if (mStoppingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009402 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009403 for (int i=0; i<mStoppingServices.size(); i++) {
9404 ServiceRecord r = mStoppingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009405 if (!matcher.match(r, r.name)) {
9406 continue;
9407 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009408 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9409 continue;
9410 }
9411 if (!printed) {
9412 if (needSep) pw.println(" ");
9413 needSep = true;
9414 pw.println(" Stopping services:");
9415 printed = true;
9416 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009417 pw.print(" * Stopping "); pw.println(r);
9418 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009419 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009420 needSep = true;
9421 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009422
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009423 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009424 if (mServiceConnections.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009425 boolean printed = false;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009426 Iterator<ArrayList<ConnectionRecord>> it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009427 = mServiceConnections.values().iterator();
9428 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009429 ArrayList<ConnectionRecord> r = it.next();
9430 for (int i=0; i<r.size(); i++) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009431 ConnectionRecord cr = r.get(i);
9432 if (!matcher.match(cr.binding.service, cr.binding.service.name)) {
9433 continue;
9434 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009435 if (dumpPackage != null && (cr.binding.client == null
9436 || !dumpPackage.equals(cr.binding.client.info.packageName))) {
9437 continue;
9438 }
9439 if (!printed) {
9440 if (needSep) pw.println(" ");
9441 needSep = true;
9442 pw.println(" Connection bindings to services:");
9443 printed = true;
9444 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009445 pw.print(" * "); pw.println(cr);
9446 cr.dump(pw, " ");
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009447 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009448 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009449 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009450 }
9451 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009452
9453 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009454 }
9455
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009456 boolean dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009457 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07009458 boolean needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009459
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009460 ItemMatcher matcher = new ItemMatcher();
9461 matcher.build(args, opti);
9462
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009463 pw.println("ACTIVITY MANAGER CONTENT PROVIDERS (dumpsys activity providers)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009464
9465 mProviderMap.dumpProvidersLocked(pw, dumpAll);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009466
9467 if (mLaunchingProviders.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009468 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009469 for (int i=mLaunchingProviders.size()-1; i>=0; i--) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009470 ContentProviderRecord r = mLaunchingProviders.get(i);
9471 if (dumpPackage != null && !dumpPackage.equals(r.name.getPackageName())) {
9472 continue;
9473 }
9474 if (!printed) {
9475 if (needSep) pw.println(" ");
9476 needSep = true;
9477 pw.println(" Launching content providers:");
9478 printed = true;
9479 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009480 pw.print(" Launching #"); pw.print(i); pw.print(": ");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009481 pw.println(r);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009482 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009483 }
9484
9485 if (mGrantedUriPermissions.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009486 if (needSep) pw.println();
9487 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009488 pw.println("Granted Uri Permissions:");
9489 for (int i=0; i<mGrantedUriPermissions.size(); i++) {
9490 int uid = mGrantedUriPermissions.keyAt(i);
9491 HashMap<Uri, UriPermission> perms
9492 = mGrantedUriPermissions.valueAt(i);
9493 pw.print(" * UID "); pw.print(uid);
9494 pw.println(" holds:");
9495 for (UriPermission perm : perms.values()) {
9496 pw.print(" "); pw.println(perm);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009497 if (dumpAll) {
9498 perm.dump(pw, " ");
9499 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009500 }
9501 }
9502 needSep = true;
9503 }
9504
9505 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009506 }
9507
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009508 boolean dumpPendingIntentsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009509 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009510 boolean needSep = false;
9511
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009512 if (mIntentSenderRecords.size() > 0) {
9513 boolean printed = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009514 Iterator<WeakReference<PendingIntentRecord>> it
9515 = mIntentSenderRecords.values().iterator();
9516 while (it.hasNext()) {
9517 WeakReference<PendingIntentRecord> ref = it.next();
9518 PendingIntentRecord rec = ref != null ? ref.get(): null;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009519 if (dumpPackage != null && (rec == null
9520 || !dumpPackage.equals(rec.key.packageName))) {
9521 continue;
9522 }
9523 if (!printed) {
9524 pw.println("ACTIVITY MANAGER PENDING INTENTS (dumpsys activity intents)");
9525 printed = true;
9526 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009527 needSep = true;
9528 if (rec != null) {
9529 pw.print(" * "); pw.println(rec);
9530 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009531 rec.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009532 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009533 } else {
9534 pw.print(" * "); pw.println(ref);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009535 }
9536 }
9537 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009538
9539 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009540 }
9541
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009542 private static final void dumpHistoryList(FileDescriptor fd, PrintWriter pw, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009543 String prefix, String label, boolean complete, boolean brief, boolean client,
9544 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009545 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009546 boolean needNL = false;
9547 final String innerPrefix = prefix + " ";
9548 final String[] args = new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009549 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009550 final ActivityRecord r = (ActivityRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009551 if (dumpPackage != null && !dumpPackage.equals(r.packageName)) {
9552 continue;
9553 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07009554 final boolean full = !brief && (complete || !r.isInHistory());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009555 if (needNL) {
9556 pw.println(" ");
9557 needNL = false;
9558 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009559 if (lastTask != r.task) {
9560 lastTask = r.task;
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009561 pw.print(prefix);
9562 pw.print(full ? "* " : " ");
9563 pw.println(lastTask);
9564 if (full) {
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009565 lastTask.dump(pw, prefix + " ");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009566 } else if (complete) {
9567 // Complete + brief == give a summary. Isn't that obvious?!?
9568 if (lastTask.intent != null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009569 pw.print(prefix); pw.print(" ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009570 pw.println(lastTask.intent.toInsecureStringWithClip());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009571 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009572 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009573 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009574 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label);
9575 pw.print(" #"); pw.print(i); pw.print(": ");
9576 pw.println(r);
9577 if (full) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009578 r.dump(pw, innerPrefix);
9579 } else if (complete) {
9580 // Complete + brief == give a summary. Isn't that obvious?!?
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009581 pw.print(innerPrefix); pw.println(r.intent.toInsecureString());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009582 if (r.app != null) {
9583 pw.print(innerPrefix); pw.println(r.app);
9584 }
9585 }
9586 if (client && r.app != null && r.app.thread != null) {
9587 // flush anything that is already in the PrintWriter since the thread is going
9588 // to write to the file descriptor directly
9589 pw.flush();
9590 try {
9591 TransferPipe tp = new TransferPipe();
9592 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009593 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9594 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009595 // Short timeout, since blocking here can
9596 // deadlock with the application.
9597 tp.go(fd, 2000);
9598 } finally {
9599 tp.kill();
9600 }
9601 } catch (IOException e) {
9602 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
9603 } catch (RemoteException e) {
9604 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
9605 }
9606 needNL = true;
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009607 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009608 }
9609 }
9610
Dianne Hackborn09c916b2009-12-08 14:50:51 -08009611 private static String buildOomTag(String prefix, String space, int val, int base) {
9612 if (val == base) {
9613 if (space == null) return prefix;
9614 return prefix + " ";
9615 }
9616 return prefix + "+" + Integer.toString(val-base);
9617 }
9618
9619 private static final int dumpProcessList(PrintWriter pw,
9620 ActivityManagerService service, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009621 String prefix, String normalLabel, String persistentLabel,
9622 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009623 int numPers = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07009624 final int N = list.size()-1;
9625 for (int i=N; i>=0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009626 ProcessRecord r = (ProcessRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009627 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9628 continue;
9629 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009630 pw.println(String.format("%s%s #%2d: %s",
9631 prefix, (r.persistent ? persistentLabel : normalLabel),
9632 i, r.toString()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009633 if (r.persistent) {
9634 numPers++;
9635 }
9636 }
9637 return numPers;
9638 }
9639
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009640 private static final boolean dumpProcessOomList(PrintWriter pw,
Dianne Hackborn905577f2011-09-07 18:31:28 -07009641 ActivityManagerService service, List<ProcessRecord> origList,
Dianne Hackborn287952c2010-09-22 22:34:31 -07009642 String prefix, String normalLabel, String persistentLabel,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009643 boolean inclDetails, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009644
Dianne Hackborn905577f2011-09-07 18:31:28 -07009645 ArrayList<Pair<ProcessRecord, Integer>> list
9646 = new ArrayList<Pair<ProcessRecord, Integer>>(origList.size());
9647 for (int i=0; i<origList.size(); i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009648 ProcessRecord r = origList.get(i);
9649 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9650 continue;
9651 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07009652 list.add(new Pair<ProcessRecord, Integer>(origList.get(i), i));
9653 }
9654
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009655 if (list.size() <= 0) {
9656 return false;
9657 }
9658
Dianne Hackborn905577f2011-09-07 18:31:28 -07009659 Comparator<Pair<ProcessRecord, Integer>> comparator
9660 = new Comparator<Pair<ProcessRecord, Integer>>() {
9661 @Override
9662 public int compare(Pair<ProcessRecord, Integer> object1,
9663 Pair<ProcessRecord, Integer> object2) {
9664 if (object1.first.setAdj != object2.first.setAdj) {
9665 return object1.first.setAdj > object2.first.setAdj ? -1 : 1;
9666 }
9667 if (object1.second.intValue() != object2.second.intValue()) {
9668 return object1.second.intValue() > object2.second.intValue() ? -1 : 1;
9669 }
9670 return 0;
9671 }
9672 };
9673
9674 Collections.sort(list, comparator);
9675
Dianne Hackborn287952c2010-09-22 22:34:31 -07009676 final long curRealtime = SystemClock.elapsedRealtime();
9677 final long realtimeSince = curRealtime - service.mLastPowerCheckRealtime;
9678 final long curUptime = SystemClock.uptimeMillis();
9679 final long uptimeSince = curUptime - service.mLastPowerCheckUptime;
9680
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009681 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07009682 ProcessRecord r = list.get(i).first;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009683 String oomAdj;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009684 if (r.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07009685 oomAdj = buildOomTag("bak", " ", r.setAdj, ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009686 } else if (r.setAdj >= ProcessList.SERVICE_B_ADJ) {
9687 oomAdj = buildOomTag("svcb ", null, r.setAdj, ProcessList.SERVICE_B_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009688 } else if (r.setAdj >= ProcessList.PREVIOUS_APP_ADJ) {
9689 oomAdj = buildOomTag("prev ", null, r.setAdj, ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009690 } else if (r.setAdj >= ProcessList.HOME_APP_ADJ) {
9691 oomAdj = buildOomTag("home ", null, r.setAdj, ProcessList.HOME_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009692 } else if (r.setAdj >= ProcessList.SERVICE_ADJ) {
9693 oomAdj = buildOomTag("svc ", null, r.setAdj, ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009694 } else if (r.setAdj >= ProcessList.BACKUP_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08009695 oomAdj = buildOomTag("bkup ", null, r.setAdj, ProcessList.BACKUP_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009696 } else if (r.setAdj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
9697 oomAdj = buildOomTag("hvy ", null, r.setAdj, ProcessList.HEAVY_WEIGHT_APP_ADJ);
9698 } else if (r.setAdj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
9699 oomAdj = buildOomTag("prcp ", null, r.setAdj, ProcessList.PERCEPTIBLE_APP_ADJ);
9700 } else if (r.setAdj >= ProcessList.VISIBLE_APP_ADJ) {
9701 oomAdj = buildOomTag("vis ", null, r.setAdj, ProcessList.VISIBLE_APP_ADJ);
9702 } else if (r.setAdj >= ProcessList.FOREGROUND_APP_ADJ) {
9703 oomAdj = buildOomTag("fore ", null, r.setAdj, ProcessList.FOREGROUND_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009704 } else if (r.setAdj >= ProcessList.PERSISTENT_PROC_ADJ) {
9705 oomAdj = buildOomTag("pers ", null, r.setAdj, ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009706 } else if (r.setAdj >= ProcessList.SYSTEM_ADJ) {
9707 oomAdj = buildOomTag("sys ", null, r.setAdj, ProcessList.SYSTEM_ADJ);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009708 } else {
9709 oomAdj = Integer.toString(r.setAdj);
9710 }
9711 String schedGroup;
9712 switch (r.setSchedGroup) {
9713 case Process.THREAD_GROUP_BG_NONINTERACTIVE:
9714 schedGroup = "B";
9715 break;
9716 case Process.THREAD_GROUP_DEFAULT:
9717 schedGroup = "F";
9718 break;
9719 default:
9720 schedGroup = Integer.toString(r.setSchedGroup);
9721 break;
9722 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07009723 String foreground;
9724 if (r.foregroundActivities) {
9725 foreground = "A";
9726 } else if (r.foregroundServices) {
9727 foreground = "S";
9728 } else {
9729 foreground = " ";
9730 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07009731 pw.println(String.format("%s%s #%2d: adj=%s/%s%s trm=%2d %s (%s)",
Dianne Hackborn287952c2010-09-22 22:34:31 -07009732 prefix, (r.persistent ? persistentLabel : normalLabel),
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009733 (origList.size()-1)-list.get(i).second, oomAdj, schedGroup,
9734 foreground, r.trimMemoryLevel, r.toShortString(), r.adjType));
Dianne Hackborn287952c2010-09-22 22:34:31 -07009735 if (r.adjSource != null || r.adjTarget != null) {
9736 pw.print(prefix);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009737 pw.print(" ");
Dianne Hackborn287952c2010-09-22 22:34:31 -07009738 if (r.adjTarget instanceof ComponentName) {
9739 pw.print(((ComponentName)r.adjTarget).flattenToShortString());
9740 } else if (r.adjTarget != null) {
9741 pw.print(r.adjTarget.toString());
9742 } else {
9743 pw.print("{null}");
9744 }
9745 pw.print("<=");
9746 if (r.adjSource instanceof ProcessRecord) {
9747 pw.print("Proc{");
9748 pw.print(((ProcessRecord)r.adjSource).toShortString());
9749 pw.println("}");
9750 } else if (r.adjSource != null) {
9751 pw.println(r.adjSource.toString());
9752 } else {
9753 pw.println("{null}");
9754 }
9755 }
9756 if (inclDetails) {
9757 pw.print(prefix);
9758 pw.print(" ");
9759 pw.print("oom: max="); pw.print(r.maxAdj);
9760 pw.print(" hidden="); pw.print(r.hiddenAdj);
9761 pw.print(" curRaw="); pw.print(r.curRawAdj);
9762 pw.print(" setRaw="); pw.print(r.setRawAdj);
9763 pw.print(" cur="); pw.print(r.curAdj);
9764 pw.print(" set="); pw.println(r.setAdj);
9765 pw.print(prefix);
9766 pw.print(" ");
9767 pw.print("keeping="); pw.print(r.keeping);
9768 pw.print(" hidden="); pw.print(r.hidden);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009769 pw.print(" empty="); pw.print(r.empty);
9770 pw.print(" hasAboveClient="); pw.println(r.hasAboveClient);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009771
9772 if (!r.keeping) {
9773 if (r.lastWakeTime != 0) {
9774 long wtime;
9775 BatteryStatsImpl stats = service.mBatteryStatsService.getActiveStatistics();
9776 synchronized (stats) {
9777 wtime = stats.getProcessWakeTime(r.info.uid,
9778 r.pid, curRealtime);
9779 }
9780 long timeUsed = wtime - r.lastWakeTime;
9781 pw.print(prefix);
9782 pw.print(" ");
9783 pw.print("keep awake over ");
9784 TimeUtils.formatDuration(realtimeSince, pw);
9785 pw.print(" used ");
9786 TimeUtils.formatDuration(timeUsed, pw);
9787 pw.print(" (");
9788 pw.print((timeUsed*100)/realtimeSince);
9789 pw.println("%)");
9790 }
9791 if (r.lastCpuTime != 0) {
9792 long timeUsed = r.curCpuTime - r.lastCpuTime;
9793 pw.print(prefix);
9794 pw.print(" ");
9795 pw.print("run cpu over ");
9796 TimeUtils.formatDuration(uptimeSince, pw);
9797 pw.print(" used ");
9798 TimeUtils.formatDuration(timeUsed, pw);
9799 pw.print(" (");
9800 pw.print((timeUsed*100)/uptimeSince);
9801 pw.println("%)");
9802 }
9803 }
9804 }
9805 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009806 return true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009807 }
9808
Dianne Hackbornb437e092011-08-05 17:50:29 -07009809 ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, String[] args) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009810 ArrayList<ProcessRecord> procs;
9811 synchronized (this) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009812 if (args != null && args.length > start
9813 && args[start].charAt(0) != '-') {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009814 procs = new ArrayList<ProcessRecord>();
9815 int pid = -1;
9816 try {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009817 pid = Integer.parseInt(args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009818 } catch (NumberFormatException e) {
9819
9820 }
9821 for (int i=mLruProcesses.size()-1; i>=0; i--) {
9822 ProcessRecord proc = mLruProcesses.get(i);
9823 if (proc.pid == pid) {
9824 procs.add(proc);
Dianne Hackbornb437e092011-08-05 17:50:29 -07009825 } else if (proc.processName.equals(args[start])) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009826 procs.add(proc);
9827 }
9828 }
9829 if (procs.size() <= 0) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009830 pw.println("No process found for: " + args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009831 return null;
9832 }
9833 } else {
9834 procs = new ArrayList<ProcessRecord>(mLruProcesses);
9835 }
9836 }
9837 return procs;
9838 }
9839
9840 final void dumpGraphicsHardwareUsage(FileDescriptor fd,
9841 PrintWriter pw, String[] args) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009842 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009843 if (procs == null) {
9844 return;
9845 }
9846
9847 long uptime = SystemClock.uptimeMillis();
9848 long realtime = SystemClock.elapsedRealtime();
9849 pw.println("Applications Graphics Acceleration Info:");
9850 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
9851
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009852 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
9853 ProcessRecord r = procs.get(i);
Chet Haase9c1e23b2011-03-24 10:51:31 -07009854 if (r.thread != null) {
9855 pw.println("\n** Graphics info for pid " + r.pid + " [" + r.processName + "] **");
9856 pw.flush();
9857 try {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009858 TransferPipe tp = new TransferPipe();
9859 try {
9860 r.thread.dumpGfxInfo(tp.getWriteFd().getFileDescriptor(), args);
9861 tp.go(fd);
9862 } finally {
9863 tp.kill();
9864 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009865 } catch (IOException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009866 pw.println("Failure while dumping the app: " + r);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009867 pw.flush();
Chet Haase9c1e23b2011-03-24 10:51:31 -07009868 } catch (RemoteException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009869 pw.println("Got a RemoteException while dumping the app " + r);
Chet Haase9c1e23b2011-03-24 10:51:31 -07009870 pw.flush();
9871 }
9872 }
9873 }
Chet Haase9c1e23b2011-03-24 10:51:31 -07009874 }
9875
Jeff Brown6754ba22011-12-14 20:20:01 -08009876 final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) {
9877 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
9878 if (procs == null) {
9879 return;
9880 }
9881
9882 pw.println("Applications Database Info:");
9883
9884 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
9885 ProcessRecord r = procs.get(i);
9886 if (r.thread != null) {
9887 pw.println("\n** Database info for pid " + r.pid + " [" + r.processName + "] **");
9888 pw.flush();
9889 try {
9890 TransferPipe tp = new TransferPipe();
9891 try {
9892 r.thread.dumpDbInfo(tp.getWriteFd().getFileDescriptor(), args);
9893 tp.go(fd);
9894 } finally {
9895 tp.kill();
9896 }
9897 } catch (IOException e) {
9898 pw.println("Failure while dumping the app: " + r);
9899 pw.flush();
9900 } catch (RemoteException e) {
9901 pw.println("Got a RemoteException while dumping the app " + r);
9902 pw.flush();
9903 }
9904 }
9905 }
9906 }
9907
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009908 final static class MemItem {
9909 final String label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009910 final String shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009911 final long pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009912 final int id;
Dianne Hackborna4bacb82011-08-24 15:12:38 -07009913 ArrayList<MemItem> subitems;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009914
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009915 public MemItem(String _label, String _shortLabel, long _pss, int _id) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009916 label = _label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009917 shortLabel = _shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009918 pss = _pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009919 id = _id;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009920 }
9921 }
9922
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009923 static final void dumpMemItems(PrintWriter pw, String prefix, ArrayList<MemItem> items,
Dianne Hackbornb437e092011-08-05 17:50:29 -07009924 boolean sort) {
9925 if (sort) {
9926 Collections.sort(items, new Comparator<MemItem>() {
9927 @Override
9928 public int compare(MemItem lhs, MemItem rhs) {
9929 if (lhs.pss < rhs.pss) {
9930 return 1;
9931 } else if (lhs.pss > rhs.pss) {
9932 return -1;
9933 }
9934 return 0;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009935 }
Dianne Hackbornb437e092011-08-05 17:50:29 -07009936 });
9937 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009938
9939 for (int i=0; i<items.size(); i++) {
9940 MemItem mi = items.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009941 pw.print(prefix); pw.printf("%7d kB: ", mi.pss); pw.println(mi.label);
Dianne Hackborna4bacb82011-08-24 15:12:38 -07009942 if (mi.subitems != null) {
9943 dumpMemItems(pw, prefix + " ", mi.subitems, true);
9944 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009945 }
9946 }
9947
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009948 // These are in KB.
9949 static final long[] DUMP_MEM_BUCKETS = new long[] {
9950 5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024,
9951 120*1024, 160*1024, 200*1024,
9952 250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024,
9953 1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024
9954 };
9955
Dianne Hackborn672342c2011-11-29 11:29:02 -08009956 static final void appendMemBucket(StringBuilder out, long memKB, String label,
9957 boolean stackLike) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009958 int start = label.lastIndexOf('.');
9959 if (start >= 0) start++;
9960 else start = 0;
9961 int end = label.length();
9962 for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) {
9963 if (DUMP_MEM_BUCKETS[i] >= memKB) {
9964 long bucket = DUMP_MEM_BUCKETS[i]/1024;
9965 out.append(bucket);
Dianne Hackborn672342c2011-11-29 11:29:02 -08009966 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009967 out.append(label, start, end);
9968 return;
9969 }
9970 }
9971 out.append(memKB/1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -08009972 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009973 out.append(label, start, end);
9974 }
9975
9976 static final int[] DUMP_MEM_OOM_ADJ = new int[] {
9977 ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ, ProcessList.FOREGROUND_APP_ADJ,
9978 ProcessList.VISIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ,
9979 ProcessList.BACKUP_APP_ADJ, ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ,
9980 ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.HIDDEN_APP_MAX_ADJ
9981 };
9982 static final String[] DUMP_MEM_OOM_LABEL = new String[] {
9983 "System", "Persistent", "Foreground",
9984 "Visible", "Perceptible", "Heavy Weight",
9985 "Backup", "A Services", "Home", "Previous",
9986 "B Services", "Background"
9987 };
9988
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009989 final void dumpApplicationMemoryUsage(FileDescriptor fd,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08009990 PrintWriter pw, String prefix, String[] args, boolean brief,
Dianne Hackborn672342c2011-11-29 11:29:02 -08009991 PrintWriter categoryPw, StringBuilder outTag, StringBuilder outStack) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009992 boolean dumpAll = false;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08009993 boolean oomOnly = false;
Dianne Hackbornb437e092011-08-05 17:50:29 -07009994
9995 int opti = 0;
9996 while (opti < args.length) {
9997 String opt = args[opti];
9998 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
9999 break;
10000 }
10001 opti++;
10002 if ("-a".equals(opt)) {
10003 dumpAll = true;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010004 } else if ("--oom".equals(opt)) {
10005 oomOnly = true;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010006 } else if ("-h".equals(opt)) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010007 pw.println("meminfo dump options: [-a] [--oom] [process]");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010008 pw.println(" -a: include all available information for each process.");
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010009 pw.println(" --oom: only show processes organized by oom adj.");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010010 pw.println("If [process] is specified it can be the name or ");
10011 pw.println("pid of a specific process to dump.");
10012 return;
10013 } else {
10014 pw.println("Unknown argument: " + opt + "; use -h for help");
10015 }
10016 }
10017
10018 ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010019 if (procs == null) {
10020 return;
10021 }
10022
Dianne Hackborn6447ca32009-04-07 19:50:08 -070010023 final boolean isCheckinRequest = scanArgs(args, "--checkin");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010024 long uptime = SystemClock.uptimeMillis();
10025 long realtime = SystemClock.elapsedRealtime();
Dianne Hackbornb437e092011-08-05 17:50:29 -070010026
10027 if (procs.size() == 1 || isCheckinRequest) {
10028 dumpAll = true;
10029 }
10030
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010031 if (isCheckinRequest) {
10032 // short checkin version
10033 pw.println(uptime + "," + realtime);
10034 pw.flush();
10035 } else {
10036 pw.println("Applications Memory Usage (kB):");
10037 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10038 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010039
Dianne Hackbornb437e092011-08-05 17:50:29 -070010040 String[] innerArgs = new String[args.length-opti];
10041 System.arraycopy(args, opti, innerArgs, 0, args.length-opti);
10042
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010043 ArrayList<MemItem> procMems = new ArrayList<MemItem>();
10044 long nativePss=0, dalvikPss=0, otherPss=0;
10045 long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
10046
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010047 long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length];
10048 ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[])
10049 new ArrayList[DUMP_MEM_OOM_LABEL.length];
Dianne Hackbornb437e092011-08-05 17:50:29 -070010050
10051 long totalPss = 0;
10052
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010053 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10054 ProcessRecord r = procs.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010055 if (r.thread != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010056 if (!isCheckinRequest && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010057 pw.println("\n** MEMINFO in pid " + r.pid + " [" + r.processName + "] **");
10058 pw.flush();
10059 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010060 Debug.MemoryInfo mi = null;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010061 if (dumpAll) {
10062 try {
10063 mi = r.thread.dumpMemInfo(fd, isCheckinRequest, dumpAll, innerArgs);
10064 } catch (RemoteException e) {
10065 if (!isCheckinRequest) {
10066 pw.println("Got RemoteException!");
10067 pw.flush();
10068 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010069 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010070 } else {
10071 mi = new Debug.MemoryInfo();
10072 Debug.getMemoryInfo(r.pid, mi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010073 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010074
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010075 if (!isCheckinRequest && mi != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010076 long myTotalPss = mi.getTotalPss();
10077 totalPss += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010078 MemItem pssItem = new MemItem(r.processName + " (pid " + r.pid + ")",
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010079 r.processName, myTotalPss, 0);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010080 procMems.add(pssItem);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010081
10082 nativePss += mi.nativePss;
10083 dalvikPss += mi.dalvikPss;
10084 otherPss += mi.otherPss;
10085 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
10086 long mem = mi.getOtherPss(j);
10087 miscPss[j] += mem;
10088 otherPss -= mem;
10089 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010090
10091 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010092 if (r.setAdj <= DUMP_MEM_OOM_ADJ[oomIndex]
10093 || oomIndex == (oomPss.length-1)) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010094 oomPss[oomIndex] += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010095 if (oomProcs[oomIndex] == null) {
10096 oomProcs[oomIndex] = new ArrayList<MemItem>();
10097 }
10098 oomProcs[oomIndex].add(pssItem);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010099 break;
10100 }
10101 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010102 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010103 }
10104 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010105
10106 if (!isCheckinRequest && procs.size() > 1) {
10107 ArrayList<MemItem> catMems = new ArrayList<MemItem>();
10108
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010109 catMems.add(new MemItem("Native", "Native", nativePss, -1));
10110 catMems.add(new MemItem("Dalvik", "Dalvik", dalvikPss, -2));
10111 catMems.add(new MemItem("Unknown", "Unknown", otherPss, -3));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010112 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010113 String label = Debug.MemoryInfo.getOtherLabel(j);
10114 catMems.add(new MemItem(label, label, miscPss[j], j));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010115 }
10116
Dianne Hackbornb437e092011-08-05 17:50:29 -070010117 ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
10118 for (int j=0; j<oomPss.length; j++) {
10119 if (oomPss[j] != 0) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010120 String label = DUMP_MEM_OOM_LABEL[j];
10121 MemItem item = new MemItem(label, label, oomPss[j],
10122 DUMP_MEM_OOM_ADJ[j]);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010123 item.subitems = oomProcs[j];
10124 oomMems.add(item);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010125 }
10126 }
10127
Dianne Hackborn672342c2011-11-29 11:29:02 -080010128 if (outTag != null || outStack != null) {
10129 if (outTag != null) {
10130 appendMemBucket(outTag, totalPss, "total", false);
10131 }
10132 if (outStack != null) {
10133 appendMemBucket(outStack, totalPss, "total", true);
10134 }
10135 boolean firstLine = true;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010136 for (int i=0; i<oomMems.size(); i++) {
10137 MemItem miCat = oomMems.get(i);
10138 if (miCat.subitems == null || miCat.subitems.size() < 1) {
10139 continue;
10140 }
10141 if (miCat.id < ProcessList.SERVICE_ADJ
10142 || miCat.id == ProcessList.HOME_APP_ADJ
10143 || miCat.id == ProcessList.PREVIOUS_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010144 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10145 outTag.append(" / ");
10146 }
10147 if (outStack != null) {
10148 if (miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10149 if (firstLine) {
10150 outStack.append(":");
10151 firstLine = false;
10152 }
10153 outStack.append("\n\t at ");
10154 } else {
10155 outStack.append("$");
10156 }
10157 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010158 for (int j=0; j<miCat.subitems.size(); j++) {
10159 MemItem mi = miCat.subitems.get(j);
10160 if (j > 0) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010161 if (outTag != null) {
10162 outTag.append(" ");
10163 }
10164 if (outStack != null) {
10165 outStack.append("$");
10166 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010167 }
Dianne Hackborn672342c2011-11-29 11:29:02 -080010168 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10169 appendMemBucket(outTag, mi.pss, mi.shortLabel, false);
10170 }
10171 if (outStack != null) {
10172 appendMemBucket(outStack, mi.pss, mi.shortLabel, true);
10173 }
10174 }
10175 if (outStack != null && miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10176 outStack.append("(");
10177 for (int k=0; k<DUMP_MEM_OOM_ADJ.length; k++) {
10178 if (DUMP_MEM_OOM_ADJ[k] == miCat.id) {
10179 outStack.append(DUMP_MEM_OOM_LABEL[k]);
10180 outStack.append(":");
10181 outStack.append(DUMP_MEM_OOM_ADJ[k]);
10182 }
10183 }
10184 outStack.append(")");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010185 }
10186 }
10187 }
10188 }
10189
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010190 if (!brief && !oomOnly) {
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010191 pw.println();
10192 pw.println("Total PSS by process:");
10193 dumpMemItems(pw, " ", procMems, true);
10194 pw.println();
10195 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010196 pw.println("Total PSS by OOM adjustment:");
10197 dumpMemItems(pw, " ", oomMems, false);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010198 if (!oomOnly) {
10199 PrintWriter out = categoryPw != null ? categoryPw : pw;
10200 out.println();
10201 out.println("Total PSS by category:");
10202 dumpMemItems(out, " ", catMems, true);
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010203 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010204 pw.println();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010205 pw.print("Total PSS: "); pw.print(totalPss); pw.println(" kB");
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010206 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010207 }
10208
10209 /**
10210 * Searches array of arguments for the specified string
10211 * @param args array of argument strings
10212 * @param value value to search for
10213 * @return true if the value is contained in the array
10214 */
10215 private static boolean scanArgs(String[] args, String value) {
10216 if (args != null) {
10217 for (String arg : args) {
10218 if (value.equals(arg)) {
10219 return true;
10220 }
10221 }
10222 }
10223 return false;
10224 }
10225
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010226 private final void killServicesLocked(ProcessRecord app,
10227 boolean allowRestart) {
10228 // Report disconnected services.
10229 if (false) {
10230 // XXX we are letting the client link to the service for
10231 // death notifications.
10232 if (app.services.size() > 0) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010233 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010234 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010235 ServiceRecord r = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010236 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010237 Iterator<ArrayList<ConnectionRecord>> jt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010238 = r.connections.values().iterator();
10239 while (jt.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010240 ArrayList<ConnectionRecord> cl = jt.next();
10241 for (int i=0; i<cl.size(); i++) {
10242 ConnectionRecord c = cl.get(i);
10243 if (c.binding.client != app) {
10244 try {
10245 //c.conn.connected(r.className, null);
10246 } catch (Exception e) {
10247 // todo: this should be asynchronous!
10248 Slog.w(TAG, "Exception thrown disconnected servce "
10249 + r.shortName
10250 + " from app " + app.processName, e);
10251 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010252 }
10253 }
10254 }
10255 }
10256 }
10257 }
10258 }
10259
10260 // Clean up any connections this application has to other services.
10261 if (app.connections.size() > 0) {
10262 Iterator<ConnectionRecord> it = app.connections.iterator();
10263 while (it.hasNext()) {
10264 ConnectionRecord r = it.next();
10265 removeConnectionLocked(r, app, null);
10266 }
10267 }
10268 app.connections.clear();
10269
10270 if (app.services.size() != 0) {
10271 // Any services running in the application need to be placed
10272 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -070010273 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010274 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010275 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010276 synchronized (sr.stats.getBatteryStats()) {
10277 sr.stats.stopLaunchedLocked();
10278 }
10279 sr.app = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010280 sr.isolatedProc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010281 sr.executeNesting = 0;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010282 if (mStoppingServices.remove(sr)) {
10283 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
10284 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010285
10286 boolean hasClients = sr.bindings.size() > 0;
10287 if (hasClients) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010288 Iterator<IntentBindRecord> bindings
10289 = sr.bindings.values().iterator();
10290 while (bindings.hasNext()) {
10291 IntentBindRecord b = bindings.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -080010292 if (DEBUG_SERVICE) Slog.v(TAG, "Killing binding " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010293 + ": shouldUnbind=" + b.hasBound);
10294 b.binder = null;
10295 b.requested = b.received = b.hasBound = false;
10296 }
10297 }
10298
Dianne Hackborn070783f2010-12-29 16:46:28 -080010299 if (sr.crashCount >= 2 && (sr.serviceInfo.applicationInfo.flags
10300 &ApplicationInfo.FLAG_PERSISTENT) == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010301 Slog.w(TAG, "Service crashed " + sr.crashCount
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010302 + " times, stopping: " + sr);
Doug Zongker2bec3d42009-12-04 12:52:44 -080010303 EventLog.writeEvent(EventLogTags.AM_SERVICE_CRASHED_TOO_MUCH,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010304 sr.crashCount, sr.shortName, app.pid);
10305 bringDownServiceLocked(sr, true);
10306 } else if (!allowRestart) {
10307 bringDownServiceLocked(sr, true);
10308 } else {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010309 boolean canceled = scheduleServiceRestartLocked(sr, true);
10310
10311 // Should the service remain running? Note that in the
10312 // extreme case of so many attempts to deliver a command
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010313 // that it failed we also will stop it here.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010314 if (sr.startRequested && (sr.stopIfKilled || canceled)) {
10315 if (sr.pendingStarts.size() == 0) {
10316 sr.startRequested = false;
10317 if (!hasClients) {
10318 // Whoops, no reason to restart!
10319 bringDownServiceLocked(sr, true);
10320 }
10321 }
10322 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010323 }
10324 }
10325
10326 if (!allowRestart) {
10327 app.services.clear();
10328 }
10329 }
10330
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010331 // Make sure we have no more records on the stopping list.
10332 int i = mStoppingServices.size();
10333 while (i > 0) {
10334 i--;
10335 ServiceRecord sr = mStoppingServices.get(i);
10336 if (sr.app == app) {
10337 mStoppingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010338 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010339 }
10340 }
10341
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010342 app.executingServices.clear();
10343 }
10344
10345 private final void removeDyingProviderLocked(ProcessRecord proc,
10346 ContentProviderRecord cpr) {
10347 synchronized (cpr) {
10348 cpr.launchingApp = null;
10349 cpr.notifyAll();
10350 }
10351
Amith Yamasani742a6712011-05-04 14:49:28 -070010352 mProviderMap.removeProviderByClass(cpr.name, UserId.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010353 String names[] = cpr.info.authority.split(";");
10354 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010355 mProviderMap.removeProviderByName(names[j], UserId.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010356 }
10357
10358 Iterator<ProcessRecord> cit = cpr.clients.iterator();
10359 while (cit.hasNext()) {
10360 ProcessRecord capp = cit.next();
10361 if (!capp.persistent && capp.thread != null
10362 && capp.pid != 0
10363 && capp.pid != MY_PID) {
Dianne Hackborn8633e682010-04-22 16:03:41 -070010364 Slog.i(TAG, "Kill " + capp.processName
10365 + " (pid " + capp.pid + "): provider " + cpr.info.name
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010366 + " in dying process " + (proc != null ? proc.processName : "??"));
Dianne Hackborn8633e682010-04-22 16:03:41 -070010367 EventLog.writeEvent(EventLogTags.AM_KILL, capp.pid,
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010368 capp.processName, capp.setAdj, "dying provider "
10369 + cpr.name.toShortString());
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070010370 Process.killProcessQuiet(capp.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010371 }
10372 }
10373
10374 mLaunchingProviders.remove(cpr);
10375 }
10376
10377 /**
10378 * Main code for cleaning up a process when it has gone away. This is
10379 * called both as a result of the process dying, or directly when stopping
10380 * a process when running in single process mode.
10381 */
10382 private final void cleanUpApplicationRecordLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010383 boolean restarting, boolean allowRestart, int index) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010384 if (index >= 0) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010385 mLruProcesses.remove(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010386 }
10387
Dianne Hackborn36124872009-10-08 16:22:03 -070010388 mProcessesToGc.remove(app);
10389
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010390 // Dismiss any open dialogs.
10391 if (app.crashDialog != null) {
10392 app.crashDialog.dismiss();
10393 app.crashDialog = null;
10394 }
10395 if (app.anrDialog != null) {
10396 app.anrDialog.dismiss();
10397 app.anrDialog = null;
10398 }
10399 if (app.waitDialog != null) {
10400 app.waitDialog.dismiss();
10401 app.waitDialog = null;
10402 }
10403
10404 app.crashing = false;
10405 app.notResponding = false;
10406
10407 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -070010408 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010409 app.thread = null;
10410 app.forcingToForeground = null;
10411 app.foregroundServices = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010412 app.foregroundActivities = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070010413 app.hasShownUi = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010414 app.hasAboveClient = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010415
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010416 killServicesLocked(app, allowRestart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010417
10418 boolean restart = false;
10419
10420 int NL = mLaunchingProviders.size();
10421
10422 // Remove published content providers.
10423 if (!app.pubProviders.isEmpty()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010424 Iterator<ContentProviderRecord> it = app.pubProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010425 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010426 ContentProviderRecord cpr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010427 cpr.provider = null;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010428 cpr.proc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010429
10430 // See if someone is waiting for this provider... in which
10431 // case we don't remove it, but just let it restart.
10432 int i = 0;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010433 if (!app.bad && allowRestart) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010434 for (; i<NL; i++) {
10435 if (mLaunchingProviders.get(i) == cpr) {
10436 restart = true;
10437 break;
10438 }
10439 }
10440 } else {
10441 i = NL;
10442 }
10443
10444 if (i >= NL) {
10445 removeDyingProviderLocked(app, cpr);
10446 NL = mLaunchingProviders.size();
10447 }
10448 }
10449 app.pubProviders.clear();
10450 }
10451
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010452 // Take care of any launching providers waiting for this process.
10453 if (checkAppInLaunchingProvidersLocked(app, false)) {
10454 restart = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010455 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010456
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010457 // Unregister from connected content providers.
10458 if (!app.conProviders.isEmpty()) {
Dianne Hackborn0c3154d2009-10-06 17:18:05 -070010459 Iterator it = app.conProviders.keySet().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010460 while (it.hasNext()) {
10461 ContentProviderRecord cpr = (ContentProviderRecord)it.next();
10462 cpr.clients.remove(app);
10463 }
10464 app.conProviders.clear();
10465 }
10466
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010467 // At this point there may be remaining entries in mLaunchingProviders
10468 // where we were the only one waiting, so they are no longer of use.
10469 // Look for these and clean up if found.
10470 // XXX Commented out for now. Trying to figure out a way to reproduce
10471 // the actual situation to identify what is actually going on.
10472 if (false) {
10473 for (int i=0; i<NL; i++) {
10474 ContentProviderRecord cpr = (ContentProviderRecord)
10475 mLaunchingProviders.get(i);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080010476 if (cpr.clients.size() <= 0 && !cpr.hasExternalProcessHandles()) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010477 synchronized (cpr) {
10478 cpr.launchingApp = null;
10479 cpr.notifyAll();
10480 }
10481 }
10482 }
10483 }
10484
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010485 skipCurrentReceiverLocked(app);
10486
10487 // Unregister any receivers.
10488 if (app.receivers.size() > 0) {
10489 Iterator<ReceiverList> it = app.receivers.iterator();
10490 while (it.hasNext()) {
10491 removeReceiverLocked(it.next());
10492 }
10493 app.receivers.clear();
10494 }
10495
Christopher Tate181fafa2009-05-14 11:12:14 -070010496 // If the app is undergoing backup, tell the backup manager about it
10497 if (mBackupTarget != null && app.pid == mBackupTarget.app.pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010498 if (DEBUG_BACKUP) Slog.d(TAG, "App " + mBackupTarget.appInfo + " died during backup");
Christopher Tate181fafa2009-05-14 11:12:14 -070010499 try {
10500 IBackupManager bm = IBackupManager.Stub.asInterface(
10501 ServiceManager.getService(Context.BACKUP_SERVICE));
10502 bm.agentDisconnected(app.info.packageName);
10503 } catch (RemoteException e) {
10504 // can't happen; backup manager is local
10505 }
10506 }
10507
Jeff Sharkey287bd832011-05-28 19:36:26 -070010508 mHandler.obtainMessage(DISPATCH_PROCESS_DIED, app.pid, app.info.uid, null).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010509
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010510 // If the caller is restarting this app, then leave it in its
10511 // current lists and let the caller take care of it.
10512 if (restarting) {
10513 return;
10514 }
10515
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010516 if (!app.persistent || app.isolated) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010517 if (DEBUG_PROCESSES) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010518 "Removing non-persistent process during cleanup: " + app);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010519 mProcessNames.remove(app.processName, app.uid);
10520 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -070010521 if (mHeavyWeightProcess == app) {
10522 mHeavyWeightProcess = null;
10523 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
10524 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010525 } else if (!app.removed) {
10526 // This app is persistent, so we need to keep its record around.
10527 // If it is not already on the pending app list, add it there
10528 // and start a new process for it.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010529 if (mPersistentStartingProcesses.indexOf(app) < 0) {
10530 mPersistentStartingProcesses.add(app);
10531 restart = true;
10532 }
10533 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070010534 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
10535 "Clean-up removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010536 mProcessesOnHold.remove(app);
10537
The Android Open Source Project4df24232009-03-05 14:34:35 -080010538 if (app == mHomeProcess) {
10539 mHomeProcess = null;
10540 }
Dianne Hackbornf35fe232011-11-01 19:25:20 -070010541 if (app == mPreviousProcess) {
10542 mPreviousProcess = null;
10543 }
10544
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010545 if (restart && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010546 // We have components that still need to be running in the
10547 // process, so re-launch it.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010548 mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010549 startProcessLocked(app, "restart", app.processName);
10550 } else if (app.pid > 0 && app.pid != MY_PID) {
10551 // Goodbye!
10552 synchronized (mPidsSelfLocked) {
10553 mPidsSelfLocked.remove(app.pid);
10554 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
10555 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010556 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010557 }
10558 }
10559
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010560 boolean checkAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) {
10561 // Look through the content providers we are waiting to have launched,
10562 // and if any run in this process then either schedule a restart of
10563 // the process or kill the client waiting for it if this process has
10564 // gone bad.
10565 int NL = mLaunchingProviders.size();
10566 boolean restart = false;
10567 for (int i=0; i<NL; i++) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010568 ContentProviderRecord cpr = mLaunchingProviders.get(i);
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010569 if (cpr.launchingApp == app) {
10570 if (!alwaysBad && !app.bad) {
10571 restart = true;
10572 } else {
10573 removeDyingProviderLocked(app, cpr);
10574 NL = mLaunchingProviders.size();
10575 }
10576 }
10577 }
10578 return restart;
10579 }
10580
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010581 // =========================================================
10582 // SERVICES
10583 // =========================================================
10584
10585 ActivityManager.RunningServiceInfo makeRunningServiceInfoLocked(ServiceRecord r) {
10586 ActivityManager.RunningServiceInfo info =
10587 new ActivityManager.RunningServiceInfo();
10588 info.service = r.name;
10589 if (r.app != null) {
10590 info.pid = r.app.pid;
10591 }
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010592 info.uid = r.appInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010593 info.process = r.processName;
10594 info.foreground = r.isForeground;
10595 info.activeSince = r.createTime;
10596 info.started = r.startRequested;
10597 info.clientCount = r.connections.size();
10598 info.crashCount = r.crashCount;
10599 info.lastActivityTime = r.lastActivity;
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010600 if (r.isForeground) {
10601 info.flags |= ActivityManager.RunningServiceInfo.FLAG_FOREGROUND;
10602 }
10603 if (r.startRequested) {
10604 info.flags |= ActivityManager.RunningServiceInfo.FLAG_STARTED;
10605 }
Dan Egnor42471dd2010-01-07 17:25:22 -080010606 if (r.app != null && r.app.pid == MY_PID) {
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010607 info.flags |= ActivityManager.RunningServiceInfo.FLAG_SYSTEM_PROCESS;
10608 }
10609 if (r.app != null && r.app.persistent) {
10610 info.flags |= ActivityManager.RunningServiceInfo.FLAG_PERSISTENT_PROCESS;
10611 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010612
10613 for (ArrayList<ConnectionRecord> connl : r.connections.values()) {
10614 for (int i=0; i<connl.size(); i++) {
10615 ConnectionRecord conn = connl.get(i);
10616 if (conn.clientLabel != 0) {
10617 info.clientPackage = conn.binding.client.info.packageName;
10618 info.clientLabel = conn.clientLabel;
10619 return info;
10620 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010621 }
10622 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010623 return info;
10624 }
10625
10626 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum,
10627 int flags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010628 enforceNotIsolatedCaller("getServices");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010629 synchronized (this) {
10630 ArrayList<ActivityManager.RunningServiceInfo> res
10631 = new ArrayList<ActivityManager.RunningServiceInfo>();
10632
Amith Yamasani742a6712011-05-04 14:49:28 -070010633 int userId = UserId.getUserId(Binder.getCallingUid());
10634 if (mServiceMap.getAllServices(userId).size() > 0) {
10635 Iterator<ServiceRecord> it
10636 = mServiceMap.getAllServices(userId).iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010637 while (it.hasNext() && res.size() < maxNum) {
10638 res.add(makeRunningServiceInfoLocked(it.next()));
10639 }
10640 }
10641
10642 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
10643 ServiceRecord r = mRestartingServices.get(i);
10644 ActivityManager.RunningServiceInfo info =
10645 makeRunningServiceInfoLocked(r);
10646 info.restarting = r.nextRestartTime;
10647 res.add(info);
10648 }
10649
10650 return res;
10651 }
10652 }
10653
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010654 public PendingIntent getRunningServiceControlPanel(ComponentName name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010655 enforceNotIsolatedCaller("getRunningServiceControlPanel");
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010656 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010657 int userId = UserId.getUserId(Binder.getCallingUid());
10658 ServiceRecord r = mServiceMap.getServiceByName(name, userId);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010659 if (r != null) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010660 for (ArrayList<ConnectionRecord> conn : r.connections.values()) {
10661 for (int i=0; i<conn.size(); i++) {
10662 if (conn.get(i).clientIntent != null) {
10663 return conn.get(i).clientIntent;
10664 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010665 }
10666 }
10667 }
10668 }
10669 return null;
10670 }
10671
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010672 private final ServiceRecord findServiceLocked(ComponentName name,
10673 IBinder token) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010674 ServiceRecord r = mServiceMap.getServiceByName(name, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010675 return r == token ? r : null;
10676 }
10677
10678 private final class ServiceLookupResult {
10679 final ServiceRecord record;
10680 final String permission;
10681
10682 ServiceLookupResult(ServiceRecord _record, String _permission) {
10683 record = _record;
10684 permission = _permission;
10685 }
10686 };
10687
10688 private ServiceLookupResult findServiceLocked(Intent service,
10689 String resolvedType) {
10690 ServiceRecord r = null;
10691 if (service.getComponent() != null) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010692 r = mServiceMap.getServiceByName(service.getComponent(), Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010693 }
10694 if (r == null) {
10695 Intent.FilterComparison filter = new Intent.FilterComparison(service);
Amith Yamasani742a6712011-05-04 14:49:28 -070010696 r = mServiceMap.getServiceByIntent(filter, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010697 }
10698
10699 if (r == null) {
10700 try {
10701 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070010702 AppGlobals.getPackageManager().resolveService(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010703 service, resolvedType, 0);
10704 ServiceInfo sInfo =
10705 rInfo != null ? rInfo.serviceInfo : null;
10706 if (sInfo == null) {
10707 return null;
10708 }
10709
10710 ComponentName name = new ComponentName(
10711 sInfo.applicationInfo.packageName, sInfo.name);
Amith Yamasani742a6712011-05-04 14:49:28 -070010712 r = mServiceMap.getServiceByName(name, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010713 } catch (RemoteException ex) {
10714 // pm is in same process, this will never happen.
10715 }
10716 }
10717 if (r != null) {
10718 int callingPid = Binder.getCallingPid();
10719 int callingUid = Binder.getCallingUid();
10720 if (checkComponentPermission(r.permission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010721 callingPid, callingUid, r.appInfo.uid, r.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010722 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010723 if (!r.exported) {
10724 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
10725 + " from pid=" + callingPid
10726 + ", uid=" + callingUid
10727 + " that is not exported from uid " + r.appInfo.uid);
10728 return new ServiceLookupResult(null, "not exported from uid "
10729 + r.appInfo.uid);
10730 }
Joe Onorato8a9b2202010-02-26 18:56:32 -080010731 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010732 + " from pid=" + callingPid
10733 + ", uid=" + callingUid
10734 + " requires " + r.permission);
10735 return new ServiceLookupResult(null, r.permission);
10736 }
10737 return new ServiceLookupResult(r, null);
10738 }
10739 return null;
10740 }
10741
10742 private class ServiceRestarter implements Runnable {
10743 private ServiceRecord mService;
10744
10745 void setService(ServiceRecord service) {
10746 mService = service;
10747 }
10748
10749 public void run() {
10750 synchronized(ActivityManagerService.this) {
10751 performServiceRestartLocked(mService);
10752 }
10753 }
10754 }
10755
10756 private ServiceLookupResult retrieveServiceLocked(Intent service,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010757 String resolvedType, int callingPid, int callingUid, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010758 ServiceRecord r = null;
Amith Yamasani742a6712011-05-04 14:49:28 -070010759 if (DEBUG_SERVICE)
10760 Slog.v(TAG, "retrieveServiceLocked: " + service + " type=" + resolvedType
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010761 + " callingUid=" + callingUid);
Amith Yamasani742a6712011-05-04 14:49:28 -070010762
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010763 if (service.getComponent() != null) {
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010764 r = mServiceMap.getServiceByName(service.getComponent(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010765 }
Amith Yamasani742a6712011-05-04 14:49:28 -070010766 if (r == null) {
10767 Intent.FilterComparison filter = new Intent.FilterComparison(service);
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010768 r = mServiceMap.getServiceByIntent(filter, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -070010769 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010770 if (r == null) {
10771 try {
10772 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070010773 AppGlobals.getPackageManager().resolveService(
Dianne Hackborn1655be42009-05-08 14:29:01 -070010774 service, resolvedType, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010775 ServiceInfo sInfo =
10776 rInfo != null ? rInfo.serviceInfo : null;
10777 if (sInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010778 Slog.w(TAG, "Unable to start service " + service +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010779 ": not found");
10780 return null;
10781 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010782 if (userId > 0) {
10783 sInfo.applicationInfo = getAppInfoForUser(sInfo.applicationInfo, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -070010784 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010785 ComponentName name = new ComponentName(
10786 sInfo.applicationInfo.packageName, sInfo.name);
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010787 r = mServiceMap.getServiceByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010788 if (r == null) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010789 Intent.FilterComparison filter = new Intent.FilterComparison(
10790 service.cloneFilter());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010791 ServiceRestarter res = new ServiceRestarter();
10792 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
10793 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
10794 synchronized (stats) {
10795 ss = stats.getServiceStatsLocked(
10796 sInfo.applicationInfo.uid, sInfo.packageName,
10797 sInfo.name);
10798 }
Dianne Hackbornb1c4a2a2010-01-19 15:36:42 -080010799 r = new ServiceRecord(this, ss, name, filter, sInfo, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010800 res.setService(r);
Amith Yamasani742a6712011-05-04 14:49:28 -070010801 mServiceMap.putServiceByName(name, UserId.getUserId(r.appInfo.uid), r);
10802 mServiceMap.putServiceByIntent(filter, UserId.getUserId(r.appInfo.uid), r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010803
10804 // Make sure this component isn't in the pending list.
10805 int N = mPendingServices.size();
10806 for (int i=0; i<N; i++) {
10807 ServiceRecord pr = mPendingServices.get(i);
10808 if (pr.name.equals(name)) {
10809 mPendingServices.remove(i);
10810 i--;
10811 N--;
10812 }
10813 }
10814 }
10815 } catch (RemoteException ex) {
10816 // pm is in same process, this will never happen.
10817 }
10818 }
10819 if (r != null) {
10820 if (checkComponentPermission(r.permission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010821 callingPid, callingUid, r.appInfo.uid, r.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010822 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010823 if (!r.exported) {
10824 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
10825 + " from pid=" + callingPid
10826 + ", uid=" + callingUid
10827 + " that is not exported from uid " + r.appInfo.uid);
10828 return new ServiceLookupResult(null, "not exported from uid "
10829 + r.appInfo.uid);
10830 }
Joe Onorato8a9b2202010-02-26 18:56:32 -080010831 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010832 + " from pid=" + callingPid
10833 + ", uid=" + callingUid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010834 + " requires " + r.permission);
10835 return new ServiceLookupResult(null, r.permission);
10836 }
10837 return new ServiceLookupResult(r, null);
10838 }
10839 return null;
10840 }
10841
Dianne Hackborn287952c2010-09-22 22:34:31 -070010842 private final void bumpServiceExecutingLocked(ServiceRecord r, String why) {
10843 if (DEBUG_SERVICE) Log.v(TAG, ">>> EXECUTING "
10844 + why + " of " + r + " in app " + r.app);
10845 else if (DEBUG_SERVICE_EXECUTING) Log.v(TAG, ">>> EXECUTING "
10846 + why + " of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010847 long now = SystemClock.uptimeMillis();
10848 if (r.executeNesting == 0 && r.app != null) {
10849 if (r.app.executingServices.size() == 0) {
10850 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
10851 msg.obj = r.app;
10852 mHandler.sendMessageAtTime(msg, now+SERVICE_TIMEOUT);
10853 }
10854 r.app.executingServices.add(r);
10855 }
10856 r.executeNesting++;
10857 r.executingStart = now;
10858 }
10859
10860 private final void sendServiceArgsLocked(ServiceRecord r,
10861 boolean oomAdjusted) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010862 final int N = r.pendingStarts.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010863 if (N == 0) {
10864 return;
10865 }
10866
Dianne Hackborn39792d22010-08-19 18:01:52 -070010867 while (r.pendingStarts.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010868 try {
Dianne Hackborn39792d22010-08-19 18:01:52 -070010869 ServiceRecord.StartItem si = r.pendingStarts.remove(0);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010870 if (DEBUG_SERVICE) Slog.v(TAG, "Sending arguments to: "
10871 + r + " " + r.intent + " args=" + si.intent);
Dianne Hackborn3a28f222011-03-01 12:25:54 -080010872 if (si.intent == null && N > 1) {
10873 // If somehow we got a dummy null intent in the middle,
10874 // then skip it. DO NOT skip a null intent when it is
10875 // the only one in the list -- this is to support the
10876 // onStartCommand(null) case.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010877 continue;
10878 }
Dianne Hackborn39792d22010-08-19 18:01:52 -070010879 si.deliveredTime = SystemClock.uptimeMillis();
10880 r.deliveredStarts.add(si);
10881 si.deliveryCount++;
Dianne Hackborn21c241e2012-03-08 13:57:23 -080010882 if (si.neededGrants != null) {
10883 grantUriPermissionUncheckedFromIntentLocked(si.neededGrants,
10884 si.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -070010885 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070010886 bumpServiceExecutingLocked(r, "start");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010887 if (!oomAdjusted) {
10888 oomAdjusted = true;
10889 updateOomAdjLocked(r.app);
10890 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010891 int flags = 0;
10892 if (si.deliveryCount > 0) {
10893 flags |= Service.START_FLAG_RETRY;
10894 }
10895 if (si.doneExecutingCount > 0) {
10896 flags |= Service.START_FLAG_REDELIVERY;
10897 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070010898 r.app.thread.scheduleServiceArgs(r, si.taskRemoved, si.id, flags, si.intent);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010899 } catch (RemoteException e) {
10900 // Remote process gone... we'll let the normal cleanup take
10901 // care of this.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010902 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while scheduling start: " + r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010903 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010904 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010905 Slog.w(TAG, "Unexpected exception", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010906 break;
10907 }
10908 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010909 }
10910
10911 private final boolean requestServiceBindingLocked(ServiceRecord r,
10912 IntentBindRecord i, boolean rebind) {
10913 if (r.app == null || r.app.thread == null) {
10914 // If service is not currently running, can't yet bind.
10915 return false;
10916 }
10917 if ((!i.requested || rebind) && i.apps.size() > 0) {
10918 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070010919 bumpServiceExecutingLocked(r, "bind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010920 r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind);
10921 if (!rebind) {
10922 i.requested = true;
10923 }
10924 i.hasBound = true;
10925 i.doRebind = false;
10926 } catch (RemoteException e) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010927 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while binding " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010928 return false;
10929 }
10930 }
10931 return true;
10932 }
10933
10934 private final void requestServiceBindingsLocked(ServiceRecord r) {
10935 Iterator<IntentBindRecord> bindings = r.bindings.values().iterator();
10936 while (bindings.hasNext()) {
10937 IntentBindRecord i = bindings.next();
10938 if (!requestServiceBindingLocked(r, i, false)) {
10939 break;
10940 }
10941 }
10942 }
10943
10944 private final void realStartServiceLocked(ServiceRecord r,
10945 ProcessRecord app) throws RemoteException {
10946 if (app.thread == null) {
10947 throw new RemoteException();
10948 }
Amith Yamasani742a6712011-05-04 14:49:28 -070010949 if (DEBUG_MU)
10950 Slog.v(TAG_MU, "realStartServiceLocked, ServiceRecord.uid = " + r.appInfo.uid
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010951 + ", ProcessRecord.uid = " + app.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010952 r.app = app;
The Android Open Source Project10592532009-03-18 17:39:46 -070010953 r.restartTime = r.lastActivity = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010954
10955 app.services.add(r);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010956 bumpServiceExecutingLocked(r, "create");
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010957 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010958
10959 boolean created = false;
10960 try {
Dianne Hackborna33e3f72009-09-29 17:28:24 -070010961 mStringBuilder.setLength(0);
Dianne Hackborn21c241e2012-03-08 13:57:23 -080010962 r.intent.getIntent().toShortString(mStringBuilder, true, false, true, false);
Doug Zongker2bec3d42009-12-04 12:52:44 -080010963 EventLog.writeEvent(EventLogTags.AM_CREATE_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010964 System.identityHashCode(r), r.shortName,
Dianne Hackborna33e3f72009-09-29 17:28:24 -070010965 mStringBuilder.toString(), r.app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010966 synchronized (r.stats.getBatteryStats()) {
10967 r.stats.startLaunchedLocked();
10968 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -070010969 ensurePackageDexOpt(r.serviceInfo.packageName);
Dianne Hackborne2515ee2011-04-27 18:52:56 -040010970 app.thread.scheduleCreateService(r, r.serviceInfo,
10971 compatibilityInfoForPackageLocked(r.serviceInfo.applicationInfo));
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070010972 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010973 created = true;
10974 } finally {
10975 if (!created) {
10976 app.services.remove(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010977 scheduleServiceRestartLocked(r, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010978 }
10979 }
10980
10981 requestServiceBindingsLocked(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010982
10983 // If the service is in the started state, and there are no
10984 // pending arguments, then fake up one so its onStartCommand() will
10985 // be called.
10986 if (r.startRequested && r.callStart && r.pendingStarts.size() == 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070010987 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Dianne Hackborn21c241e2012-03-08 13:57:23 -080010988 null, null));
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010989 }
10990
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010991 sendServiceArgsLocked(r, true);
10992 }
10993
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010994 private final boolean scheduleServiceRestartLocked(ServiceRecord r,
10995 boolean allowCancel) {
10996 boolean canceled = false;
10997
Dianne Hackbornfd12af42009-08-27 00:44:33 -070010998 final long now = SystemClock.uptimeMillis();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010999 long minDuration = SERVICE_RESTART_DURATION;
Dianne Hackborn6ccd2af2009-08-27 12:26:44 -070011000 long resetTime = SERVICE_RESET_RUN_DURATION;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011001
Dianne Hackborn070783f2010-12-29 16:46:28 -080011002 if ((r.serviceInfo.applicationInfo.flags
11003 &ApplicationInfo.FLAG_PERSISTENT) != 0) {
11004 minDuration /= 4;
11005 }
11006
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011007 // Any delivered but not yet finished starts should be put back
11008 // on the pending list.
11009 final int N = r.deliveredStarts.size();
11010 if (N > 0) {
11011 for (int i=N-1; i>=0; i--) {
11012 ServiceRecord.StartItem si = r.deliveredStarts.get(i);
Dianne Hackborn39792d22010-08-19 18:01:52 -070011013 si.removeUriPermissionsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011014 if (si.intent == null) {
11015 // We'll generate this again if needed.
11016 } else if (!allowCancel || (si.deliveryCount < ServiceRecord.MAX_DELIVERY_COUNT
11017 && si.doneExecutingCount < ServiceRecord.MAX_DONE_EXECUTING_COUNT)) {
11018 r.pendingStarts.add(0, si);
11019 long dur = SystemClock.uptimeMillis() - si.deliveredTime;
11020 dur *= 2;
11021 if (minDuration < dur) minDuration = dur;
11022 if (resetTime < dur) resetTime = dur;
11023 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011024 Slog.w(TAG, "Canceling start item " + si.intent + " in service "
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011025 + r.name);
11026 canceled = true;
11027 }
11028 }
11029 r.deliveredStarts.clear();
11030 }
11031
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011032 r.totalRestartCount++;
11033 if (r.restartDelay == 0) {
11034 r.restartCount++;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011035 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011036 } else {
11037 // If it has been a "reasonably long time" since the service
11038 // was started, then reset our restart duration back to
11039 // the beginning, so we don't infinitely increase the duration
11040 // on a service that just occasionally gets killed (which is
11041 // a normal case, due to process being killed to reclaim memory).
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011042 if (now > (r.restartTime+resetTime)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011043 r.restartCount = 1;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011044 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011045 } else {
Dianne Hackborn070783f2010-12-29 16:46:28 -080011046 if ((r.serviceInfo.applicationInfo.flags
11047 &ApplicationInfo.FLAG_PERSISTENT) != 0) {
11048 // Services in peristent processes will restart much more
11049 // quickly, since they are pretty important. (Think SystemUI).
11050 r.restartDelay += minDuration/2;
11051 } else {
11052 r.restartDelay *= SERVICE_RESTART_DURATION_FACTOR;
11053 if (r.restartDelay < minDuration) {
11054 r.restartDelay = minDuration;
11055 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011056 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011057 }
11058 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011059
11060 r.nextRestartTime = now + r.restartDelay;
11061
11062 // Make sure that we don't end up restarting a bunch of services
11063 // all at the same time.
11064 boolean repeat;
11065 do {
11066 repeat = false;
11067 for (int i=mRestartingServices.size()-1; i>=0; i--) {
11068 ServiceRecord r2 = mRestartingServices.get(i);
11069 if (r2 != r && r.nextRestartTime
11070 >= (r2.nextRestartTime-SERVICE_MIN_RESTART_TIME_BETWEEN)
11071 && r.nextRestartTime
11072 < (r2.nextRestartTime+SERVICE_MIN_RESTART_TIME_BETWEEN)) {
11073 r.nextRestartTime = r2.nextRestartTime + SERVICE_MIN_RESTART_TIME_BETWEEN;
11074 r.restartDelay = r.nextRestartTime - now;
11075 repeat = true;
11076 break;
11077 }
11078 }
11079 } while (repeat);
11080
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011081 if (!mRestartingServices.contains(r)) {
11082 mRestartingServices.add(r);
11083 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011084
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011085 r.cancelNotification();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011086
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011087 mHandler.removeCallbacks(r.restarter);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011088 mHandler.postAtTime(r.restarter, r.nextRestartTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011089 r.nextRestartTime = SystemClock.uptimeMillis() + r.restartDelay;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011090 Slog.w(TAG, "Scheduling restart of crashed service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011091 + r.shortName + " in " + r.restartDelay + "ms");
Doug Zongker2bec3d42009-12-04 12:52:44 -080011092 EventLog.writeEvent(EventLogTags.AM_SCHEDULE_SERVICE_RESTART,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011093 r.shortName, r.restartDelay);
11094
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011095 return canceled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011096 }
11097
11098 final void performServiceRestartLocked(ServiceRecord r) {
11099 if (!mRestartingServices.contains(r)) {
11100 return;
11101 }
11102 bringUpServiceLocked(r, r.intent.getIntent().getFlags(), true);
11103 }
11104
11105 private final boolean unscheduleServiceRestartLocked(ServiceRecord r) {
11106 if (r.restartDelay == 0) {
11107 return false;
11108 }
11109 r.resetRestartCounter();
11110 mRestartingServices.remove(r);
11111 mHandler.removeCallbacks(r.restarter);
11112 return true;
11113 }
11114
11115 private final boolean bringUpServiceLocked(ServiceRecord r,
11116 int intentFlags, boolean whileRestarting) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011117 //Slog.i(TAG, "Bring up service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011118 //r.dump(" ");
11119
Dianne Hackborn36124872009-10-08 16:22:03 -070011120 if (r.app != null && r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011121 sendServiceArgsLocked(r, false);
11122 return true;
11123 }
11124
11125 if (!whileRestarting && r.restartDelay > 0) {
11126 // If waiting for a restart, then do nothing.
11127 return true;
11128 }
11129
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011130 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing up " + r + " " + r.intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011131
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011132 // We are now bringing the service up, so no longer in the
11133 // restarting state.
11134 mRestartingServices.remove(r);
11135
Dianne Hackborne7f97212011-02-24 14:40:20 -080011136 // Service is now being launched, its package can't be stopped.
11137 try {
11138 AppGlobals.getPackageManager().setPackageStoppedState(
11139 r.packageName, false);
11140 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080011141 } catch (IllegalArgumentException e) {
11142 Slog.w(TAG, "Failed trying to unstop package "
11143 + r.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080011144 }
11145
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011146 final boolean isolated = (r.serviceInfo.flags&ServiceInfo.FLAG_ISOLATED_PROCESS) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011147 final String appName = r.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011148 ProcessRecord app;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011149
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011150 if (!isolated) {
11151 app = getProcessRecordLocked(appName, r.appInfo.uid);
11152 if (DEBUG_MU)
11153 Slog.v(TAG_MU, "bringUpServiceLocked: appInfo.uid=" + r.appInfo.uid + " app=" + app);
11154 if (app != null && app.thread != null) {
11155 try {
11156 app.addPackage(r.appInfo.packageName);
11157 realStartServiceLocked(r, app);
11158 return true;
11159 } catch (RemoteException e) {
11160 Slog.w(TAG, "Exception when starting service " + r.shortName, e);
11161 }
11162
11163 // If a dead object exception was thrown -- fall through to
11164 // restart the application.
11165 }
11166 } else {
11167 // If this service runs in an isolated process, then each time
11168 // we call startProcessLocked() we will get a new isolated
11169 // process, starting another process if we are currently waiting
11170 // for a previous process to come up. To deal with this, we store
11171 // in the service any current isolated process it is running in or
11172 // waiting to have come up.
11173 app = r.isolatedProc;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011174 }
11175
Dianne Hackborn36124872009-10-08 16:22:03 -070011176 // Not running -- get it started, and enqueue this service record
11177 // to be executed when the app comes up.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011178 if (app == null) {
11179 if ((app=startProcessLocked(appName, r.appInfo, true, intentFlags,
11180 "service", r.name, false, isolated)) == null) {
11181 Slog.w(TAG, "Unable to launch app "
11182 + r.appInfo.packageName + "/"
11183 + r.appInfo.uid + " for service "
11184 + r.intent.getIntent() + ": process is bad");
11185 bringDownServiceLocked(r, true);
11186 return false;
11187 }
11188 if (isolated) {
11189 r.isolatedProc = app;
11190 }
Dianne Hackborn36124872009-10-08 16:22:03 -070011191 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011192
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011193 if (!mPendingServices.contains(r)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011194 mPendingServices.add(r);
11195 }
Dianne Hackborn36124872009-10-08 16:22:03 -070011196
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011197 return true;
11198 }
11199
11200 private final void bringDownServiceLocked(ServiceRecord r, boolean force) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011201 //Slog.i(TAG, "Bring down service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011202 //r.dump(" ");
11203
11204 // Does it still need to run?
11205 if (!force && r.startRequested) {
11206 return;
11207 }
11208 if (r.connections.size() > 0) {
11209 if (!force) {
11210 // XXX should probably keep a count of the number of auto-create
11211 // connections directly in the service.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011212 Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011213 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011214 ArrayList<ConnectionRecord> cr = it.next();
11215 for (int i=0; i<cr.size(); i++) {
11216 if ((cr.get(i).flags&Context.BIND_AUTO_CREATE) != 0) {
11217 return;
11218 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011219 }
11220 }
11221 }
11222
11223 // Report to all of the connections that the service is no longer
11224 // available.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011225 Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011226 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011227 ArrayList<ConnectionRecord> c = it.next();
11228 for (int i=0; i<c.size(); i++) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011229 ConnectionRecord cr = c.get(i);
11230 // There is still a connection to the service that is
11231 // being brought down. Mark it as dead.
11232 cr.serviceDead = true;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011233 try {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011234 cr.conn.connected(r.name, null);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011235 } catch (Exception e) {
11236 Slog.w(TAG, "Failure disconnecting service " + r.name +
11237 " to connection " + c.get(i).conn.asBinder() +
11238 " (in " + c.get(i).binding.client.processName + ")", e);
11239 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011240 }
11241 }
11242 }
11243
11244 // Tell the service that it has been unbound.
11245 if (r.bindings.size() > 0 && r.app != null && r.app.thread != null) {
11246 Iterator<IntentBindRecord> it = r.bindings.values().iterator();
11247 while (it.hasNext()) {
11248 IntentBindRecord ibr = it.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -080011249 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down binding " + ibr
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011250 + ": hasBound=" + ibr.hasBound);
11251 if (r.app != null && r.app.thread != null && ibr.hasBound) {
11252 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011253 bumpServiceExecutingLocked(r, "bring down unbind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011254 updateOomAdjLocked(r.app);
11255 ibr.hasBound = false;
11256 r.app.thread.scheduleUnbindService(r,
11257 ibr.intent.getIntent());
11258 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011259 Slog.w(TAG, "Exception when unbinding service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011260 + r.shortName, e);
11261 serviceDoneExecutingLocked(r, true);
11262 }
11263 }
11264 }
11265 }
11266
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011267 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down " + r + " " + r.intent);
Doug Zongker2bec3d42009-12-04 12:52:44 -080011268 EventLog.writeEvent(EventLogTags.AM_DESTROY_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011269 System.identityHashCode(r), r.shortName,
11270 (r.app != null) ? r.app.pid : -1);
11271
Amith Yamasani742a6712011-05-04 14:49:28 -070011272 mServiceMap.removeServiceByName(r.name, r.userId);
11273 mServiceMap.removeServiceByIntent(r.intent, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011274 r.totalRestartCount = 0;
11275 unscheduleServiceRestartLocked(r);
11276
11277 // Also make sure it is not on the pending list.
11278 int N = mPendingServices.size();
11279 for (int i=0; i<N; i++) {
11280 if (mPendingServices.get(i) == r) {
11281 mPendingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011282 if (DEBUG_SERVICE) Slog.v(TAG, "Removed pending: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011283 i--;
11284 N--;
11285 }
11286 }
11287
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011288 r.cancelNotification();
11289 r.isForeground = false;
11290 r.foregroundId = 0;
11291 r.foregroundNoti = null;
11292
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011293 // Clear start entries.
Dianne Hackborn39792d22010-08-19 18:01:52 -070011294 r.clearDeliveredStartsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011295 r.pendingStarts.clear();
11296
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011297 if (r.app != null) {
11298 synchronized (r.stats.getBatteryStats()) {
11299 r.stats.stopLaunchedLocked();
11300 }
11301 r.app.services.remove(r);
11302 if (r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011303 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011304 bumpServiceExecutingLocked(r, "stop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011305 mStoppingServices.add(r);
11306 updateOomAdjLocked(r.app);
11307 r.app.thread.scheduleStopService(r);
11308 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011309 Slog.w(TAG, "Exception when stopping service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011310 + r.shortName, e);
11311 serviceDoneExecutingLocked(r, true);
11312 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011313 updateServiceForegroundLocked(r.app, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011314 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011315 if (DEBUG_SERVICE) Slog.v(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011316 TAG, "Removed service that has no process: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011317 }
11318 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011319 if (DEBUG_SERVICE) Slog.v(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011320 TAG, "Removed service that is not running: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011321 }
Vairavan Srinivasana207ce22010-12-23 13:51:48 -080011322
11323 if (r.bindings.size() > 0) {
11324 r.bindings.clear();
11325 }
11326
11327 if (r.restarter instanceof ServiceRestarter) {
11328 ((ServiceRestarter)r.restarter).setService(null);
11329 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011330 }
11331
11332 ComponentName startServiceLocked(IApplicationThread caller,
11333 Intent service, String resolvedType,
11334 int callingPid, int callingUid) {
11335 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011336 if (DEBUG_SERVICE) Slog.v(TAG, "startService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011337 + " type=" + resolvedType + " args=" + service.getExtras());
11338
11339 if (caller != null) {
11340 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11341 if (callerApp == null) {
11342 throw new SecurityException(
11343 "Unable to find app for caller " + caller
11344 + " (pid=" + Binder.getCallingPid()
11345 + ") when starting service " + service);
11346 }
11347 }
11348
11349 ServiceLookupResult res =
11350 retrieveServiceLocked(service, resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011351 callingPid, callingUid, UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011352 if (res == null) {
11353 return null;
11354 }
11355 if (res.record == null) {
11356 return new ComponentName("!", res.permission != null
11357 ? res.permission : "private to package");
11358 }
11359 ServiceRecord r = res.record;
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011360 NeededUriGrants neededGrants = checkGrantUriPermissionFromIntentLocked(
11361 callingUid, r.packageName, service, service.getFlags(), null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011362 if (unscheduleServiceRestartLocked(r)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011363 if (DEBUG_SERVICE) Slog.v(TAG, "START SERVICE WHILE RESTART PENDING: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011364 }
11365 r.startRequested = true;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011366 r.callStart = false;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011367 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011368 service, neededGrants));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011369 r.lastActivity = SystemClock.uptimeMillis();
11370 synchronized (r.stats.getBatteryStats()) {
11371 r.stats.startRunningLocked();
11372 }
11373 if (!bringUpServiceLocked(r, service.getFlags(), false)) {
11374 return new ComponentName("!", "Service process is bad");
11375 }
11376 return r.name;
11377 }
11378 }
11379
11380 public ComponentName startService(IApplicationThread caller, Intent service,
11381 String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011382 enforceNotIsolatedCaller("startService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011383 // Refuse possible leaked file descriptors
11384 if (service != null && service.hasFileDescriptors() == true) {
11385 throw new IllegalArgumentException("File descriptors passed in Intent");
11386 }
11387
Amith Yamasani742a6712011-05-04 14:49:28 -070011388 if (DEBUG_SERVICE)
11389 Slog.v(TAG, "startService: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011390 synchronized(this) {
11391 final int callingPid = Binder.getCallingPid();
11392 final int callingUid = Binder.getCallingUid();
11393 final long origId = Binder.clearCallingIdentity();
11394 ComponentName res = startServiceLocked(caller, service,
11395 resolvedType, callingPid, callingUid);
11396 Binder.restoreCallingIdentity(origId);
11397 return res;
11398 }
11399 }
11400
11401 ComponentName startServiceInPackage(int uid,
11402 Intent service, String resolvedType) {
11403 synchronized(this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070011404 if (DEBUG_SERVICE)
11405 Slog.v(TAG, "startServiceInPackage: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011406 final long origId = Binder.clearCallingIdentity();
11407 ComponentName res = startServiceLocked(null, service,
11408 resolvedType, -1, uid);
11409 Binder.restoreCallingIdentity(origId);
11410 return res;
11411 }
11412 }
11413
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011414 private void stopServiceLocked(ServiceRecord service) {
11415 synchronized (service.stats.getBatteryStats()) {
11416 service.stats.stopRunningLocked();
11417 }
11418 service.startRequested = false;
11419 service.callStart = false;
11420 bringDownServiceLocked(service, false);
11421 }
11422
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011423 public int stopService(IApplicationThread caller, Intent service,
11424 String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011425 enforceNotIsolatedCaller("stopService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011426 // Refuse possible leaked file descriptors
11427 if (service != null && service.hasFileDescriptors() == true) {
11428 throw new IllegalArgumentException("File descriptors passed in Intent");
11429 }
11430
11431 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011432 if (DEBUG_SERVICE) Slog.v(TAG, "stopService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011433 + " type=" + resolvedType);
11434
11435 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11436 if (caller != null && callerApp == null) {
11437 throw new SecurityException(
11438 "Unable to find app for caller " + caller
11439 + " (pid=" + Binder.getCallingPid()
11440 + ") when stopping service " + service);
11441 }
11442
11443 // If this service is active, make sure it is stopped.
11444 ServiceLookupResult r = findServiceLocked(service, resolvedType);
11445 if (r != null) {
11446 if (r.record != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011447 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011448 try {
11449 stopServiceLocked(r.record);
11450 } finally {
11451 Binder.restoreCallingIdentity(origId);
11452 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011453 return 1;
11454 }
11455 return -1;
11456 }
11457 }
11458
11459 return 0;
11460 }
11461
11462 public IBinder peekService(Intent service, String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011463 enforceNotIsolatedCaller("peekService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011464 // Refuse possible leaked file descriptors
11465 if (service != null && service.hasFileDescriptors() == true) {
11466 throw new IllegalArgumentException("File descriptors passed in Intent");
11467 }
11468
11469 IBinder ret = null;
11470
11471 synchronized(this) {
11472 ServiceLookupResult r = findServiceLocked(service, resolvedType);
11473
11474 if (r != null) {
11475 // r.record is null if findServiceLocked() failed the caller permission check
11476 if (r.record == null) {
11477 throw new SecurityException(
11478 "Permission Denial: Accessing service " + r.record.name
11479 + " from pid=" + Binder.getCallingPid()
11480 + ", uid=" + Binder.getCallingUid()
11481 + " requires " + r.permission);
11482 }
11483 IntentBindRecord ib = r.record.bindings.get(r.record.intent);
11484 if (ib != null) {
11485 ret = ib.binder;
11486 }
11487 }
11488 }
11489
11490 return ret;
11491 }
11492
11493 public boolean stopServiceToken(ComponentName className, IBinder token,
11494 int startId) {
11495 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011496 if (DEBUG_SERVICE) Slog.v(TAG, "stopServiceToken: " + className
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011497 + " " + token + " startId=" + startId);
11498 ServiceRecord r = findServiceLocked(className, token);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011499 if (r != null) {
11500 if (startId >= 0) {
11501 // Asked to only stop if done with all work. Note that
11502 // to avoid leaks, we will take this as dropping all
11503 // start items up to and including this one.
11504 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
11505 if (si != null) {
11506 while (r.deliveredStarts.size() > 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -070011507 ServiceRecord.StartItem cur = r.deliveredStarts.remove(0);
11508 cur.removeUriPermissionsLocked();
11509 if (cur == si) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011510 break;
11511 }
11512 }
11513 }
11514
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011515 if (r.getLastStartId() != startId) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011516 return false;
11517 }
11518
11519 if (r.deliveredStarts.size() > 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011520 Slog.w(TAG, "stopServiceToken startId " + startId
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011521 + " is last, but have " + r.deliveredStarts.size()
11522 + " remaining args");
11523 }
11524 }
11525
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011526 synchronized (r.stats.getBatteryStats()) {
11527 r.stats.stopRunningLocked();
11528 r.startRequested = false;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011529 r.callStart = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011530 }
11531 final long origId = Binder.clearCallingIdentity();
11532 bringDownServiceLocked(r, false);
11533 Binder.restoreCallingIdentity(origId);
11534 return true;
11535 }
11536 }
11537 return false;
11538 }
11539
11540 public void setServiceForeground(ComponentName className, IBinder token,
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011541 int id, Notification notification, boolean removeNotification) {
11542 final long origId = Binder.clearCallingIdentity();
11543 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011544 synchronized(this) {
11545 ServiceRecord r = findServiceLocked(className, token);
11546 if (r != null) {
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011547 if (id != 0) {
11548 if (notification == null) {
11549 throw new IllegalArgumentException("null notification");
11550 }
11551 if (r.foregroundId != id) {
11552 r.cancelNotification();
11553 r.foregroundId = id;
11554 }
11555 notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
11556 r.foregroundNoti = notification;
11557 r.isForeground = true;
11558 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011559 if (r.app != null) {
11560 updateServiceForegroundLocked(r.app, true);
11561 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011562 } else {
11563 if (r.isForeground) {
11564 r.isForeground = false;
11565 if (r.app != null) {
Dianne Hackborn8633e682010-04-22 16:03:41 -070011566 updateLruProcessLocked(r.app, false, true);
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011567 updateServiceForegroundLocked(r.app, true);
11568 }
11569 }
11570 if (removeNotification) {
11571 r.cancelNotification();
11572 r.foregroundId = 0;
11573 r.foregroundNoti = null;
11574 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011575 }
11576 }
11577 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011578 } finally {
11579 Binder.restoreCallingIdentity(origId);
11580 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011581 }
11582
11583 public void updateServiceForegroundLocked(ProcessRecord proc, boolean oomAdj) {
11584 boolean anyForeground = false;
Dianne Hackborn860755f2010-06-03 18:47:52 -070011585 for (ServiceRecord sr : proc.services) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011586 if (sr.isForeground) {
11587 anyForeground = true;
11588 break;
11589 }
11590 }
11591 if (anyForeground != proc.foregroundServices) {
11592 proc.foregroundServices = anyForeground;
11593 if (oomAdj) {
11594 updateOomAdjLocked();
11595 }
11596 }
11597 }
11598
11599 public int bindService(IApplicationThread caller, IBinder token,
11600 Intent service, String resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011601 IServiceConnection connection, int flags, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011602 enforceNotIsolatedCaller("bindService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011603 // Refuse possible leaked file descriptors
11604 if (service != null && service.hasFileDescriptors() == true) {
11605 throw new IllegalArgumentException("File descriptors passed in Intent");
11606 }
11607
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011608 checkValidCaller(Binder.getCallingUid(), userId);
11609
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011610 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011611 if (DEBUG_SERVICE) Slog.v(TAG, "bindService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011612 + " type=" + resolvedType + " conn=" + connection.asBinder()
11613 + " flags=0x" + Integer.toHexString(flags));
Amith Yamasani742a6712011-05-04 14:49:28 -070011614 if (DEBUG_MU)
11615 Slog.i(TAG_MU, "bindService uid=" + Binder.getCallingUid() + " origUid="
11616 + Binder.getOrigCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011617 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11618 if (callerApp == null) {
11619 throw new SecurityException(
11620 "Unable to find app for caller " + caller
11621 + " (pid=" + Binder.getCallingPid()
11622 + ") when binding service " + service);
11623 }
11624
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011625 ActivityRecord activity = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011626 if (token != null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070011627 activity = mMainStack.isInStackLocked(token);
11628 if (activity == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011629 Slog.w(TAG, "Binding with unknown activity: " + token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011630 return 0;
11631 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011632 }
11633
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011634 int clientLabel = 0;
11635 PendingIntent clientIntent = null;
11636
11637 if (callerApp.info.uid == Process.SYSTEM_UID) {
11638 // Hacky kind of thing -- allow system stuff to tell us
11639 // what they are, so we can report this elsewhere for
11640 // others to know why certain services are running.
11641 try {
11642 clientIntent = (PendingIntent)service.getParcelableExtra(
11643 Intent.EXTRA_CLIENT_INTENT);
11644 } catch (RuntimeException e) {
11645 }
11646 if (clientIntent != null) {
11647 clientLabel = service.getIntExtra(Intent.EXTRA_CLIENT_LABEL, 0);
11648 if (clientLabel != 0) {
11649 // There are no useful extras in the intent, trash them.
11650 // System code calling with this stuff just needs to know
11651 // this will happen.
11652 service = service.cloneFilter();
11653 }
11654 }
11655 }
11656
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011657 ServiceLookupResult res =
11658 retrieveServiceLocked(service, resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011659 Binder.getCallingPid(), Binder.getCallingUid(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011660 if (res == null) {
11661 return 0;
11662 }
11663 if (res.record == null) {
11664 return -1;
11665 }
11666 ServiceRecord s = res.record;
11667
11668 final long origId = Binder.clearCallingIdentity();
11669
11670 if (unscheduleServiceRestartLocked(s)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011671 if (DEBUG_SERVICE) Slog.v(TAG, "BIND SERVICE WHILE RESTART PENDING: "
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011672 + s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011673 }
11674
11675 AppBindRecord b = s.retrieveAppBindingLocked(service, callerApp);
11676 ConnectionRecord c = new ConnectionRecord(b, activity,
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011677 connection, flags, clientLabel, clientIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011678
11679 IBinder binder = connection.asBinder();
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011680 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
11681 if (clist == null) {
11682 clist = new ArrayList<ConnectionRecord>();
11683 s.connections.put(binder, clist);
11684 }
11685 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011686 b.connections.add(c);
11687 if (activity != null) {
11688 if (activity.connections == null) {
11689 activity.connections = new HashSet<ConnectionRecord>();
11690 }
11691 activity.connections.add(c);
11692 }
11693 b.client.connections.add(c);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070011694 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
11695 b.client.hasAboveClient = true;
11696 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011697 clist = mServiceConnections.get(binder);
11698 if (clist == null) {
11699 clist = new ArrayList<ConnectionRecord>();
11700 mServiceConnections.put(binder, clist);
11701 }
11702 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011703
11704 if ((flags&Context.BIND_AUTO_CREATE) != 0) {
11705 s.lastActivity = SystemClock.uptimeMillis();
11706 if (!bringUpServiceLocked(s, service.getFlags(), false)) {
11707 return 0;
11708 }
11709 }
11710
11711 if (s.app != null) {
11712 // This could have made the service more important.
11713 updateOomAdjLocked(s.app);
11714 }
11715
Joe Onorato8a9b2202010-02-26 18:56:32 -080011716 if (DEBUG_SERVICE) Slog.v(TAG, "Bind " + s + " with " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011717 + ": received=" + b.intent.received
11718 + " apps=" + b.intent.apps.size()
11719 + " doRebind=" + b.intent.doRebind);
11720
11721 if (s.app != null && b.intent.received) {
11722 // Service is already running, so we can immediately
11723 // publish the connection.
11724 try {
11725 c.conn.connected(s.name, b.intent.binder);
11726 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011727 Slog.w(TAG, "Failure sending service " + s.shortName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011728 + " to connection " + c.conn.asBinder()
11729 + " (in " + c.binding.client.processName + ")", e);
11730 }
11731
11732 // If this is the first app connected back to this binding,
11733 // and the service had previously asked to be told when
11734 // rebound, then do so.
11735 if (b.intent.apps.size() == 1 && b.intent.doRebind) {
11736 requestServiceBindingLocked(s, b.intent, true);
11737 }
11738 } else if (!b.intent.requested) {
11739 requestServiceBindingLocked(s, b.intent, false);
11740 }
11741
11742 Binder.restoreCallingIdentity(origId);
11743 }
11744
11745 return 1;
11746 }
11747
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070011748 void removeConnectionLocked(
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011749 ConnectionRecord c, ProcessRecord skipApp, ActivityRecord skipAct) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011750 IBinder binder = c.conn.asBinder();
11751 AppBindRecord b = c.binding;
11752 ServiceRecord s = b.service;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011753 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
11754 if (clist != null) {
11755 clist.remove(c);
11756 if (clist.size() == 0) {
11757 s.connections.remove(binder);
11758 }
11759 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011760 b.connections.remove(c);
11761 if (c.activity != null && c.activity != skipAct) {
11762 if (c.activity.connections != null) {
11763 c.activity.connections.remove(c);
11764 }
11765 }
11766 if (b.client != skipApp) {
11767 b.client.connections.remove(c);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070011768 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
11769 b.client.updateHasAboveClientLocked();
11770 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011771 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011772 clist = mServiceConnections.get(binder);
11773 if (clist != null) {
11774 clist.remove(c);
11775 if (clist.size() == 0) {
11776 mServiceConnections.remove(binder);
11777 }
11778 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011779
11780 if (b.connections.size() == 0) {
11781 b.intent.apps.remove(b.client);
11782 }
11783
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011784 if (!c.serviceDead) {
11785 if (DEBUG_SERVICE) Slog.v(TAG, "Disconnecting binding " + b.intent
11786 + ": shouldUnbind=" + b.intent.hasBound);
11787 if (s.app != null && s.app.thread != null && b.intent.apps.size() == 0
11788 && b.intent.hasBound) {
11789 try {
11790 bumpServiceExecutingLocked(s, "unbind");
11791 updateOomAdjLocked(s.app);
11792 b.intent.hasBound = false;
11793 // Assume the client doesn't want to know about a rebind;
11794 // we will deal with that later if it asks for one.
11795 b.intent.doRebind = false;
11796 s.app.thread.scheduleUnbindService(s, b.intent.intent.getIntent());
11797 } catch (Exception e) {
11798 Slog.w(TAG, "Exception when unbinding service " + s.shortName, e);
11799 serviceDoneExecutingLocked(s, true);
11800 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011801 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011802
11803 if ((c.flags&Context.BIND_AUTO_CREATE) != 0) {
11804 bringDownServiceLocked(s, false);
11805 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011806 }
11807 }
11808
11809 public boolean unbindService(IServiceConnection connection) {
11810 synchronized (this) {
11811 IBinder binder = connection.asBinder();
Joe Onorato8a9b2202010-02-26 18:56:32 -080011812 if (DEBUG_SERVICE) Slog.v(TAG, "unbindService: conn=" + binder);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011813 ArrayList<ConnectionRecord> clist = mServiceConnections.get(binder);
11814 if (clist == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011815 Slog.w(TAG, "Unbind failed: could not find connection for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011816 + connection.asBinder());
11817 return false;
11818 }
11819
11820 final long origId = Binder.clearCallingIdentity();
11821
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011822 while (clist.size() > 0) {
11823 ConnectionRecord r = clist.get(0);
11824 removeConnectionLocked(r, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011825
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011826 if (r.binding.service.app != null) {
11827 // This could have made the service less important.
11828 updateOomAdjLocked(r.binding.service.app);
11829 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011830 }
11831
11832 Binder.restoreCallingIdentity(origId);
11833 }
11834
11835 return true;
11836 }
11837
11838 public void publishService(IBinder token, Intent intent, IBinder service) {
11839 // Refuse possible leaked file descriptors
11840 if (intent != null && intent.hasFileDescriptors() == true) {
11841 throw new IllegalArgumentException("File descriptors passed in Intent");
11842 }
11843
11844 synchronized(this) {
11845 if (!(token instanceof ServiceRecord)) {
11846 throw new IllegalArgumentException("Invalid service token");
11847 }
11848 ServiceRecord r = (ServiceRecord)token;
11849
11850 final long origId = Binder.clearCallingIdentity();
11851
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011852 if (DEBUG_SERVICE) Slog.v(TAG, "PUBLISHING " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011853 + " " + intent + ": " + service);
11854 if (r != null) {
11855 Intent.FilterComparison filter
11856 = new Intent.FilterComparison(intent);
11857 IntentBindRecord b = r.bindings.get(filter);
11858 if (b != null && !b.received) {
11859 b.binder = service;
11860 b.requested = true;
11861 b.received = true;
11862 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011863 Iterator<ArrayList<ConnectionRecord>> it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011864 = r.connections.values().iterator();
11865 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011866 ArrayList<ConnectionRecord> clist = it.next();
11867 for (int i=0; i<clist.size(); i++) {
11868 ConnectionRecord c = clist.get(i);
11869 if (!filter.equals(c.binding.intent.intent)) {
11870 if (DEBUG_SERVICE) Slog.v(
11871 TAG, "Not publishing to: " + c);
11872 if (DEBUG_SERVICE) Slog.v(
11873 TAG, "Bound intent: " + c.binding.intent.intent);
11874 if (DEBUG_SERVICE) Slog.v(
11875 TAG, "Published intent: " + intent);
11876 continue;
11877 }
11878 if (DEBUG_SERVICE) Slog.v(TAG, "Publishing to: " + c);
11879 try {
11880 c.conn.connected(r.name, service);
11881 } catch (Exception e) {
11882 Slog.w(TAG, "Failure sending service " + r.name +
11883 " to connection " + c.conn.asBinder() +
11884 " (in " + c.binding.client.processName + ")", e);
11885 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011886 }
11887 }
11888 }
11889 }
11890
11891 serviceDoneExecutingLocked(r, mStoppingServices.contains(r));
11892
11893 Binder.restoreCallingIdentity(origId);
11894 }
11895 }
11896 }
11897
11898 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
11899 // Refuse possible leaked file descriptors
11900 if (intent != null && intent.hasFileDescriptors() == true) {
11901 throw new IllegalArgumentException("File descriptors passed in Intent");
11902 }
11903
11904 synchronized(this) {
11905 if (!(token instanceof ServiceRecord)) {
11906 throw new IllegalArgumentException("Invalid service token");
11907 }
11908 ServiceRecord r = (ServiceRecord)token;
11909
11910 final long origId = Binder.clearCallingIdentity();
11911
11912 if (r != null) {
11913 Intent.FilterComparison filter
11914 = new Intent.FilterComparison(intent);
11915 IntentBindRecord b = r.bindings.get(filter);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011916 if (DEBUG_SERVICE) Slog.v(TAG, "unbindFinished in " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011917 + " at " + b + ": apps="
11918 + (b != null ? b.apps.size() : 0));
Per Edelberg78f9fff2010-08-30 20:01:35 +020011919
11920 boolean inStopping = mStoppingServices.contains(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011921 if (b != null) {
Per Edelberg78f9fff2010-08-30 20:01:35 +020011922 if (b.apps.size() > 0 && !inStopping) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011923 // Applications have already bound since the last
11924 // unbind, so just rebind right here.
11925 requestServiceBindingLocked(r, b, true);
11926 } else {
11927 // Note to tell the service the next time there is
11928 // a new client.
11929 b.doRebind = true;
11930 }
11931 }
11932
Per Edelberg78f9fff2010-08-30 20:01:35 +020011933 serviceDoneExecutingLocked(r, inStopping);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011934
11935 Binder.restoreCallingIdentity(origId);
11936 }
11937 }
11938 }
11939
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011940 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011941 synchronized(this) {
11942 if (!(token instanceof ServiceRecord)) {
11943 throw new IllegalArgumentException("Invalid service token");
11944 }
11945 ServiceRecord r = (ServiceRecord)token;
11946 boolean inStopping = mStoppingServices.contains(token);
11947 if (r != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011948 if (r != token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011949 Slog.w(TAG, "Done executing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011950 + " with incorrect token: given " + token
11951 + ", expected " + r);
11952 return;
11953 }
11954
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011955 if (type == 1) {
11956 // This is a call from a service start... take care of
11957 // book-keeping.
11958 r.callStart = true;
11959 switch (res) {
11960 case Service.START_STICKY_COMPATIBILITY:
11961 case Service.START_STICKY: {
11962 // We are done with the associated start arguments.
11963 r.findDeliveredStart(startId, true);
11964 // Don't stop if killed.
11965 r.stopIfKilled = false;
11966 break;
11967 }
11968 case Service.START_NOT_STICKY: {
11969 // We are done with the associated start arguments.
11970 r.findDeliveredStart(startId, true);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011971 if (r.getLastStartId() == startId) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011972 // There is no more work, and this service
11973 // doesn't want to hang around if killed.
11974 r.stopIfKilled = true;
11975 }
11976 break;
11977 }
11978 case Service.START_REDELIVER_INTENT: {
11979 // We'll keep this item until they explicitly
11980 // call stop for it, but keep track of the fact
11981 // that it was delivered.
11982 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
11983 if (si != null) {
11984 si.deliveryCount = 0;
11985 si.doneExecutingCount++;
11986 // Don't stop if killed.
11987 r.stopIfKilled = true;
11988 }
11989 break;
11990 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011991 case Service.START_TASK_REMOVED_COMPLETE: {
11992 // Special processing for onTaskRemoved(). Don't
11993 // impact normal onStartCommand() processing.
11994 r.findDeliveredStart(startId, true);
11995 break;
11996 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011997 default:
11998 throw new IllegalArgumentException(
11999 "Unknown service start result: " + res);
12000 }
12001 if (res == Service.START_STICKY_COMPATIBILITY) {
12002 r.callStart = false;
12003 }
12004 }
Amith Yamasani742a6712011-05-04 14:49:28 -070012005 if (DEBUG_MU)
12006 Slog.v(TAG_MU, "before serviceDontExecutingLocked, uid="
12007 + Binder.getOrigCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012008 final long origId = Binder.clearCallingIdentity();
12009 serviceDoneExecutingLocked(r, inStopping);
12010 Binder.restoreCallingIdentity(origId);
12011 } else {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012012 Slog.w(TAG, "Done executing unknown service from pid "
12013 + Binder.getCallingPid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012014 }
12015 }
12016 }
12017
12018 public void serviceDoneExecutingLocked(ServiceRecord r, boolean inStopping) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012019 if (DEBUG_SERVICE) Slog.v(TAG, "<<< DONE EXECUTING " + r
12020 + ": nesting=" + r.executeNesting
12021 + ", inStopping=" + inStopping + ", app=" + r.app);
Dianne Hackborn287952c2010-09-22 22:34:31 -070012022 else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG, "<<< DONE EXECUTING " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012023 r.executeNesting--;
12024 if (r.executeNesting <= 0 && r.app != null) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012025 if (DEBUG_SERVICE) Slog.v(TAG,
12026 "Nesting at 0 of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012027 r.app.executingServices.remove(r);
12028 if (r.app.executingServices.size() == 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012029 if (DEBUG_SERVICE || DEBUG_SERVICE_EXECUTING) Slog.v(TAG,
12030 "No more executingServices of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012031 mHandler.removeMessages(SERVICE_TIMEOUT_MSG, r.app);
12032 }
12033 if (inStopping) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012034 if (DEBUG_SERVICE) Slog.v(TAG,
12035 "doneExecuting remove stopping " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012036 mStoppingServices.remove(r);
Mattias Petersson3996b412010-10-27 09:32:51 +020012037 r.bindings.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012038 }
12039 updateOomAdjLocked(r.app);
12040 }
12041 }
12042
12043 void serviceTimeout(ProcessRecord proc) {
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012044 String anrMessage = null;
12045
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012046 synchronized(this) {
12047 if (proc.executingServices.size() == 0 || proc.thread == null) {
12048 return;
12049 }
12050 long maxTime = SystemClock.uptimeMillis() - SERVICE_TIMEOUT;
12051 Iterator<ServiceRecord> it = proc.executingServices.iterator();
12052 ServiceRecord timeout = null;
12053 long nextTime = 0;
12054 while (it.hasNext()) {
12055 ServiceRecord sr = it.next();
12056 if (sr.executingStart < maxTime) {
12057 timeout = sr;
12058 break;
12059 }
12060 if (sr.executingStart > nextTime) {
12061 nextTime = sr.executingStart;
12062 }
12063 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012064 if (timeout != null && mLruProcesses.contains(proc)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012065 Slog.w(TAG, "Timeout executing service: " + timeout);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012066 anrMessage = "Executing service " + timeout.shortName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012067 } else {
12068 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
12069 msg.obj = proc;
12070 mHandler.sendMessageAtTime(msg, nextTime+SERVICE_TIMEOUT);
12071 }
12072 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012073
12074 if (anrMessage != null) {
12075 appNotResponding(proc, null, null, anrMessage);
12076 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012077 }
12078
12079 // =========================================================
Christopher Tate181fafa2009-05-14 11:12:14 -070012080 // BACKUP AND RESTORE
12081 // =========================================================
12082
12083 // Cause the target app to be launched if necessary and its backup agent
12084 // instantiated. The backup agent will invoke backupAgentCreated() on the
12085 // activity manager to announce its creation.
12086 public boolean bindBackupAgent(ApplicationInfo app, int backupMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012087 if (DEBUG_BACKUP) Slog.v(TAG, "startBackupAgent: app=" + app + " mode=" + backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070012088 enforceCallingPermission("android.permission.BACKUP", "startBackupAgent");
12089
12090 synchronized(this) {
12091 // !!! TODO: currently no check here that we're already bound
12092 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
12093 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
12094 synchronized (stats) {
12095 ss = stats.getServiceStatsLocked(app.uid, app.packageName, app.name);
12096 }
12097
Dianne Hackborne7f97212011-02-24 14:40:20 -080012098 // Backup agent is now in use, its package can't be stopped.
12099 try {
12100 AppGlobals.getPackageManager().setPackageStoppedState(
12101 app.packageName, false);
12102 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080012103 } catch (IllegalArgumentException e) {
12104 Slog.w(TAG, "Failed trying to unstop package "
12105 + app.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080012106 }
12107
Christopher Tate181fafa2009-05-14 11:12:14 -070012108 BackupRecord r = new BackupRecord(ss, app, backupMode);
Christopher Tate4a627c72011-04-01 14:43:32 -070012109 ComponentName hostingName = (backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL)
12110 ? new ComponentName(app.packageName, app.backupAgentName)
12111 : new ComponentName("android", "FullBackupAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -070012112 // startProcessLocked() returns existing proc's record if it's already running
12113 ProcessRecord proc = startProcessLocked(app.processName, app,
Dianne Hackborna0c283e2012-02-09 10:47:01 -080012114 false, 0, "backup", hostingName, false, false);
Christopher Tate181fafa2009-05-14 11:12:14 -070012115 if (proc == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012116 Slog.e(TAG, "Unable to start backup agent process " + r);
Christopher Tate181fafa2009-05-14 11:12:14 -070012117 return false;
12118 }
12119
12120 r.app = proc;
12121 mBackupTarget = r;
12122 mBackupAppName = app.packageName;
12123
Christopher Tate6fa95972009-06-05 18:43:55 -070012124 // Try not to kill the process during backup
12125 updateOomAdjLocked(proc);
12126
Christopher Tate181fafa2009-05-14 11:12:14 -070012127 // If the process is already attached, schedule the creation of the backup agent now.
12128 // If it is not yet live, this will be done when it attaches to the framework.
12129 if (proc.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012130 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc already running: " + proc);
Christopher Tate181fafa2009-05-14 11:12:14 -070012131 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040012132 proc.thread.scheduleCreateBackupAgent(app,
12133 compatibilityInfoForPackageLocked(app), backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070012134 } catch (RemoteException e) {
Christopher Tate436344a2009-09-30 16:17:37 -070012135 // Will time out on the backup manager side
Christopher Tate181fafa2009-05-14 11:12:14 -070012136 }
12137 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012138 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc not running, waiting for attach");
Christopher Tate181fafa2009-05-14 11:12:14 -070012139 }
12140 // Invariants: at this point, the target app process exists and the application
12141 // is either already running or in the process of coming up. mBackupTarget and
12142 // mBackupAppName describe the app, so that when it binds back to the AM we
12143 // know that it's scheduled for a backup-agent operation.
12144 }
12145
12146 return true;
12147 }
12148
12149 // A backup agent has just come up
12150 public void backupAgentCreated(String agentPackageName, IBinder agent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012151 if (DEBUG_BACKUP) Slog.v(TAG, "backupAgentCreated: " + agentPackageName
Christopher Tate181fafa2009-05-14 11:12:14 -070012152 + " = " + agent);
12153
12154 synchronized(this) {
12155 if (!agentPackageName.equals(mBackupAppName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012156 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
Christopher Tate181fafa2009-05-14 11:12:14 -070012157 return;
12158 }
Dianne Hackborn06740692010-09-22 22:46:21 -070012159 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012160
Dianne Hackborn06740692010-09-22 22:46:21 -070012161 long oldIdent = Binder.clearCallingIdentity();
12162 try {
12163 IBackupManager bm = IBackupManager.Stub.asInterface(
12164 ServiceManager.getService(Context.BACKUP_SERVICE));
12165 bm.agentConnected(agentPackageName, agent);
12166 } catch (RemoteException e) {
12167 // can't happen; the backup manager service is local
12168 } catch (Exception e) {
12169 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: ");
12170 e.printStackTrace();
12171 } finally {
12172 Binder.restoreCallingIdentity(oldIdent);
Christopher Tate181fafa2009-05-14 11:12:14 -070012173 }
12174 }
12175
12176 // done with this agent
12177 public void unbindBackupAgent(ApplicationInfo appInfo) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012178 if (DEBUG_BACKUP) Slog.v(TAG, "unbindBackupAgent: " + appInfo);
Christopher Tate8a27f922009-06-26 11:49:18 -070012179 if (appInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012180 Slog.w(TAG, "unbind backup agent for null app");
Christopher Tate8a27f922009-06-26 11:49:18 -070012181 return;
12182 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012183
12184 synchronized(this) {
Christopher Tate8a27f922009-06-26 11:49:18 -070012185 if (mBackupAppName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012186 Slog.w(TAG, "Unbinding backup agent with no active backup");
Christopher Tate8a27f922009-06-26 11:49:18 -070012187 return;
12188 }
12189
Christopher Tate181fafa2009-05-14 11:12:14 -070012190 if (!mBackupAppName.equals(appInfo.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012191 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
Christopher Tate181fafa2009-05-14 11:12:14 -070012192 return;
12193 }
12194
Christopher Tate6fa95972009-06-05 18:43:55 -070012195 ProcessRecord proc = mBackupTarget.app;
12196 mBackupTarget = null;
12197 mBackupAppName = null;
12198
12199 // Not backing this app up any more; reset its OOM adjustment
12200 updateOomAdjLocked(proc);
12201
Christopher Tatec7b31e32009-06-10 15:49:30 -070012202 // If the app crashed during backup, 'thread' will be null here
12203 if (proc.thread != null) {
12204 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040012205 proc.thread.scheduleDestroyBackupAgent(appInfo,
12206 compatibilityInfoForPackageLocked(appInfo));
Christopher Tatec7b31e32009-06-10 15:49:30 -070012207 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012208 Slog.e(TAG, "Exception when unbinding backup agent:");
Christopher Tatec7b31e32009-06-10 15:49:30 -070012209 e.printStackTrace();
12210 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012211 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012212 }
12213 }
12214 // =========================================================
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012215 // BROADCASTS
12216 // =========================================================
12217
Josh Bartel7f208742010-02-25 11:01:44 -060012218 private final List getStickiesLocked(String action, IntentFilter filter,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012219 List cur) {
12220 final ContentResolver resolver = mContext.getContentResolver();
12221 final ArrayList<Intent> list = mStickyBroadcasts.get(action);
12222 if (list == null) {
12223 return cur;
12224 }
12225 int N = list.size();
12226 for (int i=0; i<N; i++) {
12227 Intent intent = list.get(i);
12228 if (filter.match(resolver, intent, true, TAG) >= 0) {
12229 if (cur == null) {
12230 cur = new ArrayList<Intent>();
12231 }
12232 cur.add(intent);
12233 }
12234 }
12235 return cur;
12236 }
12237
Christopher Tatef46723b2012-01-26 14:19:24 -080012238 boolean isPendingBroadcastProcessLocked(int pid) {
12239 return mFgBroadcastQueue.isPendingBroadcastProcessLocked(pid)
12240 || mBgBroadcastQueue.isPendingBroadcastProcessLocked(pid);
12241 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012242
Christopher Tatef46723b2012-01-26 14:19:24 -080012243 void skipPendingBroadcastLocked(int pid) {
12244 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
12245 for (BroadcastQueue queue : mBroadcastQueues) {
12246 queue.skipPendingBroadcastLocked(pid);
12247 }
12248 }
12249
12250 // The app just attached; send any pending broadcasts that it should receive
12251 boolean sendPendingBroadcastsLocked(ProcessRecord app) {
12252 boolean didSomething = false;
12253 for (BroadcastQueue queue : mBroadcastQueues) {
12254 didSomething |= queue.sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012255 }
Christopher Tatef46723b2012-01-26 14:19:24 -080012256 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012257 }
12258
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012259 public Intent registerReceiver(IApplicationThread caller, String callerPackage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012260 IIntentReceiver receiver, IntentFilter filter, String permission) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012261 enforceNotIsolatedCaller("registerReceiver");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012262 synchronized(this) {
12263 ProcessRecord callerApp = null;
12264 if (caller != null) {
12265 callerApp = getRecordForAppLocked(caller);
12266 if (callerApp == null) {
12267 throw new SecurityException(
12268 "Unable to find app for caller " + caller
12269 + " (pid=" + Binder.getCallingPid()
12270 + ") when registering receiver " + receiver);
12271 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012272 if (callerApp.info.uid != Process.SYSTEM_UID &&
12273 !callerApp.pkgList.contains(callerPackage)) {
12274 throw new SecurityException("Given caller package " + callerPackage
12275 + " is not running in process " + callerApp);
12276 }
12277 } else {
12278 callerPackage = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012279 }
12280
12281 List allSticky = null;
12282
12283 // Look for any matching sticky broadcasts...
12284 Iterator actions = filter.actionsIterator();
12285 if (actions != null) {
12286 while (actions.hasNext()) {
12287 String action = (String)actions.next();
Josh Bartel7f208742010-02-25 11:01:44 -060012288 allSticky = getStickiesLocked(action, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012289 }
12290 } else {
Josh Bartel7f208742010-02-25 11:01:44 -060012291 allSticky = getStickiesLocked(null, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012292 }
12293
12294 // The first sticky in the list is returned directly back to
12295 // the client.
12296 Intent sticky = allSticky != null ? (Intent)allSticky.get(0) : null;
12297
Joe Onorato8a9b2202010-02-26 18:56:32 -080012298 if (DEBUG_BROADCAST) Slog.v(TAG, "Register receiver " + filter
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012299 + ": " + sticky);
12300
12301 if (receiver == null) {
12302 return sticky;
12303 }
12304
12305 ReceiverList rl
12306 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
12307 if (rl == null) {
12308 rl = new ReceiverList(this, callerApp,
12309 Binder.getCallingPid(),
12310 Binder.getCallingUid(), receiver);
12311 if (rl.app != null) {
12312 rl.app.receivers.add(rl);
12313 } else {
12314 try {
12315 receiver.asBinder().linkToDeath(rl, 0);
12316 } catch (RemoteException e) {
12317 return sticky;
12318 }
12319 rl.linkedToDeath = true;
12320 }
12321 mRegisteredReceivers.put(receiver.asBinder(), rl);
12322 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012323 BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage, permission);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012324 rl.add(bf);
12325 if (!bf.debugCheck()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012326 Slog.w(TAG, "==> For Dynamic broadast");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012327 }
12328 mReceiverResolver.addFilter(bf);
12329
12330 // Enqueue broadcasts for all existing stickies that match
12331 // this filter.
12332 if (allSticky != null) {
12333 ArrayList receivers = new ArrayList();
12334 receivers.add(bf);
12335
12336 int N = allSticky.size();
12337 for (int i=0; i<N; i++) {
12338 Intent intent = (Intent)allSticky.get(i);
Christopher Tatef46723b2012-01-26 14:19:24 -080012339 BroadcastQueue queue = broadcastQueueForIntent(intent);
12340 BroadcastRecord r = new BroadcastRecord(queue, intent, null,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012341 null, -1, -1, null, receivers, null, 0, null, null,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012342 false, true, true);
Christopher Tatef46723b2012-01-26 14:19:24 -080012343 queue.enqueueParallelBroadcastLocked(r);
12344 queue.scheduleBroadcastsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012345 }
12346 }
12347
12348 return sticky;
12349 }
12350 }
12351
12352 public void unregisterReceiver(IIntentReceiver receiver) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012353 if (DEBUG_BROADCAST) Slog.v(TAG, "Unregister receiver: " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012354
Christopher Tatef46723b2012-01-26 14:19:24 -080012355 final long origId = Binder.clearCallingIdentity();
12356 try {
12357 boolean doTrim = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012358
Christopher Tatef46723b2012-01-26 14:19:24 -080012359 synchronized(this) {
12360 ReceiverList rl
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012361 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
Christopher Tatef46723b2012-01-26 14:19:24 -080012362 if (rl != null) {
12363 if (rl.curBroadcast != null) {
12364 BroadcastRecord r = rl.curBroadcast;
12365 final boolean doNext = finishReceiverLocked(
12366 receiver.asBinder(), r.resultCode, r.resultData,
12367 r.resultExtras, r.resultAbort, true);
12368 if (doNext) {
12369 doTrim = true;
12370 r.queue.processNextBroadcast(false);
12371 }
12372 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012373
Christopher Tatef46723b2012-01-26 14:19:24 -080012374 if (rl.app != null) {
12375 rl.app.receivers.remove(rl);
12376 }
12377 removeReceiverLocked(rl);
12378 if (rl.linkedToDeath) {
12379 rl.linkedToDeath = false;
12380 rl.receiver.asBinder().unlinkToDeath(rl, 0);
12381 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012382 }
12383 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012384
Christopher Tatef46723b2012-01-26 14:19:24 -080012385 // If we actually concluded any broadcasts, we might now be able
12386 // to trim the recipients' apps from our working set
12387 if (doTrim) {
12388 trimApplications();
12389 return;
12390 }
12391
12392 } finally {
12393 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012394 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012395 }
12396
12397 void removeReceiverLocked(ReceiverList rl) {
12398 mRegisteredReceivers.remove(rl.receiver.asBinder());
12399 int N = rl.size();
12400 for (int i=0; i<N; i++) {
12401 mReceiverResolver.removeFilter(rl.get(i));
12402 }
12403 }
12404
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012405 private final void sendPackageBroadcastLocked(int cmd, String[] packages) {
12406 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
12407 ProcessRecord r = mLruProcesses.get(i);
12408 if (r.thread != null) {
12409 try {
12410 r.thread.dispatchPackageBroadcast(cmd, packages);
12411 } catch (RemoteException ex) {
12412 }
12413 }
12414 }
12415 }
12416
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012417 private final int broadcastIntentLocked(ProcessRecord callerApp,
12418 String callerPackage, Intent intent, String resolvedType,
12419 IIntentReceiver resultTo, int resultCode, String resultData,
12420 Bundle map, String requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070012421 boolean ordered, boolean sticky, int callingPid, int callingUid,
12422 int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012423 intent = new Intent(intent);
12424
Dianne Hackborne7f97212011-02-24 14:40:20 -080012425 // By default broadcasts do not go to stopped apps.
12426 intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
12427
Joe Onorato8a9b2202010-02-26 18:56:32 -080012428 if (DEBUG_BROADCAST_LIGHT) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012429 TAG, (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
12430 + " ordered=" + ordered);
12431 if ((resultTo != null) && !ordered) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012432 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012433 }
12434
12435 // Handle special intents: if this broadcast is from the package
12436 // manager about a package being removed, we need to remove all of
12437 // its activities from the history stack.
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012438 final boolean uidRemoved = Intent.ACTION_UID_REMOVED.equals(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012439 intent.getAction());
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012440 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())
12441 || Intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction())
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080012442 || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012443 || uidRemoved) {
12444 if (checkComponentPermission(
12445 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080012446 callingPid, callingUid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012447 == PackageManager.PERMISSION_GRANTED) {
12448 if (uidRemoved) {
12449 final Bundle intentExtras = intent.getExtras();
12450 final int uid = intentExtras != null
12451 ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
12452 if (uid >= 0) {
12453 BatteryStatsImpl bs = mBatteryStatsService.getActiveStatistics();
12454 synchronized (bs) {
12455 bs.removeUidStatsLocked(uid);
12456 }
12457 }
12458 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012459 // If resources are unvailble just force stop all
12460 // those packages and flush the attribute cache as well.
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080012461 if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012462 String list[] = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
12463 if (list != null && (list.length > 0)) {
12464 for (String pkg : list) {
Christopher Tate3dacd842011-08-19 14:56:15 -070012465 forceStopPackageLocked(pkg, -1, false, true, true, false);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012466 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012467 sendPackageBroadcastLocked(
12468 IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE, list);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012469 }
12470 } else {
12471 Uri data = intent.getData();
12472 String ssp;
12473 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
12474 if (!intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false)) {
12475 forceStopPackageLocked(ssp,
Christopher Tate3dacd842011-08-19 14:56:15 -070012476 intent.getIntExtra(Intent.EXTRA_UID, -1), false, true, true, false);
Dianne Hackbornde7faf62009-06-30 13:27:30 -070012477 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012478 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012479 sendPackageBroadcastLocked(IApplicationThread.PACKAGE_REMOVED,
12480 new String[] {ssp});
12481 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012482 }
12483 }
12484 }
12485 } else {
12486 String msg = "Permission Denial: " + intent.getAction()
12487 + " broadcast from " + callerPackage + " (pid=" + callingPid
12488 + ", uid=" + callingUid + ")"
12489 + " requires "
12490 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012491 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012492 throw new SecurityException(msg);
12493 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012494
12495 // Special case for adding a package: by default turn on compatibility
12496 // mode.
12497 } else if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -070012498 Uri data = intent.getData();
12499 String ssp;
12500 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
12501 mCompatModePackages.handlePackageAddedLocked(ssp,
12502 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false));
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012503 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012504 }
12505
12506 /*
12507 * If this is the time zone changed action, queue up a message that will reset the timezone
12508 * of all currently running processes. This message will get queued up before the broadcast
12509 * happens.
12510 */
12511 if (intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) {
12512 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
12513 }
12514
Robert Greenwalt03595d02010-11-02 14:08:23 -070012515 if (intent.ACTION_CLEAR_DNS_CACHE.equals(intent.getAction())) {
12516 mHandler.sendEmptyMessage(CLEAR_DNS_CACHE);
12517 }
12518
Robert Greenwalt434203a2010-10-11 16:00:27 -070012519 if (Proxy.PROXY_CHANGE_ACTION.equals(intent.getAction())) {
12520 ProxyProperties proxy = intent.getParcelableExtra("proxy");
12521 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY, proxy));
12522 }
12523
Dianne Hackborn854060af2009-07-09 18:14:31 -070012524 /*
12525 * Prevent non-system code (defined here to be non-persistent
12526 * processes) from sending protected broadcasts.
12527 */
12528 if (callingUid == Process.SYSTEM_UID || callingUid == Process.PHONE_UID
12529 || callingUid == Process.SHELL_UID || callingUid == 0) {
12530 // Always okay.
12531 } else if (callerApp == null || !callerApp.persistent) {
12532 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012533 if (AppGlobals.getPackageManager().isProtectedBroadcast(
Dianne Hackborn854060af2009-07-09 18:14:31 -070012534 intent.getAction())) {
12535 String msg = "Permission Denial: not allowed to send broadcast "
12536 + intent.getAction() + " from pid="
12537 + callingPid + ", uid=" + callingUid;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012538 Slog.w(TAG, msg);
Dianne Hackborn854060af2009-07-09 18:14:31 -070012539 throw new SecurityException(msg);
12540 }
12541 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012542 Slog.w(TAG, "Remote exception", e);
Dianne Hackborna4972e92012-03-14 10:38:05 -070012543 return ActivityManager.BROADCAST_SUCCESS;
Dianne Hackborn854060af2009-07-09 18:14:31 -070012544 }
12545 }
12546
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012547 // Add to the sticky list if requested.
12548 if (sticky) {
12549 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
12550 callingPid, callingUid)
12551 != PackageManager.PERMISSION_GRANTED) {
12552 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
12553 + callingPid + ", uid=" + callingUid
12554 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012555 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012556 throw new SecurityException(msg);
12557 }
12558 if (requiredPermission != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012559 Slog.w(TAG, "Can't broadcast sticky intent " + intent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012560 + " and enforce permission " + requiredPermission);
Dianne Hackborna4972e92012-03-14 10:38:05 -070012561 return ActivityManager.BROADCAST_STICKY_CANT_HAVE_PERMISSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012562 }
12563 if (intent.getComponent() != null) {
12564 throw new SecurityException(
12565 "Sticky broadcasts can't target a specific component");
12566 }
12567 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
12568 if (list == null) {
12569 list = new ArrayList<Intent>();
12570 mStickyBroadcasts.put(intent.getAction(), list);
12571 }
12572 int N = list.size();
12573 int i;
12574 for (i=0; i<N; i++) {
12575 if (intent.filterEquals(list.get(i))) {
12576 // This sticky already exists, replace it.
12577 list.set(i, new Intent(intent));
12578 break;
12579 }
12580 }
12581 if (i >= N) {
12582 list.add(new Intent(intent));
12583 }
12584 }
12585
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012586 // Figure out who all will receive this broadcast.
12587 List receivers = null;
12588 List<BroadcastFilter> registeredReceivers = null;
12589 try {
12590 if (intent.getComponent() != null) {
12591 // Broadcast is going to one specific receiver class...
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012592 ActivityInfo ai = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -070012593 getReceiverInfo(intent.getComponent(), STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012594 if (ai != null) {
12595 receivers = new ArrayList();
12596 ResolveInfo ri = new ResolveInfo();
Amith Yamasani742a6712011-05-04 14:49:28 -070012597 ri.activityInfo = getActivityInfoForUser(ai, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012598 receivers.add(ri);
12599 }
12600 } else {
Amith Yamasani742a6712011-05-04 14:49:28 -070012601 // TODO: Apply userId
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012602 // Need to resolve the intent to interested receivers...
12603 if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
12604 == 0) {
12605 receivers =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012606 AppGlobals.getPackageManager().queryIntentReceivers(
Dianne Hackborn1655be42009-05-08 14:29:01 -070012607 intent, resolvedType, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012608 }
Mihai Preda074edef2009-05-18 17:13:31 +020012609 registeredReceivers = mReceiverResolver.queryIntent(intent, resolvedType, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012610 }
12611 } catch (RemoteException ex) {
12612 // pm is in same process, this will never happen.
12613 }
12614
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012615 final boolean replacePending =
12616 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
12617
Joe Onorato8a9b2202010-02-26 18:56:32 -080012618 if (DEBUG_BROADCAST) Slog.v(TAG, "Enqueing broadcast: " + intent.getAction()
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012619 + " replacePending=" + replacePending);
12620
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012621 int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
12622 if (!ordered && NR > 0) {
12623 // If we are not serializing this broadcast, then send the
12624 // registered receivers separately so they don't wait for the
12625 // components to be launched.
Christopher Tatef46723b2012-01-26 14:19:24 -080012626 final BroadcastQueue queue = broadcastQueueForIntent(intent);
12627 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012628 callerPackage, callingPid, callingUid, requiredPermission,
12629 registeredReceivers, resultTo, resultCode, resultData, map,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012630 ordered, sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012631 if (DEBUG_BROADCAST) Slog.v(
Christopher Tatef46723b2012-01-26 14:19:24 -080012632 TAG, "Enqueueing parallel broadcast " + r);
12633 final boolean replaced = replacePending && queue.replaceParallelBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012634 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012635 queue.enqueueParallelBroadcastLocked(r);
12636 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012637 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012638 registeredReceivers = null;
12639 NR = 0;
12640 }
12641
12642 // Merge into one list.
12643 int ir = 0;
12644 if (receivers != null) {
12645 // A special case for PACKAGE_ADDED: do not allow the package
12646 // being added to see this broadcast. This prevents them from
12647 // using this as a back door to get run as soon as they are
12648 // installed. Maybe in the future we want to have a special install
12649 // broadcast or such for apps, but we'd like to deliberately make
12650 // this decision.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012651 String skipPackages[] = null;
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012652 if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
12653 || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
12654 || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012655 Uri data = intent.getData();
12656 if (data != null) {
12657 String pkgName = data.getSchemeSpecificPart();
12658 if (pkgName != null) {
12659 skipPackages = new String[] { pkgName };
12660 }
12661 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012662 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012663 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
The Android Open Source Project10592532009-03-18 17:39:46 -070012664 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012665 if (skipPackages != null && (skipPackages.length > 0)) {
12666 for (String skipPackage : skipPackages) {
12667 if (skipPackage != null) {
12668 int NT = receivers.size();
12669 for (int it=0; it<NT; it++) {
12670 ResolveInfo curt = (ResolveInfo)receivers.get(it);
12671 if (curt.activityInfo.packageName.equals(skipPackage)) {
12672 receivers.remove(it);
12673 it--;
12674 NT--;
12675 }
12676 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012677 }
12678 }
12679 }
12680
12681 int NT = receivers != null ? receivers.size() : 0;
12682 int it = 0;
12683 ResolveInfo curt = null;
12684 BroadcastFilter curr = null;
12685 while (it < NT && ir < NR) {
12686 if (curt == null) {
12687 curt = (ResolveInfo)receivers.get(it);
12688 }
12689 if (curr == null) {
12690 curr = registeredReceivers.get(ir);
12691 }
12692 if (curr.getPriority() >= curt.priority) {
12693 // Insert this broadcast record into the final list.
12694 receivers.add(it, curr);
12695 ir++;
12696 curr = null;
12697 it++;
12698 NT++;
12699 } else {
12700 // Skip to the next ResolveInfo in the final list.
12701 it++;
12702 curt = null;
12703 }
12704 }
12705 }
12706 while (ir < NR) {
12707 if (receivers == null) {
12708 receivers = new ArrayList();
12709 }
12710 receivers.add(registeredReceivers.get(ir));
12711 ir++;
12712 }
12713
12714 if ((receivers != null && receivers.size() > 0)
12715 || resultTo != null) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012716 BroadcastQueue queue = broadcastQueueForIntent(intent);
12717 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012718 callerPackage, callingPid, callingUid, requiredPermission,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012719 receivers, resultTo, resultCode, resultData, map, ordered,
12720 sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012721 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012722 TAG, "Enqueueing ordered broadcast " + r
Christopher Tatef46723b2012-01-26 14:19:24 -080012723 + ": prev had " + queue.mOrderedBroadcasts.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012724 if (DEBUG_BROADCAST) {
12725 int seq = r.intent.getIntExtra("seq", -1);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012726 Slog.i(TAG, "Enqueueing broadcast " + r.intent.getAction() + " seq=" + seq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012727 }
Christopher Tatef46723b2012-01-26 14:19:24 -080012728 boolean replaced = replacePending && queue.replaceOrderedBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012729 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012730 queue.enqueueOrderedBroadcastLocked(r);
12731 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012732 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012733 }
12734
Dianne Hackborna4972e92012-03-14 10:38:05 -070012735 return ActivityManager.BROADCAST_SUCCESS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012736 }
12737
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012738 final Intent verifyBroadcastLocked(Intent intent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012739 // Refuse possible leaked file descriptors
12740 if (intent != null && intent.hasFileDescriptors() == true) {
12741 throw new IllegalArgumentException("File descriptors passed in Intent");
12742 }
12743
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012744 int flags = intent.getFlags();
12745
12746 if (!mProcessesReady) {
12747 // if the caller really truly claims to know what they're doing, go
12748 // ahead and allow the broadcast without launching any receivers
12749 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
12750 intent = new Intent(intent);
12751 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
12752 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
12753 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
12754 + " before boot completion");
12755 throw new IllegalStateException("Cannot broadcast before boot completed");
12756 }
12757 }
12758
12759 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
12760 throw new IllegalArgumentException(
12761 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
12762 }
12763
12764 return intent;
12765 }
12766
12767 public final int broadcastIntent(IApplicationThread caller,
12768 Intent intent, String resolvedType, IIntentReceiver resultTo,
12769 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070012770 String requiredPermission, boolean serialized, boolean sticky, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012771 enforceNotIsolatedCaller("broadcastIntent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012772 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012773 intent = verifyBroadcastLocked(intent);
Dianne Hackborn9acc0302009-08-25 00:27:12 -070012774
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012775 final ProcessRecord callerApp = getRecordForAppLocked(caller);
12776 final int callingPid = Binder.getCallingPid();
12777 final int callingUid = Binder.getCallingUid();
12778 final long origId = Binder.clearCallingIdentity();
12779 int res = broadcastIntentLocked(callerApp,
12780 callerApp != null ? callerApp.info.packageName : null,
12781 intent, resolvedType, resultTo,
Amith Yamasani742a6712011-05-04 14:49:28 -070012782 resultCode, resultData, map, requiredPermission, serialized, sticky,
12783 callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012784 Binder.restoreCallingIdentity(origId);
12785 return res;
12786 }
12787 }
12788
12789 int broadcastIntentInPackage(String packageName, int uid,
12790 Intent intent, String resolvedType, IIntentReceiver resultTo,
12791 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070012792 String requiredPermission, boolean serialized, boolean sticky, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012793 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012794 intent = verifyBroadcastLocked(intent);
12795
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012796 final long origId = Binder.clearCallingIdentity();
12797 int res = broadcastIntentLocked(null, packageName, intent, resolvedType,
12798 resultTo, resultCode, resultData, map, requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070012799 serialized, sticky, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012800 Binder.restoreCallingIdentity(origId);
12801 return res;
12802 }
12803 }
12804
Amith Yamasani742a6712011-05-04 14:49:28 -070012805 // TODO: Use the userId; maybe mStickyBroadcasts need to be tied to the user.
12806 public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012807 // Refuse possible leaked file descriptors
12808 if (intent != null && intent.hasFileDescriptors() == true) {
12809 throw new IllegalArgumentException("File descriptors passed in Intent");
12810 }
12811
12812 synchronized(this) {
12813 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
12814 != PackageManager.PERMISSION_GRANTED) {
12815 String msg = "Permission Denial: unbroadcastIntent() from pid="
12816 + Binder.getCallingPid()
12817 + ", uid=" + Binder.getCallingUid()
12818 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012819 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012820 throw new SecurityException(msg);
12821 }
12822 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
12823 if (list != null) {
12824 int N = list.size();
12825 int i;
12826 for (i=0; i<N; i++) {
12827 if (intent.filterEquals(list.get(i))) {
12828 list.remove(i);
12829 break;
12830 }
12831 }
12832 }
12833 }
12834 }
12835
12836 private final boolean finishReceiverLocked(IBinder receiver, int resultCode,
12837 String resultData, Bundle resultExtras, boolean resultAbort,
12838 boolean explicit) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012839 final BroadcastRecord r = broadcastRecordForReceiverLocked(receiver);
12840 if (r == null) {
12841 Slog.w(TAG, "finishReceiver called but not found on queue");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012842 return false;
12843 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012844
Christopher Tatef46723b2012-01-26 14:19:24 -080012845 return r.queue.finishReceiverLocked(r, resultCode, resultData, resultExtras, resultAbort,
12846 explicit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012847 }
12848
12849 public void finishReceiver(IBinder who, int resultCode, String resultData,
12850 Bundle resultExtras, boolean resultAbort) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012851 if (DEBUG_BROADCAST) Slog.v(TAG, "Finish receiver: " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012852
12853 // Refuse possible leaked file descriptors
12854 if (resultExtras != null && resultExtras.hasFileDescriptors()) {
12855 throw new IllegalArgumentException("File descriptors passed in Bundle");
12856 }
12857
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012858 final long origId = Binder.clearCallingIdentity();
Christopher Tatef46723b2012-01-26 14:19:24 -080012859 try {
12860 boolean doNext = false;
12861 BroadcastRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012862
Christopher Tatef46723b2012-01-26 14:19:24 -080012863 synchronized(this) {
12864 r = broadcastRecordForReceiverLocked(who);
12865 if (r != null) {
12866 doNext = r.queue.finishReceiverLocked(r, resultCode,
12867 resultData, resultExtras, resultAbort, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012868 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012869 }
Jeff Brown4d94a762010-09-23 11:33:28 -070012870
Christopher Tatef46723b2012-01-26 14:19:24 -080012871 if (doNext) {
12872 r.queue.processNextBroadcast(false);
12873 }
12874 trimApplications();
12875 } finally {
12876 Binder.restoreCallingIdentity(origId);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012877 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012878 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012879
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012880 // =========================================================
12881 // INSTRUMENTATION
12882 // =========================================================
12883
12884 public boolean startInstrumentation(ComponentName className,
12885 String profileFile, int flags, Bundle arguments,
12886 IInstrumentationWatcher watcher) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012887 enforceNotIsolatedCaller("startInstrumentation");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012888 // Refuse possible leaked file descriptors
12889 if (arguments != null && arguments.hasFileDescriptors()) {
12890 throw new IllegalArgumentException("File descriptors passed in Bundle");
12891 }
12892
12893 synchronized(this) {
12894 InstrumentationInfo ii = null;
12895 ApplicationInfo ai = null;
12896 try {
12897 ii = mContext.getPackageManager().getInstrumentationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070012898 className, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012899 ai = mContext.getPackageManager().getApplicationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070012900 ii.targetPackage, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012901 } catch (PackageManager.NameNotFoundException e) {
12902 }
12903 if (ii == null) {
12904 reportStartInstrumentationFailure(watcher, className,
12905 "Unable to find instrumentation info for: " + className);
12906 return false;
12907 }
12908 if (ai == null) {
12909 reportStartInstrumentationFailure(watcher, className,
12910 "Unable to find instrumentation target package: " + ii.targetPackage);
12911 return false;
12912 }
12913
12914 int match = mContext.getPackageManager().checkSignatures(
12915 ii.targetPackage, ii.packageName);
12916 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
12917 String msg = "Permission Denial: starting instrumentation "
12918 + className + " from pid="
12919 + Binder.getCallingPid()
12920 + ", uid=" + Binder.getCallingPid()
12921 + " not allowed because package " + ii.packageName
12922 + " does not have a signature matching the target "
12923 + ii.targetPackage;
12924 reportStartInstrumentationFailure(watcher, className, msg);
12925 throw new SecurityException(msg);
12926 }
12927
12928 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -070012929 // Instrumentation can kill and relaunch even persistent processes
12930 forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080012931 ProcessRecord app = addAppLocked(ai, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012932 app.instrumentationClass = className;
Dianne Hackborn1655be42009-05-08 14:29:01 -070012933 app.instrumentationInfo = ai;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012934 app.instrumentationProfileFile = profileFile;
12935 app.instrumentationArguments = arguments;
12936 app.instrumentationWatcher = watcher;
12937 app.instrumentationResultClass = className;
12938 Binder.restoreCallingIdentity(origId);
12939 }
12940
12941 return true;
12942 }
12943
12944 /**
12945 * Report errors that occur while attempting to start Instrumentation. Always writes the
12946 * error to the logs, but if somebody is watching, send the report there too. This enables
12947 * the "am" command to report errors with more information.
12948 *
12949 * @param watcher The IInstrumentationWatcher. Null if there isn't one.
12950 * @param cn The component name of the instrumentation.
12951 * @param report The error report.
12952 */
12953 private void reportStartInstrumentationFailure(IInstrumentationWatcher watcher,
12954 ComponentName cn, String report) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012955 Slog.w(TAG, report);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012956 try {
12957 if (watcher != null) {
12958 Bundle results = new Bundle();
12959 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
12960 results.putString("Error", report);
12961 watcher.instrumentationStatus(cn, -1, results);
12962 }
12963 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012964 Slog.w(TAG, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012965 }
12966 }
12967
12968 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
12969 if (app.instrumentationWatcher != null) {
12970 try {
12971 // NOTE: IInstrumentationWatcher *must* be oneway here
12972 app.instrumentationWatcher.instrumentationFinished(
12973 app.instrumentationClass,
12974 resultCode,
12975 results);
12976 } catch (RemoteException e) {
12977 }
12978 }
12979 app.instrumentationWatcher = null;
12980 app.instrumentationClass = null;
Dianne Hackborn1655be42009-05-08 14:29:01 -070012981 app.instrumentationInfo = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012982 app.instrumentationProfileFile = null;
12983 app.instrumentationArguments = null;
12984
Christopher Tate3dacd842011-08-19 14:56:15 -070012985 forceStopPackageLocked(app.processName, -1, false, false, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012986 }
12987
12988 public void finishInstrumentation(IApplicationThread target,
12989 int resultCode, Bundle results) {
12990 // Refuse possible leaked file descriptors
12991 if (results != null && results.hasFileDescriptors()) {
12992 throw new IllegalArgumentException("File descriptors passed in Intent");
12993 }
12994
12995 synchronized(this) {
12996 ProcessRecord app = getRecordForAppLocked(target);
12997 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012998 Slog.w(TAG, "finishInstrumentation: no app for " + target);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012999 return;
13000 }
13001 final long origId = Binder.clearCallingIdentity();
13002 finishInstrumentationLocked(app, resultCode, results);
13003 Binder.restoreCallingIdentity(origId);
13004 }
13005 }
13006
13007 // =========================================================
13008 // CONFIGURATION
13009 // =========================================================
13010
13011 public ConfigurationInfo getDeviceConfigurationInfo() {
13012 ConfigurationInfo config = new ConfigurationInfo();
13013 synchronized (this) {
13014 config.reqTouchScreen = mConfiguration.touchscreen;
13015 config.reqKeyboardType = mConfiguration.keyboard;
13016 config.reqNavigation = mConfiguration.navigation;
Dianne Hackbornfae76f52009-07-16 13:41:23 -070013017 if (mConfiguration.navigation == Configuration.NAVIGATION_DPAD
13018 || mConfiguration.navigation == Configuration.NAVIGATION_TRACKBALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013019 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
13020 }
Dianne Hackbornfae76f52009-07-16 13:41:23 -070013021 if (mConfiguration.keyboard != Configuration.KEYBOARD_UNDEFINED
13022 && mConfiguration.keyboard != Configuration.KEYBOARD_NOKEYS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013023 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
13024 }
Jack Palevichb90d28c2009-07-22 15:35:24 -070013025 config.reqGlEsVersion = GL_ES_VERSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013026 }
13027 return config;
13028 }
13029
13030 public Configuration getConfiguration() {
13031 Configuration ci;
13032 synchronized(this) {
13033 ci = new Configuration(mConfiguration);
13034 }
13035 return ci;
13036 }
13037
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013038 public void updatePersistentConfiguration(Configuration values) {
13039 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
13040 "updateConfiguration()");
13041 enforceCallingPermission(android.Manifest.permission.WRITE_SETTINGS,
13042 "updateConfiguration()");
13043 if (values == null) {
13044 throw new NullPointerException("Configuration must not be null");
13045 }
13046
13047 synchronized(this) {
13048 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn813075a62011-11-14 17:45:19 -080013049 updateConfigurationLocked(values, null, true, false);
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013050 Binder.restoreCallingIdentity(origId);
13051 }
13052 }
13053
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013054 public void updateConfiguration(Configuration values) {
13055 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
13056 "updateConfiguration()");
13057
13058 synchronized(this) {
13059 if (values == null && mWindowManager != null) {
13060 // sentinel: fetch the current configuration from the window manager
13061 values = mWindowManager.computeNewConfiguration();
13062 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013063
13064 if (mWindowManager != null) {
13065 mProcessList.applyDisplaySize(mWindowManager);
13066 }
13067
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013068 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013069 if (values != null) {
13070 Settings.System.clearConfiguration(values);
13071 }
Dianne Hackborn813075a62011-11-14 17:45:19 -080013072 updateConfigurationLocked(values, null, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013073 Binder.restoreCallingIdentity(origId);
13074 }
13075 }
13076
13077 /**
13078 * Do either or both things: (1) change the current configuration, and (2)
13079 * make sure the given activity is running with the (now) current
13080 * configuration. Returns true if the activity has been left running, or
13081 * false if <var>starting</var> is being destroyed to match the new
13082 * configuration.
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013083 * @param persistent TODO
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013084 */
Dianne Hackborna573f6a2012-02-09 16:12:18 -080013085 boolean updateConfigurationLocked(Configuration values,
Dianne Hackborn813075a62011-11-14 17:45:19 -080013086 ActivityRecord starting, boolean persistent, boolean initLocale) {
Mike Lockwood3a74bd32011-08-12 13:55:22 -070013087 // do nothing if we are headless
13088 if (mHeadless) return true;
13089
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013090 int changes = 0;
13091
13092 boolean kept = true;
13093
13094 if (values != null) {
13095 Configuration newConfig = new Configuration(mConfiguration);
13096 changes = newConfig.updateFrom(values);
13097 if (changes != 0) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013098 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013099 Slog.i(TAG, "Updating configuration to: " + values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013100 }
13101
Doug Zongker2bec3d42009-12-04 12:52:44 -080013102 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013103
Dianne Hackborn813075a62011-11-14 17:45:19 -080013104 if (values.locale != null && !initLocale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013105 saveLocaleLocked(values.locale,
13106 !values.locale.equals(mConfiguration.locale),
13107 values.userSetLocale);
13108 }
13109
Dianne Hackborne36d6e22010-02-17 19:46:25 -080013110 mConfigurationSeq++;
13111 if (mConfigurationSeq <= 0) {
13112 mConfigurationSeq = 1;
13113 }
13114 newConfig.seq = mConfigurationSeq;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013115 mConfiguration = newConfig;
Joe Onorato8a9b2202010-02-26 18:56:32 -080013116 Slog.i(TAG, "Config changed: " + newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013117
13118 final Configuration configCopy = new Configuration(mConfiguration);
Joe Onorato54a4a412011-11-02 20:50:08 -070013119
13120 // TODO: If our config changes, should we auto dismiss any currently
13121 // showing dialogs?
13122 mShowDialogs = shouldShowDialogs(newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013123
Dianne Hackborn826d17c2009-11-12 12:55:51 -080013124 AttributeCache ac = AttributeCache.instance();
13125 if (ac != null) {
Dianne Hackborn813075a62011-11-14 17:45:19 -080013126 ac.updateConfiguration(configCopy);
Dianne Hackborn826d17c2009-11-12 12:55:51 -080013127 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013128
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070013129 // Make sure all resources in our process are updated
13130 // right now, so that anyone who is going to retrieve
13131 // resource values after we return will be sure to get
13132 // the new ones. This is especially important during
13133 // boot, where the first config change needs to guarantee
13134 // all resources have that config before following boot
13135 // code is executed.
Dianne Hackborn813075a62011-11-14 17:45:19 -080013136 mSystemThread.applyConfigurationToResources(configCopy);
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070013137
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013138 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080013139 Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013140 msg.obj = new Configuration(configCopy);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080013141 mHandler.sendMessage(msg);
13142 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013143
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013144 for (int i=mLruProcesses.size()-1; i>=0; i--) {
13145 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013146 try {
13147 if (app.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013148 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending to proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013149 + app.processName + " new config " + mConfiguration);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013150 app.thread.scheduleConfigurationChanged(configCopy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013151 }
13152 } catch (Exception e) {
13153 }
13154 }
13155 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080013156 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
13157 | Intent.FLAG_RECEIVER_REPLACE_PENDING);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013158 broadcastIntentLocked(null, null, intent, null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070013159 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080013160 if ((changes&ActivityInfo.CONFIG_LOCALE) != 0) {
13161 broadcastIntentLocked(null, null,
13162 new Intent(Intent.ACTION_LOCALE_CHANGED),
13163 null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070013164 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080013165 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013166 }
13167 }
13168
13169 if (changes != 0 && starting == null) {
13170 // If the configuration changed, and the caller is not already
13171 // in the process of starting an activity, then find the top
13172 // activity to check if its configuration needs to change.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013173 starting = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013174 }
13175
13176 if (starting != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013177 kept = mMainStack.ensureActivityConfigurationLocked(starting, changes);
Dianne Hackborn5f4d6432010-12-21 20:40:11 -080013178 // And we need to make sure at this point that all other activities
13179 // are made visible with the correct configuration.
13180 mMainStack.ensureActivitiesVisibleLocked(starting, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013181 }
13182
Dianne Hackborne36d6e22010-02-17 19:46:25 -080013183 if (values != null && mWindowManager != null) {
13184 mWindowManager.setNewConfiguration(mConfiguration);
13185 }
13186
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013187 return kept;
13188 }
Joe Onorato54a4a412011-11-02 20:50:08 -070013189
13190 /**
13191 * Decide based on the configuration whether we should shouw the ANR,
13192 * crash, etc dialogs. The idea is that if there is no affordnace to
13193 * press the on-screen buttons, we shouldn't show the dialog.
13194 *
13195 * A thought: SystemUI might also want to get told about this, the Power
13196 * dialog / global actions also might want different behaviors.
13197 */
13198 private static final boolean shouldShowDialogs(Configuration config) {
13199 return !(config.keyboard == Configuration.KEYBOARD_NOKEYS
13200 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH);
13201 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013202
13203 /**
13204 * Save the locale. You must be inside a synchronized (this) block.
13205 */
13206 private void saveLocaleLocked(Locale l, boolean isDiff, boolean isPersist) {
13207 if(isDiff) {
13208 SystemProperties.set("user.language", l.getLanguage());
13209 SystemProperties.set("user.region", l.getCountry());
13210 }
13211
13212 if(isPersist) {
13213 SystemProperties.set("persist.sys.language", l.getLanguage());
13214 SystemProperties.set("persist.sys.country", l.getCountry());
13215 SystemProperties.set("persist.sys.localevar", l.getVariant());
13216 }
13217 }
13218
13219 // =========================================================
13220 // LIFETIME MANAGEMENT
13221 // =========================================================
13222
Christopher Tatef46723b2012-01-26 14:19:24 -080013223 // Returns which broadcast queue the app is the current [or imminent] receiver
13224 // on, or 'null' if the app is not an active broadcast recipient.
13225 private BroadcastQueue isReceivingBroadcast(ProcessRecord app) {
13226 BroadcastRecord r = app.curReceiver;
13227 if (r != null) {
13228 return r.queue;
13229 }
13230
13231 // It's not the current receiver, but it might be starting up to become one
13232 synchronized (this) {
13233 for (BroadcastQueue queue : mBroadcastQueues) {
13234 r = queue.mPendingBroadcast;
13235 if (r != null && r.curApp == app) {
13236 // found it; report which queue it's in
13237 return queue;
13238 }
13239 }
13240 }
13241
13242 return null;
13243 }
13244
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013245 private final int computeOomAdjLocked(ProcessRecord app, int hiddenAdj,
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013246 ProcessRecord TOP_APP, boolean recursed, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013247 if (mAdjSeq == app.adjSeq) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013248 // This adjustment has already been computed. If we are calling
13249 // from the top, we may have already computed our adjustment with
13250 // an earlier hidden adjustment that isn't really for us... if
13251 // so, use the new hidden adjustment.
13252 if (!recursed && app.hidden) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013253 app.curAdj = app.curRawAdj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013254 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013255 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013256 }
13257
13258 if (app.thread == null) {
13259 app.adjSeq = mAdjSeq;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013260 app.curSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013261 return (app.curAdj=ProcessList.HIDDEN_APP_MAX_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013262 }
13263
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013264 app.adjTypeCode = ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN;
13265 app.adjSource = null;
13266 app.adjTarget = null;
13267 app.empty = false;
13268 app.hidden = false;
13269
13270 final int activitiesSize = app.activities.size();
13271
Dianne Hackborn7d608422011-08-07 16:24:18 -070013272 if (app.maxAdj <= ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013273 // The max adjustment doesn't allow this app to be anything
13274 // below foreground, so it is not worth doing work for it.
13275 app.adjType = "fixed";
13276 app.adjSeq = mAdjSeq;
13277 app.curRawAdj = app.maxAdj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013278 app.foregroundActivities = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013279 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013280 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013281 // System process can do UI, and when they do we want to have
13282 // them trim their memory after the user leaves the UI. To
13283 // facilitate this, here we need to determine whether or not it
13284 // is currently showing UI.
13285 app.systemNoUi = true;
13286 if (app == TOP_APP) {
13287 app.systemNoUi = false;
13288 } else if (activitiesSize > 0) {
13289 for (int j = 0; j < activitiesSize; j++) {
13290 final ActivityRecord r = app.activities.get(j);
13291 if (r.visible) {
13292 app.systemNoUi = false;
13293 break;
13294 }
13295 }
13296 }
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013297 return (app.curAdj=app.maxAdj);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013298 }
13299
13300 final boolean hadForegroundActivities = app.foregroundActivities;
13301
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013302 app.foregroundActivities = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013303 app.keeping = false;
13304 app.systemNoUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013305
The Android Open Source Project4df24232009-03-05 14:34:35 -080013306 // Determine the importance of the process, starting with most
13307 // important to least, and assign an appropriate OOM adjustment.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013308 int adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013309 int schedGroup;
Christopher Tatef46723b2012-01-26 14:19:24 -080013310 BroadcastQueue queue;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013311 if (app == TOP_APP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013312 // The last app on the list is the foreground app.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013313 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013314 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013315 app.adjType = "top-activity";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013316 app.foregroundActivities = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013317 } else if (app.instrumentationClass != null) {
13318 // Don't want to kill running instrumentation.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013319 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013320 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013321 app.adjType = "instrumentation";
Christopher Tatef46723b2012-01-26 14:19:24 -080013322 } else if ((queue = isReceivingBroadcast(app)) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013323 // An app that is currently receiving a broadcast also
Christopher Tatef46723b2012-01-26 14:19:24 -080013324 // counts as being in the foreground for OOM killer purposes.
13325 // It's placed in a sched group based on the nature of the
13326 // broadcast as reflected by which queue it's active in.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013327 adj = ProcessList.FOREGROUND_APP_ADJ;
Christopher Tatef46723b2012-01-26 14:19:24 -080013328 schedGroup = (queue == mFgBroadcastQueue)
13329 ? Process.THREAD_GROUP_DEFAULT : Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013330 app.adjType = "broadcast";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013331 } else if (app.executingServices.size() > 0) {
13332 // An app that is currently executing a service callback also
13333 // counts as being in the foreground.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013334 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013335 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013336 app.adjType = "exec-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013337 } else if (activitiesSize > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013338 // This app is in the background with paused activities.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013339 // We inspect activities to potentially upgrade adjustment further below.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013340 adj = hiddenAdj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013341 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013342 app.hidden = true;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013343 app.adjType = "bg-activities";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013344 } else {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013345 // A very not-needed process. If this is lower in the lru list,
13346 // we will push it in to the empty bucket.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013347 adj = hiddenAdj;
13348 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013349 app.hidden = true;
13350 app.empty = true;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013351 app.adjType = "bg-empty";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013352 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013353
13354 // Examine all activities if not already foreground.
13355 if (!app.foregroundActivities && activitiesSize > 0) {
13356 for (int j = 0; j < activitiesSize; j++) {
13357 final ActivityRecord r = app.activities.get(j);
13358 if (r.visible) {
13359 // App has a visible activity; only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013360 if (adj > ProcessList.VISIBLE_APP_ADJ) {
13361 adj = ProcessList.VISIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013362 app.adjType = "visible";
13363 }
13364 schedGroup = Process.THREAD_GROUP_DEFAULT;
13365 app.hidden = false;
13366 app.foregroundActivities = true;
13367 break;
13368 } else if (r.state == ActivityState.PAUSING || r.state == ActivityState.PAUSED
13369 || r.state == ActivityState.STOPPING) {
13370 // Only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013371 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13372 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013373 app.adjType = "stopping";
13374 }
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -080013375 app.hidden = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013376 app.foregroundActivities = true;
13377 }
13378 }
13379 }
13380
Dianne Hackborn7d608422011-08-07 16:24:18 -070013381 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013382 if (app.foregroundServices) {
13383 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013384 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013385 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013386 app.adjType = "foreground-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013387 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013388 } else if (app.forcingToForeground != null) {
13389 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013390 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013391 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013392 app.adjType = "force-foreground";
13393 app.adjSource = app.forcingToForeground;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013394 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013395 }
13396 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013397
Dianne Hackborn7d608422011-08-07 16:24:18 -070013398 if (adj > ProcessList.HEAVY_WEIGHT_APP_ADJ && app == mHeavyWeightProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013399 // We don't want to kill the current heavy-weight process.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013400 adj = ProcessList.HEAVY_WEIGHT_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013401 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013402 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013403 app.adjType = "heavy";
13404 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013405
Dianne Hackborn7d608422011-08-07 16:24:18 -070013406 if (adj > ProcessList.HOME_APP_ADJ && app == mHomeProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013407 // This process is hosting what we currently consider to be the
13408 // home app, so we don't want to let it go into the background.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013409 adj = ProcessList.HOME_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013410 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013411 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013412 app.adjType = "home";
13413 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013414
Dianne Hackbornf35fe232011-11-01 19:25:20 -070013415 if (adj > ProcessList.PREVIOUS_APP_ADJ && app == mPreviousProcess
13416 && app.activities.size() > 0) {
13417 // This was the previous process that showed UI to the user.
13418 // We want to try to keep it around more aggressively, to give
13419 // a good experience around switching between two apps.
13420 adj = ProcessList.PREVIOUS_APP_ADJ;
13421 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
13422 app.hidden = false;
13423 app.adjType = "previous";
13424 }
13425
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013426 if (false) Slog.i(TAG, "OOM " + app + ": initial adj=" + adj
13427 + " reason=" + app.adjType);
13428
The Android Open Source Project4df24232009-03-05 14:34:35 -080013429 // By default, we use the computed adjustment. It may be changed if
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013430 // there are applications dependent on our services or providers, but
13431 // this gives us a baseline and makes sure we don't get into an
13432 // infinite recursion.
13433 app.adjSeq = mAdjSeq;
13434 app.curRawAdj = adj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013435
Christopher Tate6fa95972009-06-05 18:43:55 -070013436 if (mBackupTarget != null && app == mBackupTarget.app) {
13437 // If possible we want to avoid killing apps while they're being backed up
Dianne Hackborn7d608422011-08-07 16:24:18 -070013438 if (adj > ProcessList.BACKUP_APP_ADJ) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013439 if (DEBUG_BACKUP) Slog.v(TAG, "oom BACKUP_APP_ADJ for " + app);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013440 adj = ProcessList.BACKUP_APP_ADJ;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013441 app.adjType = "backup";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013442 app.hidden = false;
Christopher Tate6fa95972009-06-05 18:43:55 -070013443 }
13444 }
13445
Dianne Hackborn7d608422011-08-07 16:24:18 -070013446 if (app.services.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013447 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013448 final long now = SystemClock.uptimeMillis();
13449 // This process is more important if the top activity is
13450 // bound to the service.
Dianne Hackborn860755f2010-06-03 18:47:52 -070013451 Iterator<ServiceRecord> jt = app.services.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013452 while (jt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013453 ServiceRecord s = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013454 if (s.startRequested) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013455 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013456 // If this process has shown some UI, let it immediately
13457 // go to the LRU list because it may be pretty heavy with
13458 // UI stuff. We'll tag it with a label just to help
13459 // debug and understand what is going on.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013460 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013461 app.adjType = "started-bg-ui-services";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013462 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013463 } else {
13464 if (now < (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
13465 // This service has seen some activity within
13466 // recent memory, so we will keep its process ahead
13467 // of the background processes.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013468 if (adj > ProcessList.SERVICE_ADJ) {
13469 adj = ProcessList.SERVICE_ADJ;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013470 app.adjType = "started-services";
13471 app.hidden = false;
13472 }
13473 }
13474 // If we have let the service slide into the background
13475 // state, still have some text describing what it is doing
13476 // even though the service no longer has an impact.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013477 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013478 app.adjType = "started-bg-services";
13479 }
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080013480 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013481 // Don't kill this process because it is doing work; it
13482 // has said it is doing work.
13483 app.keeping = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013484 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013485 if (s.connections.size() > 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013486 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013487 Iterator<ArrayList<ConnectionRecord>> kt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013488 = s.connections.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013489 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013490 ArrayList<ConnectionRecord> clist = kt.next();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013491 for (int i=0; i<clist.size() && adj > ProcessList.FOREGROUND_APP_ADJ; i++) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013492 // XXX should compute this based on the max of
13493 // all connected clients.
13494 ConnectionRecord cr = clist.get(i);
13495 if (cr.binding.client == app) {
13496 // Binding to ourself is not interesting.
13497 continue;
13498 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013499 if ((cr.flags&Context.BIND_WAIVE_PRIORITY) == 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013500 ProcessRecord client = cr.binding.client;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013501 int clientAdj = adj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013502 int myHiddenAdj = hiddenAdj;
13503 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013504 if (client.hiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013505 myHiddenAdj = client.hiddenAdj;
13506 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013507 myHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013508 }
13509 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013510 clientAdj = computeOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013511 client, myHiddenAdj, TOP_APP, true, doingAll);
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013512 String adjType = null;
13513 if ((cr.flags&Context.BIND_ALLOW_OOM_MANAGEMENT) != 0) {
13514 // Not doing bind OOM management, so treat
13515 // this guy more like a started service.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013516 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -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.
13521 if (adj > clientAdj) {
13522 adjType = "bound-bg-ui-services";
13523 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013524 app.hidden = false;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013525 clientAdj = adj;
13526 } else {
13527 if (now >= (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
13528 // This service has not seen activity within
13529 // recent memory, so allow it to drop to the
13530 // LRU list if there is no other reason to keep
13531 // it around. We'll also tag it with a label just
13532 // to help debug and undertand what is going on.
13533 if (adj > clientAdj) {
13534 adjType = "bound-bg-services";
13535 }
13536 clientAdj = adj;
13537 }
13538 }
13539 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013540 if (adj > clientAdj) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013541 // If this process has recently shown UI, and
13542 // the process that is binding to it is less
13543 // important than being visible, then we don't
13544 // care about the binding as much as we care
13545 // about letting this process get into the LRU
13546 // list to be killed and restarted if needed for
13547 // memory.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013548 if (app.hasShownUi && app != mHomeProcess
13549 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013550 adjType = "bound-bg-ui-services";
13551 } else {
13552 if ((cr.flags&(Context.BIND_ABOVE_CLIENT
13553 |Context.BIND_IMPORTANT)) != 0) {
13554 adj = clientAdj;
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070013555 } else if ((cr.flags&Context.BIND_NOT_VISIBLE) != 0
13556 && clientAdj < ProcessList.PERCEPTIBLE_APP_ADJ
13557 && adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13558 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13559 } else if (clientAdj > ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013560 adj = clientAdj;
13561 } else {
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070013562 app.pendingUiClean = true;
13563 if (adj > ProcessList.VISIBLE_APP_ADJ) {
13564 adj = ProcessList.VISIBLE_APP_ADJ;
13565 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013566 }
13567 if (!client.hidden) {
13568 app.hidden = false;
13569 }
13570 if (client.keeping) {
13571 app.keeping = true;
13572 }
13573 adjType = "service";
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013574 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013575 }
13576 if (adjType != null) {
13577 app.adjType = adjType;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013578 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13579 .REASON_SERVICE_IN_USE;
13580 app.adjSource = cr.binding.client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013581 app.adjSourceOom = clientAdj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013582 app.adjTarget = s.name;
13583 }
13584 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
13585 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
13586 schedGroup = Process.THREAD_GROUP_DEFAULT;
13587 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013588 }
13589 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013590 if ((cr.flags&Context.BIND_ADJUST_WITH_ACTIVITY) != 0) {
13591 ActivityRecord a = cr.activity;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013592 if (a != null && adj > ProcessList.FOREGROUND_APP_ADJ &&
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013593 (a.visible || a.state == ActivityState.RESUMED
13594 || a.state == ActivityState.PAUSING)) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013595 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013596 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
13597 schedGroup = Process.THREAD_GROUP_DEFAULT;
13598 }
13599 app.hidden = false;
13600 app.adjType = "service";
13601 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13602 .REASON_SERVICE_IN_USE;
13603 app.adjSource = a;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013604 app.adjSourceOom = adj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013605 app.adjTarget = s.name;
13606 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013607 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013608 }
13609 }
13610 }
13611 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013612
Dianne Hackborn287952c2010-09-22 22:34:31 -070013613 // Finally, if this process has active services running in it, we
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013614 // would like to avoid killing it unless it would prevent the current
13615 // application from running. By default we put the process in
13616 // with the rest of the background processes; as we scan through
13617 // its services we may bump it up from there.
13618 if (adj > hiddenAdj) {
13619 adj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013620 app.hidden = false;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013621 app.adjType = "bg-services";
13622 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013623 }
13624
Dianne Hackborn7d608422011-08-07 16:24:18 -070013625 if (app.pubProviders.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013626 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013627 Iterator<ContentProviderRecord> jt = app.pubProviders.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013628 while (jt.hasNext() && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013629 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013630 ContentProviderRecord cpr = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013631 if (cpr.clients.size() != 0) {
13632 Iterator<ProcessRecord> kt = cpr.clients.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013633 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013634 ProcessRecord client = kt.next();
The Android Open Source Project10592532009-03-18 17:39:46 -070013635 if (client == app) {
13636 // Being our own client is not interesting.
13637 continue;
13638 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013639 int myHiddenAdj = hiddenAdj;
13640 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013641 if (client.hiddenAdj > ProcessList.FOREGROUND_APP_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013642 myHiddenAdj = client.hiddenAdj;
13643 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013644 myHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013645 }
13646 }
13647 int clientAdj = computeOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013648 client, myHiddenAdj, TOP_APP, true, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013649 if (adj > clientAdj) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013650 if (app.hasShownUi && app != mHomeProcess
13651 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013652 app.adjType = "bg-ui-provider";
13653 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013654 adj = clientAdj > ProcessList.FOREGROUND_APP_ADJ
13655 ? clientAdj : ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013656 app.adjType = "provider";
13657 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013658 if (!client.hidden) {
13659 app.hidden = false;
13660 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013661 if (client.keeping) {
13662 app.keeping = true;
13663 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070013664 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13665 .REASON_PROVIDER_IN_USE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013666 app.adjSource = client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013667 app.adjSourceOom = clientAdj;
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070013668 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013669 }
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013670 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
13671 schedGroup = Process.THREAD_GROUP_DEFAULT;
13672 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013673 }
13674 }
13675 // If the provider has external (non-framework) process
13676 // dependencies, ensure that its adjustment is at least
13677 // FOREGROUND_APP_ADJ.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080013678 if (cpr.hasExternalProcessHandles()) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013679 if (adj > ProcessList.FOREGROUND_APP_ADJ) {
13680 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013681 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013682 app.hidden = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013683 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013684 app.adjType = "provider";
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070013685 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013686 }
13687 }
13688 }
13689 }
13690
13691 app.curRawAdj = adj;
13692
Joe Onorato8a9b2202010-02-26 18:56:32 -080013693 //Slog.i(TAG, "OOM ADJ " + app + ": pid=" + app.pid +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013694 // " adj=" + adj + " curAdj=" + app.curAdj + " maxAdj=" + app.maxAdj);
13695 if (adj > app.maxAdj) {
13696 adj = app.maxAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013697 if (app.maxAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013698 schedGroup = Process.THREAD_GROUP_DEFAULT;
13699 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013700 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013701 if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070013702 app.keeping = true;
13703 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013704
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013705 if (app.hasAboveClient) {
13706 // If this process has bound to any services with BIND_ABOVE_CLIENT,
13707 // then we need to drop its adjustment to be lower than the service's
13708 // in order to honor the request. We want to drop it by one adjustment
13709 // level... but there is special meaning applied to various levels so
13710 // we will skip some of them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013711 if (adj < ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013712 // System process will not get dropped, ever
Dianne Hackborn7d608422011-08-07 16:24:18 -070013713 } else if (adj < ProcessList.VISIBLE_APP_ADJ) {
13714 adj = ProcessList.VISIBLE_APP_ADJ;
13715 } else if (adj < ProcessList.PERCEPTIBLE_APP_ADJ) {
13716 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13717 } else if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
13718 adj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013719 } else if (adj < ProcessList.HIDDEN_APP_MAX_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013720 adj++;
13721 }
13722 }
13723
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013724 if (adj == ProcessList.SERVICE_ADJ) {
13725 if (doingAll) {
13726 app.serviceb = mNewNumServiceProcs > (mNumServiceProcs/3);
13727 mNewNumServiceProcs++;
13728 }
13729 if (app.serviceb) {
13730 adj = ProcessList.SERVICE_B_ADJ;
13731 }
13732 } else {
13733 app.serviceb = false;
13734 }
13735
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013736 app.curAdj = adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013737 app.curSchedGroup = schedGroup;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013738
13739 if (hadForegroundActivities != app.foregroundActivities) {
Jeff Sharkey287bd832011-05-28 19:36:26 -070013740 mHandler.obtainMessage(DISPATCH_FOREGROUND_ACTIVITIES_CHANGED, app.pid, app.info.uid,
13741 app.foregroundActivities).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013742 }
13743
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013744 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013745 }
13746
13747 /**
13748 * Ask a given process to GC right now.
13749 */
13750 final void performAppGcLocked(ProcessRecord app) {
13751 try {
13752 app.lastRequestedGc = SystemClock.uptimeMillis();
13753 if (app.thread != null) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013754 if (app.reportLowMemory) {
13755 app.reportLowMemory = false;
13756 app.thread.scheduleLowMemory();
13757 } else {
13758 app.thread.processInBackground();
13759 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013760 }
13761 } catch (Exception e) {
13762 // whatever.
13763 }
13764 }
13765
13766 /**
13767 * Returns true if things are idle enough to perform GCs.
13768 */
Josh Bartel7f208742010-02-25 11:01:44 -060013769 private final boolean canGcNowLocked() {
Christopher Tatef46723b2012-01-26 14:19:24 -080013770 boolean processingBroadcasts = false;
13771 for (BroadcastQueue q : mBroadcastQueues) {
13772 if (q.mParallelBroadcasts.size() != 0 || q.mOrderedBroadcasts.size() != 0) {
13773 processingBroadcasts = true;
13774 }
13775 }
13776 return !processingBroadcasts
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013777 && (mSleeping || (mMainStack.mResumedActivity != null &&
13778 mMainStack.mResumedActivity.idle));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013779 }
13780
13781 /**
13782 * Perform GCs on all processes that are waiting for it, but only
13783 * if things are idle.
13784 */
13785 final void performAppGcsLocked() {
13786 final int N = mProcessesToGc.size();
13787 if (N <= 0) {
13788 return;
13789 }
Josh Bartel7f208742010-02-25 11:01:44 -060013790 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013791 while (mProcessesToGc.size() > 0) {
13792 ProcessRecord proc = mProcessesToGc.remove(0);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013793 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013794 if ((proc.lastRequestedGc+GC_MIN_INTERVAL)
13795 <= SystemClock.uptimeMillis()) {
13796 // To avoid spamming the system, we will GC processes one
13797 // at a time, waiting a few seconds between each.
13798 performAppGcLocked(proc);
13799 scheduleAppGcsLocked();
13800 return;
13801 } else {
13802 // It hasn't been long enough since we last GCed this
13803 // process... put it in the list to wait for its time.
13804 addProcessToGcListLocked(proc);
13805 break;
13806 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013807 }
13808 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013809
13810 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013811 }
13812 }
13813
13814 /**
13815 * If all looks good, perform GCs on all processes waiting for them.
13816 */
13817 final void performAppGcsIfAppropriateLocked() {
Josh Bartel7f208742010-02-25 11:01:44 -060013818 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013819 performAppGcsLocked();
13820 return;
13821 }
13822 // Still not idle, wait some more.
13823 scheduleAppGcsLocked();
13824 }
13825
13826 /**
13827 * Schedule the execution of all pending app GCs.
13828 */
13829 final void scheduleAppGcsLocked() {
13830 mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013831
13832 if (mProcessesToGc.size() > 0) {
13833 // Schedule a GC for the time to the next process.
13834 ProcessRecord proc = mProcessesToGc.get(0);
13835 Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG);
13836
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013837 long when = proc.lastRequestedGc + GC_MIN_INTERVAL;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013838 long now = SystemClock.uptimeMillis();
13839 if (when < (now+GC_TIMEOUT)) {
13840 when = now + GC_TIMEOUT;
13841 }
13842 mHandler.sendMessageAtTime(msg, when);
13843 }
13844 }
13845
13846 /**
13847 * Add a process to the array of processes waiting to be GCed. Keeps the
13848 * list in sorted order by the last GC time. The process can't already be
13849 * on the list.
13850 */
13851 final void addProcessToGcListLocked(ProcessRecord proc) {
13852 boolean added = false;
13853 for (int i=mProcessesToGc.size()-1; i>=0; i--) {
13854 if (mProcessesToGc.get(i).lastRequestedGc <
13855 proc.lastRequestedGc) {
13856 added = true;
13857 mProcessesToGc.add(i+1, proc);
13858 break;
13859 }
13860 }
13861 if (!added) {
13862 mProcessesToGc.add(0, proc);
13863 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013864 }
13865
13866 /**
13867 * Set up to ask a process to GC itself. This will either do it
13868 * immediately, or put it on the list of processes to gc the next
13869 * time things are idle.
13870 */
13871 final void scheduleAppGcLocked(ProcessRecord app) {
13872 long now = SystemClock.uptimeMillis();
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013873 if ((app.lastRequestedGc+GC_MIN_INTERVAL) > now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013874 return;
13875 }
13876 if (!mProcessesToGc.contains(app)) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013877 addProcessToGcListLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013878 scheduleAppGcsLocked();
13879 }
13880 }
13881
Dianne Hackborn287952c2010-09-22 22:34:31 -070013882 final void checkExcessivePowerUsageLocked(boolean doKills) {
13883 updateCpuStatsNow();
13884
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013885 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013886 boolean doWakeKills = doKills;
13887 boolean doCpuKills = doKills;
13888 if (mLastPowerCheckRealtime == 0) {
13889 doWakeKills = false;
13890 }
13891 if (mLastPowerCheckUptime == 0) {
13892 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013893 }
13894 if (stats.isScreenOn()) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070013895 doWakeKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013896 }
13897 final long curRealtime = SystemClock.elapsedRealtime();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013898 final long realtimeSince = curRealtime - mLastPowerCheckRealtime;
13899 final long curUptime = SystemClock.uptimeMillis();
13900 final long uptimeSince = curUptime - mLastPowerCheckUptime;
13901 mLastPowerCheckRealtime = curRealtime;
13902 mLastPowerCheckUptime = curUptime;
13903 if (realtimeSince < WAKE_LOCK_MIN_CHECK_DURATION) {
13904 doWakeKills = false;
13905 }
13906 if (uptimeSince < CPU_MIN_CHECK_DURATION) {
13907 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013908 }
13909 int i = mLruProcesses.size();
13910 while (i > 0) {
13911 i--;
13912 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013913 if (!app.keeping) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013914 long wtime;
13915 synchronized (stats) {
13916 wtime = stats.getProcessWakeTime(app.info.uid,
13917 app.pid, curRealtime);
13918 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013919 long wtimeUsed = wtime - app.lastWakeTime;
13920 long cputimeUsed = app.curCpuTime - app.lastCpuTime;
13921 if (DEBUG_POWER) {
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013922 StringBuilder sb = new StringBuilder(128);
13923 sb.append("Wake for ");
13924 app.toShortString(sb);
13925 sb.append(": over ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013926 TimeUtils.formatDuration(realtimeSince, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013927 sb.append(" used ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013928 TimeUtils.formatDuration(wtimeUsed, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013929 sb.append(" (");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013930 sb.append((wtimeUsed*100)/realtimeSince);
13931 sb.append("%)");
13932 Slog.i(TAG, sb.toString());
13933 sb.setLength(0);
13934 sb.append("CPU for ");
13935 app.toShortString(sb);
13936 sb.append(": over ");
13937 TimeUtils.formatDuration(uptimeSince, sb);
13938 sb.append(" used ");
13939 TimeUtils.formatDuration(cputimeUsed, sb);
13940 sb.append(" (");
13941 sb.append((cputimeUsed*100)/uptimeSince);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013942 sb.append("%)");
13943 Slog.i(TAG, sb.toString());
13944 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013945 // If a process has held a wake lock for more
13946 // than 50% of the time during this period,
13947 // that sounds pad. Kill!
Dianne Hackborn287952c2010-09-22 22:34:31 -070013948 if (doWakeKills && realtimeSince > 0
13949 && ((wtimeUsed*100)/realtimeSince) >= 50) {
13950 synchronized (stats) {
13951 stats.reportExcessiveWakeLocked(app.info.uid, app.processName,
13952 realtimeSince, wtimeUsed);
13953 }
13954 Slog.w(TAG, "Excessive wake lock in " + app.processName
13955 + " (pid " + app.pid + "): held " + wtimeUsed
13956 + " during " + realtimeSince);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013957 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13958 app.processName, app.setAdj, "excessive wake lock");
13959 Process.killProcessQuiet(app.pid);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013960 } else if (doCpuKills && uptimeSince > 0
13961 && ((cputimeUsed*100)/uptimeSince) >= 50) {
13962 synchronized (stats) {
13963 stats.reportExcessiveCpuLocked(app.info.uid, app.processName,
13964 uptimeSince, cputimeUsed);
13965 }
13966 Slog.w(TAG, "Excessive CPU in " + app.processName
13967 + " (pid " + app.pid + "): used " + cputimeUsed
13968 + " during " + uptimeSince);
13969 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13970 app.processName, app.setAdj, "excessive cpu");
13971 Process.killProcessQuiet(app.pid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013972 } else {
13973 app.lastWakeTime = wtime;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013974 app.lastCpuTime = app.curCpuTime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013975 }
13976 }
13977 }
13978 }
13979
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013980 private final boolean updateOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013981 ProcessRecord app, int hiddenAdj, ProcessRecord TOP_APP, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013982 app.hiddenAdj = hiddenAdj;
13983
13984 if (app.thread == null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013985 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013986 }
13987
Dianne Hackborn287952c2010-09-22 22:34:31 -070013988 final boolean wasKeeping = app.keeping;
13989
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013990 boolean success = true;
13991
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013992 computeOomAdjLocked(app, hiddenAdj, TOP_APP, false, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013993
Jeff Brown10e89712011-07-08 18:52:57 -070013994 if (app.curRawAdj != app.setRawAdj) {
Dianne Hackborn905577f2011-09-07 18:31:28 -070013995 if (false) {
13996 // Removing for now. Forcing GCs is not so useful anymore
13997 // with Dalvik, and the new memory level hint facility is
13998 // better for what we need to do these days.
13999 if (app.curRawAdj > ProcessList.FOREGROUND_APP_ADJ
14000 && app.setRawAdj <= ProcessList.FOREGROUND_APP_ADJ) {
14001 // If this app is transitioning from foreground to
14002 // non-foreground, have it do a gc.
14003 scheduleAppGcLocked(app);
14004 } else if (app.curRawAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
14005 && app.setRawAdj < ProcessList.HIDDEN_APP_MIN_ADJ) {
14006 // Likewise do a gc when an app is moving in to the
14007 // background (such as a service stopping).
14008 scheduleAppGcLocked(app);
14009 }
Jeff Brown10e89712011-07-08 18:52:57 -070014010 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070014011
Jeff Brown10e89712011-07-08 18:52:57 -070014012 if (wasKeeping && !app.keeping) {
14013 // This app is no longer something we want to keep. Note
14014 // its current wake lock time to later know to kill it if
14015 // it is not behaving well.
14016 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
14017 synchronized (stats) {
14018 app.lastWakeTime = stats.getProcessWakeTime(app.info.uid,
14019 app.pid, SystemClock.elapsedRealtime());
14020 }
14021 app.lastCpuTime = app.curCpuTime;
14022 }
14023
14024 app.setRawAdj = app.curRawAdj;
14025 }
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014026
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014027 if (app.curAdj != app.setAdj) {
14028 if (Process.setOomAdj(app.pid, app.curAdj)) {
Dianne Hackbornbbb09ac2011-11-30 11:31:29 -080014029 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014030 TAG, "Set " + app.pid + " " + app.processName +
14031 " adj " + app.curAdj + ": " + app.adjType);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014032 app.setAdj = app.curAdj;
Jeff Brown10e89712011-07-08 18:52:57 -070014033 } else {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014034 success = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014035 Slog.w(TAG, "Failed setting oom adj of " + app + " to " + app.curAdj);
Jeff Brown10e89712011-07-08 18:52:57 -070014036 }
14037 }
14038 if (app.setSchedGroup != app.curSchedGroup) {
14039 app.setSchedGroup = app.curSchedGroup;
14040 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
14041 "Setting process group of " + app.processName
14042 + " to " + app.curSchedGroup);
14043 if (app.waitingToKill != null &&
14044 app.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
14045 Slog.i(TAG, "Killing " + app.toShortString() + ": " + app.waitingToKill);
14046 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14047 app.processName, app.setAdj, app.waitingToKill);
14048 Process.killProcessQuiet(app.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014049 success = false;
Jeff Brown10e89712011-07-08 18:52:57 -070014050 } else {
14051 if (true) {
14052 long oldId = Binder.clearCallingIdentity();
14053 try {
14054 Process.setProcessGroup(app.pid, app.curSchedGroup);
14055 } catch (Exception e) {
14056 Slog.w(TAG, "Failed setting process group of " + app.pid
14057 + " to " + app.curSchedGroup);
14058 e.printStackTrace();
14059 } finally {
14060 Binder.restoreCallingIdentity(oldId);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014061 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014062 } else {
Jeff Brown10e89712011-07-08 18:52:57 -070014063 if (app.thread != null) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070014064 try {
Jeff Brown10e89712011-07-08 18:52:57 -070014065 app.thread.setSchedulingGroup(app.curSchedGroup);
14066 } catch (RemoteException e) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070014067 }
14068 }
14069 }
14070 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014071 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014072 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014073 }
14074
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014075 private final ActivityRecord resumedAppLocked() {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014076 ActivityRecord resumedActivity = mMainStack.mResumedActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014077 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -080014078 resumedActivity = mMainStack.mPausingActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014079 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014080 resumedActivity = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014081 }
14082 }
14083 return resumedActivity;
14084 }
14085
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014086 private final boolean updateOomAdjLocked(ProcessRecord app) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014087 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014088 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
14089 int curAdj = app.curAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070014090 final boolean wasHidden = curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
14091 && curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014092
14093 mAdjSeq++;
14094
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014095 boolean success = updateOomAdjLocked(app, app.hiddenAdj, TOP_APP, false);
Dianne Hackborn7d608422011-08-07 16:24:18 -070014096 final boolean nowHidden = app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
14097 && app.curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014098 if (nowHidden != wasHidden) {
14099 // Changed to/from hidden state, so apps after it in the LRU
14100 // list may also be changed.
14101 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014102 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014103 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014104 }
14105
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014106 final void updateOomAdjLocked() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014107 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014108 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
14109
14110 if (false) {
14111 RuntimeException e = new RuntimeException();
14112 e.fillInStackTrace();
Joe Onorato8a9b2202010-02-26 18:56:32 -080014113 Slog.i(TAG, "updateOomAdj: top=" + TOP_ACT, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014114 }
14115
14116 mAdjSeq++;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014117 mNewNumServiceProcs = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014118
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014119 // Let's determine how many processes we have running vs.
14120 // how many slots we have for background processes; we may want
14121 // to put multiple processes in a slot of there are enough of
14122 // them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014123 int numSlots = ProcessList.HIDDEN_APP_MAX_ADJ - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014124 int factor = (mLruProcesses.size()-4)/numSlots;
14125 if (factor < 1) factor = 1;
14126 int step = 0;
Dianne Hackborn8633e682010-04-22 16:03:41 -070014127 int numHidden = 0;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014128
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014129 // First update the OOM adjustment for each of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014130 // application processes based on their current state.
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014131 int i = mLruProcesses.size();
Dianne Hackborn7d608422011-08-07 16:24:18 -070014132 int curHiddenAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014133 while (i > 0) {
14134 i--;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014135 ProcessRecord app = mLruProcesses.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080014136 //Slog.i(TAG, "OOM " + app + ": cur hidden=" + curHiddenAdj);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014137 updateOomAdjLocked(app, curHiddenAdj, TOP_APP, true);
14138 if (curHiddenAdj < ProcessList.HIDDEN_APP_MAX_ADJ
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014139 && app.curAdj == curHiddenAdj) {
14140 step++;
14141 if (step >= factor) {
14142 step = 0;
14143 curHiddenAdj++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014144 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014145 }
14146 if (!app.killedBackground) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070014147 if (app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014148 numHidden++;
14149 if (numHidden > mProcessLimit) {
14150 Slog.i(TAG, "No longer want " + app.processName
14151 + " (pid " + app.pid + "): hidden #" + numHidden);
14152 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14153 app.processName, app.setAdj, "too many background");
14154 app.killedBackground = true;
14155 Process.killProcessQuiet(app.pid);
Dianne Hackborn8633e682010-04-22 16:03:41 -070014156 }
14157 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -080014158 if (!app.killedBackground && app.isolated && app.services.size() <= 0) {
14159 // If this is an isolated process, and there are no
14160 // services running in it, then the process is no longer
14161 // needed. We agressively kill these because we can by
14162 // definition not re-use the same process again, and it is
14163 // good to avoid having whatever code was running in them
14164 // left sitting around after no longer needed.
14165 Slog.i(TAG, "Isolated process " + app.processName
14166 + " (pid " + app.pid + ") no longer needed");
14167 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14168 app.processName, app.setAdj, "isolated not needed");
14169 app.killedBackground = true;
14170 Process.killProcessQuiet(app.pid);
14171 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014172 }
14173 }
14174
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014175 mNumServiceProcs = mNewNumServiceProcs;
14176
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014177 // Now determine the memory trimming level of background processes.
14178 // Unfortunately we need to start at the back of the list to do this
14179 // properly. We only do this if the number of background apps we
14180 // are managing to keep around is less than half the maximum we desire;
14181 // if we are keeping a good number around, we'll let them use whatever
14182 // memory they want.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014183 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/2)) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014184 final int N = mLruProcesses.size();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080014185 factor = numHidden/3;
14186 int minFactor = 2;
14187 if (mHomeProcess != null) minFactor++;
14188 if (mPreviousProcess != null) minFactor++;
14189 if (factor < minFactor) factor = minFactor;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014190 step = 0;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014191 int fgTrimLevel;
14192 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/5)) {
14193 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL;
14194 } else if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/3)) {
14195 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW;
14196 } else {
14197 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE;
14198 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014199 int curLevel = ComponentCallbacks2.TRIM_MEMORY_COMPLETE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014200 for (i=0; i<N; i++) {
14201 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080014202 if (app.curAdj >= ProcessList.HOME_APP_ADJ
14203 && app.curAdj != ProcessList.SERVICE_B_ADJ
14204 && !app.killedBackground) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014205 if (app.trimMemoryLevel < curLevel && app.thread != null) {
14206 try {
14207 app.thread.scheduleTrimMemory(curLevel);
14208 } catch (RemoteException e) {
14209 }
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080014210 if (false) {
14211 // For now we won't do this; our memory trimming seems
14212 // to be good enough at this point that destroying
14213 // activities causes more harm than good.
14214 if (curLevel >= ComponentCallbacks2.TRIM_MEMORY_COMPLETE
14215 && app != mHomeProcess && app != mPreviousProcess) {
14216 // For these apps we will also finish their activities
14217 // to help them free memory.
14218 mMainStack.destroyActivitiesLocked(app, false, "trim");
14219 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014220 }
14221 }
14222 app.trimMemoryLevel = curLevel;
14223 step++;
14224 if (step >= factor) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014225 step = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014226 switch (curLevel) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014227 case ComponentCallbacks2.TRIM_MEMORY_COMPLETE:
14228 curLevel = ComponentCallbacks2.TRIM_MEMORY_MODERATE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014229 break;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014230 case ComponentCallbacks2.TRIM_MEMORY_MODERATE:
14231 curLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014232 break;
14233 }
14234 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070014235 } else if (app.curAdj == ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014236 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014237 && app.thread != null) {
14238 try {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014239 app.thread.scheduleTrimMemory(
14240 ComponentCallbacks2.TRIM_MEMORY_BACKGROUND);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014241 } catch (RemoteException e) {
14242 }
14243 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014244 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014245 } else {
14246 if ((app.curAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
14247 && app.pendingUiClean) {
14248 // If this application is now in the background and it
14249 // had done UI, then give it the special trim level to
14250 // have it free UI resources.
14251 final int level = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
14252 if (app.trimMemoryLevel < level && app.thread != null) {
14253 try {
14254 app.thread.scheduleTrimMemory(level);
14255 } catch (RemoteException e) {
14256 }
14257 }
14258 app.pendingUiClean = false;
14259 }
14260 if (app.trimMemoryLevel < fgTrimLevel && app.thread != null) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014261 try {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014262 app.thread.scheduleTrimMemory(fgTrimLevel);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014263 } catch (RemoteException e) {
14264 }
14265 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014266 app.trimMemoryLevel = fgTrimLevel;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014267 }
14268 }
14269 } else {
14270 final int N = mLruProcesses.size();
14271 for (i=0; i<N; i++) {
14272 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -070014273 if ((app.curAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014274 && app.pendingUiClean) {
14275 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
14276 && app.thread != null) {
14277 try {
14278 app.thread.scheduleTrimMemory(
14279 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
14280 } catch (RemoteException e) {
14281 }
14282 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014283 app.pendingUiClean = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014284 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014285 app.trimMemoryLevel = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014286 }
14287 }
14288
14289 if (mAlwaysFinishActivities) {
Dianne Hackborn28695e02011-11-02 21:59:51 -070014290 mMainStack.destroyActivitiesLocked(null, false, "always-finish");
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014291 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014292 }
14293
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014294 final void trimApplications() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014295 synchronized (this) {
14296 int i;
14297
14298 // First remove any unused application processes whose package
14299 // has been removed.
14300 for (i=mRemovedProcesses.size()-1; i>=0; i--) {
14301 final ProcessRecord app = mRemovedProcesses.get(i);
14302 if (app.activities.size() == 0
14303 && app.curReceiver == null && app.services.size() == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080014304 Slog.i(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014305 TAG, "Exiting empty application process "
14306 + app.processName + " ("
14307 + (app.thread != null ? app.thread.asBinder() : null)
14308 + ")\n");
14309 if (app.pid > 0 && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070014310 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14311 app.processName, app.setAdj, "empty");
14312 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014313 } else {
14314 try {
14315 app.thread.scheduleExit();
14316 } catch (Exception e) {
14317 // Ignore exceptions.
14318 }
14319 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070014320 cleanUpApplicationRecordLocked(app, false, true, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014321 mRemovedProcesses.remove(i);
14322
14323 if (app.persistent) {
14324 if (app.persistent) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080014325 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014326 }
14327 }
14328 }
14329 }
14330
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014331 // Now update the oom adj for all processes.
14332 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014333 }
14334 }
14335
14336 /** This method sends the specified signal to each of the persistent apps */
14337 public void signalPersistentProcesses(int sig) throws RemoteException {
14338 if (sig != Process.SIGNAL_USR1) {
14339 throw new SecurityException("Only SIGNAL_USR1 is allowed");
14340 }
14341
14342 synchronized (this) {
14343 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
14344 != PackageManager.PERMISSION_GRANTED) {
14345 throw new SecurityException("Requires permission "
14346 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
14347 }
14348
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014349 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
14350 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014351 if (r.thread != null && r.persistent) {
14352 Process.sendSignal(r.pid, sig);
14353 }
14354 }
14355 }
14356 }
14357
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014358 private void stopProfilerLocked(ProcessRecord proc, String path, int profileType) {
14359 if (proc == null || proc == mProfileProc) {
14360 proc = mProfileProc;
14361 path = mProfileFile;
14362 profileType = mProfileType;
14363 clearProfilerLocked();
14364 }
14365 if (proc == null) {
14366 return;
14367 }
14368 try {
14369 proc.thread.profilerControl(false, path, null, profileType);
14370 } catch (RemoteException e) {
14371 throw new IllegalStateException("Process disappeared");
14372 }
14373 }
14374
14375 private void clearProfilerLocked() {
14376 if (mProfileFd != null) {
14377 try {
14378 mProfileFd.close();
14379 } catch (IOException e) {
14380 }
14381 }
14382 mProfileApp = null;
14383 mProfileProc = null;
14384 mProfileFile = null;
14385 mProfileType = 0;
14386 mAutoStopProfiler = false;
14387 }
14388
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014389 public boolean profileControl(String process, boolean start,
Romain Guy7eabe552011-07-21 14:56:34 -070014390 String path, ParcelFileDescriptor fd, int profileType) throws RemoteException {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014391
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014392 try {
14393 synchronized (this) {
14394 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14395 // its own permission.
14396 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14397 != PackageManager.PERMISSION_GRANTED) {
14398 throw new SecurityException("Requires permission "
14399 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014400 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014401
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014402 if (start && fd == null) {
14403 throw new IllegalArgumentException("null fd");
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014404 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014405
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014406 ProcessRecord proc = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014407 if (process != null) {
14408 try {
14409 int pid = Integer.parseInt(process);
14410 synchronized (mPidsSelfLocked) {
14411 proc = mPidsSelfLocked.get(pid);
14412 }
14413 } catch (NumberFormatException e) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014414 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014415
14416 if (proc == null) {
14417 HashMap<String, SparseArray<ProcessRecord>> all
14418 = mProcessNames.getMap();
14419 SparseArray<ProcessRecord> procs = all.get(process);
14420 if (procs != null && procs.size() > 0) {
14421 proc = procs.valueAt(0);
14422 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014423 }
14424 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014425
14426 if (start && (proc == null || proc.thread == null)) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014427 throw new IllegalArgumentException("Unknown process: " + process);
14428 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014429
14430 if (start) {
14431 stopProfilerLocked(null, null, 0);
14432 setProfileApp(proc.info, proc.processName, path, fd, false);
14433 mProfileProc = proc;
14434 mProfileType = profileType;
14435 try {
14436 fd = fd.dup();
14437 } catch (IOException e) {
14438 fd = null;
14439 }
14440 proc.thread.profilerControl(start, path, fd, profileType);
14441 fd = null;
14442 mProfileFd = null;
14443 } else {
14444 stopProfilerLocked(proc, path, profileType);
14445 if (fd != null) {
14446 try {
14447 fd.close();
14448 } catch (IOException e) {
14449 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014450 }
14451 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014452
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014453 return true;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014454 }
14455 } catch (RemoteException e) {
14456 throw new IllegalStateException("Process disappeared");
14457 } finally {
14458 if (fd != null) {
14459 try {
14460 fd.close();
14461 } catch (IOException e) {
14462 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014463 }
14464 }
14465 }
Andy McFadden824c5102010-07-09 16:26:57 -070014466
14467 public boolean dumpHeap(String process, boolean managed,
14468 String path, ParcelFileDescriptor fd) throws RemoteException {
14469
14470 try {
14471 synchronized (this) {
14472 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14473 // its own permission (same as profileControl).
14474 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14475 != PackageManager.PERMISSION_GRANTED) {
14476 throw new SecurityException("Requires permission "
14477 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
14478 }
14479
14480 if (fd == null) {
14481 throw new IllegalArgumentException("null fd");
14482 }
14483
14484 ProcessRecord proc = null;
14485 try {
14486 int pid = Integer.parseInt(process);
14487 synchronized (mPidsSelfLocked) {
14488 proc = mPidsSelfLocked.get(pid);
14489 }
14490 } catch (NumberFormatException e) {
14491 }
14492
14493 if (proc == null) {
14494 HashMap<String, SparseArray<ProcessRecord>> all
14495 = mProcessNames.getMap();
14496 SparseArray<ProcessRecord> procs = all.get(process);
14497 if (procs != null && procs.size() > 0) {
14498 proc = procs.valueAt(0);
14499 }
14500 }
14501
14502 if (proc == null || proc.thread == null) {
14503 throw new IllegalArgumentException("Unknown process: " + process);
14504 }
14505
Dianne Hackbornf02e57b2011-03-01 22:21:04 -080014506 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
14507 if (!isDebuggable) {
Andy McFadden824c5102010-07-09 16:26:57 -070014508 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
14509 throw new SecurityException("Process not debuggable: " + proc);
14510 }
14511 }
14512
14513 proc.thread.dumpHeap(managed, path, fd);
14514 fd = null;
14515 return true;
14516 }
14517 } catch (RemoteException e) {
14518 throw new IllegalStateException("Process disappeared");
14519 } finally {
14520 if (fd != null) {
14521 try {
14522 fd.close();
14523 } catch (IOException e) {
14524 }
14525 }
14526 }
14527 }
14528
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014529 /** In this method we try to acquire our lock to make sure that we have not deadlocked */
14530 public void monitor() {
14531 synchronized (this) { }
14532 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014533
Dianne Hackborna573f6a2012-02-09 16:12:18 -080014534 void onCoreSettingsChange(Bundle settings) {
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014535 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
14536 ProcessRecord processRecord = mLruProcesses.get(i);
14537 try {
14538 if (processRecord.thread != null) {
14539 processRecord.thread.setCoreSettings(settings);
14540 }
14541 } catch (RemoteException re) {
14542 /* ignore */
14543 }
14544 }
14545 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014546
14547 // Multi-user methods
14548
Amith Yamasani742a6712011-05-04 14:49:28 -070014549 private int mCurrentUserId;
14550 private SparseIntArray mLoggedInUsers = new SparseIntArray(5);
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014551 private ArrayList<UserListener> mUserListeners = new ArrayList<UserListener>(3);
14552
14553 public interface UserListener {
14554 public void onUserChanged(int userId);
14555
14556 public void onUserAdded(int userId);
14557
14558 public void onUserRemoved(int userId);
14559
14560 public void onUserLoggedOut(int userId);
14561 }
14562
14563 public void addUserListener(UserListener listener) {
14564 synchronized (this) {
14565 if (!mUserListeners.contains(listener)) {
14566 mUserListeners.add(listener);
14567 }
14568 }
14569 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014570
14571 public boolean switchUser(int userId) {
14572 final int callingUid = Binder.getCallingUid();
14573 if (callingUid != 0 && callingUid != Process.myUid()) {
14574 Slog.e(TAG, "Trying to switch user from unauthorized app");
14575 return false;
14576 }
14577 if (mCurrentUserId == userId)
14578 return true;
14579
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014580 ArrayList<UserListener> listeners;
14581
Amith Yamasani742a6712011-05-04 14:49:28 -070014582 synchronized (this) {
14583 // Check if user is already logged in, otherwise check if user exists first before
14584 // adding to the list of logged in users.
14585 if (mLoggedInUsers.indexOfKey(userId) < 0) {
14586 if (!userExists(userId)) {
14587 return false;
14588 }
14589 mLoggedInUsers.append(userId, userId);
14590 }
14591
14592 mCurrentUserId = userId;
14593 boolean haveActivities = mMainStack.switchUser(userId);
14594 if (!haveActivities) {
14595 startHomeActivityLocked(userId);
14596 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014597
14598 listeners = (ArrayList<UserListener>) mUserListeners.clone();
14599 }
14600 // Inform the listeners
14601 for (UserListener listener : listeners) {
14602 listener.onUserChanged(userId);
Amith Yamasani742a6712011-05-04 14:49:28 -070014603 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014604 return true;
14605 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014606
14607 private boolean userExists(int userId) {
14608 try {
14609 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
14610 for (UserInfo user : users) {
14611 if (user.id == userId) {
14612 return true;
14613 }
14614 }
14615 } catch (RemoteException re) {
14616 // Won't happen, in same process
14617 }
14618
14619 return false;
14620 }
14621
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014622 private void checkValidCaller(int uid, int userId) {
14623 if (UserId.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) return;
14624
14625 throw new SecurityException("Caller uid=" + uid
14626 + " is not privileged to communicate with user=" + userId);
14627 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014628
14629 private int applyUserId(int uid, int userId) {
14630 return UserId.getUid(userId, uid);
14631 }
14632
14633 private ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080014634 if (info == null) return null;
Amith Yamasani742a6712011-05-04 14:49:28 -070014635 ApplicationInfo newInfo = new ApplicationInfo(info);
14636 newInfo.uid = applyUserId(info.uid, userId);
14637 if (newInfo.uid >= Process.FIRST_APPLICATION_UID) {
14638 newInfo.dataDir = USER_DATA_DIR + userId + "/"
14639 + info.packageName;
14640 }
14641 return newInfo;
14642 }
14643
14644 ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080014645 if (aInfo == null || aInfo.applicationInfo.uid < Process.FIRST_APPLICATION_UID
Amith Yamasani742a6712011-05-04 14:49:28 -070014646 || userId < 1) {
14647 return aInfo;
14648 }
14649
14650 ActivityInfo info = new ActivityInfo(aInfo);
14651 info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId);
14652 return info;
14653 }
14654
14655 static class ServiceMap {
14656
14657 private final SparseArray<HashMap<ComponentName, ServiceRecord>> mServicesByNamePerUser
14658 = new SparseArray<HashMap<ComponentName, ServiceRecord>>();
14659 private final SparseArray<HashMap<Intent.FilterComparison, ServiceRecord>>
14660 mServicesByIntentPerUser = new SparseArray<
14661 HashMap<Intent.FilterComparison, ServiceRecord>>();
14662
14663 ServiceRecord getServiceByName(ComponentName name, int callingUser) {
14664 // TODO: Deal with global services
14665 if (DEBUG_MU)
14666 Slog.v(TAG_MU, "getServiceByName(" + name + "), callingUser = " + callingUser);
14667 return getServices(callingUser).get(name);
14668 }
14669
14670 ServiceRecord getServiceByName(ComponentName name) {
14671 return getServiceByName(name, -1);
14672 }
14673
14674 ServiceRecord getServiceByIntent(Intent.FilterComparison filter, int callingUser) {
14675 // TODO: Deal with global services
14676 if (DEBUG_MU)
14677 Slog.v(TAG_MU, "getServiceByIntent(" + filter + "), callingUser = " + callingUser);
14678 return getServicesByIntent(callingUser).get(filter);
14679 }
14680
14681 ServiceRecord getServiceByIntent(Intent.FilterComparison filter) {
14682 return getServiceByIntent(filter, -1);
14683 }
14684
14685 void putServiceByName(ComponentName name, int callingUser, ServiceRecord value) {
14686 // TODO: Deal with global services
14687 getServices(callingUser).put(name, value);
14688 }
14689
14690 void putServiceByIntent(Intent.FilterComparison filter, int callingUser,
14691 ServiceRecord value) {
14692 // TODO: Deal with global services
14693 getServicesByIntent(callingUser).put(filter, value);
14694 }
14695
14696 void removeServiceByName(ComponentName name, int callingUser) {
14697 // TODO: Deal with global services
14698 ServiceRecord removed = getServices(callingUser).remove(name);
14699 if (DEBUG_MU)
14700 Slog.v(TAG, "removeServiceByName user=" + callingUser + " name=" + name
14701 + " removed=" + removed);
14702 }
14703
14704 void removeServiceByIntent(Intent.FilterComparison filter, int callingUser) {
14705 // TODO: Deal with global services
14706 ServiceRecord removed = getServicesByIntent(callingUser).remove(filter);
14707 if (DEBUG_MU)
14708 Slog.v(TAG_MU, "removeServiceByIntent user=" + callingUser + " intent=" + filter
14709 + " removed=" + removed);
14710 }
14711
14712 Collection<ServiceRecord> getAllServices(int callingUser) {
14713 // TODO: Deal with global services
14714 return getServices(callingUser).values();
14715 }
14716
14717 private HashMap<ComponentName, ServiceRecord> getServices(int callingUser) {
14718 HashMap map = mServicesByNamePerUser.get(callingUser);
14719 if (map == null) {
14720 map = new HashMap<ComponentName, ServiceRecord>();
14721 mServicesByNamePerUser.put(callingUser, map);
14722 }
14723 return map;
14724 }
14725
14726 private HashMap<Intent.FilterComparison, ServiceRecord> getServicesByIntent(
14727 int callingUser) {
14728 HashMap map = mServicesByIntentPerUser.get(callingUser);
14729 if (map == null) {
14730 map = new HashMap<Intent.FilterComparison, ServiceRecord>();
14731 mServicesByIntentPerUser.put(callingUser, map);
14732 }
14733 return map;
14734 }
14735 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014736}