blob: d21212fe6ecbbaa0ba43f5549223deaa02ce6a22 [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) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007397 long now = SystemClock.uptimeMillis();
7398
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007399 Long crashTime;
7400 if (!app.isolated) {
7401 crashTime = mProcessCrashTimes.get(app.info.processName, app.uid);
7402 } else {
7403 crashTime = null;
7404 }
Dianne Hackborn7d608422011-08-07 16:24:18 -07007405 if (crashTime != null && now < crashTime+ProcessList.MIN_CRASH_INTERVAL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007406 // This process loses!
Joe Onorato8a9b2202010-02-26 18:56:32 -08007407 Slog.w(TAG, "Process " + app.info.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007408 + " has crashed too many times: killing!");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007409 EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007410 app.info.processName, app.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007411 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
7412 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007413 if (r.app == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007414 Slog.w(TAG, " Force finishing activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007415 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007416 r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED, null, "crashed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007417 }
7418 }
7419 if (!app.persistent) {
7420 // We don't want to start this process again until the user
7421 // explicitly does so... but for persistent process, we really
7422 // need to keep it running. If a persistent process is actually
7423 // repeatedly crashing, then badness for everyone.
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007424 EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007425 app.info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007426 if (!app.isolated) {
7427 // XXX We don't have a way to mark isolated processes
7428 // as bad, since they don't have a peristent identity.
7429 mBadProcesses.put(app.info.processName, app.uid, now);
7430 mProcessCrashTimes.remove(app.info.processName, app.uid);
7431 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007432 app.bad = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007433 app.removed = true;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07007434 // Don't let services in this process be restarted and potentially
7435 // annoy the user repeatedly. Unless it is persistent, since those
7436 // processes run critical code.
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007437 removeProcessLocked(app, false, false, "crash");
Dianne Hackborncb44d962011-03-10 17:02:27 -08007438 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007439 return false;
7440 }
Dianne Hackborncb44d962011-03-10 17:02:27 -08007441 mMainStack.resumeTopActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007442 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007443 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007444 if (r.app == app) {
7445 // If the top running activity is from this crashing
7446 // process, then terminate it to avoid getting in a loop.
7447 Slog.w(TAG, " Force finishing activity "
7448 + r.intent.getComponent().flattenToShortString());
Dianne Hackbornbe707852011-11-11 14:32:10 -08007449 int index = mMainStack.indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007450 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007451 Activity.RESULT_CANCELED, null, "crashed");
Dianne Hackborn070783f2010-12-29 16:46:28 -08007452 // Also terminate any activities below it that aren't yet
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007453 // stopped, to avoid a situation where one will get
7454 // re-start our crashing activity once it gets resumed again.
7455 index--;
7456 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007457 r = (ActivityRecord)mMainStack.mHistory.get(index);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007458 if (r.state == ActivityState.RESUMED
7459 || r.state == ActivityState.PAUSING
7460 || r.state == ActivityState.PAUSED) {
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08007461 if (!r.isHomeActivity || mHomeProcess != r.app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007462 Slog.w(TAG, " Force finishing activity "
7463 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007464 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007465 Activity.RESULT_CANCELED, null, "crashed");
7466 }
7467 }
7468 }
7469 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007470 }
7471
7472 // Bump up the crash count of any services currently running in the proc.
7473 if (app.services.size() != 0) {
7474 // Any services running in the application need to be placed
7475 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -07007476 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007477 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07007478 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007479 sr.crashCount++;
7480 }
7481 }
Mattias Larssona4fd0072010-06-22 22:37:03 +02007482
7483 // If the crashing process is what we consider to be the "home process" and it has been
7484 // replaced by a third-party app, clear the package preferred activities from packages
7485 // with a home activity running in the process to prevent a repeatedly crashing app
7486 // from blocking the user to manually clear the list.
7487 if (app == mHomeProcess && mHomeProcess.activities.size() > 0
7488 && (mHomeProcess.info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
7489 Iterator it = mHomeProcess.activities.iterator();
7490 while (it.hasNext()) {
Jean-Baptiste Queru5ea89f72010-07-30 09:30:31 -07007491 ActivityRecord r = (ActivityRecord)it.next();
Mattias Larssona4fd0072010-06-22 22:37:03 +02007492 if (r.isHomeActivity) {
7493 Log.i(TAG, "Clearing package preferred activities from " + r.packageName);
7494 try {
7495 ActivityThread.getPackageManager()
7496 .clearPackagePreferredActivities(r.packageName);
7497 } catch (RemoteException c) {
7498 // pm is in same process, this will never happen.
7499 }
7500 }
7501 }
7502 }
7503
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007504 if (!app.isolated) {
7505 // XXX Can't keep track of crash times for isolated processes,
7506 // because they don't have a perisistent identity.
7507 mProcessCrashTimes.put(app.info.processName, app.uid, now);
7508 }
7509
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007510 return true;
7511 }
7512
7513 void startAppProblemLocked(ProcessRecord app) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08007514 app.errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver(
7515 mContext, app.info.packageName, app.info.flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007516 skipCurrentReceiverLocked(app);
7517 }
7518
7519 void skipCurrentReceiverLocked(ProcessRecord app) {
Christopher Tatef46723b2012-01-26 14:19:24 -08007520 for (BroadcastQueue queue : mBroadcastQueues) {
7521 queue.skipCurrentReceiverLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007522 }
7523 }
7524
Dan Egnor60d87622009-12-16 16:32:58 -08007525 /**
7526 * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes.
7527 * The application process will exit immediately after this call returns.
7528 * @param app object of the crashing app, null for the system server
7529 * @param crashInfo describing the exception
7530 */
7531 public void handleApplicationCrash(IBinder app, ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007532 ProcessRecord r = findAppProcess(app, "Crash");
Jeff Sharkeya353d262011-10-28 11:12:06 -07007533 final String processName = app == null ? "system_server"
7534 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08007535
7536 EventLog.writeEvent(EventLogTags.AM_CRASH, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07007537 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08007538 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08007539 crashInfo.exceptionClassName,
7540 crashInfo.exceptionMessage,
7541 crashInfo.throwFileName,
7542 crashInfo.throwLineNumber);
7543
Jeff Sharkeya353d262011-10-28 11:12:06 -07007544 addErrorToDropBox("crash", r, processName, null, null, null, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08007545
7546 crashApplication(r, crashInfo);
7547 }
7548
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007549 public void handleApplicationStrictModeViolation(
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007550 IBinder app,
7551 int violationMask,
7552 StrictMode.ViolationInfo info) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007553 ProcessRecord r = findAppProcess(app, "StrictMode");
7554 if (r == null) {
7555 return;
7556 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007557
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007558 if ((violationMask & StrictMode.PENALTY_DROPBOX) != 0) {
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08007559 Integer stackFingerprint = info.hashCode();
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007560 boolean logIt = true;
7561 synchronized (mAlreadyLoggedViolatedStacks) {
7562 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) {
7563 logIt = false;
7564 // TODO: sub-sample into EventLog for these, with
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007565 // the info.durationMillis? Then we'd get
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007566 // the relative pain numbers, without logging all
7567 // the stack traces repeatedly. We'd want to do
7568 // likewise in the client code, which also does
7569 // dup suppression, before the Binder call.
7570 } else {
7571 if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) {
7572 mAlreadyLoggedViolatedStacks.clear();
7573 }
7574 mAlreadyLoggedViolatedStacks.add(stackFingerprint);
7575 }
7576 }
7577 if (logIt) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007578 logStrictModeViolationToDropBox(r, info);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007579 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007580 }
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007581
7582 if ((violationMask & StrictMode.PENALTY_DIALOG) != 0) {
7583 AppErrorResult result = new AppErrorResult();
7584 synchronized (this) {
7585 final long origId = Binder.clearCallingIdentity();
7586
7587 Message msg = Message.obtain();
7588 msg.what = SHOW_STRICT_MODE_VIOLATION_MSG;
7589 HashMap<String, Object> data = new HashMap<String, Object>();
7590 data.put("result", result);
7591 data.put("app", r);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007592 data.put("violationMask", violationMask);
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007593 data.put("info", info);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007594 msg.obj = data;
7595 mHandler.sendMessage(msg);
7596
7597 Binder.restoreCallingIdentity(origId);
7598 }
7599 int res = result.get();
Dianne Hackbornb424b632010-08-18 15:59:05 -07007600 Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007601 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007602 }
7603
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007604 // Depending on the policy in effect, there could be a bunch of
7605 // these in quick succession so we try to batch these together to
7606 // minimize disk writes, number of dropbox entries, and maximize
7607 // compression, by having more fewer, larger records.
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007608 private void logStrictModeViolationToDropBox(
7609 ProcessRecord process,
7610 StrictMode.ViolationInfo info) {
7611 if (info == null) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007612 return;
7613 }
7614 final boolean isSystemApp = process == null ||
7615 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM |
7616 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07007617 final String processName = process == null ? "unknown" : process.processName;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007618 final String dropboxTag = isSystemApp ? "system_app_strictmode" : "data_app_strictmode";
7619 final DropBoxManager dbox = (DropBoxManager)
7620 mContext.getSystemService(Context.DROPBOX_SERVICE);
7621
7622 // Exit early if the dropbox isn't configured to accept this report type.
7623 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
7624
7625 boolean bufferWasEmpty;
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007626 boolean needsFlush;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007627 final StringBuilder sb = isSystemApp ? mStrictModeBuffer : new StringBuilder(1024);
7628 synchronized (sb) {
7629 bufferWasEmpty = sb.length() == 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07007630 appendDropBoxProcessHeaders(process, processName, sb);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007631 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
7632 sb.append("System-App: ").append(isSystemApp).append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007633 sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n");
7634 if (info.violationNumThisLoop != 0) {
7635 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n");
7636 }
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07007637 if (info.numAnimationsRunning != 0) {
7638 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n");
7639 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07007640 if (info.broadcastIntentAction != null) {
7641 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n");
7642 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08007643 if (info.durationMillis != -1) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007644 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n");
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007645 }
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08007646 if (info.numInstances != -1) {
7647 sb.append("Instance-Count: ").append(info.numInstances).append("\n");
7648 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08007649 if (info.tags != null) {
7650 for (String tag : info.tags) {
7651 sb.append("Span-Tag: ").append(tag).append("\n");
7652 }
7653 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007654 sb.append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007655 if (info.crashInfo != null && info.crashInfo.stackTrace != null) {
7656 sb.append(info.crashInfo.stackTrace);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007657 }
7658 sb.append("\n");
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007659
7660 // Only buffer up to ~64k. Various logging bits truncate
7661 // things at 128k.
7662 needsFlush = (sb.length() > 64 * 1024);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007663 }
7664
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007665 // Flush immediately if the buffer's grown too large, or this
7666 // is a non-system app. Non-system apps are isolated with a
7667 // different tag & policy and not batched.
7668 //
7669 // Batching is useful during internal testing with
7670 // StrictMode settings turned up high. Without batching,
7671 // thousands of separate files could be created on boot.
7672 if (!isSystemApp || needsFlush) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007673 new Thread("Error dump: " + dropboxTag) {
7674 @Override
7675 public void run() {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007676 String report;
7677 synchronized (sb) {
7678 report = sb.toString();
7679 sb.delete(0, sb.length());
7680 sb.trimToSize();
7681 }
7682 if (report.length() != 0) {
7683 dbox.addText(dropboxTag, report);
7684 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007685 }
7686 }.start();
7687 return;
7688 }
7689
7690 // System app batching:
7691 if (!bufferWasEmpty) {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007692 // An existing dropbox-writing thread is outstanding, so
7693 // we don't need to start it up. The existing thread will
7694 // catch the buffer appends we just did.
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007695 return;
7696 }
7697
7698 // Worker thread to both batch writes and to avoid blocking the caller on I/O.
7699 // (After this point, we shouldn't access AMS internal data structures.)
7700 new Thread("Error dump: " + dropboxTag) {
7701 @Override
7702 public void run() {
7703 // 5 second sleep to let stacks arrive and be batched together
7704 try {
7705 Thread.sleep(5000); // 5 seconds
7706 } catch (InterruptedException e) {}
7707
7708 String errorReport;
7709 synchronized (mStrictModeBuffer) {
7710 errorReport = mStrictModeBuffer.toString();
7711 if (errorReport.length() == 0) {
7712 return;
7713 }
7714 mStrictModeBuffer.delete(0, mStrictModeBuffer.length());
7715 mStrictModeBuffer.trimToSize();
7716 }
7717 dbox.addText(dropboxTag, errorReport);
7718 }
7719 }.start();
7720 }
7721
Dan Egnor60d87622009-12-16 16:32:58 -08007722 /**
7723 * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors.
7724 * @param app object of the crashing app, null for the system server
7725 * @param tag reported by the caller
7726 * @param crashInfo describing the context of the error
7727 * @return true if the process should exit immediately (WTF is fatal)
7728 */
7729 public boolean handleApplicationWtf(IBinder app, String tag,
Dan Egnorb7f03672009-12-09 16:22:32 -08007730 ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007731 ProcessRecord r = findAppProcess(app, "WTF");
Jeff Sharkeya353d262011-10-28 11:12:06 -07007732 final String processName = app == null ? "system_server"
7733 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08007734
7735 EventLog.writeEvent(EventLogTags.AM_WTF, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07007736 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08007737 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08007738 tag, crashInfo.exceptionMessage);
7739
Jeff Sharkeya353d262011-10-28 11:12:06 -07007740 addErrorToDropBox("wtf", r, processName, null, null, tag, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08007741
Dianne Hackborn1ab43772011-03-15 14:38:02 -07007742 if (r != null && r.pid != Process.myPid() &&
7743 Settings.Secure.getInt(mContext.getContentResolver(),
7744 Settings.Secure.WTF_IS_FATAL, 0) != 0) {
Dan Egnor60d87622009-12-16 16:32:58 -08007745 crashApplication(r, crashInfo);
7746 return true;
7747 } else {
7748 return false;
7749 }
7750 }
7751
7752 /**
7753 * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit})
7754 * @return the corresponding {@link ProcessRecord} object, or null if none could be found
7755 */
Dianne Hackborncb44d962011-03-10 17:02:27 -08007756 private ProcessRecord findAppProcess(IBinder app, String reason) {
Dan Egnor60d87622009-12-16 16:32:58 -08007757 if (app == null) {
7758 return null;
7759 }
7760
7761 synchronized (this) {
7762 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
7763 final int NA = apps.size();
7764 for (int ia=0; ia<NA; ia++) {
7765 ProcessRecord p = apps.valueAt(ia);
7766 if (p.thread != null && p.thread.asBinder() == app) {
7767 return p;
7768 }
7769 }
7770 }
7771
Dianne Hackborncb44d962011-03-10 17:02:27 -08007772 Slog.w(TAG, "Can't find mystery application for " + reason
7773 + " from pid=" + Binder.getCallingPid()
7774 + " uid=" + Binder.getCallingUid() + ": " + app);
Dan Egnor60d87622009-12-16 16:32:58 -08007775 return null;
7776 }
7777 }
7778
7779 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007780 * Utility function for addErrorToDropBox and handleStrictModeViolation's logging
7781 * to append various headers to the dropbox log text.
Dan Egnor60d87622009-12-16 16:32:58 -08007782 */
Jeff Sharkeya353d262011-10-28 11:12:06 -07007783 private void appendDropBoxProcessHeaders(ProcessRecord process, String processName,
7784 StringBuilder sb) {
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08007785 // Watchdog thread ends up invoking this function (with
7786 // a null ProcessRecord) to add the stack file to dropbox.
7787 // Do not acquire a lock on this (am) in such cases, as it
7788 // could cause a potential deadlock, if and when watchdog
7789 // is invoked due to unavailability of lock on am and it
7790 // would prevent watchdog from killing system_server.
7791 if (process == null) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07007792 sb.append("Process: ").append(processName).append("\n");
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08007793 return;
7794 }
Brad Fitzpatrick1e02d362010-09-10 09:19:50 -07007795 // Note: ProcessRecord 'process' is guarded by the service
7796 // instance. (notably process.pkgList, which could otherwise change
7797 // concurrently during execution of this method)
7798 synchronized (this) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07007799 sb.append("Process: ").append(processName).append("\n");
Dan Egnora455d192010-03-12 08:52:28 -08007800 int flags = process.info.flags;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007801 IPackageManager pm = AppGlobals.getPackageManager();
Dan Egnora455d192010-03-12 08:52:28 -08007802 sb.append("Flags: 0x").append(Integer.toString(flags, 16)).append("\n");
7803 for (String pkg : process.pkgList) {
7804 sb.append("Package: ").append(pkg);
Dan Egnor42471dd2010-01-07 17:25:22 -08007805 try {
Dan Egnora455d192010-03-12 08:52:28 -08007806 PackageInfo pi = pm.getPackageInfo(pkg, 0);
7807 if (pi != null) {
7808 sb.append(" v").append(pi.versionCode);
7809 if (pi.versionName != null) {
7810 sb.append(" (").append(pi.versionName).append(")");
7811 }
7812 }
7813 } catch (RemoteException e) {
7814 Slog.e(TAG, "Error getting package info: " + pkg, e);
Dan Egnor60d87622009-12-16 16:32:58 -08007815 }
Dan Egnora455d192010-03-12 08:52:28 -08007816 sb.append("\n");
Dan Egnor60d87622009-12-16 16:32:58 -08007817 }
Dan Egnora455d192010-03-12 08:52:28 -08007818 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007819 }
7820
7821 private static String processClass(ProcessRecord process) {
7822 if (process == null || process.pid == MY_PID) {
7823 return "system_server";
7824 } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
7825 return "system_app";
7826 } else {
7827 return "data_app";
7828 }
7829 }
7830
7831 /**
7832 * Write a description of an error (crash, WTF, ANR) to the drop box.
7833 * @param eventType to include in the drop box tag ("crash", "wtf", etc.)
7834 * @param process which caused the error, null means the system server
7835 * @param activity which triggered the error, null if unknown
7836 * @param parent activity related to the error, null if unknown
7837 * @param subject line related to the error, null if absent
7838 * @param report in long form describing the error, null if absent
7839 * @param logFile to include in the report, null if none
7840 * @param crashInfo giving an application stack trace, null if absent
7841 */
7842 public void addErrorToDropBox(String eventType,
Jeff Sharkeya353d262011-10-28 11:12:06 -07007843 ProcessRecord process, String processName, ActivityRecord activity,
7844 ActivityRecord parent, String subject,
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007845 final String report, final File logFile,
7846 final ApplicationErrorReport.CrashInfo crashInfo) {
7847 // NOTE -- this must never acquire the ActivityManagerService lock,
7848 // otherwise the watchdog may be prevented from resetting the system.
7849
7850 final String dropboxTag = processClass(process) + "_" + eventType;
7851 final DropBoxManager dbox = (DropBoxManager)
7852 mContext.getSystemService(Context.DROPBOX_SERVICE);
7853
7854 // Exit early if the dropbox isn't configured to accept this report type.
7855 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
7856
7857 final StringBuilder sb = new StringBuilder(1024);
Jeff Sharkeya353d262011-10-28 11:12:06 -07007858 appendDropBoxProcessHeaders(process, processName, sb);
Dan Egnora455d192010-03-12 08:52:28 -08007859 if (activity != null) {
7860 sb.append("Activity: ").append(activity.shortComponentName).append("\n");
7861 }
7862 if (parent != null && parent.app != null && parent.app.pid != process.pid) {
7863 sb.append("Parent-Process: ").append(parent.app.processName).append("\n");
7864 }
7865 if (parent != null && parent != activity) {
7866 sb.append("Parent-Activity: ").append(parent.shortComponentName).append("\n");
7867 }
7868 if (subject != null) {
7869 sb.append("Subject: ").append(subject).append("\n");
7870 }
7871 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
Christian Lindeberg03d2ca62010-09-28 14:52:20 +02007872 if (Debug.isDebuggerConnected()) {
7873 sb.append("Debugger: Connected\n");
7874 }
Dan Egnora455d192010-03-12 08:52:28 -08007875 sb.append("\n");
7876
7877 // Do the rest in a worker thread to avoid blocking the caller on I/O
7878 // (After this point, we shouldn't access AMS internal data structures.)
7879 Thread worker = new Thread("Error dump: " + dropboxTag) {
7880 @Override
7881 public void run() {
7882 if (report != null) {
7883 sb.append(report);
7884 }
7885 if (logFile != null) {
7886 try {
7887 sb.append(FileUtils.readTextFile(logFile, 128 * 1024, "\n\n[[TRUNCATED]]"));
7888 } catch (IOException e) {
7889 Slog.e(TAG, "Error reading " + logFile, e);
7890 }
7891 }
7892 if (crashInfo != null && crashInfo.stackTrace != null) {
7893 sb.append(crashInfo.stackTrace);
7894 }
7895
7896 String setting = Settings.Secure.ERROR_LOGCAT_PREFIX + dropboxTag;
7897 int lines = Settings.Secure.getInt(mContext.getContentResolver(), setting, 0);
7898 if (lines > 0) {
7899 sb.append("\n");
7900
7901 // Merge several logcat streams, and take the last N lines
7902 InputStreamReader input = null;
7903 try {
7904 java.lang.Process logcat = new ProcessBuilder("/system/bin/logcat",
7905 "-v", "time", "-b", "events", "-b", "system", "-b", "main",
7906 "-t", String.valueOf(lines)).redirectErrorStream(true).start();
7907
7908 try { logcat.getOutputStream().close(); } catch (IOException e) {}
7909 try { logcat.getErrorStream().close(); } catch (IOException e) {}
7910 input = new InputStreamReader(logcat.getInputStream());
7911
7912 int num;
7913 char[] buf = new char[8192];
7914 while ((num = input.read(buf)) > 0) sb.append(buf, 0, num);
7915 } catch (IOException e) {
7916 Slog.e(TAG, "Error running logcat", e);
7917 } finally {
7918 if (input != null) try { input.close(); } catch (IOException e) {}
7919 }
7920 }
7921
7922 dbox.addText(dropboxTag, sb.toString());
Dan Egnor60d87622009-12-16 16:32:58 -08007923 }
Dan Egnora455d192010-03-12 08:52:28 -08007924 };
7925
7926 if (process == null || process.pid == MY_PID) {
7927 worker.run(); // We may be about to die -- need to run this synchronously
7928 } else {
7929 worker.start();
Dan Egnor60d87622009-12-16 16:32:58 -08007930 }
7931 }
7932
7933 /**
7934 * Bring up the "unexpected error" dialog box for a crashing app.
7935 * Deal with edge cases (intercepts from instrumented applications,
7936 * ActivityController, error intent receivers, that sort of thing).
7937 * @param r the application crashing
7938 * @param crashInfo describing the failure
7939 */
7940 private void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) {
Dan Egnorb7f03672009-12-09 16:22:32 -08007941 long timeMillis = System.currentTimeMillis();
7942 String shortMsg = crashInfo.exceptionClassName;
7943 String longMsg = crashInfo.exceptionMessage;
7944 String stackTrace = crashInfo.stackTrace;
7945 if (shortMsg != null && longMsg != null) {
7946 longMsg = shortMsg + ": " + longMsg;
7947 } else if (shortMsg != null) {
7948 longMsg = shortMsg;
7949 }
7950
Dan Egnor60d87622009-12-16 16:32:58 -08007951 AppErrorResult result = new AppErrorResult();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007952 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007953 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007954 try {
7955 String name = r != null ? r.processName : null;
7956 int pid = r != null ? r.pid : Binder.getCallingPid();
Dan Egnor60d87622009-12-16 16:32:58 -08007957 if (!mController.appCrashed(name, pid,
Dan Egnorb7f03672009-12-09 16:22:32 -08007958 shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007959 Slog.w(TAG, "Force-killing crashed app " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007960 + " at watcher's request");
7961 Process.killProcess(pid);
Dan Egnorb7f03672009-12-09 16:22:32 -08007962 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007963 }
7964 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007965 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007966 }
7967 }
7968
7969 final long origId = Binder.clearCallingIdentity();
7970
7971 // If this process is running instrumentation, finish it.
7972 if (r != null && r.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007973 Slog.w(TAG, "Error in app " + r.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007974 + " running instrumentation " + r.instrumentationClass + ":");
Joe Onorato8a9b2202010-02-26 18:56:32 -08007975 if (shortMsg != null) Slog.w(TAG, " " + shortMsg);
7976 if (longMsg != null) Slog.w(TAG, " " + longMsg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007977 Bundle info = new Bundle();
7978 info.putString("shortMsg", shortMsg);
7979 info.putString("longMsg", longMsg);
7980 finishInstrumentationLocked(r, Activity.RESULT_CANCELED, info);
7981 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08007982 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007983 }
7984
Dan Egnor60d87622009-12-16 16:32:58 -08007985 // If we can't identify the process or it's already exceeded its crash quota,
7986 // quit right away without showing a crash dialog.
7987 if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007988 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08007989 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007990 }
7991
7992 Message msg = Message.obtain();
7993 msg.what = SHOW_ERROR_MSG;
7994 HashMap data = new HashMap();
7995 data.put("result", result);
7996 data.put("app", r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007997 msg.obj = data;
7998 mHandler.sendMessage(msg);
7999
8000 Binder.restoreCallingIdentity(origId);
8001 }
8002
8003 int res = result.get();
8004
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008005 Intent appErrorIntent = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008006 synchronized (this) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008007 if (r != null && !r.isolated) {
8008 // XXX Can't keep track of crash time for isolated processes,
8009 // since they don't have a persistent identity.
8010 mProcessCrashTimes.put(r.info.processName, r.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008011 SystemClock.uptimeMillis());
8012 }
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008013 if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008014 appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008015 }
8016 }
8017
8018 if (appErrorIntent != null) {
8019 try {
8020 mContext.startActivity(appErrorIntent);
8021 } catch (ActivityNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008022 Slog.w(TAG, "bug report receiver dissappeared", e);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008023 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008024 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008025 }
Dan Egnorb7f03672009-12-09 16:22:32 -08008026
8027 Intent createAppErrorIntentLocked(ProcessRecord r,
8028 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
8029 ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008030 if (report == null) {
8031 return null;
8032 }
8033 Intent result = new Intent(Intent.ACTION_APP_ERROR);
8034 result.setComponent(r.errorReportReceiver);
8035 result.putExtra(Intent.EXTRA_BUG_REPORT, report);
8036 result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
8037 return result;
8038 }
8039
Dan Egnorb7f03672009-12-09 16:22:32 -08008040 private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r,
8041 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008042 if (r.errorReportReceiver == null) {
8043 return null;
8044 }
8045
8046 if (!r.crashing && !r.notResponding) {
8047 return null;
8048 }
8049
Dan Egnorb7f03672009-12-09 16:22:32 -08008050 ApplicationErrorReport report = new ApplicationErrorReport();
8051 report.packageName = r.info.packageName;
8052 report.installerPackageName = r.errorReportReceiver.getPackageName();
8053 report.processName = r.processName;
8054 report.time = timeMillis;
Jacek Surazskie0ee6ef2010-01-07 16:23:03 +01008055 report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008056
Dan Egnorb7f03672009-12-09 16:22:32 -08008057 if (r.crashing) {
8058 report.type = ApplicationErrorReport.TYPE_CRASH;
8059 report.crashInfo = crashInfo;
8060 } else if (r.notResponding) {
8061 report.type = ApplicationErrorReport.TYPE_ANR;
8062 report.anrInfo = new ApplicationErrorReport.AnrInfo();
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008063
Dan Egnorb7f03672009-12-09 16:22:32 -08008064 report.anrInfo.activity = r.notRespondingReport.tag;
8065 report.anrInfo.cause = r.notRespondingReport.shortMsg;
8066 report.anrInfo.info = r.notRespondingReport.longMsg;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008067 }
8068
Dan Egnorb7f03672009-12-09 16:22:32 -08008069 return report;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008070 }
8071
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008072 public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008073 enforceNotIsolatedCaller("getProcessesInErrorState");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008074 // assume our apps are happy - lazy create the list
8075 List<ActivityManager.ProcessErrorStateInfo> errList = null;
8076
8077 synchronized (this) {
8078
8079 // iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008080 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8081 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008082 if ((app.thread != null) && (app.crashing || app.notResponding)) {
8083 // This one's in trouble, so we'll generate a report for it
8084 // crashes are higher priority (in case there's a crash *and* an anr)
8085 ActivityManager.ProcessErrorStateInfo report = null;
8086 if (app.crashing) {
8087 report = app.crashingReport;
8088 } else if (app.notResponding) {
8089 report = app.notRespondingReport;
8090 }
8091
8092 if (report != null) {
8093 if (errList == null) {
8094 errList = new ArrayList<ActivityManager.ProcessErrorStateInfo>(1);
8095 }
8096 errList.add(report);
8097 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008098 Slog.w(TAG, "Missing app error report, app = " + app.processName +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008099 " crashing = " + app.crashing +
8100 " notResponding = " + app.notResponding);
8101 }
8102 }
8103 }
8104 }
8105
8106 return errList;
8107 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07008108
8109 static int oomAdjToImportance(int adj, ActivityManager.RunningAppProcessInfo currApp) {
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008110 if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008111 if (currApp != null) {
8112 currApp.lru = adj - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
8113 }
8114 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008115 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
8116 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008117 } else if (adj >= ProcessList.HOME_APP_ADJ) {
8118 if (currApp != null) {
8119 currApp.lru = 0;
8120 }
8121 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008122 } else if (adj >= ProcessList.SERVICE_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008123 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
8124 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
8125 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
8126 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
8127 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
8128 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
8129 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
8130 } else {
8131 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
8132 }
8133 }
8134
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008135 private void fillInProcMemInfo(ProcessRecord app,
8136 ActivityManager.RunningAppProcessInfo outInfo) {
8137 outInfo.pid = app.pid;
8138 outInfo.uid = app.info.uid;
8139 if (mHeavyWeightProcess == app) {
8140 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_CANT_SAVE_STATE;
8141 }
8142 if (app.persistent) {
8143 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_PERSISTENT;
8144 }
8145 outInfo.lastTrimLevel = app.trimMemoryLevel;
8146 int adj = app.curAdj;
8147 outInfo.importance = oomAdjToImportance(adj, outInfo);
8148 outInfo.importanceReasonCode = app.adjTypeCode;
8149 }
8150
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008151 public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008152 enforceNotIsolatedCaller("getRunningAppProcesses");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008153 // Lazy instantiation of list
8154 List<ActivityManager.RunningAppProcessInfo> runList = null;
8155 synchronized (this) {
8156 // Iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008157 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8158 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008159 if ((app.thread != null) && (!app.crashing && !app.notResponding)) {
8160 // Generate process state info for running application
8161 ActivityManager.RunningAppProcessInfo currApp =
8162 new ActivityManager.RunningAppProcessInfo(app.processName,
8163 app.pid, app.getPackageList());
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008164 fillInProcMemInfo(app, currApp);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008165 if (app.adjSource instanceof ProcessRecord) {
8166 currApp.importanceReasonPid = ((ProcessRecord)app.adjSource).pid;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008167 currApp.importanceReasonImportance = oomAdjToImportance(
8168 app.adjSourceOom, null);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008169 } else if (app.adjSource instanceof ActivityRecord) {
8170 ActivityRecord r = (ActivityRecord)app.adjSource;
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008171 if (r.app != null) currApp.importanceReasonPid = r.app.pid;
8172 }
8173 if (app.adjTarget instanceof ComponentName) {
8174 currApp.importanceReasonComponent = (ComponentName)app.adjTarget;
8175 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08008176 //Slog.v(TAG, "Proc " + app.processName + ": imp=" + currApp.importance
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008177 // + " lru=" + currApp.lru);
8178 if (runList == null) {
8179 runList = new ArrayList<ActivityManager.RunningAppProcessInfo>();
8180 }
8181 runList.add(currApp);
8182 }
8183 }
8184 }
8185 return runList;
8186 }
8187
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008188 public List<ApplicationInfo> getRunningExternalApplications() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008189 enforceNotIsolatedCaller("getRunningExternalApplications");
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008190 List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses();
8191 List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>();
8192 if (runningApps != null && runningApps.size() > 0) {
8193 Set<String> extList = new HashSet<String>();
8194 for (ActivityManager.RunningAppProcessInfo app : runningApps) {
8195 if (app.pkgList != null) {
8196 for (String pkg : app.pkgList) {
8197 extList.add(pkg);
8198 }
8199 }
8200 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008201 IPackageManager pm = AppGlobals.getPackageManager();
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008202 for (String pkg : extList) {
8203 try {
8204 ApplicationInfo info = pm.getApplicationInfo(pkg, 0);
8205 if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
8206 retList.add(info);
8207 }
8208 } catch (RemoteException e) {
8209 }
8210 }
8211 }
8212 return retList;
8213 }
8214
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008215 @Override
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008216 public void getMyMemoryState(ActivityManager.RunningAppProcessInfo outInfo) {
8217 enforceNotIsolatedCaller("getMyMemoryState");
8218 synchronized (this) {
8219 ProcessRecord proc;
8220 synchronized (mPidsSelfLocked) {
8221 proc = mPidsSelfLocked.get(Binder.getCallingPid());
8222 }
8223 fillInProcMemInfo(proc, outInfo);
8224 }
8225 }
8226
8227 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008228 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008229 if (checkCallingPermission(android.Manifest.permission.DUMP)
8230 != PackageManager.PERMISSION_GRANTED) {
8231 pw.println("Permission Denial: can't dump ActivityManager from from pid="
8232 + Binder.getCallingPid()
8233 + ", uid=" + Binder.getCallingUid()
8234 + " without permission "
8235 + android.Manifest.permission.DUMP);
8236 return;
8237 }
8238
8239 boolean dumpAll = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008240 boolean dumpClient = false;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008241 String dumpPackage = null;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008242
8243 int opti = 0;
8244 while (opti < args.length) {
8245 String opt = args[opti];
8246 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
8247 break;
8248 }
8249 opti++;
8250 if ("-a".equals(opt)) {
8251 dumpAll = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008252 } else if ("-c".equals(opt)) {
8253 dumpClient = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008254 } else if ("-h".equals(opt)) {
8255 pw.println("Activity manager dump options:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008256 pw.println(" [-a] [-c] [-h] [cmd] ...");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008257 pw.println(" cmd may be one of:");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008258 pw.println(" a[ctivities]: activity stack state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008259 pw.println(" b[roadcasts] [PACKAGE_NAME]: broadcast state");
8260 pw.println(" i[ntents] [PACKAGE_NAME]: pending intent state");
8261 pw.println(" p[rocesses] [PACKAGE_NAME]: process state");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008262 pw.println(" o[om]: out of memory management");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008263 pw.println(" prov[iders] [COMP_SPEC ...]: content provider state");
Marco Nelissen18cb2872011-11-15 11:19:53 -08008264 pw.println(" provider [COMP_SPEC]: provider client-side state");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008265 pw.println(" s[ervices] [COMP_SPEC ...]: service state");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008266 pw.println(" service [COMP_SPEC]: service client-side state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008267 pw.println(" package [PACKAGE_NAME]: all state related to given package");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008268 pw.println(" all: dump all activities");
8269 pw.println(" top: dump the top activity");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008270 pw.println(" cmd may also be a COMP_SPEC to dump activities.");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008271 pw.println(" COMP_SPEC may be a component name (com.foo/.myApp),");
8272 pw.println(" a partial substring in a component name, a");
8273 pw.println(" hex object identifier.");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008274 pw.println(" -a: include all available server state.");
8275 pw.println(" -c: include client state.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008276 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008277 } else {
8278 pw.println("Unknown argument: " + opt + "; use -h for help");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008279 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008280 }
8281
8282 // Is the caller requesting to dump a particular piece of data?
8283 if (opti < args.length) {
8284 String cmd = args[opti];
8285 opti++;
8286 if ("activities".equals(cmd) || "a".equals(cmd)) {
8287 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008288 dumpActivitiesLocked(fd, pw, args, opti, true, dumpClient, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008289 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008290 return;
8291 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008292 String[] newArgs;
8293 String name;
8294 if (opti >= args.length) {
8295 name = null;
8296 newArgs = EMPTY_STRING_ARRAY;
8297 } else {
8298 name = args[opti];
8299 opti++;
8300 newArgs = new String[args.length - opti];
8301 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8302 args.length - opti);
8303 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008304 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008305 dumpBroadcastsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008306 }
8307 return;
8308 } else if ("intents".equals(cmd) || "i".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008309 String[] newArgs;
8310 String name;
8311 if (opti >= args.length) {
8312 name = null;
8313 newArgs = EMPTY_STRING_ARRAY;
8314 } else {
8315 name = args[opti];
8316 opti++;
8317 newArgs = new String[args.length - opti];
8318 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8319 args.length - opti);
8320 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008321 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008322 dumpPendingIntentsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008323 }
8324 return;
8325 } else if ("processes".equals(cmd) || "p".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008326 String[] newArgs;
8327 String name;
8328 if (opti >= args.length) {
8329 name = null;
8330 newArgs = EMPTY_STRING_ARRAY;
8331 } else {
8332 name = args[opti];
8333 opti++;
8334 newArgs = new String[args.length - opti];
8335 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8336 args.length - opti);
8337 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008338 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008339 dumpProcessesLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008340 }
8341 return;
Dianne Hackborn287952c2010-09-22 22:34:31 -07008342 } else if ("oom".equals(cmd) || "o".equals(cmd)) {
8343 synchronized (this) {
8344 dumpOomLocked(fd, pw, args, opti, true);
8345 }
8346 return;
Marco Nelissen18cb2872011-11-15 11:19:53 -08008347 } else if ("provider".equals(cmd)) {
8348 String[] newArgs;
8349 String name;
8350 if (opti >= args.length) {
8351 name = null;
8352 newArgs = EMPTY_STRING_ARRAY;
8353 } else {
8354 name = args[opti];
8355 opti++;
8356 newArgs = new String[args.length - opti];
8357 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
8358 }
8359 if (!dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) {
8360 pw.println("No providers match: " + name);
8361 pw.println("Use -h for help.");
8362 }
8363 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008364 } else if ("providers".equals(cmd) || "prov".equals(cmd)) {
8365 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008366 dumpProvidersLocked(fd, pw, args, opti, true, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008367 }
8368 return;
8369 } else if ("service".equals(cmd)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008370 String[] newArgs;
8371 String name;
8372 if (opti >= args.length) {
8373 name = null;
8374 newArgs = EMPTY_STRING_ARRAY;
8375 } else {
8376 name = args[opti];
8377 opti++;
8378 newArgs = new String[args.length - opti];
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008379 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8380 args.length - opti);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008381 }
8382 if (!dumpService(fd, pw, name, newArgs, 0, dumpAll)) {
8383 pw.println("No services match: " + name);
8384 pw.println("Use -h for help.");
8385 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008386 return;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008387 } else if ("package".equals(cmd)) {
8388 String[] newArgs;
8389 if (opti >= args.length) {
8390 pw.println("package: no package name specified");
8391 pw.println("Use -h for help.");
8392 return;
8393 } else {
8394 dumpPackage = args[opti];
8395 opti++;
8396 newArgs = new String[args.length - opti];
8397 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8398 args.length - opti);
8399 args = newArgs;
8400 opti = 0;
8401 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008402 } else if ("services".equals(cmd) || "s".equals(cmd)) {
8403 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008404 dumpServicesLocked(fd, pw, args, opti, true, dumpClient, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008405 }
8406 return;
Dianne Hackborn625ac272010-09-17 18:29:22 -07008407 } else {
8408 // Dumping a single activity?
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008409 if (!dumpActivity(fd, pw, cmd, args, opti, dumpAll)) {
8410 pw.println("Bad activity command, or no activities match: " + cmd);
8411 pw.println("Use -h for help.");
Dianne Hackborn625ac272010-09-17 18:29:22 -07008412 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08008413 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008414 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008415 }
8416
8417 // No piece of data specified, dump everything.
8418 synchronized (this) {
8419 boolean needSep;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008420 needSep = dumpPendingIntentsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008421 if (needSep) {
8422 pw.println(" ");
8423 }
8424 if (dumpAll) {
8425 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008426 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008427 needSep = dumpBroadcastsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008428 if (needSep) {
8429 pw.println(" ");
8430 }
8431 if (dumpAll) {
8432 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008433 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008434 needSep = dumpProvidersLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008435 if (needSep) {
8436 pw.println(" ");
8437 }
8438 if (dumpAll) {
8439 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008440 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008441 needSep = dumpServicesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008442 if (needSep) {
8443 pw.println(" ");
8444 }
8445 if (dumpAll) {
8446 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008447 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008448 needSep = dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008449 if (needSep) {
8450 pw.println(" ");
8451 }
8452 if (dumpAll) {
8453 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008454 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008455 dumpProcessesLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008456 }
8457 }
8458
8459 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008460 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008461 pw.println("ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
8462 pw.println(" Main stack:");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008463 dumpHistoryList(fd, pw, mMainStack.mHistory, " ", "Hist", true, !dumpAll, dumpClient,
8464 dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008465 pw.println(" ");
8466 pw.println(" Running activities (most recent first):");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008467 dumpHistoryList(fd, pw, mMainStack.mLRUActivities, " ", "Run", false, !dumpAll, false,
8468 dumpPackage);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008469 if (mMainStack.mWaitingVisibleActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008470 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008471 pw.println(" Activities waiting for another to become visible:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008472 dumpHistoryList(fd, pw, mMainStack.mWaitingVisibleActivities, " ", "Wait", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008473 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008474 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008475 if (mMainStack.mStoppingActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008476 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008477 pw.println(" Activities waiting to stop:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008478 dumpHistoryList(fd, pw, mMainStack.mStoppingActivities, " ", "Stop", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008479 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008480 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008481 if (mMainStack.mGoingToSleepActivities.size() > 0) {
8482 pw.println(" ");
8483 pw.println(" Activities waiting to sleep:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008484 dumpHistoryList(fd, pw, mMainStack.mGoingToSleepActivities, " ", "Sleep", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008485 !dumpAll, false, dumpPackage);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008486 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008487 if (mMainStack.mFinishingActivities.size() > 0) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008488 pw.println(" ");
8489 pw.println(" Activities waiting to finish:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008490 dumpHistoryList(fd, pw, mMainStack.mFinishingActivities, " ", "Fin", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008491 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008492 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008493
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008494 pw.println(" ");
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08008495 if (mMainStack.mPausingActivity != null) {
8496 pw.println(" mPausingActivity: " + mMainStack.mPausingActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008497 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008498 pw.println(" mResumedActivity: " + mMainStack.mResumedActivity);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008499 pw.println(" mFocusedActivity: " + mFocusedActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008500 if (dumpAll) {
8501 pw.println(" mLastPausedActivity: " + mMainStack.mLastPausedActivity);
8502 pw.println(" mSleepTimeout: " + mMainStack.mSleepTimeout);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07008503 pw.println(" mDismissKeyguardOnNextActivity: "
8504 + mMainStack.mDismissKeyguardOnNextActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008505 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008506
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008507 if (mRecentTasks.size() > 0) {
8508 pw.println();
8509 pw.println(" Recent tasks:");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008510
8511 final int N = mRecentTasks.size();
8512 for (int i=0; i<N; i++) {
8513 TaskRecord tr = mRecentTasks.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008514 if (dumpPackage != null) {
8515 if (tr.realActivity == null ||
8516 !dumpPackage.equals(tr.realActivity)) {
8517 continue;
8518 }
8519 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008520 pw.print(" * Recent #"); pw.print(i); pw.print(": ");
8521 pw.println(tr);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008522 if (dumpAll) {
8523 mRecentTasks.get(i).dump(pw, " ");
8524 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008525 }
8526 }
8527
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008528 if (dumpAll) {
8529 pw.println(" ");
8530 pw.println(" mCurTask: " + mCurTask);
8531 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008532
8533 return true;
8534 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008535
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008536 boolean dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008537 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008538 boolean needSep = false;
8539 int numPers = 0;
8540
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008541 pw.println("ACTIVITY MANAGER RUNNING PROCESSES (dumpsys activity processes)");
8542
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008543 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008544 for (SparseArray<ProcessRecord> procs : mProcessNames.getMap().values()) {
8545 final int NA = procs.size();
8546 for (int ia=0; ia<NA; ia++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008547 ProcessRecord r = procs.valueAt(ia);
8548 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8549 continue;
8550 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008551 if (!needSep) {
8552 pw.println(" All known processes:");
8553 needSep = true;
8554 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008555 pw.print(r.persistent ? " *PERS*" : " *APP*");
8556 pw.print(" UID "); pw.print(procs.keyAt(ia));
8557 pw.print(" "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008558 r.dump(pw, " ");
8559 if (r.persistent) {
8560 numPers++;
8561 }
8562 }
8563 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008564 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008565
8566 if (mIsolatedProcesses.size() > 0) {
8567 if (needSep) pw.println(" ");
8568 needSep = true;
8569 pw.println(" Isolated process list (sorted by uid):");
8570 for (int i=0; i<mIsolatedProcesses.size(); i++) {
8571 ProcessRecord r = mIsolatedProcesses.valueAt(i);
8572 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8573 continue;
8574 }
8575 pw.println(String.format("%sIsolated #%2d: %s",
8576 " ", i, r.toString()));
8577 }
8578 }
8579
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008580 if (mLruProcesses.size() > 0) {
8581 if (needSep) pw.println(" ");
8582 needSep = true;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008583 pw.println(" Process LRU list (sorted by oom_adj):");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008584 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008585 "Proc", "PERS", false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008586 needSep = true;
8587 }
8588
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008589 if (dumpAll) {
8590 synchronized (mPidsSelfLocked) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008591 boolean printed = false;
8592 for (int i=0; i<mPidsSelfLocked.size(); i++) {
8593 ProcessRecord r = mPidsSelfLocked.valueAt(i);
8594 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8595 continue;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008596 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008597 if (!printed) {
8598 if (needSep) pw.println(" ");
8599 needSep = true;
8600 pw.println(" PID mappings:");
8601 printed = true;
8602 }
8603 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i));
8604 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008605 }
8606 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008607 }
8608
8609 if (mForegroundProcesses.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008610 synchronized (mPidsSelfLocked) {
8611 boolean printed = false;
8612 for (int i=0; i<mForegroundProcesses.size(); i++) {
8613 ProcessRecord r = mPidsSelfLocked.get(
8614 mForegroundProcesses.valueAt(i).pid);
8615 if (dumpPackage != null && (r == null
8616 || !dumpPackage.equals(r.info.packageName))) {
8617 continue;
8618 }
8619 if (!printed) {
8620 if (needSep) pw.println(" ");
8621 needSep = true;
8622 pw.println(" Foreground Processes:");
8623 printed = true;
8624 }
8625 pw.print(" PID #"); pw.print(mForegroundProcesses.keyAt(i));
8626 pw.print(": "); pw.println(mForegroundProcesses.valueAt(i));
8627 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008628 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008629 }
8630
8631 if (mPersistentStartingProcesses.size() > 0) {
8632 if (needSep) pw.println(" ");
8633 needSep = true;
8634 pw.println(" Persisent processes that are starting:");
8635 dumpProcessList(pw, this, mPersistentStartingProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008636 "Starting Norm", "Restarting PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008637 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008638
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008639 if (mRemovedProcesses.size() > 0) {
8640 if (needSep) pw.println(" ");
8641 needSep = true;
8642 pw.println(" Processes that are being removed:");
8643 dumpProcessList(pw, this, mRemovedProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008644 "Removed Norm", "Removed PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008645 }
8646
8647 if (mProcessesOnHold.size() > 0) {
8648 if (needSep) pw.println(" ");
8649 needSep = true;
8650 pw.println(" Processes that are on old until the system is ready:");
8651 dumpProcessList(pw, this, mProcessesOnHold, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008652 "OnHold Norm", "OnHold PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008653 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008654
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008655 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008656
8657 if (mProcessCrashTimes.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008658 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008659 long now = SystemClock.uptimeMillis();
8660 for (Map.Entry<String, SparseArray<Long>> procs
8661 : mProcessCrashTimes.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008662 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008663 SparseArray<Long> uids = procs.getValue();
8664 final int N = uids.size();
8665 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008666 int puid = uids.keyAt(i);
8667 ProcessRecord r = mProcessNames.get(pname, puid);
8668 if (dumpPackage != null && (r == null
8669 || !dumpPackage.equals(r.info.packageName))) {
8670 continue;
8671 }
8672 if (!printed) {
8673 if (needSep) pw.println(" ");
8674 needSep = true;
8675 pw.println(" Time since processes crashed:");
8676 printed = true;
8677 }
8678 pw.print(" Process "); pw.print(pname);
8679 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008680 pw.print(": last crashed ");
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008681 TimeUtils.formatDuration(now-uids.valueAt(i), pw);
8682 pw.println(" ago");
Dianne Hackbornfd12af42009-08-27 00:44:33 -07008683 }
8684 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008685 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008686
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008687 if (mBadProcesses.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008688 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008689 for (Map.Entry<String, SparseArray<Long>> procs
8690 : mBadProcesses.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008691 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008692 SparseArray<Long> uids = procs.getValue();
8693 final int N = uids.size();
8694 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008695 int puid = uids.keyAt(i);
8696 ProcessRecord r = mProcessNames.get(pname, puid);
8697 if (dumpPackage != null && (r == null
8698 || !dumpPackage.equals(r.info.packageName))) {
8699 continue;
8700 }
8701 if (!printed) {
8702 if (needSep) pw.println(" ");
8703 needSep = true;
8704 pw.println(" Bad processes:");
8705 }
8706 pw.print(" Bad process "); pw.print(pname);
8707 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008708 pw.print(": crashed at time ");
8709 pw.println(uids.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008710 }
8711 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008712 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008713
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008714 pw.println();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008715 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07008716 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn50685602011-12-01 12:23:37 -08008717 if (dumpAll) {
8718 StringBuilder sb = new StringBuilder(128);
8719 sb.append(" mPreviousProcessVisibleTime: ");
8720 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
8721 pw.println(sb);
8722 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07008723 if (mHeavyWeightProcess != null) {
8724 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
8725 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008726 pw.println(" mConfiguration: " + mConfiguration);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008727 if (dumpAll) {
8728 pw.println(" mConfigWillChange: " + mMainStack.mConfigWillChange);
Dianne Hackborn3d0724d2011-05-12 15:39:41 -07008729 if (mCompatModePackages.getPackages().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008730 boolean printed = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07008731 for (Map.Entry<String, Integer> entry
8732 : mCompatModePackages.getPackages().entrySet()) {
8733 String pkg = entry.getKey();
8734 int mode = entry.getValue();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008735 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
8736 continue;
8737 }
8738 if (!printed) {
8739 pw.println(" mScreenCompatPackages:");
8740 printed = true;
8741 }
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07008742 pw.print(" "); pw.print(pkg); pw.print(": ");
8743 pw.print(mode); pw.println();
8744 }
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07008745 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008746 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008747 pw.println(" mSleeping=" + mSleeping + " mShuttingDown=" + mShuttingDown);
8748 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
8749 || mOrigWaitForDebugger) {
8750 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp
8751 + " mDebugTransient=" + mDebugTransient
8752 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger);
8753 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08008754 if (mOpenGlTraceApp != null) {
8755 pw.println(" mOpenGlTraceApp=" + mOpenGlTraceApp);
8756 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07008757 if (mProfileApp != null || mProfileProc != null || mProfileFile != null
8758 || mProfileFd != null) {
8759 pw.println(" mProfileApp=" + mProfileApp + " mProfileProc=" + mProfileProc);
8760 pw.println(" mProfileFile=" + mProfileFile + " mProfileFd=" + mProfileFd);
8761 pw.println(" mProfileType=" + mProfileType + " mAutoStopProfiler="
8762 + mAutoStopProfiler);
8763 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008764 if (mAlwaysFinishActivities || mController != null) {
8765 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities
8766 + " mController=" + mController);
8767 }
8768 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008769 pw.println(" Total persistent processes: " + numPers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008770 pw.println(" mStartRunning=" + mStartRunning
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07008771 + " mProcessesReady=" + mProcessesReady
8772 + " mSystemReady=" + mSystemReady);
8773 pw.println(" mBooting=" + mBooting
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008774 + " mBooted=" + mBooted
8775 + " mFactoryTest=" + mFactoryTest);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008776 pw.print(" mLastPowerCheckRealtime=");
8777 TimeUtils.formatDuration(mLastPowerCheckRealtime, pw);
8778 pw.println("");
8779 pw.print(" mLastPowerCheckUptime=");
8780 TimeUtils.formatDuration(mLastPowerCheckUptime, pw);
8781 pw.println("");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008782 pw.println(" mGoingToSleep=" + mMainStack.mGoingToSleep);
8783 pw.println(" mLaunchingActivity=" + mMainStack.mLaunchingActivity);
Dianne Hackborn906497c2010-05-10 15:57:38 -07008784 pw.println(" mAdjSeq=" + mAdjSeq + " mLruSeq=" + mLruSeq);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008785 pw.println(" mNumServiceProcs=" + mNumServiceProcs
8786 + " mNewNumServiceProcs=" + mNewNumServiceProcs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008787 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008788
8789 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008790 }
8791
Dianne Hackborn287952c2010-09-22 22:34:31 -07008792 boolean dumpProcessesToGc(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008793 int opti, boolean needSep, boolean dumpAll, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07008794 if (mProcessesToGc.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008795 boolean printed = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -07008796 long now = SystemClock.uptimeMillis();
8797 for (int i=0; i<mProcessesToGc.size(); i++) {
8798 ProcessRecord proc = mProcessesToGc.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008799 if (dumpPackage != null && !dumpPackage.equals(proc.info.packageName)) {
8800 continue;
8801 }
8802 if (!printed) {
8803 if (needSep) pw.println(" ");
8804 needSep = true;
8805 pw.println(" Processes that are waiting to GC:");
8806 printed = true;
8807 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008808 pw.print(" Process "); pw.println(proc);
8809 pw.print(" lowMem="); pw.print(proc.reportLowMemory);
8810 pw.print(", last gced=");
8811 pw.print(now-proc.lastRequestedGc);
8812 pw.print(" ms ago, last lowMem=");
8813 pw.print(now-proc.lastLowMemory);
8814 pw.println(" ms ago");
8815
8816 }
8817 }
8818 return needSep;
8819 }
8820
8821 boolean dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args,
8822 int opti, boolean dumpAll) {
8823 boolean needSep = false;
8824
8825 if (mLruProcesses.size() > 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07008826 if (needSep) pw.println(" ");
8827 needSep = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -07008828 pw.println(" OOM levels:");
Dianne Hackborn7d608422011-08-07 16:24:18 -07008829 pw.print(" SYSTEM_ADJ: "); pw.println(ProcessList.SYSTEM_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008830 pw.print(" PERSISTENT_PROC_ADJ: "); pw.println(ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07008831 pw.print(" FOREGROUND_APP_ADJ: "); pw.println(ProcessList.FOREGROUND_APP_ADJ);
8832 pw.print(" VISIBLE_APP_ADJ: "); pw.println(ProcessList.VISIBLE_APP_ADJ);
8833 pw.print(" PERCEPTIBLE_APP_ADJ: "); pw.println(ProcessList.PERCEPTIBLE_APP_ADJ);
8834 pw.print(" HEAVY_WEIGHT_APP_ADJ: "); pw.println(ProcessList.HEAVY_WEIGHT_APP_ADJ);
8835 pw.print(" BACKUP_APP_ADJ: "); pw.println(ProcessList.BACKUP_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008836 pw.print(" SERVICE_ADJ: "); pw.println(ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07008837 pw.print(" HOME_APP_ADJ: "); pw.println(ProcessList.HOME_APP_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07008838 pw.print(" PREVIOUS_APP_ADJ: "); pw.println(ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008839 pw.print(" SERVICE_B_ADJ: "); pw.println(ProcessList.SERVICE_B_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07008840 pw.print(" HIDDEN_APP_MIN_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008841 pw.print(" HIDDEN_APP_MAX_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MAX_ADJ);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07008842
8843 if (needSep) pw.println(" ");
8844 needSep = true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07008845 pw.println(" Process OOM control:");
Dianne Hackborn905577f2011-09-07 18:31:28 -07008846 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008847 "Proc", "PERS", true, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008848 needSep = true;
8849 }
8850
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008851 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008852
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008853 pw.println();
Dianne Hackborn287952c2010-09-22 22:34:31 -07008854 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07008855 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008856 if (mHeavyWeightProcess != null) {
8857 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
8858 }
8859
8860 return true;
8861 }
8862
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008863 /**
8864 * There are three ways to call this:
8865 * - no service specified: dump all the services
8866 * - a flattened component name that matched an existing service was specified as the
8867 * first arg: dump that one service
8868 * - the first arg isn't the flattened component name of an existing service:
8869 * dump all services whose component contains the first arg as a substring
8870 */
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008871 protected boolean dumpService(FileDescriptor fd, PrintWriter pw, String name, String[] args,
8872 int opti, boolean dumpAll) {
8873 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008874
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008875 if ("all".equals(name)) {
Dianne Hackborn14bfa392010-07-24 19:58:06 -07008876 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07008877 try {
8878 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
8879 for (UserInfo user : users) {
8880 for (ServiceRecord r1 : mServiceMap.getAllServices(user.id)) {
8881 services.add(r1);
8882 }
8883 }
8884 } catch (RemoteException re) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008885 }
8886 }
8887 } else {
8888 ComponentName componentName = name != null
8889 ? ComponentName.unflattenFromString(name) : null;
8890 int objectId = 0;
8891 if (componentName == null) {
8892 // Not a '/' separated full component name; maybe an object ID?
8893 try {
8894 objectId = Integer.parseInt(name, 16);
8895 name = null;
8896 componentName = null;
8897 } catch (RuntimeException e) {
8898 }
8899 }
8900
8901 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07008902 try {
8903 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
8904 for (UserInfo user : users) {
8905 for (ServiceRecord r1 : mServiceMap.getAllServices(user.id)) {
8906 if (componentName != null) {
8907 if (r1.name.equals(componentName)) {
8908 services.add(r1);
8909 }
8910 } else if (name != null) {
8911 if (r1.name.flattenToString().contains(name)) {
8912 services.add(r1);
8913 }
8914 } else if (System.identityHashCode(r1) == objectId) {
8915 services.add(r1);
8916 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008917 }
Dianne Hackborn14bfa392010-07-24 19:58:06 -07008918 }
Amith Yamasani742a6712011-05-04 14:49:28 -07008919 } catch (RemoteException re) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008920 }
8921 }
8922 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008923
8924 if (services.size() <= 0) {
8925 return false;
8926 }
8927
8928 boolean needSep = false;
8929 for (int i=0; i<services.size(); i++) {
8930 if (needSep) {
8931 pw.println();
8932 }
8933 needSep = true;
8934 dumpService("", fd, pw, services.get(i), args, dumpAll);
8935 }
8936 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008937 }
8938
8939 /**
8940 * Invokes IApplicationThread.dumpService() on the thread of the specified service if
8941 * there is a thread associated with the service.
8942 */
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008943 private void dumpService(String prefix, FileDescriptor fd, PrintWriter pw,
8944 final ServiceRecord r, String[] args, boolean dumpAll) {
8945 String innerPrefix = prefix + " ";
8946 synchronized (this) {
8947 pw.print(prefix); pw.print("SERVICE ");
8948 pw.print(r.shortName); pw.print(" ");
8949 pw.print(Integer.toHexString(System.identityHashCode(r)));
8950 pw.print(" pid=");
8951 if (r.app != null) pw.println(r.app.pid);
8952 else pw.println("(not running)");
8953 if (dumpAll) {
8954 r.dump(pw, innerPrefix);
8955 }
8956 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008957 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008958 pw.print(prefix); pw.println(" Client:");
8959 pw.flush();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008960 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008961 TransferPipe tp = new TransferPipe();
8962 try {
8963 r.app.thread.dumpService(tp.getWriteFd().getFileDescriptor(), r, args);
8964 tp.setBufferPrefix(prefix + " ");
8965 tp.go(fd);
8966 } finally {
8967 tp.kill();
8968 }
8969 } catch (IOException e) {
8970 pw.println(prefix + " Failure while dumping the service: " + e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008971 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008972 pw.println(prefix + " Got a RemoteException while dumping the service");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008973 }
8974 }
8975 }
8976
Marco Nelissen18cb2872011-11-15 11:19:53 -08008977 /**
8978 * There are three ways to call this:
8979 * - no provider specified: dump all the providers
8980 * - a flattened component name that matched an existing provider was specified as the
8981 * first arg: dump that one provider
8982 * - the first arg isn't the flattened component name of an existing provider:
8983 * dump all providers whose component contains the first arg as a substring
8984 */
8985 protected boolean dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args,
8986 int opti, boolean dumpAll) {
Marco Nelissende7408c2012-02-08 14:57:38 -08008987 return mProviderMap.dumpProvider(fd, pw, name, args, opti, dumpAll);
Marco Nelissen18cb2872011-11-15 11:19:53 -08008988 }
8989
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008990 static class ItemMatcher {
8991 ArrayList<ComponentName> components;
8992 ArrayList<String> strings;
8993 ArrayList<Integer> objects;
8994 boolean all;
8995
8996 ItemMatcher() {
8997 all = true;
8998 }
8999
9000 void build(String name) {
9001 ComponentName componentName = ComponentName.unflattenFromString(name);
9002 if (componentName != null) {
9003 if (components == null) {
9004 components = new ArrayList<ComponentName>();
9005 }
9006 components.add(componentName);
9007 all = false;
9008 } else {
9009 int objectId = 0;
9010 // Not a '/' separated full component name; maybe an object ID?
9011 try {
9012 objectId = Integer.parseInt(name, 16);
9013 if (objects == null) {
9014 objects = new ArrayList<Integer>();
9015 }
9016 objects.add(objectId);
9017 all = false;
9018 } catch (RuntimeException e) {
9019 // Not an integer; just do string match.
9020 if (strings == null) {
9021 strings = new ArrayList<String>();
9022 }
9023 strings.add(name);
9024 all = false;
9025 }
9026 }
9027 }
9028
9029 int build(String[] args, int opti) {
9030 for (; opti<args.length; opti++) {
9031 String name = args[opti];
9032 if ("--".equals(name)) {
9033 return opti+1;
9034 }
9035 build(name);
9036 }
9037 return opti;
9038 }
9039
9040 boolean match(Object object, ComponentName comp) {
9041 if (all) {
9042 return true;
9043 }
9044 if (components != null) {
9045 for (int i=0; i<components.size(); i++) {
9046 if (components.get(i).equals(comp)) {
9047 return true;
9048 }
9049 }
9050 }
9051 if (objects != null) {
9052 for (int i=0; i<objects.size(); i++) {
9053 if (System.identityHashCode(object) == objects.get(i)) {
9054 return true;
9055 }
9056 }
9057 }
9058 if (strings != null) {
9059 String flat = comp.flattenToString();
9060 for (int i=0; i<strings.size(); i++) {
9061 if (flat.contains(strings.get(i))) {
9062 return true;
9063 }
9064 }
9065 }
9066 return false;
9067 }
9068 }
9069
Dianne Hackborn625ac272010-09-17 18:29:22 -07009070 /**
9071 * There are three things that cmd can be:
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009072 * - a flattened component name that matches an existing activity
Dianne Hackborn625ac272010-09-17 18:29:22 -07009073 * - the cmd arg isn't the flattened component name of an existing activity:
9074 * dump all activity whose component contains the cmd as a substring
9075 * - A hex number of the ActivityRecord object instance.
9076 */
9077 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9078 int opti, boolean dumpAll) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009079 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009080
9081 if ("all".equals(name)) {
9082 synchronized (this) {
9083 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009084 activities.add(r1);
9085 }
9086 }
Dianne Hackbornf9302322011-06-14 18:36:14 -07009087 } else if ("top".equals(name)) {
9088 synchronized (this) {
9089 final int N = mMainStack.mHistory.size();
9090 if (N > 0) {
9091 activities.add((ActivityRecord)mMainStack.mHistory.get(N-1));
9092 }
9093 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009094 } else {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009095 ItemMatcher matcher = new ItemMatcher();
9096 matcher.build(name);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009097
9098 synchronized (this) {
9099 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009100 if (matcher.match(r1, r1.intent.getComponent())) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009101 activities.add(r1);
9102 }
9103 }
9104 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009105 }
9106
9107 if (activities.size() <= 0) {
9108 return false;
9109 }
9110
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009111 String[] newArgs = new String[args.length - opti];
9112 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
9113
Dianne Hackborn30d71892010-12-11 10:37:55 -08009114 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009115 boolean needSep = false;
Dianne Hackborn30d71892010-12-11 10:37:55 -08009116 for (int i=activities.size()-1; i>=0; i--) {
9117 ActivityRecord r = (ActivityRecord)activities.get(i);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009118 if (needSep) {
9119 pw.println();
9120 }
9121 needSep = true;
9122 synchronized (this) {
9123 if (lastTask != r.task) {
9124 lastTask = r.task;
9125 pw.print("TASK "); pw.print(lastTask.affinity);
9126 pw.print(" id="); pw.println(lastTask.taskId);
9127 if (dumpAll) {
9128 lastTask.dump(pw, " ");
9129 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08009130 }
9131 }
9132 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009133 }
9134 return true;
9135 }
9136
9137 /**
9138 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
9139 * there is a thread associated with the activity.
9140 */
Dianne Hackborn30d71892010-12-11 10:37:55 -08009141 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009142 final ActivityRecord r, String[] args, boolean dumpAll) {
9143 String innerPrefix = prefix + " ";
Dianne Hackborn30d71892010-12-11 10:37:55 -08009144 synchronized (this) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009145 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
9146 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
9147 pw.print(" pid=");
Dianne Hackborn30d71892010-12-11 10:37:55 -08009148 if (r.app != null) pw.println(r.app.pid);
9149 else pw.println("(not running)");
9150 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009151 r.dump(pw, innerPrefix);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009152 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009153 }
9154 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009155 // flush anything that is already in the PrintWriter since the thread is going
9156 // to write to the file descriptor directly
9157 pw.flush();
Dianne Hackborn625ac272010-09-17 18:29:22 -07009158 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009159 TransferPipe tp = new TransferPipe();
9160 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009161 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9162 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009163 tp.go(fd);
9164 } finally {
9165 tp.kill();
9166 }
9167 } catch (IOException e) {
9168 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009169 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009170 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
Dianne Hackborn625ac272010-09-17 18:29:22 -07009171 }
9172 }
9173 }
9174
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009175 boolean dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009176 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009177 boolean needSep = false;
9178
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009179 pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009180 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009181 if (mRegisteredReceivers.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009182 boolean printed = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009183 Iterator it = mRegisteredReceivers.values().iterator();
9184 while (it.hasNext()) {
9185 ReceiverList r = (ReceiverList)it.next();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009186 if (dumpPackage != null && (r.app == null ||
9187 !dumpPackage.equals(r.app.info.packageName))) {
9188 continue;
9189 }
9190 if (!printed) {
9191 pw.println(" Registered Receivers:");
9192 needSep = true;
9193 printed = true;
9194 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009195 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009196 r.dump(pw, " ");
9197 }
9198 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009199
9200 if (mReceiverResolver.dump(pw, needSep ?
9201 "\n Receiver Resolver Table:" : " Receiver Resolver Table:",
9202 " ", dumpPackage, false)) {
9203 needSep = true;
9204 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009205 }
Christopher Tatef46723b2012-01-26 14:19:24 -08009206
9207 for (BroadcastQueue q : mBroadcastQueues) {
9208 needSep = q.dumpLocked(fd, pw, args, opti, dumpAll, dumpPackage, needSep);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009209 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009210
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009211 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009212
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009213 if (mStickyBroadcasts != null && dumpPackage == null) {
9214 if (needSep) {
9215 pw.println();
9216 }
9217 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009218 pw.println(" Sticky broadcasts:");
9219 StringBuilder sb = new StringBuilder(128);
9220 for (Map.Entry<String, ArrayList<Intent>> ent
9221 : mStickyBroadcasts.entrySet()) {
9222 pw.print(" * Sticky action "); pw.print(ent.getKey());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009223 if (dumpAll) {
9224 pw.println(":");
9225 ArrayList<Intent> intents = ent.getValue();
9226 final int N = intents.size();
9227 for (int i=0; i<N; i++) {
9228 sb.setLength(0);
9229 sb.append(" Intent: ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009230 intents.get(i).toShortString(sb, false, true, false, false);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009231 pw.println(sb.toString());
9232 Bundle bundle = intents.get(i).getExtras();
9233 if (bundle != null) {
9234 pw.print(" ");
9235 pw.println(bundle.toString());
9236 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009237 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009238 } else {
9239 pw.println("");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009240 }
9241 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009242 needSep = true;
9243 }
9244
9245 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009246 pw.println();
Christopher Tatef46723b2012-01-26 14:19:24 -08009247 for (BroadcastQueue queue : mBroadcastQueues) {
9248 pw.println(" mBroadcastsScheduled [" + queue.mQueueName + "]="
9249 + queue.mBroadcastsScheduled);
9250 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009251 pw.println(" mHandler:");
9252 mHandler.dump(new PrintWriterPrinter(pw), " ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009253 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009254 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009255
9256 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009257 }
9258
Marco Nelissen18cb2872011-11-15 11:19:53 -08009259 /**
9260 * Prints a list of ServiceRecords (dumpsys activity services)
9261 */
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009262 boolean dumpServicesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009263 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009264 boolean needSep = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009265
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009266 ItemMatcher matcher = new ItemMatcher();
9267 matcher.build(args, opti);
9268
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009269 pw.println("ACTIVITY MANAGER SERVICES (dumpsys activity services)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009270 try {
9271 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
9272 for (UserInfo user : users) {
9273 if (mServiceMap.getAllServices(user.id).size() > 0) {
9274 boolean printed = false;
9275 long nowReal = SystemClock.elapsedRealtime();
9276 Iterator<ServiceRecord> it = mServiceMap.getAllServices(
9277 user.id).iterator();
9278 needSep = false;
9279 while (it.hasNext()) {
9280 ServiceRecord r = it.next();
9281 if (!matcher.match(r, r.name)) {
9282 continue;
9283 }
9284 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9285 continue;
9286 }
9287 if (!printed) {
9288 pw.println(" Active services:");
9289 printed = true;
9290 }
9291 if (needSep) {
9292 pw.println();
9293 }
9294 pw.print(" * ");
9295 pw.println(r);
9296 if (dumpAll) {
9297 r.dump(pw, " ");
9298 needSep = true;
9299 } else {
9300 pw.print(" app=");
9301 pw.println(r.app);
9302 pw.print(" created=");
9303 TimeUtils.formatDuration(r.createTime, nowReal, pw);
9304 pw.print(" started=");
9305 pw.print(r.startRequested);
9306 pw.print(" connections=");
9307 pw.println(r.connections.size());
9308 if (r.connections.size() > 0) {
9309 pw.println(" Connections:");
9310 for (ArrayList<ConnectionRecord> clist : r.connections.values()) {
9311 for (int i = 0; i < clist.size(); i++) {
9312 ConnectionRecord conn = clist.get(i);
9313 pw.print(" ");
9314 pw.print(conn.binding.intent.intent.getIntent()
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009315 .toShortString(false, false, false, false));
Amith Yamasani742a6712011-05-04 14:49:28 -07009316 pw.print(" -> ");
9317 ProcessRecord proc = conn.binding.client;
9318 pw.println(proc != null ? proc.toShortString() : "null");
9319 }
9320 }
Dianne Hackborn8ec8d412011-11-14 18:27:24 -08009321 }
9322 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009323 if (dumpClient && r.app != null && r.app.thread != null) {
9324 pw.println(" Client:");
9325 pw.flush();
9326 try {
9327 TransferPipe tp = new TransferPipe();
9328 try {
9329 r.app.thread.dumpService(tp.getWriteFd().getFileDescriptor(),
9330 r, args);
9331 tp.setBufferPrefix(" ");
9332 // Short timeout, since blocking here can
9333 // deadlock with the application.
9334 tp.go(fd, 2000);
9335 } finally {
9336 tp.kill();
9337 }
9338 } catch (IOException e) {
9339 pw.println(" Failure while dumping the service: " + e);
9340 } catch (RemoteException e) {
9341 pw.println(" Got a RemoteException while dumping the service");
9342 }
9343 needSep = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009344 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009345 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009346 needSep = printed;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009347 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009348 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009349 } catch (RemoteException re) {
9350
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009351 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009352
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009353 if (mPendingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009354 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009355 for (int i=0; i<mPendingServices.size(); i++) {
9356 ServiceRecord r = mPendingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009357 if (!matcher.match(r, r.name)) {
9358 continue;
9359 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009360 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9361 continue;
9362 }
9363 if (!printed) {
9364 if (needSep) pw.println(" ");
9365 needSep = true;
9366 pw.println(" Pending services:");
9367 printed = true;
9368 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009369 pw.print(" * Pending "); pw.println(r);
9370 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009371 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009372 needSep = true;
9373 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009374
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009375 if (mRestartingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009376 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009377 for (int i=0; i<mRestartingServices.size(); i++) {
9378 ServiceRecord r = mRestartingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009379 if (!matcher.match(r, r.name)) {
9380 continue;
9381 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009382 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9383 continue;
9384 }
9385 if (!printed) {
9386 if (needSep) pw.println(" ");
9387 needSep = true;
9388 pw.println(" Restarting services:");
9389 printed = true;
9390 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009391 pw.print(" * Restarting "); pw.println(r);
9392 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009393 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009394 needSep = true;
9395 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009396
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009397 if (mStoppingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009398 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009399 for (int i=0; i<mStoppingServices.size(); i++) {
9400 ServiceRecord r = mStoppingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009401 if (!matcher.match(r, r.name)) {
9402 continue;
9403 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009404 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9405 continue;
9406 }
9407 if (!printed) {
9408 if (needSep) pw.println(" ");
9409 needSep = true;
9410 pw.println(" Stopping services:");
9411 printed = true;
9412 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009413 pw.print(" * Stopping "); pw.println(r);
9414 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009415 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009416 needSep = true;
9417 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009418
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009419 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009420 if (mServiceConnections.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009421 boolean printed = false;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009422 Iterator<ArrayList<ConnectionRecord>> it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009423 = mServiceConnections.values().iterator();
9424 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009425 ArrayList<ConnectionRecord> r = it.next();
9426 for (int i=0; i<r.size(); i++) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009427 ConnectionRecord cr = r.get(i);
9428 if (!matcher.match(cr.binding.service, cr.binding.service.name)) {
9429 continue;
9430 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009431 if (dumpPackage != null && (cr.binding.client == null
9432 || !dumpPackage.equals(cr.binding.client.info.packageName))) {
9433 continue;
9434 }
9435 if (!printed) {
9436 if (needSep) pw.println(" ");
9437 needSep = true;
9438 pw.println(" Connection bindings to services:");
9439 printed = true;
9440 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009441 pw.print(" * "); pw.println(cr);
9442 cr.dump(pw, " ");
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009443 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009444 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009445 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009446 }
9447 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009448
9449 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009450 }
9451
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009452 boolean dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009453 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07009454 boolean needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009455
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009456 ItemMatcher matcher = new ItemMatcher();
9457 matcher.build(args, opti);
9458
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009459 pw.println("ACTIVITY MANAGER CONTENT PROVIDERS (dumpsys activity providers)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009460
9461 mProviderMap.dumpProvidersLocked(pw, dumpAll);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009462
9463 if (mLaunchingProviders.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009464 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009465 for (int i=mLaunchingProviders.size()-1; i>=0; i--) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009466 ContentProviderRecord r = mLaunchingProviders.get(i);
9467 if (dumpPackage != null && !dumpPackage.equals(r.name.getPackageName())) {
9468 continue;
9469 }
9470 if (!printed) {
9471 if (needSep) pw.println(" ");
9472 needSep = true;
9473 pw.println(" Launching content providers:");
9474 printed = true;
9475 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009476 pw.print(" Launching #"); pw.print(i); pw.print(": ");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009477 pw.println(r);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009478 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009479 }
9480
9481 if (mGrantedUriPermissions.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009482 if (needSep) pw.println();
9483 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009484 pw.println("Granted Uri Permissions:");
9485 for (int i=0; i<mGrantedUriPermissions.size(); i++) {
9486 int uid = mGrantedUriPermissions.keyAt(i);
9487 HashMap<Uri, UriPermission> perms
9488 = mGrantedUriPermissions.valueAt(i);
9489 pw.print(" * UID "); pw.print(uid);
9490 pw.println(" holds:");
9491 for (UriPermission perm : perms.values()) {
9492 pw.print(" "); pw.println(perm);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009493 if (dumpAll) {
9494 perm.dump(pw, " ");
9495 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009496 }
9497 }
9498 needSep = true;
9499 }
9500
9501 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009502 }
9503
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009504 boolean dumpPendingIntentsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009505 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009506 boolean needSep = false;
9507
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009508 if (mIntentSenderRecords.size() > 0) {
9509 boolean printed = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009510 Iterator<WeakReference<PendingIntentRecord>> it
9511 = mIntentSenderRecords.values().iterator();
9512 while (it.hasNext()) {
9513 WeakReference<PendingIntentRecord> ref = it.next();
9514 PendingIntentRecord rec = ref != null ? ref.get(): null;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009515 if (dumpPackage != null && (rec == null
9516 || !dumpPackage.equals(rec.key.packageName))) {
9517 continue;
9518 }
9519 if (!printed) {
9520 pw.println("ACTIVITY MANAGER PENDING INTENTS (dumpsys activity intents)");
9521 printed = true;
9522 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009523 needSep = true;
9524 if (rec != null) {
9525 pw.print(" * "); pw.println(rec);
9526 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009527 rec.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009528 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009529 } else {
9530 pw.print(" * "); pw.println(ref);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009531 }
9532 }
9533 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009534
9535 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009536 }
9537
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009538 private static final void dumpHistoryList(FileDescriptor fd, PrintWriter pw, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009539 String prefix, String label, boolean complete, boolean brief, boolean client,
9540 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009541 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009542 boolean needNL = false;
9543 final String innerPrefix = prefix + " ";
9544 final String[] args = new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009545 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009546 final ActivityRecord r = (ActivityRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009547 if (dumpPackage != null && !dumpPackage.equals(r.packageName)) {
9548 continue;
9549 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07009550 final boolean full = !brief && (complete || !r.isInHistory());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009551 if (needNL) {
9552 pw.println(" ");
9553 needNL = false;
9554 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009555 if (lastTask != r.task) {
9556 lastTask = r.task;
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009557 pw.print(prefix);
9558 pw.print(full ? "* " : " ");
9559 pw.println(lastTask);
9560 if (full) {
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009561 lastTask.dump(pw, prefix + " ");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009562 } else if (complete) {
9563 // Complete + brief == give a summary. Isn't that obvious?!?
9564 if (lastTask.intent != null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009565 pw.print(prefix); pw.print(" ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009566 pw.println(lastTask.intent.toInsecureStringWithClip());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009567 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009568 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009569 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009570 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label);
9571 pw.print(" #"); pw.print(i); pw.print(": ");
9572 pw.println(r);
9573 if (full) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009574 r.dump(pw, innerPrefix);
9575 } else if (complete) {
9576 // Complete + brief == give a summary. Isn't that obvious?!?
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009577 pw.print(innerPrefix); pw.println(r.intent.toInsecureString());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009578 if (r.app != null) {
9579 pw.print(innerPrefix); pw.println(r.app);
9580 }
9581 }
9582 if (client && r.app != null && r.app.thread != null) {
9583 // flush anything that is already in the PrintWriter since the thread is going
9584 // to write to the file descriptor directly
9585 pw.flush();
9586 try {
9587 TransferPipe tp = new TransferPipe();
9588 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009589 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9590 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009591 // Short timeout, since blocking here can
9592 // deadlock with the application.
9593 tp.go(fd, 2000);
9594 } finally {
9595 tp.kill();
9596 }
9597 } catch (IOException e) {
9598 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
9599 } catch (RemoteException e) {
9600 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
9601 }
9602 needNL = true;
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009603 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009604 }
9605 }
9606
Dianne Hackborn09c916b2009-12-08 14:50:51 -08009607 private static String buildOomTag(String prefix, String space, int val, int base) {
9608 if (val == base) {
9609 if (space == null) return prefix;
9610 return prefix + " ";
9611 }
9612 return prefix + "+" + Integer.toString(val-base);
9613 }
9614
9615 private static final int dumpProcessList(PrintWriter pw,
9616 ActivityManagerService service, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009617 String prefix, String normalLabel, String persistentLabel,
9618 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009619 int numPers = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07009620 final int N = list.size()-1;
9621 for (int i=N; i>=0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009622 ProcessRecord r = (ProcessRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009623 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9624 continue;
9625 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009626 pw.println(String.format("%s%s #%2d: %s",
9627 prefix, (r.persistent ? persistentLabel : normalLabel),
9628 i, r.toString()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009629 if (r.persistent) {
9630 numPers++;
9631 }
9632 }
9633 return numPers;
9634 }
9635
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009636 private static final boolean dumpProcessOomList(PrintWriter pw,
Dianne Hackborn905577f2011-09-07 18:31:28 -07009637 ActivityManagerService service, List<ProcessRecord> origList,
Dianne Hackborn287952c2010-09-22 22:34:31 -07009638 String prefix, String normalLabel, String persistentLabel,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009639 boolean inclDetails, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009640
Dianne Hackborn905577f2011-09-07 18:31:28 -07009641 ArrayList<Pair<ProcessRecord, Integer>> list
9642 = new ArrayList<Pair<ProcessRecord, Integer>>(origList.size());
9643 for (int i=0; i<origList.size(); i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009644 ProcessRecord r = origList.get(i);
9645 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9646 continue;
9647 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07009648 list.add(new Pair<ProcessRecord, Integer>(origList.get(i), i));
9649 }
9650
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009651 if (list.size() <= 0) {
9652 return false;
9653 }
9654
Dianne Hackborn905577f2011-09-07 18:31:28 -07009655 Comparator<Pair<ProcessRecord, Integer>> comparator
9656 = new Comparator<Pair<ProcessRecord, Integer>>() {
9657 @Override
9658 public int compare(Pair<ProcessRecord, Integer> object1,
9659 Pair<ProcessRecord, Integer> object2) {
9660 if (object1.first.setAdj != object2.first.setAdj) {
9661 return object1.first.setAdj > object2.first.setAdj ? -1 : 1;
9662 }
9663 if (object1.second.intValue() != object2.second.intValue()) {
9664 return object1.second.intValue() > object2.second.intValue() ? -1 : 1;
9665 }
9666 return 0;
9667 }
9668 };
9669
9670 Collections.sort(list, comparator);
9671
Dianne Hackborn287952c2010-09-22 22:34:31 -07009672 final long curRealtime = SystemClock.elapsedRealtime();
9673 final long realtimeSince = curRealtime - service.mLastPowerCheckRealtime;
9674 final long curUptime = SystemClock.uptimeMillis();
9675 final long uptimeSince = curUptime - service.mLastPowerCheckUptime;
9676
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009677 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07009678 ProcessRecord r = list.get(i).first;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009679 String oomAdj;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009680 if (r.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07009681 oomAdj = buildOomTag("bak", " ", r.setAdj, ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009682 } else if (r.setAdj >= ProcessList.SERVICE_B_ADJ) {
9683 oomAdj = buildOomTag("svcb ", null, r.setAdj, ProcessList.SERVICE_B_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009684 } else if (r.setAdj >= ProcessList.PREVIOUS_APP_ADJ) {
9685 oomAdj = buildOomTag("prev ", null, r.setAdj, ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009686 } else if (r.setAdj >= ProcessList.HOME_APP_ADJ) {
9687 oomAdj = buildOomTag("home ", null, r.setAdj, ProcessList.HOME_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009688 } else if (r.setAdj >= ProcessList.SERVICE_ADJ) {
9689 oomAdj = buildOomTag("svc ", null, r.setAdj, ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009690 } else if (r.setAdj >= ProcessList.BACKUP_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08009691 oomAdj = buildOomTag("bkup ", null, r.setAdj, ProcessList.BACKUP_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009692 } else if (r.setAdj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
9693 oomAdj = buildOomTag("hvy ", null, r.setAdj, ProcessList.HEAVY_WEIGHT_APP_ADJ);
9694 } else if (r.setAdj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
9695 oomAdj = buildOomTag("prcp ", null, r.setAdj, ProcessList.PERCEPTIBLE_APP_ADJ);
9696 } else if (r.setAdj >= ProcessList.VISIBLE_APP_ADJ) {
9697 oomAdj = buildOomTag("vis ", null, r.setAdj, ProcessList.VISIBLE_APP_ADJ);
9698 } else if (r.setAdj >= ProcessList.FOREGROUND_APP_ADJ) {
9699 oomAdj = buildOomTag("fore ", null, r.setAdj, ProcessList.FOREGROUND_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009700 } else if (r.setAdj >= ProcessList.PERSISTENT_PROC_ADJ) {
9701 oomAdj = buildOomTag("pers ", null, r.setAdj, ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009702 } else if (r.setAdj >= ProcessList.SYSTEM_ADJ) {
9703 oomAdj = buildOomTag("sys ", null, r.setAdj, ProcessList.SYSTEM_ADJ);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009704 } else {
9705 oomAdj = Integer.toString(r.setAdj);
9706 }
9707 String schedGroup;
9708 switch (r.setSchedGroup) {
9709 case Process.THREAD_GROUP_BG_NONINTERACTIVE:
9710 schedGroup = "B";
9711 break;
9712 case Process.THREAD_GROUP_DEFAULT:
9713 schedGroup = "F";
9714 break;
9715 default:
9716 schedGroup = Integer.toString(r.setSchedGroup);
9717 break;
9718 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07009719 String foreground;
9720 if (r.foregroundActivities) {
9721 foreground = "A";
9722 } else if (r.foregroundServices) {
9723 foreground = "S";
9724 } else {
9725 foreground = " ";
9726 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07009727 pw.println(String.format("%s%s #%2d: adj=%s/%s%s trm=%2d %s (%s)",
Dianne Hackborn287952c2010-09-22 22:34:31 -07009728 prefix, (r.persistent ? persistentLabel : normalLabel),
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009729 (origList.size()-1)-list.get(i).second, oomAdj, schedGroup,
9730 foreground, r.trimMemoryLevel, r.toShortString(), r.adjType));
Dianne Hackborn287952c2010-09-22 22:34:31 -07009731 if (r.adjSource != null || r.adjTarget != null) {
9732 pw.print(prefix);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009733 pw.print(" ");
Dianne Hackborn287952c2010-09-22 22:34:31 -07009734 if (r.adjTarget instanceof ComponentName) {
9735 pw.print(((ComponentName)r.adjTarget).flattenToShortString());
9736 } else if (r.adjTarget != null) {
9737 pw.print(r.adjTarget.toString());
9738 } else {
9739 pw.print("{null}");
9740 }
9741 pw.print("<=");
9742 if (r.adjSource instanceof ProcessRecord) {
9743 pw.print("Proc{");
9744 pw.print(((ProcessRecord)r.adjSource).toShortString());
9745 pw.println("}");
9746 } else if (r.adjSource != null) {
9747 pw.println(r.adjSource.toString());
9748 } else {
9749 pw.println("{null}");
9750 }
9751 }
9752 if (inclDetails) {
9753 pw.print(prefix);
9754 pw.print(" ");
9755 pw.print("oom: max="); pw.print(r.maxAdj);
9756 pw.print(" hidden="); pw.print(r.hiddenAdj);
9757 pw.print(" curRaw="); pw.print(r.curRawAdj);
9758 pw.print(" setRaw="); pw.print(r.setRawAdj);
9759 pw.print(" cur="); pw.print(r.curAdj);
9760 pw.print(" set="); pw.println(r.setAdj);
9761 pw.print(prefix);
9762 pw.print(" ");
9763 pw.print("keeping="); pw.print(r.keeping);
9764 pw.print(" hidden="); pw.print(r.hidden);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009765 pw.print(" empty="); pw.print(r.empty);
9766 pw.print(" hasAboveClient="); pw.println(r.hasAboveClient);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009767
9768 if (!r.keeping) {
9769 if (r.lastWakeTime != 0) {
9770 long wtime;
9771 BatteryStatsImpl stats = service.mBatteryStatsService.getActiveStatistics();
9772 synchronized (stats) {
9773 wtime = stats.getProcessWakeTime(r.info.uid,
9774 r.pid, curRealtime);
9775 }
9776 long timeUsed = wtime - r.lastWakeTime;
9777 pw.print(prefix);
9778 pw.print(" ");
9779 pw.print("keep awake over ");
9780 TimeUtils.formatDuration(realtimeSince, pw);
9781 pw.print(" used ");
9782 TimeUtils.formatDuration(timeUsed, pw);
9783 pw.print(" (");
9784 pw.print((timeUsed*100)/realtimeSince);
9785 pw.println("%)");
9786 }
9787 if (r.lastCpuTime != 0) {
9788 long timeUsed = r.curCpuTime - r.lastCpuTime;
9789 pw.print(prefix);
9790 pw.print(" ");
9791 pw.print("run cpu over ");
9792 TimeUtils.formatDuration(uptimeSince, pw);
9793 pw.print(" used ");
9794 TimeUtils.formatDuration(timeUsed, pw);
9795 pw.print(" (");
9796 pw.print((timeUsed*100)/uptimeSince);
9797 pw.println("%)");
9798 }
9799 }
9800 }
9801 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009802 return true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009803 }
9804
Dianne Hackbornb437e092011-08-05 17:50:29 -07009805 ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, String[] args) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009806 ArrayList<ProcessRecord> procs;
9807 synchronized (this) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009808 if (args != null && args.length > start
9809 && args[start].charAt(0) != '-') {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009810 procs = new ArrayList<ProcessRecord>();
9811 int pid = -1;
9812 try {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009813 pid = Integer.parseInt(args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009814 } catch (NumberFormatException e) {
9815
9816 }
9817 for (int i=mLruProcesses.size()-1; i>=0; i--) {
9818 ProcessRecord proc = mLruProcesses.get(i);
9819 if (proc.pid == pid) {
9820 procs.add(proc);
Dianne Hackbornb437e092011-08-05 17:50:29 -07009821 } else if (proc.processName.equals(args[start])) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009822 procs.add(proc);
9823 }
9824 }
9825 if (procs.size() <= 0) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009826 pw.println("No process found for: " + args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009827 return null;
9828 }
9829 } else {
9830 procs = new ArrayList<ProcessRecord>(mLruProcesses);
9831 }
9832 }
9833 return procs;
9834 }
9835
9836 final void dumpGraphicsHardwareUsage(FileDescriptor fd,
9837 PrintWriter pw, String[] args) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009838 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009839 if (procs == null) {
9840 return;
9841 }
9842
9843 long uptime = SystemClock.uptimeMillis();
9844 long realtime = SystemClock.elapsedRealtime();
9845 pw.println("Applications Graphics Acceleration Info:");
9846 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
9847
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009848 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
9849 ProcessRecord r = procs.get(i);
Chet Haase9c1e23b2011-03-24 10:51:31 -07009850 if (r.thread != null) {
9851 pw.println("\n** Graphics info for pid " + r.pid + " [" + r.processName + "] **");
9852 pw.flush();
9853 try {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009854 TransferPipe tp = new TransferPipe();
9855 try {
9856 r.thread.dumpGfxInfo(tp.getWriteFd().getFileDescriptor(), args);
9857 tp.go(fd);
9858 } finally {
9859 tp.kill();
9860 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009861 } catch (IOException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009862 pw.println("Failure while dumping the app: " + r);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009863 pw.flush();
Chet Haase9c1e23b2011-03-24 10:51:31 -07009864 } catch (RemoteException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009865 pw.println("Got a RemoteException while dumping the app " + r);
Chet Haase9c1e23b2011-03-24 10:51:31 -07009866 pw.flush();
9867 }
9868 }
9869 }
Chet Haase9c1e23b2011-03-24 10:51:31 -07009870 }
9871
Jeff Brown6754ba22011-12-14 20:20:01 -08009872 final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) {
9873 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
9874 if (procs == null) {
9875 return;
9876 }
9877
9878 pw.println("Applications Database Info:");
9879
9880 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
9881 ProcessRecord r = procs.get(i);
9882 if (r.thread != null) {
9883 pw.println("\n** Database info for pid " + r.pid + " [" + r.processName + "] **");
9884 pw.flush();
9885 try {
9886 TransferPipe tp = new TransferPipe();
9887 try {
9888 r.thread.dumpDbInfo(tp.getWriteFd().getFileDescriptor(), args);
9889 tp.go(fd);
9890 } finally {
9891 tp.kill();
9892 }
9893 } catch (IOException e) {
9894 pw.println("Failure while dumping the app: " + r);
9895 pw.flush();
9896 } catch (RemoteException e) {
9897 pw.println("Got a RemoteException while dumping the app " + r);
9898 pw.flush();
9899 }
9900 }
9901 }
9902 }
9903
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009904 final static class MemItem {
9905 final String label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009906 final String shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009907 final long pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009908 final int id;
Dianne Hackborna4bacb82011-08-24 15:12:38 -07009909 ArrayList<MemItem> subitems;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009910
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009911 public MemItem(String _label, String _shortLabel, long _pss, int _id) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009912 label = _label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009913 shortLabel = _shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009914 pss = _pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009915 id = _id;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009916 }
9917 }
9918
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009919 static final void dumpMemItems(PrintWriter pw, String prefix, ArrayList<MemItem> items,
Dianne Hackbornb437e092011-08-05 17:50:29 -07009920 boolean sort) {
9921 if (sort) {
9922 Collections.sort(items, new Comparator<MemItem>() {
9923 @Override
9924 public int compare(MemItem lhs, MemItem rhs) {
9925 if (lhs.pss < rhs.pss) {
9926 return 1;
9927 } else if (lhs.pss > rhs.pss) {
9928 return -1;
9929 }
9930 return 0;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009931 }
Dianne Hackbornb437e092011-08-05 17:50:29 -07009932 });
9933 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009934
9935 for (int i=0; i<items.size(); i++) {
9936 MemItem mi = items.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009937 pw.print(prefix); pw.printf("%7d kB: ", mi.pss); pw.println(mi.label);
Dianne Hackborna4bacb82011-08-24 15:12:38 -07009938 if (mi.subitems != null) {
9939 dumpMemItems(pw, prefix + " ", mi.subitems, true);
9940 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009941 }
9942 }
9943
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009944 // These are in KB.
9945 static final long[] DUMP_MEM_BUCKETS = new long[] {
9946 5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024,
9947 120*1024, 160*1024, 200*1024,
9948 250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024,
9949 1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024
9950 };
9951
Dianne Hackborn672342c2011-11-29 11:29:02 -08009952 static final void appendMemBucket(StringBuilder out, long memKB, String label,
9953 boolean stackLike) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009954 int start = label.lastIndexOf('.');
9955 if (start >= 0) start++;
9956 else start = 0;
9957 int end = label.length();
9958 for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) {
9959 if (DUMP_MEM_BUCKETS[i] >= memKB) {
9960 long bucket = DUMP_MEM_BUCKETS[i]/1024;
9961 out.append(bucket);
Dianne Hackborn672342c2011-11-29 11:29:02 -08009962 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009963 out.append(label, start, end);
9964 return;
9965 }
9966 }
9967 out.append(memKB/1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -08009968 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009969 out.append(label, start, end);
9970 }
9971
9972 static final int[] DUMP_MEM_OOM_ADJ = new int[] {
9973 ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ, ProcessList.FOREGROUND_APP_ADJ,
9974 ProcessList.VISIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ,
9975 ProcessList.BACKUP_APP_ADJ, ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ,
9976 ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.HIDDEN_APP_MAX_ADJ
9977 };
9978 static final String[] DUMP_MEM_OOM_LABEL = new String[] {
9979 "System", "Persistent", "Foreground",
9980 "Visible", "Perceptible", "Heavy Weight",
9981 "Backup", "A Services", "Home", "Previous",
9982 "B Services", "Background"
9983 };
9984
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009985 final void dumpApplicationMemoryUsage(FileDescriptor fd,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08009986 PrintWriter pw, String prefix, String[] args, boolean brief,
Dianne Hackborn672342c2011-11-29 11:29:02 -08009987 PrintWriter categoryPw, StringBuilder outTag, StringBuilder outStack) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009988 boolean dumpAll = false;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08009989 boolean oomOnly = false;
Dianne Hackbornb437e092011-08-05 17:50:29 -07009990
9991 int opti = 0;
9992 while (opti < args.length) {
9993 String opt = args[opti];
9994 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
9995 break;
9996 }
9997 opti++;
9998 if ("-a".equals(opt)) {
9999 dumpAll = true;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010000 } else if ("--oom".equals(opt)) {
10001 oomOnly = true;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010002 } else if ("-h".equals(opt)) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010003 pw.println("meminfo dump options: [-a] [--oom] [process]");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010004 pw.println(" -a: include all available information for each process.");
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010005 pw.println(" --oom: only show processes organized by oom adj.");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010006 pw.println("If [process] is specified it can be the name or ");
10007 pw.println("pid of a specific process to dump.");
10008 return;
10009 } else {
10010 pw.println("Unknown argument: " + opt + "; use -h for help");
10011 }
10012 }
10013
10014 ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010015 if (procs == null) {
10016 return;
10017 }
10018
Dianne Hackborn6447ca32009-04-07 19:50:08 -070010019 final boolean isCheckinRequest = scanArgs(args, "--checkin");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010020 long uptime = SystemClock.uptimeMillis();
10021 long realtime = SystemClock.elapsedRealtime();
Dianne Hackbornb437e092011-08-05 17:50:29 -070010022
10023 if (procs.size() == 1 || isCheckinRequest) {
10024 dumpAll = true;
10025 }
10026
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010027 if (isCheckinRequest) {
10028 // short checkin version
10029 pw.println(uptime + "," + realtime);
10030 pw.flush();
10031 } else {
10032 pw.println("Applications Memory Usage (kB):");
10033 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10034 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010035
Dianne Hackbornb437e092011-08-05 17:50:29 -070010036 String[] innerArgs = new String[args.length-opti];
10037 System.arraycopy(args, opti, innerArgs, 0, args.length-opti);
10038
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010039 ArrayList<MemItem> procMems = new ArrayList<MemItem>();
10040 long nativePss=0, dalvikPss=0, otherPss=0;
10041 long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
10042
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010043 long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length];
10044 ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[])
10045 new ArrayList[DUMP_MEM_OOM_LABEL.length];
Dianne Hackbornb437e092011-08-05 17:50:29 -070010046
10047 long totalPss = 0;
10048
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010049 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10050 ProcessRecord r = procs.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010051 if (r.thread != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010052 if (!isCheckinRequest && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010053 pw.println("\n** MEMINFO in pid " + r.pid + " [" + r.processName + "] **");
10054 pw.flush();
10055 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010056 Debug.MemoryInfo mi = null;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010057 if (dumpAll) {
10058 try {
10059 mi = r.thread.dumpMemInfo(fd, isCheckinRequest, dumpAll, innerArgs);
10060 } catch (RemoteException e) {
10061 if (!isCheckinRequest) {
10062 pw.println("Got RemoteException!");
10063 pw.flush();
10064 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010065 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010066 } else {
10067 mi = new Debug.MemoryInfo();
10068 Debug.getMemoryInfo(r.pid, mi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010069 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010070
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010071 if (!isCheckinRequest && mi != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010072 long myTotalPss = mi.getTotalPss();
10073 totalPss += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010074 MemItem pssItem = new MemItem(r.processName + " (pid " + r.pid + ")",
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010075 r.processName, myTotalPss, 0);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010076 procMems.add(pssItem);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010077
10078 nativePss += mi.nativePss;
10079 dalvikPss += mi.dalvikPss;
10080 otherPss += mi.otherPss;
10081 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
10082 long mem = mi.getOtherPss(j);
10083 miscPss[j] += mem;
10084 otherPss -= mem;
10085 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010086
10087 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010088 if (r.setAdj <= DUMP_MEM_OOM_ADJ[oomIndex]
10089 || oomIndex == (oomPss.length-1)) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010090 oomPss[oomIndex] += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010091 if (oomProcs[oomIndex] == null) {
10092 oomProcs[oomIndex] = new ArrayList<MemItem>();
10093 }
10094 oomProcs[oomIndex].add(pssItem);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010095 break;
10096 }
10097 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010098 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010099 }
10100 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010101
10102 if (!isCheckinRequest && procs.size() > 1) {
10103 ArrayList<MemItem> catMems = new ArrayList<MemItem>();
10104
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010105 catMems.add(new MemItem("Native", "Native", nativePss, -1));
10106 catMems.add(new MemItem("Dalvik", "Dalvik", dalvikPss, -2));
10107 catMems.add(new MemItem("Unknown", "Unknown", otherPss, -3));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010108 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010109 String label = Debug.MemoryInfo.getOtherLabel(j);
10110 catMems.add(new MemItem(label, label, miscPss[j], j));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010111 }
10112
Dianne Hackbornb437e092011-08-05 17:50:29 -070010113 ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
10114 for (int j=0; j<oomPss.length; j++) {
10115 if (oomPss[j] != 0) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010116 String label = DUMP_MEM_OOM_LABEL[j];
10117 MemItem item = new MemItem(label, label, oomPss[j],
10118 DUMP_MEM_OOM_ADJ[j]);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010119 item.subitems = oomProcs[j];
10120 oomMems.add(item);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010121 }
10122 }
10123
Dianne Hackborn672342c2011-11-29 11:29:02 -080010124 if (outTag != null || outStack != null) {
10125 if (outTag != null) {
10126 appendMemBucket(outTag, totalPss, "total", false);
10127 }
10128 if (outStack != null) {
10129 appendMemBucket(outStack, totalPss, "total", true);
10130 }
10131 boolean firstLine = true;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010132 for (int i=0; i<oomMems.size(); i++) {
10133 MemItem miCat = oomMems.get(i);
10134 if (miCat.subitems == null || miCat.subitems.size() < 1) {
10135 continue;
10136 }
10137 if (miCat.id < ProcessList.SERVICE_ADJ
10138 || miCat.id == ProcessList.HOME_APP_ADJ
10139 || miCat.id == ProcessList.PREVIOUS_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010140 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10141 outTag.append(" / ");
10142 }
10143 if (outStack != null) {
10144 if (miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10145 if (firstLine) {
10146 outStack.append(":");
10147 firstLine = false;
10148 }
10149 outStack.append("\n\t at ");
10150 } else {
10151 outStack.append("$");
10152 }
10153 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010154 for (int j=0; j<miCat.subitems.size(); j++) {
10155 MemItem mi = miCat.subitems.get(j);
10156 if (j > 0) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010157 if (outTag != null) {
10158 outTag.append(" ");
10159 }
10160 if (outStack != null) {
10161 outStack.append("$");
10162 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010163 }
Dianne Hackborn672342c2011-11-29 11:29:02 -080010164 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10165 appendMemBucket(outTag, mi.pss, mi.shortLabel, false);
10166 }
10167 if (outStack != null) {
10168 appendMemBucket(outStack, mi.pss, mi.shortLabel, true);
10169 }
10170 }
10171 if (outStack != null && miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10172 outStack.append("(");
10173 for (int k=0; k<DUMP_MEM_OOM_ADJ.length; k++) {
10174 if (DUMP_MEM_OOM_ADJ[k] == miCat.id) {
10175 outStack.append(DUMP_MEM_OOM_LABEL[k]);
10176 outStack.append(":");
10177 outStack.append(DUMP_MEM_OOM_ADJ[k]);
10178 }
10179 }
10180 outStack.append(")");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010181 }
10182 }
10183 }
10184 }
10185
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010186 if (!brief && !oomOnly) {
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010187 pw.println();
10188 pw.println("Total PSS by process:");
10189 dumpMemItems(pw, " ", procMems, true);
10190 pw.println();
10191 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010192 pw.println("Total PSS by OOM adjustment:");
10193 dumpMemItems(pw, " ", oomMems, false);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010194 if (!oomOnly) {
10195 PrintWriter out = categoryPw != null ? categoryPw : pw;
10196 out.println();
10197 out.println("Total PSS by category:");
10198 dumpMemItems(out, " ", catMems, true);
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010199 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010200 pw.println();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010201 pw.print("Total PSS: "); pw.print(totalPss); pw.println(" kB");
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010202 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010203 }
10204
10205 /**
10206 * Searches array of arguments for the specified string
10207 * @param args array of argument strings
10208 * @param value value to search for
10209 * @return true if the value is contained in the array
10210 */
10211 private static boolean scanArgs(String[] args, String value) {
10212 if (args != null) {
10213 for (String arg : args) {
10214 if (value.equals(arg)) {
10215 return true;
10216 }
10217 }
10218 }
10219 return false;
10220 }
10221
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010222 private final void killServicesLocked(ProcessRecord app,
10223 boolean allowRestart) {
10224 // Report disconnected services.
10225 if (false) {
10226 // XXX we are letting the client link to the service for
10227 // death notifications.
10228 if (app.services.size() > 0) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010229 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010230 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010231 ServiceRecord r = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010232 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010233 Iterator<ArrayList<ConnectionRecord>> jt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010234 = r.connections.values().iterator();
10235 while (jt.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010236 ArrayList<ConnectionRecord> cl = jt.next();
10237 for (int i=0; i<cl.size(); i++) {
10238 ConnectionRecord c = cl.get(i);
10239 if (c.binding.client != app) {
10240 try {
10241 //c.conn.connected(r.className, null);
10242 } catch (Exception e) {
10243 // todo: this should be asynchronous!
10244 Slog.w(TAG, "Exception thrown disconnected servce "
10245 + r.shortName
10246 + " from app " + app.processName, e);
10247 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010248 }
10249 }
10250 }
10251 }
10252 }
10253 }
10254 }
10255
10256 // Clean up any connections this application has to other services.
10257 if (app.connections.size() > 0) {
10258 Iterator<ConnectionRecord> it = app.connections.iterator();
10259 while (it.hasNext()) {
10260 ConnectionRecord r = it.next();
10261 removeConnectionLocked(r, app, null);
10262 }
10263 }
10264 app.connections.clear();
10265
10266 if (app.services.size() != 0) {
10267 // Any services running in the application need to be placed
10268 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -070010269 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010270 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010271 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010272 synchronized (sr.stats.getBatteryStats()) {
10273 sr.stats.stopLaunchedLocked();
10274 }
10275 sr.app = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010276 sr.isolatedProc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010277 sr.executeNesting = 0;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010278 if (mStoppingServices.remove(sr)) {
10279 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
10280 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010281
10282 boolean hasClients = sr.bindings.size() > 0;
10283 if (hasClients) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010284 Iterator<IntentBindRecord> bindings
10285 = sr.bindings.values().iterator();
10286 while (bindings.hasNext()) {
10287 IntentBindRecord b = bindings.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -080010288 if (DEBUG_SERVICE) Slog.v(TAG, "Killing binding " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010289 + ": shouldUnbind=" + b.hasBound);
10290 b.binder = null;
10291 b.requested = b.received = b.hasBound = false;
10292 }
10293 }
10294
Dianne Hackborn070783f2010-12-29 16:46:28 -080010295 if (sr.crashCount >= 2 && (sr.serviceInfo.applicationInfo.flags
10296 &ApplicationInfo.FLAG_PERSISTENT) == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010297 Slog.w(TAG, "Service crashed " + sr.crashCount
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010298 + " times, stopping: " + sr);
Doug Zongker2bec3d42009-12-04 12:52:44 -080010299 EventLog.writeEvent(EventLogTags.AM_SERVICE_CRASHED_TOO_MUCH,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010300 sr.crashCount, sr.shortName, app.pid);
10301 bringDownServiceLocked(sr, true);
10302 } else if (!allowRestart) {
10303 bringDownServiceLocked(sr, true);
10304 } else {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010305 boolean canceled = scheduleServiceRestartLocked(sr, true);
10306
10307 // Should the service remain running? Note that in the
10308 // extreme case of so many attempts to deliver a command
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010309 // that it failed we also will stop it here.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010310 if (sr.startRequested && (sr.stopIfKilled || canceled)) {
10311 if (sr.pendingStarts.size() == 0) {
10312 sr.startRequested = false;
10313 if (!hasClients) {
10314 // Whoops, no reason to restart!
10315 bringDownServiceLocked(sr, true);
10316 }
10317 }
10318 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010319 }
10320 }
10321
10322 if (!allowRestart) {
10323 app.services.clear();
10324 }
10325 }
10326
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010327 // Make sure we have no more records on the stopping list.
10328 int i = mStoppingServices.size();
10329 while (i > 0) {
10330 i--;
10331 ServiceRecord sr = mStoppingServices.get(i);
10332 if (sr.app == app) {
10333 mStoppingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010334 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010335 }
10336 }
10337
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010338 app.executingServices.clear();
10339 }
10340
10341 private final void removeDyingProviderLocked(ProcessRecord proc,
10342 ContentProviderRecord cpr) {
10343 synchronized (cpr) {
10344 cpr.launchingApp = null;
10345 cpr.notifyAll();
10346 }
10347
Amith Yamasani742a6712011-05-04 14:49:28 -070010348 mProviderMap.removeProviderByClass(cpr.name, UserId.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010349 String names[] = cpr.info.authority.split(";");
10350 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010351 mProviderMap.removeProviderByName(names[j], UserId.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010352 }
10353
10354 Iterator<ProcessRecord> cit = cpr.clients.iterator();
10355 while (cit.hasNext()) {
10356 ProcessRecord capp = cit.next();
10357 if (!capp.persistent && capp.thread != null
10358 && capp.pid != 0
10359 && capp.pid != MY_PID) {
Dianne Hackborn8633e682010-04-22 16:03:41 -070010360 Slog.i(TAG, "Kill " + capp.processName
10361 + " (pid " + capp.pid + "): provider " + cpr.info.name
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010362 + " in dying process " + (proc != null ? proc.processName : "??"));
Dianne Hackborn8633e682010-04-22 16:03:41 -070010363 EventLog.writeEvent(EventLogTags.AM_KILL, capp.pid,
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010364 capp.processName, capp.setAdj, "dying provider "
10365 + cpr.name.toShortString());
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070010366 Process.killProcessQuiet(capp.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010367 }
10368 }
10369
10370 mLaunchingProviders.remove(cpr);
10371 }
10372
10373 /**
10374 * Main code for cleaning up a process when it has gone away. This is
10375 * called both as a result of the process dying, or directly when stopping
10376 * a process when running in single process mode.
10377 */
10378 private final void cleanUpApplicationRecordLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010379 boolean restarting, boolean allowRestart, int index) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010380 if (index >= 0) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010381 mLruProcesses.remove(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010382 }
10383
Dianne Hackborn36124872009-10-08 16:22:03 -070010384 mProcessesToGc.remove(app);
10385
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010386 // Dismiss any open dialogs.
10387 if (app.crashDialog != null) {
10388 app.crashDialog.dismiss();
10389 app.crashDialog = null;
10390 }
10391 if (app.anrDialog != null) {
10392 app.anrDialog.dismiss();
10393 app.anrDialog = null;
10394 }
10395 if (app.waitDialog != null) {
10396 app.waitDialog.dismiss();
10397 app.waitDialog = null;
10398 }
10399
10400 app.crashing = false;
10401 app.notResponding = false;
10402
10403 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -070010404 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010405 app.thread = null;
10406 app.forcingToForeground = null;
10407 app.foregroundServices = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010408 app.foregroundActivities = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070010409 app.hasShownUi = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010410 app.hasAboveClient = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010411
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010412 killServicesLocked(app, allowRestart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010413
10414 boolean restart = false;
10415
10416 int NL = mLaunchingProviders.size();
10417
10418 // Remove published content providers.
10419 if (!app.pubProviders.isEmpty()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010420 Iterator<ContentProviderRecord> it = app.pubProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010421 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010422 ContentProviderRecord cpr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010423 cpr.provider = null;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010424 cpr.proc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010425
10426 // See if someone is waiting for this provider... in which
10427 // case we don't remove it, but just let it restart.
10428 int i = 0;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010429 if (!app.bad && allowRestart) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010430 for (; i<NL; i++) {
10431 if (mLaunchingProviders.get(i) == cpr) {
10432 restart = true;
10433 break;
10434 }
10435 }
10436 } else {
10437 i = NL;
10438 }
10439
10440 if (i >= NL) {
10441 removeDyingProviderLocked(app, cpr);
10442 NL = mLaunchingProviders.size();
10443 }
10444 }
10445 app.pubProviders.clear();
10446 }
10447
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010448 // Take care of any launching providers waiting for this process.
10449 if (checkAppInLaunchingProvidersLocked(app, false)) {
10450 restart = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010451 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010452
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010453 // Unregister from connected content providers.
10454 if (!app.conProviders.isEmpty()) {
Dianne Hackborn0c3154d2009-10-06 17:18:05 -070010455 Iterator it = app.conProviders.keySet().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010456 while (it.hasNext()) {
10457 ContentProviderRecord cpr = (ContentProviderRecord)it.next();
10458 cpr.clients.remove(app);
10459 }
10460 app.conProviders.clear();
10461 }
10462
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010463 // At this point there may be remaining entries in mLaunchingProviders
10464 // where we were the only one waiting, so they are no longer of use.
10465 // Look for these and clean up if found.
10466 // XXX Commented out for now. Trying to figure out a way to reproduce
10467 // the actual situation to identify what is actually going on.
10468 if (false) {
10469 for (int i=0; i<NL; i++) {
10470 ContentProviderRecord cpr = (ContentProviderRecord)
10471 mLaunchingProviders.get(i);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080010472 if (cpr.clients.size() <= 0 && !cpr.hasExternalProcessHandles()) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010473 synchronized (cpr) {
10474 cpr.launchingApp = null;
10475 cpr.notifyAll();
10476 }
10477 }
10478 }
10479 }
10480
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010481 skipCurrentReceiverLocked(app);
10482
10483 // Unregister any receivers.
10484 if (app.receivers.size() > 0) {
10485 Iterator<ReceiverList> it = app.receivers.iterator();
10486 while (it.hasNext()) {
10487 removeReceiverLocked(it.next());
10488 }
10489 app.receivers.clear();
10490 }
10491
Christopher Tate181fafa2009-05-14 11:12:14 -070010492 // If the app is undergoing backup, tell the backup manager about it
10493 if (mBackupTarget != null && app.pid == mBackupTarget.app.pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010494 if (DEBUG_BACKUP) Slog.d(TAG, "App " + mBackupTarget.appInfo + " died during backup");
Christopher Tate181fafa2009-05-14 11:12:14 -070010495 try {
10496 IBackupManager bm = IBackupManager.Stub.asInterface(
10497 ServiceManager.getService(Context.BACKUP_SERVICE));
10498 bm.agentDisconnected(app.info.packageName);
10499 } catch (RemoteException e) {
10500 // can't happen; backup manager is local
10501 }
10502 }
10503
Jeff Sharkey287bd832011-05-28 19:36:26 -070010504 mHandler.obtainMessage(DISPATCH_PROCESS_DIED, app.pid, app.info.uid, null).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010505
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010506 // If the caller is restarting this app, then leave it in its
10507 // current lists and let the caller take care of it.
10508 if (restarting) {
10509 return;
10510 }
10511
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010512 if (!app.persistent || app.isolated) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010513 if (DEBUG_PROCESSES) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010514 "Removing non-persistent process during cleanup: " + app);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010515 mProcessNames.remove(app.processName, app.uid);
10516 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -070010517 if (mHeavyWeightProcess == app) {
10518 mHeavyWeightProcess = null;
10519 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
10520 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010521 } else if (!app.removed) {
10522 // This app is persistent, so we need to keep its record around.
10523 // If it is not already on the pending app list, add it there
10524 // and start a new process for it.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010525 if (mPersistentStartingProcesses.indexOf(app) < 0) {
10526 mPersistentStartingProcesses.add(app);
10527 restart = true;
10528 }
10529 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070010530 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
10531 "Clean-up removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010532 mProcessesOnHold.remove(app);
10533
The Android Open Source Project4df24232009-03-05 14:34:35 -080010534 if (app == mHomeProcess) {
10535 mHomeProcess = null;
10536 }
Dianne Hackbornf35fe232011-11-01 19:25:20 -070010537 if (app == mPreviousProcess) {
10538 mPreviousProcess = null;
10539 }
10540
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010541 if (restart && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010542 // We have components that still need to be running in the
10543 // process, so re-launch it.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010544 mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010545 startProcessLocked(app, "restart", app.processName);
10546 } else if (app.pid > 0 && app.pid != MY_PID) {
10547 // Goodbye!
10548 synchronized (mPidsSelfLocked) {
10549 mPidsSelfLocked.remove(app.pid);
10550 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
10551 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010552 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010553 }
10554 }
10555
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010556 boolean checkAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) {
10557 // Look through the content providers we are waiting to have launched,
10558 // and if any run in this process then either schedule a restart of
10559 // the process or kill the client waiting for it if this process has
10560 // gone bad.
10561 int NL = mLaunchingProviders.size();
10562 boolean restart = false;
10563 for (int i=0; i<NL; i++) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010564 ContentProviderRecord cpr = mLaunchingProviders.get(i);
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010565 if (cpr.launchingApp == app) {
10566 if (!alwaysBad && !app.bad) {
10567 restart = true;
10568 } else {
10569 removeDyingProviderLocked(app, cpr);
10570 NL = mLaunchingProviders.size();
10571 }
10572 }
10573 }
10574 return restart;
10575 }
10576
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010577 // =========================================================
10578 // SERVICES
10579 // =========================================================
10580
10581 ActivityManager.RunningServiceInfo makeRunningServiceInfoLocked(ServiceRecord r) {
10582 ActivityManager.RunningServiceInfo info =
10583 new ActivityManager.RunningServiceInfo();
10584 info.service = r.name;
10585 if (r.app != null) {
10586 info.pid = r.app.pid;
10587 }
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010588 info.uid = r.appInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010589 info.process = r.processName;
10590 info.foreground = r.isForeground;
10591 info.activeSince = r.createTime;
10592 info.started = r.startRequested;
10593 info.clientCount = r.connections.size();
10594 info.crashCount = r.crashCount;
10595 info.lastActivityTime = r.lastActivity;
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010596 if (r.isForeground) {
10597 info.flags |= ActivityManager.RunningServiceInfo.FLAG_FOREGROUND;
10598 }
10599 if (r.startRequested) {
10600 info.flags |= ActivityManager.RunningServiceInfo.FLAG_STARTED;
10601 }
Dan Egnor42471dd2010-01-07 17:25:22 -080010602 if (r.app != null && r.app.pid == MY_PID) {
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010603 info.flags |= ActivityManager.RunningServiceInfo.FLAG_SYSTEM_PROCESS;
10604 }
10605 if (r.app != null && r.app.persistent) {
10606 info.flags |= ActivityManager.RunningServiceInfo.FLAG_PERSISTENT_PROCESS;
10607 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010608
10609 for (ArrayList<ConnectionRecord> connl : r.connections.values()) {
10610 for (int i=0; i<connl.size(); i++) {
10611 ConnectionRecord conn = connl.get(i);
10612 if (conn.clientLabel != 0) {
10613 info.clientPackage = conn.binding.client.info.packageName;
10614 info.clientLabel = conn.clientLabel;
10615 return info;
10616 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010617 }
10618 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010619 return info;
10620 }
10621
10622 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum,
10623 int flags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010624 enforceNotIsolatedCaller("getServices");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010625 synchronized (this) {
10626 ArrayList<ActivityManager.RunningServiceInfo> res
10627 = new ArrayList<ActivityManager.RunningServiceInfo>();
10628
Amith Yamasani742a6712011-05-04 14:49:28 -070010629 int userId = UserId.getUserId(Binder.getCallingUid());
10630 if (mServiceMap.getAllServices(userId).size() > 0) {
10631 Iterator<ServiceRecord> it
10632 = mServiceMap.getAllServices(userId).iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010633 while (it.hasNext() && res.size() < maxNum) {
10634 res.add(makeRunningServiceInfoLocked(it.next()));
10635 }
10636 }
10637
10638 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
10639 ServiceRecord r = mRestartingServices.get(i);
10640 ActivityManager.RunningServiceInfo info =
10641 makeRunningServiceInfoLocked(r);
10642 info.restarting = r.nextRestartTime;
10643 res.add(info);
10644 }
10645
10646 return res;
10647 }
10648 }
10649
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010650 public PendingIntent getRunningServiceControlPanel(ComponentName name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010651 enforceNotIsolatedCaller("getRunningServiceControlPanel");
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010652 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010653 int userId = UserId.getUserId(Binder.getCallingUid());
10654 ServiceRecord r = mServiceMap.getServiceByName(name, userId);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010655 if (r != null) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010656 for (ArrayList<ConnectionRecord> conn : r.connections.values()) {
10657 for (int i=0; i<conn.size(); i++) {
10658 if (conn.get(i).clientIntent != null) {
10659 return conn.get(i).clientIntent;
10660 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010661 }
10662 }
10663 }
10664 }
10665 return null;
10666 }
10667
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010668 private final ServiceRecord findServiceLocked(ComponentName name,
10669 IBinder token) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010670 ServiceRecord r = mServiceMap.getServiceByName(name, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010671 return r == token ? r : null;
10672 }
10673
10674 private final class ServiceLookupResult {
10675 final ServiceRecord record;
10676 final String permission;
10677
10678 ServiceLookupResult(ServiceRecord _record, String _permission) {
10679 record = _record;
10680 permission = _permission;
10681 }
10682 };
10683
10684 private ServiceLookupResult findServiceLocked(Intent service,
10685 String resolvedType) {
10686 ServiceRecord r = null;
10687 if (service.getComponent() != null) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010688 r = mServiceMap.getServiceByName(service.getComponent(), Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010689 }
10690 if (r == null) {
10691 Intent.FilterComparison filter = new Intent.FilterComparison(service);
Amith Yamasani742a6712011-05-04 14:49:28 -070010692 r = mServiceMap.getServiceByIntent(filter, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010693 }
10694
10695 if (r == null) {
10696 try {
10697 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070010698 AppGlobals.getPackageManager().resolveService(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010699 service, resolvedType, 0);
10700 ServiceInfo sInfo =
10701 rInfo != null ? rInfo.serviceInfo : null;
10702 if (sInfo == null) {
10703 return null;
10704 }
10705
10706 ComponentName name = new ComponentName(
10707 sInfo.applicationInfo.packageName, sInfo.name);
Amith Yamasani742a6712011-05-04 14:49:28 -070010708 r = mServiceMap.getServiceByName(name, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010709 } catch (RemoteException ex) {
10710 // pm is in same process, this will never happen.
10711 }
10712 }
10713 if (r != null) {
10714 int callingPid = Binder.getCallingPid();
10715 int callingUid = Binder.getCallingUid();
10716 if (checkComponentPermission(r.permission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010717 callingPid, callingUid, r.appInfo.uid, r.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010718 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010719 if (!r.exported) {
10720 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
10721 + " from pid=" + callingPid
10722 + ", uid=" + callingUid
10723 + " that is not exported from uid " + r.appInfo.uid);
10724 return new ServiceLookupResult(null, "not exported from uid "
10725 + r.appInfo.uid);
10726 }
Joe Onorato8a9b2202010-02-26 18:56:32 -080010727 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010728 + " from pid=" + callingPid
10729 + ", uid=" + callingUid
10730 + " requires " + r.permission);
10731 return new ServiceLookupResult(null, r.permission);
10732 }
10733 return new ServiceLookupResult(r, null);
10734 }
10735 return null;
10736 }
10737
10738 private class ServiceRestarter implements Runnable {
10739 private ServiceRecord mService;
10740
10741 void setService(ServiceRecord service) {
10742 mService = service;
10743 }
10744
10745 public void run() {
10746 synchronized(ActivityManagerService.this) {
10747 performServiceRestartLocked(mService);
10748 }
10749 }
10750 }
10751
10752 private ServiceLookupResult retrieveServiceLocked(Intent service,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010753 String resolvedType, int callingPid, int callingUid, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010754 ServiceRecord r = null;
Amith Yamasani742a6712011-05-04 14:49:28 -070010755 if (DEBUG_SERVICE)
10756 Slog.v(TAG, "retrieveServiceLocked: " + service + " type=" + resolvedType
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010757 + " callingUid=" + callingUid);
Amith Yamasani742a6712011-05-04 14:49:28 -070010758
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010759 if (service.getComponent() != null) {
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010760 r = mServiceMap.getServiceByName(service.getComponent(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010761 }
Amith Yamasani742a6712011-05-04 14:49:28 -070010762 if (r == null) {
10763 Intent.FilterComparison filter = new Intent.FilterComparison(service);
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010764 r = mServiceMap.getServiceByIntent(filter, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -070010765 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010766 if (r == null) {
10767 try {
10768 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070010769 AppGlobals.getPackageManager().resolveService(
Dianne Hackborn1655be42009-05-08 14:29:01 -070010770 service, resolvedType, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010771 ServiceInfo sInfo =
10772 rInfo != null ? rInfo.serviceInfo : null;
10773 if (sInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010774 Slog.w(TAG, "Unable to start service " + service +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010775 ": not found");
10776 return null;
10777 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010778 if (userId > 0) {
10779 sInfo.applicationInfo = getAppInfoForUser(sInfo.applicationInfo, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -070010780 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010781 ComponentName name = new ComponentName(
10782 sInfo.applicationInfo.packageName, sInfo.name);
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010783 r = mServiceMap.getServiceByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010784 if (r == null) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010785 Intent.FilterComparison filter = new Intent.FilterComparison(
10786 service.cloneFilter());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010787 ServiceRestarter res = new ServiceRestarter();
10788 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
10789 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
10790 synchronized (stats) {
10791 ss = stats.getServiceStatsLocked(
10792 sInfo.applicationInfo.uid, sInfo.packageName,
10793 sInfo.name);
10794 }
Dianne Hackbornb1c4a2a2010-01-19 15:36:42 -080010795 r = new ServiceRecord(this, ss, name, filter, sInfo, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010796 res.setService(r);
Amith Yamasani742a6712011-05-04 14:49:28 -070010797 mServiceMap.putServiceByName(name, UserId.getUserId(r.appInfo.uid), r);
10798 mServiceMap.putServiceByIntent(filter, UserId.getUserId(r.appInfo.uid), r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010799
10800 // Make sure this component isn't in the pending list.
10801 int N = mPendingServices.size();
10802 for (int i=0; i<N; i++) {
10803 ServiceRecord pr = mPendingServices.get(i);
10804 if (pr.name.equals(name)) {
10805 mPendingServices.remove(i);
10806 i--;
10807 N--;
10808 }
10809 }
10810 }
10811 } catch (RemoteException ex) {
10812 // pm is in same process, this will never happen.
10813 }
10814 }
10815 if (r != null) {
10816 if (checkComponentPermission(r.permission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010817 callingPid, callingUid, r.appInfo.uid, r.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010818 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010819 if (!r.exported) {
10820 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
10821 + " from pid=" + callingPid
10822 + ", uid=" + callingUid
10823 + " that is not exported from uid " + r.appInfo.uid);
10824 return new ServiceLookupResult(null, "not exported from uid "
10825 + r.appInfo.uid);
10826 }
Joe Onorato8a9b2202010-02-26 18:56:32 -080010827 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010828 + " from pid=" + callingPid
10829 + ", uid=" + callingUid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010830 + " requires " + r.permission);
10831 return new ServiceLookupResult(null, r.permission);
10832 }
10833 return new ServiceLookupResult(r, null);
10834 }
10835 return null;
10836 }
10837
Dianne Hackborn287952c2010-09-22 22:34:31 -070010838 private final void bumpServiceExecutingLocked(ServiceRecord r, String why) {
10839 if (DEBUG_SERVICE) Log.v(TAG, ">>> EXECUTING "
10840 + why + " of " + r + " in app " + r.app);
10841 else if (DEBUG_SERVICE_EXECUTING) Log.v(TAG, ">>> EXECUTING "
10842 + why + " of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010843 long now = SystemClock.uptimeMillis();
10844 if (r.executeNesting == 0 && r.app != null) {
10845 if (r.app.executingServices.size() == 0) {
10846 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
10847 msg.obj = r.app;
10848 mHandler.sendMessageAtTime(msg, now+SERVICE_TIMEOUT);
10849 }
10850 r.app.executingServices.add(r);
10851 }
10852 r.executeNesting++;
10853 r.executingStart = now;
10854 }
10855
10856 private final void sendServiceArgsLocked(ServiceRecord r,
10857 boolean oomAdjusted) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010858 final int N = r.pendingStarts.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010859 if (N == 0) {
10860 return;
10861 }
10862
Dianne Hackborn39792d22010-08-19 18:01:52 -070010863 while (r.pendingStarts.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010864 try {
Dianne Hackborn39792d22010-08-19 18:01:52 -070010865 ServiceRecord.StartItem si = r.pendingStarts.remove(0);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010866 if (DEBUG_SERVICE) Slog.v(TAG, "Sending arguments to: "
10867 + r + " " + r.intent + " args=" + si.intent);
Dianne Hackborn3a28f222011-03-01 12:25:54 -080010868 if (si.intent == null && N > 1) {
10869 // If somehow we got a dummy null intent in the middle,
10870 // then skip it. DO NOT skip a null intent when it is
10871 // the only one in the list -- this is to support the
10872 // onStartCommand(null) case.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010873 continue;
10874 }
Dianne Hackborn39792d22010-08-19 18:01:52 -070010875 si.deliveredTime = SystemClock.uptimeMillis();
10876 r.deliveredStarts.add(si);
10877 si.deliveryCount++;
Dianne Hackborn21c241e2012-03-08 13:57:23 -080010878 if (si.neededGrants != null) {
10879 grantUriPermissionUncheckedFromIntentLocked(si.neededGrants,
10880 si.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -070010881 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070010882 bumpServiceExecutingLocked(r, "start");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010883 if (!oomAdjusted) {
10884 oomAdjusted = true;
10885 updateOomAdjLocked(r.app);
10886 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010887 int flags = 0;
10888 if (si.deliveryCount > 0) {
10889 flags |= Service.START_FLAG_RETRY;
10890 }
10891 if (si.doneExecutingCount > 0) {
10892 flags |= Service.START_FLAG_REDELIVERY;
10893 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070010894 r.app.thread.scheduleServiceArgs(r, si.taskRemoved, si.id, flags, si.intent);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010895 } catch (RemoteException e) {
10896 // Remote process gone... we'll let the normal cleanup take
10897 // care of this.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010898 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while scheduling start: " + r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010899 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010900 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010901 Slog.w(TAG, "Unexpected exception", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010902 break;
10903 }
10904 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010905 }
10906
10907 private final boolean requestServiceBindingLocked(ServiceRecord r,
10908 IntentBindRecord i, boolean rebind) {
10909 if (r.app == null || r.app.thread == null) {
10910 // If service is not currently running, can't yet bind.
10911 return false;
10912 }
10913 if ((!i.requested || rebind) && i.apps.size() > 0) {
10914 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070010915 bumpServiceExecutingLocked(r, "bind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010916 r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind);
10917 if (!rebind) {
10918 i.requested = true;
10919 }
10920 i.hasBound = true;
10921 i.doRebind = false;
10922 } catch (RemoteException e) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010923 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while binding " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010924 return false;
10925 }
10926 }
10927 return true;
10928 }
10929
10930 private final void requestServiceBindingsLocked(ServiceRecord r) {
10931 Iterator<IntentBindRecord> bindings = r.bindings.values().iterator();
10932 while (bindings.hasNext()) {
10933 IntentBindRecord i = bindings.next();
10934 if (!requestServiceBindingLocked(r, i, false)) {
10935 break;
10936 }
10937 }
10938 }
10939
10940 private final void realStartServiceLocked(ServiceRecord r,
10941 ProcessRecord app) throws RemoteException {
10942 if (app.thread == null) {
10943 throw new RemoteException();
10944 }
Amith Yamasani742a6712011-05-04 14:49:28 -070010945 if (DEBUG_MU)
10946 Slog.v(TAG_MU, "realStartServiceLocked, ServiceRecord.uid = " + r.appInfo.uid
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010947 + ", ProcessRecord.uid = " + app.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010948 r.app = app;
The Android Open Source Project10592532009-03-18 17:39:46 -070010949 r.restartTime = r.lastActivity = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010950
10951 app.services.add(r);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010952 bumpServiceExecutingLocked(r, "create");
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010953 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010954
10955 boolean created = false;
10956 try {
Dianne Hackborna33e3f72009-09-29 17:28:24 -070010957 mStringBuilder.setLength(0);
Dianne Hackborn21c241e2012-03-08 13:57:23 -080010958 r.intent.getIntent().toShortString(mStringBuilder, true, false, true, false);
Doug Zongker2bec3d42009-12-04 12:52:44 -080010959 EventLog.writeEvent(EventLogTags.AM_CREATE_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010960 System.identityHashCode(r), r.shortName,
Dianne Hackborna33e3f72009-09-29 17:28:24 -070010961 mStringBuilder.toString(), r.app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010962 synchronized (r.stats.getBatteryStats()) {
10963 r.stats.startLaunchedLocked();
10964 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -070010965 ensurePackageDexOpt(r.serviceInfo.packageName);
Dianne Hackborne2515ee2011-04-27 18:52:56 -040010966 app.thread.scheduleCreateService(r, r.serviceInfo,
10967 compatibilityInfoForPackageLocked(r.serviceInfo.applicationInfo));
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070010968 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010969 created = true;
10970 } finally {
10971 if (!created) {
10972 app.services.remove(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010973 scheduleServiceRestartLocked(r, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010974 }
10975 }
10976
10977 requestServiceBindingsLocked(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010978
10979 // If the service is in the started state, and there are no
10980 // pending arguments, then fake up one so its onStartCommand() will
10981 // be called.
10982 if (r.startRequested && r.callStart && r.pendingStarts.size() == 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070010983 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Dianne Hackborn21c241e2012-03-08 13:57:23 -080010984 null, null));
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010985 }
10986
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010987 sendServiceArgsLocked(r, true);
10988 }
10989
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010990 private final boolean scheduleServiceRestartLocked(ServiceRecord r,
10991 boolean allowCancel) {
10992 boolean canceled = false;
10993
Dianne Hackbornfd12af42009-08-27 00:44:33 -070010994 final long now = SystemClock.uptimeMillis();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010995 long minDuration = SERVICE_RESTART_DURATION;
Dianne Hackborn6ccd2af2009-08-27 12:26:44 -070010996 long resetTime = SERVICE_RESET_RUN_DURATION;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010997
Dianne Hackborn070783f2010-12-29 16:46:28 -080010998 if ((r.serviceInfo.applicationInfo.flags
10999 &ApplicationInfo.FLAG_PERSISTENT) != 0) {
11000 minDuration /= 4;
11001 }
11002
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011003 // Any delivered but not yet finished starts should be put back
11004 // on the pending list.
11005 final int N = r.deliveredStarts.size();
11006 if (N > 0) {
11007 for (int i=N-1; i>=0; i--) {
11008 ServiceRecord.StartItem si = r.deliveredStarts.get(i);
Dianne Hackborn39792d22010-08-19 18:01:52 -070011009 si.removeUriPermissionsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011010 if (si.intent == null) {
11011 // We'll generate this again if needed.
11012 } else if (!allowCancel || (si.deliveryCount < ServiceRecord.MAX_DELIVERY_COUNT
11013 && si.doneExecutingCount < ServiceRecord.MAX_DONE_EXECUTING_COUNT)) {
11014 r.pendingStarts.add(0, si);
11015 long dur = SystemClock.uptimeMillis() - si.deliveredTime;
11016 dur *= 2;
11017 if (minDuration < dur) minDuration = dur;
11018 if (resetTime < dur) resetTime = dur;
11019 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011020 Slog.w(TAG, "Canceling start item " + si.intent + " in service "
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011021 + r.name);
11022 canceled = true;
11023 }
11024 }
11025 r.deliveredStarts.clear();
11026 }
11027
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011028 r.totalRestartCount++;
11029 if (r.restartDelay == 0) {
11030 r.restartCount++;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011031 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011032 } else {
11033 // If it has been a "reasonably long time" since the service
11034 // was started, then reset our restart duration back to
11035 // the beginning, so we don't infinitely increase the duration
11036 // on a service that just occasionally gets killed (which is
11037 // a normal case, due to process being killed to reclaim memory).
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011038 if (now > (r.restartTime+resetTime)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011039 r.restartCount = 1;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011040 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011041 } else {
Dianne Hackborn070783f2010-12-29 16:46:28 -080011042 if ((r.serviceInfo.applicationInfo.flags
11043 &ApplicationInfo.FLAG_PERSISTENT) != 0) {
11044 // Services in peristent processes will restart much more
11045 // quickly, since they are pretty important. (Think SystemUI).
11046 r.restartDelay += minDuration/2;
11047 } else {
11048 r.restartDelay *= SERVICE_RESTART_DURATION_FACTOR;
11049 if (r.restartDelay < minDuration) {
11050 r.restartDelay = minDuration;
11051 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011052 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011053 }
11054 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011055
11056 r.nextRestartTime = now + r.restartDelay;
11057
11058 // Make sure that we don't end up restarting a bunch of services
11059 // all at the same time.
11060 boolean repeat;
11061 do {
11062 repeat = false;
11063 for (int i=mRestartingServices.size()-1; i>=0; i--) {
11064 ServiceRecord r2 = mRestartingServices.get(i);
11065 if (r2 != r && r.nextRestartTime
11066 >= (r2.nextRestartTime-SERVICE_MIN_RESTART_TIME_BETWEEN)
11067 && r.nextRestartTime
11068 < (r2.nextRestartTime+SERVICE_MIN_RESTART_TIME_BETWEEN)) {
11069 r.nextRestartTime = r2.nextRestartTime + SERVICE_MIN_RESTART_TIME_BETWEEN;
11070 r.restartDelay = r.nextRestartTime - now;
11071 repeat = true;
11072 break;
11073 }
11074 }
11075 } while (repeat);
11076
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011077 if (!mRestartingServices.contains(r)) {
11078 mRestartingServices.add(r);
11079 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011080
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011081 r.cancelNotification();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011082
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011083 mHandler.removeCallbacks(r.restarter);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011084 mHandler.postAtTime(r.restarter, r.nextRestartTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011085 r.nextRestartTime = SystemClock.uptimeMillis() + r.restartDelay;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011086 Slog.w(TAG, "Scheduling restart of crashed service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011087 + r.shortName + " in " + r.restartDelay + "ms");
Doug Zongker2bec3d42009-12-04 12:52:44 -080011088 EventLog.writeEvent(EventLogTags.AM_SCHEDULE_SERVICE_RESTART,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011089 r.shortName, r.restartDelay);
11090
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011091 return canceled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011092 }
11093
11094 final void performServiceRestartLocked(ServiceRecord r) {
11095 if (!mRestartingServices.contains(r)) {
11096 return;
11097 }
11098 bringUpServiceLocked(r, r.intent.getIntent().getFlags(), true);
11099 }
11100
11101 private final boolean unscheduleServiceRestartLocked(ServiceRecord r) {
11102 if (r.restartDelay == 0) {
11103 return false;
11104 }
11105 r.resetRestartCounter();
11106 mRestartingServices.remove(r);
11107 mHandler.removeCallbacks(r.restarter);
11108 return true;
11109 }
11110
11111 private final boolean bringUpServiceLocked(ServiceRecord r,
11112 int intentFlags, boolean whileRestarting) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011113 //Slog.i(TAG, "Bring up service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011114 //r.dump(" ");
11115
Dianne Hackborn36124872009-10-08 16:22:03 -070011116 if (r.app != null && r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011117 sendServiceArgsLocked(r, false);
11118 return true;
11119 }
11120
11121 if (!whileRestarting && r.restartDelay > 0) {
11122 // If waiting for a restart, then do nothing.
11123 return true;
11124 }
11125
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011126 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing up " + r + " " + r.intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011127
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011128 // We are now bringing the service up, so no longer in the
11129 // restarting state.
11130 mRestartingServices.remove(r);
11131
Dianne Hackborne7f97212011-02-24 14:40:20 -080011132 // Service is now being launched, its package can't be stopped.
11133 try {
11134 AppGlobals.getPackageManager().setPackageStoppedState(
11135 r.packageName, false);
11136 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080011137 } catch (IllegalArgumentException e) {
11138 Slog.w(TAG, "Failed trying to unstop package "
11139 + r.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080011140 }
11141
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011142 final boolean isolated = (r.serviceInfo.flags&ServiceInfo.FLAG_ISOLATED_PROCESS) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011143 final String appName = r.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011144 ProcessRecord app;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011145
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011146 if (!isolated) {
11147 app = getProcessRecordLocked(appName, r.appInfo.uid);
11148 if (DEBUG_MU)
11149 Slog.v(TAG_MU, "bringUpServiceLocked: appInfo.uid=" + r.appInfo.uid + " app=" + app);
11150 if (app != null && app.thread != null) {
11151 try {
11152 app.addPackage(r.appInfo.packageName);
11153 realStartServiceLocked(r, app);
11154 return true;
11155 } catch (RemoteException e) {
11156 Slog.w(TAG, "Exception when starting service " + r.shortName, e);
11157 }
11158
11159 // If a dead object exception was thrown -- fall through to
11160 // restart the application.
11161 }
11162 } else {
11163 // If this service runs in an isolated process, then each time
11164 // we call startProcessLocked() we will get a new isolated
11165 // process, starting another process if we are currently waiting
11166 // for a previous process to come up. To deal with this, we store
11167 // in the service any current isolated process it is running in or
11168 // waiting to have come up.
11169 app = r.isolatedProc;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011170 }
11171
Dianne Hackborn36124872009-10-08 16:22:03 -070011172 // Not running -- get it started, and enqueue this service record
11173 // to be executed when the app comes up.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011174 if (app == null) {
11175 if ((app=startProcessLocked(appName, r.appInfo, true, intentFlags,
11176 "service", r.name, false, isolated)) == null) {
11177 Slog.w(TAG, "Unable to launch app "
11178 + r.appInfo.packageName + "/"
11179 + r.appInfo.uid + " for service "
11180 + r.intent.getIntent() + ": process is bad");
11181 bringDownServiceLocked(r, true);
11182 return false;
11183 }
11184 if (isolated) {
11185 r.isolatedProc = app;
11186 }
Dianne Hackborn36124872009-10-08 16:22:03 -070011187 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011188
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011189 if (!mPendingServices.contains(r)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011190 mPendingServices.add(r);
11191 }
Dianne Hackborn36124872009-10-08 16:22:03 -070011192
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011193 return true;
11194 }
11195
11196 private final void bringDownServiceLocked(ServiceRecord r, boolean force) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011197 //Slog.i(TAG, "Bring down service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011198 //r.dump(" ");
11199
11200 // Does it still need to run?
11201 if (!force && r.startRequested) {
11202 return;
11203 }
11204 if (r.connections.size() > 0) {
11205 if (!force) {
11206 // XXX should probably keep a count of the number of auto-create
11207 // connections directly in the service.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011208 Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011209 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011210 ArrayList<ConnectionRecord> cr = it.next();
11211 for (int i=0; i<cr.size(); i++) {
11212 if ((cr.get(i).flags&Context.BIND_AUTO_CREATE) != 0) {
11213 return;
11214 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011215 }
11216 }
11217 }
11218
11219 // Report to all of the connections that the service is no longer
11220 // available.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011221 Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011222 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011223 ArrayList<ConnectionRecord> c = it.next();
11224 for (int i=0; i<c.size(); i++) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011225 ConnectionRecord cr = c.get(i);
11226 // There is still a connection to the service that is
11227 // being brought down. Mark it as dead.
11228 cr.serviceDead = true;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011229 try {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011230 cr.conn.connected(r.name, null);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011231 } catch (Exception e) {
11232 Slog.w(TAG, "Failure disconnecting service " + r.name +
11233 " to connection " + c.get(i).conn.asBinder() +
11234 " (in " + c.get(i).binding.client.processName + ")", e);
11235 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011236 }
11237 }
11238 }
11239
11240 // Tell the service that it has been unbound.
11241 if (r.bindings.size() > 0 && r.app != null && r.app.thread != null) {
11242 Iterator<IntentBindRecord> it = r.bindings.values().iterator();
11243 while (it.hasNext()) {
11244 IntentBindRecord ibr = it.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -080011245 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down binding " + ibr
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011246 + ": hasBound=" + ibr.hasBound);
11247 if (r.app != null && r.app.thread != null && ibr.hasBound) {
11248 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011249 bumpServiceExecutingLocked(r, "bring down unbind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011250 updateOomAdjLocked(r.app);
11251 ibr.hasBound = false;
11252 r.app.thread.scheduleUnbindService(r,
11253 ibr.intent.getIntent());
11254 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011255 Slog.w(TAG, "Exception when unbinding service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011256 + r.shortName, e);
11257 serviceDoneExecutingLocked(r, true);
11258 }
11259 }
11260 }
11261 }
11262
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011263 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down " + r + " " + r.intent);
Doug Zongker2bec3d42009-12-04 12:52:44 -080011264 EventLog.writeEvent(EventLogTags.AM_DESTROY_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011265 System.identityHashCode(r), r.shortName,
11266 (r.app != null) ? r.app.pid : -1);
11267
Amith Yamasani742a6712011-05-04 14:49:28 -070011268 mServiceMap.removeServiceByName(r.name, r.userId);
11269 mServiceMap.removeServiceByIntent(r.intent, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011270 r.totalRestartCount = 0;
11271 unscheduleServiceRestartLocked(r);
11272
11273 // Also make sure it is not on the pending list.
11274 int N = mPendingServices.size();
11275 for (int i=0; i<N; i++) {
11276 if (mPendingServices.get(i) == r) {
11277 mPendingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011278 if (DEBUG_SERVICE) Slog.v(TAG, "Removed pending: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011279 i--;
11280 N--;
11281 }
11282 }
11283
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011284 r.cancelNotification();
11285 r.isForeground = false;
11286 r.foregroundId = 0;
11287 r.foregroundNoti = null;
11288
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011289 // Clear start entries.
Dianne Hackborn39792d22010-08-19 18:01:52 -070011290 r.clearDeliveredStartsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011291 r.pendingStarts.clear();
11292
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011293 if (r.app != null) {
11294 synchronized (r.stats.getBatteryStats()) {
11295 r.stats.stopLaunchedLocked();
11296 }
11297 r.app.services.remove(r);
11298 if (r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011299 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011300 bumpServiceExecutingLocked(r, "stop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011301 mStoppingServices.add(r);
11302 updateOomAdjLocked(r.app);
11303 r.app.thread.scheduleStopService(r);
11304 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011305 Slog.w(TAG, "Exception when stopping service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011306 + r.shortName, e);
11307 serviceDoneExecutingLocked(r, true);
11308 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011309 updateServiceForegroundLocked(r.app, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011310 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011311 if (DEBUG_SERVICE) Slog.v(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011312 TAG, "Removed service that has no process: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011313 }
11314 } 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 is not running: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011317 }
Vairavan Srinivasana207ce22010-12-23 13:51:48 -080011318
11319 if (r.bindings.size() > 0) {
11320 r.bindings.clear();
11321 }
11322
11323 if (r.restarter instanceof ServiceRestarter) {
11324 ((ServiceRestarter)r.restarter).setService(null);
11325 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011326 }
11327
11328 ComponentName startServiceLocked(IApplicationThread caller,
11329 Intent service, String resolvedType,
11330 int callingPid, int callingUid) {
11331 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011332 if (DEBUG_SERVICE) Slog.v(TAG, "startService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011333 + " type=" + resolvedType + " args=" + service.getExtras());
11334
11335 if (caller != null) {
11336 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11337 if (callerApp == null) {
11338 throw new SecurityException(
11339 "Unable to find app for caller " + caller
11340 + " (pid=" + Binder.getCallingPid()
11341 + ") when starting service " + service);
11342 }
11343 }
11344
11345 ServiceLookupResult res =
11346 retrieveServiceLocked(service, resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011347 callingPid, callingUid, UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011348 if (res == null) {
11349 return null;
11350 }
11351 if (res.record == null) {
11352 return new ComponentName("!", res.permission != null
11353 ? res.permission : "private to package");
11354 }
11355 ServiceRecord r = res.record;
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011356 NeededUriGrants neededGrants = checkGrantUriPermissionFromIntentLocked(
11357 callingUid, r.packageName, service, service.getFlags(), null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011358 if (unscheduleServiceRestartLocked(r)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011359 if (DEBUG_SERVICE) Slog.v(TAG, "START SERVICE WHILE RESTART PENDING: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011360 }
11361 r.startRequested = true;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011362 r.callStart = false;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011363 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011364 service, neededGrants));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011365 r.lastActivity = SystemClock.uptimeMillis();
11366 synchronized (r.stats.getBatteryStats()) {
11367 r.stats.startRunningLocked();
11368 }
11369 if (!bringUpServiceLocked(r, service.getFlags(), false)) {
11370 return new ComponentName("!", "Service process is bad");
11371 }
11372 return r.name;
11373 }
11374 }
11375
11376 public ComponentName startService(IApplicationThread caller, Intent service,
11377 String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011378 enforceNotIsolatedCaller("startService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011379 // Refuse possible leaked file descriptors
11380 if (service != null && service.hasFileDescriptors() == true) {
11381 throw new IllegalArgumentException("File descriptors passed in Intent");
11382 }
11383
Amith Yamasani742a6712011-05-04 14:49:28 -070011384 if (DEBUG_SERVICE)
11385 Slog.v(TAG, "startService: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011386 synchronized(this) {
11387 final int callingPid = Binder.getCallingPid();
11388 final int callingUid = Binder.getCallingUid();
11389 final long origId = Binder.clearCallingIdentity();
11390 ComponentName res = startServiceLocked(caller, service,
11391 resolvedType, callingPid, callingUid);
11392 Binder.restoreCallingIdentity(origId);
11393 return res;
11394 }
11395 }
11396
11397 ComponentName startServiceInPackage(int uid,
11398 Intent service, String resolvedType) {
11399 synchronized(this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070011400 if (DEBUG_SERVICE)
11401 Slog.v(TAG, "startServiceInPackage: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011402 final long origId = Binder.clearCallingIdentity();
11403 ComponentName res = startServiceLocked(null, service,
11404 resolvedType, -1, uid);
11405 Binder.restoreCallingIdentity(origId);
11406 return res;
11407 }
11408 }
11409
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011410 private void stopServiceLocked(ServiceRecord service) {
11411 synchronized (service.stats.getBatteryStats()) {
11412 service.stats.stopRunningLocked();
11413 }
11414 service.startRequested = false;
11415 service.callStart = false;
11416 bringDownServiceLocked(service, false);
11417 }
11418
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011419 public int stopService(IApplicationThread caller, Intent service,
11420 String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011421 enforceNotIsolatedCaller("stopService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011422 // Refuse possible leaked file descriptors
11423 if (service != null && service.hasFileDescriptors() == true) {
11424 throw new IllegalArgumentException("File descriptors passed in Intent");
11425 }
11426
11427 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011428 if (DEBUG_SERVICE) Slog.v(TAG, "stopService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011429 + " type=" + resolvedType);
11430
11431 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11432 if (caller != null && callerApp == null) {
11433 throw new SecurityException(
11434 "Unable to find app for caller " + caller
11435 + " (pid=" + Binder.getCallingPid()
11436 + ") when stopping service " + service);
11437 }
11438
11439 // If this service is active, make sure it is stopped.
11440 ServiceLookupResult r = findServiceLocked(service, resolvedType);
11441 if (r != null) {
11442 if (r.record != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011443 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011444 try {
11445 stopServiceLocked(r.record);
11446 } finally {
11447 Binder.restoreCallingIdentity(origId);
11448 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011449 return 1;
11450 }
11451 return -1;
11452 }
11453 }
11454
11455 return 0;
11456 }
11457
11458 public IBinder peekService(Intent service, String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011459 enforceNotIsolatedCaller("peekService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011460 // Refuse possible leaked file descriptors
11461 if (service != null && service.hasFileDescriptors() == true) {
11462 throw new IllegalArgumentException("File descriptors passed in Intent");
11463 }
11464
11465 IBinder ret = null;
11466
11467 synchronized(this) {
11468 ServiceLookupResult r = findServiceLocked(service, resolvedType);
11469
11470 if (r != null) {
11471 // r.record is null if findServiceLocked() failed the caller permission check
11472 if (r.record == null) {
11473 throw new SecurityException(
11474 "Permission Denial: Accessing service " + r.record.name
11475 + " from pid=" + Binder.getCallingPid()
11476 + ", uid=" + Binder.getCallingUid()
11477 + " requires " + r.permission);
11478 }
11479 IntentBindRecord ib = r.record.bindings.get(r.record.intent);
11480 if (ib != null) {
11481 ret = ib.binder;
11482 }
11483 }
11484 }
11485
11486 return ret;
11487 }
11488
11489 public boolean stopServiceToken(ComponentName className, IBinder token,
11490 int startId) {
11491 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011492 if (DEBUG_SERVICE) Slog.v(TAG, "stopServiceToken: " + className
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011493 + " " + token + " startId=" + startId);
11494 ServiceRecord r = findServiceLocked(className, token);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011495 if (r != null) {
11496 if (startId >= 0) {
11497 // Asked to only stop if done with all work. Note that
11498 // to avoid leaks, we will take this as dropping all
11499 // start items up to and including this one.
11500 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
11501 if (si != null) {
11502 while (r.deliveredStarts.size() > 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -070011503 ServiceRecord.StartItem cur = r.deliveredStarts.remove(0);
11504 cur.removeUriPermissionsLocked();
11505 if (cur == si) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011506 break;
11507 }
11508 }
11509 }
11510
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011511 if (r.getLastStartId() != startId) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011512 return false;
11513 }
11514
11515 if (r.deliveredStarts.size() > 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011516 Slog.w(TAG, "stopServiceToken startId " + startId
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011517 + " is last, but have " + r.deliveredStarts.size()
11518 + " remaining args");
11519 }
11520 }
11521
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011522 synchronized (r.stats.getBatteryStats()) {
11523 r.stats.stopRunningLocked();
11524 r.startRequested = false;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011525 r.callStart = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011526 }
11527 final long origId = Binder.clearCallingIdentity();
11528 bringDownServiceLocked(r, false);
11529 Binder.restoreCallingIdentity(origId);
11530 return true;
11531 }
11532 }
11533 return false;
11534 }
11535
11536 public void setServiceForeground(ComponentName className, IBinder token,
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011537 int id, Notification notification, boolean removeNotification) {
11538 final long origId = Binder.clearCallingIdentity();
11539 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011540 synchronized(this) {
11541 ServiceRecord r = findServiceLocked(className, token);
11542 if (r != null) {
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011543 if (id != 0) {
11544 if (notification == null) {
11545 throw new IllegalArgumentException("null notification");
11546 }
11547 if (r.foregroundId != id) {
11548 r.cancelNotification();
11549 r.foregroundId = id;
11550 }
11551 notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
11552 r.foregroundNoti = notification;
11553 r.isForeground = true;
11554 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011555 if (r.app != null) {
11556 updateServiceForegroundLocked(r.app, true);
11557 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011558 } else {
11559 if (r.isForeground) {
11560 r.isForeground = false;
11561 if (r.app != null) {
Dianne Hackborn8633e682010-04-22 16:03:41 -070011562 updateLruProcessLocked(r.app, false, true);
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011563 updateServiceForegroundLocked(r.app, true);
11564 }
11565 }
11566 if (removeNotification) {
11567 r.cancelNotification();
11568 r.foregroundId = 0;
11569 r.foregroundNoti = null;
11570 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011571 }
11572 }
11573 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011574 } finally {
11575 Binder.restoreCallingIdentity(origId);
11576 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011577 }
11578
11579 public void updateServiceForegroundLocked(ProcessRecord proc, boolean oomAdj) {
11580 boolean anyForeground = false;
Dianne Hackborn860755f2010-06-03 18:47:52 -070011581 for (ServiceRecord sr : proc.services) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011582 if (sr.isForeground) {
11583 anyForeground = true;
11584 break;
11585 }
11586 }
11587 if (anyForeground != proc.foregroundServices) {
11588 proc.foregroundServices = anyForeground;
11589 if (oomAdj) {
11590 updateOomAdjLocked();
11591 }
11592 }
11593 }
11594
11595 public int bindService(IApplicationThread caller, IBinder token,
11596 Intent service, String resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011597 IServiceConnection connection, int flags, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011598 enforceNotIsolatedCaller("bindService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011599 // Refuse possible leaked file descriptors
11600 if (service != null && service.hasFileDescriptors() == true) {
11601 throw new IllegalArgumentException("File descriptors passed in Intent");
11602 }
11603
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011604 checkValidCaller(Binder.getCallingUid(), userId);
11605
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011606 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011607 if (DEBUG_SERVICE) Slog.v(TAG, "bindService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011608 + " type=" + resolvedType + " conn=" + connection.asBinder()
11609 + " flags=0x" + Integer.toHexString(flags));
Amith Yamasani742a6712011-05-04 14:49:28 -070011610 if (DEBUG_MU)
11611 Slog.i(TAG_MU, "bindService uid=" + Binder.getCallingUid() + " origUid="
11612 + Binder.getOrigCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011613 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11614 if (callerApp == null) {
11615 throw new SecurityException(
11616 "Unable to find app for caller " + caller
11617 + " (pid=" + Binder.getCallingPid()
11618 + ") when binding service " + service);
11619 }
11620
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011621 ActivityRecord activity = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011622 if (token != null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070011623 activity = mMainStack.isInStackLocked(token);
11624 if (activity == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011625 Slog.w(TAG, "Binding with unknown activity: " + token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011626 return 0;
11627 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011628 }
11629
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011630 int clientLabel = 0;
11631 PendingIntent clientIntent = null;
11632
11633 if (callerApp.info.uid == Process.SYSTEM_UID) {
11634 // Hacky kind of thing -- allow system stuff to tell us
11635 // what they are, so we can report this elsewhere for
11636 // others to know why certain services are running.
11637 try {
11638 clientIntent = (PendingIntent)service.getParcelableExtra(
11639 Intent.EXTRA_CLIENT_INTENT);
11640 } catch (RuntimeException e) {
11641 }
11642 if (clientIntent != null) {
11643 clientLabel = service.getIntExtra(Intent.EXTRA_CLIENT_LABEL, 0);
11644 if (clientLabel != 0) {
11645 // There are no useful extras in the intent, trash them.
11646 // System code calling with this stuff just needs to know
11647 // this will happen.
11648 service = service.cloneFilter();
11649 }
11650 }
11651 }
11652
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011653 ServiceLookupResult res =
11654 retrieveServiceLocked(service, resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011655 Binder.getCallingPid(), Binder.getCallingUid(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011656 if (res == null) {
11657 return 0;
11658 }
11659 if (res.record == null) {
11660 return -1;
11661 }
11662 ServiceRecord s = res.record;
11663
11664 final long origId = Binder.clearCallingIdentity();
11665
11666 if (unscheduleServiceRestartLocked(s)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011667 if (DEBUG_SERVICE) Slog.v(TAG, "BIND SERVICE WHILE RESTART PENDING: "
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011668 + s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011669 }
11670
11671 AppBindRecord b = s.retrieveAppBindingLocked(service, callerApp);
11672 ConnectionRecord c = new ConnectionRecord(b, activity,
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011673 connection, flags, clientLabel, clientIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011674
11675 IBinder binder = connection.asBinder();
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011676 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
11677 if (clist == null) {
11678 clist = new ArrayList<ConnectionRecord>();
11679 s.connections.put(binder, clist);
11680 }
11681 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011682 b.connections.add(c);
11683 if (activity != null) {
11684 if (activity.connections == null) {
11685 activity.connections = new HashSet<ConnectionRecord>();
11686 }
11687 activity.connections.add(c);
11688 }
11689 b.client.connections.add(c);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070011690 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
11691 b.client.hasAboveClient = true;
11692 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011693 clist = mServiceConnections.get(binder);
11694 if (clist == null) {
11695 clist = new ArrayList<ConnectionRecord>();
11696 mServiceConnections.put(binder, clist);
11697 }
11698 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011699
11700 if ((flags&Context.BIND_AUTO_CREATE) != 0) {
11701 s.lastActivity = SystemClock.uptimeMillis();
11702 if (!bringUpServiceLocked(s, service.getFlags(), false)) {
11703 return 0;
11704 }
11705 }
11706
11707 if (s.app != null) {
11708 // This could have made the service more important.
11709 updateOomAdjLocked(s.app);
11710 }
11711
Joe Onorato8a9b2202010-02-26 18:56:32 -080011712 if (DEBUG_SERVICE) Slog.v(TAG, "Bind " + s + " with " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011713 + ": received=" + b.intent.received
11714 + " apps=" + b.intent.apps.size()
11715 + " doRebind=" + b.intent.doRebind);
11716
11717 if (s.app != null && b.intent.received) {
11718 // Service is already running, so we can immediately
11719 // publish the connection.
11720 try {
11721 c.conn.connected(s.name, b.intent.binder);
11722 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011723 Slog.w(TAG, "Failure sending service " + s.shortName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011724 + " to connection " + c.conn.asBinder()
11725 + " (in " + c.binding.client.processName + ")", e);
11726 }
11727
11728 // If this is the first app connected back to this binding,
11729 // and the service had previously asked to be told when
11730 // rebound, then do so.
11731 if (b.intent.apps.size() == 1 && b.intent.doRebind) {
11732 requestServiceBindingLocked(s, b.intent, true);
11733 }
11734 } else if (!b.intent.requested) {
11735 requestServiceBindingLocked(s, b.intent, false);
11736 }
11737
11738 Binder.restoreCallingIdentity(origId);
11739 }
11740
11741 return 1;
11742 }
11743
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070011744 void removeConnectionLocked(
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011745 ConnectionRecord c, ProcessRecord skipApp, ActivityRecord skipAct) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011746 IBinder binder = c.conn.asBinder();
11747 AppBindRecord b = c.binding;
11748 ServiceRecord s = b.service;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011749 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
11750 if (clist != null) {
11751 clist.remove(c);
11752 if (clist.size() == 0) {
11753 s.connections.remove(binder);
11754 }
11755 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011756 b.connections.remove(c);
11757 if (c.activity != null && c.activity != skipAct) {
11758 if (c.activity.connections != null) {
11759 c.activity.connections.remove(c);
11760 }
11761 }
11762 if (b.client != skipApp) {
11763 b.client.connections.remove(c);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070011764 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
11765 b.client.updateHasAboveClientLocked();
11766 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011767 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011768 clist = mServiceConnections.get(binder);
11769 if (clist != null) {
11770 clist.remove(c);
11771 if (clist.size() == 0) {
11772 mServiceConnections.remove(binder);
11773 }
11774 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011775
11776 if (b.connections.size() == 0) {
11777 b.intent.apps.remove(b.client);
11778 }
11779
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011780 if (!c.serviceDead) {
11781 if (DEBUG_SERVICE) Slog.v(TAG, "Disconnecting binding " + b.intent
11782 + ": shouldUnbind=" + b.intent.hasBound);
11783 if (s.app != null && s.app.thread != null && b.intent.apps.size() == 0
11784 && b.intent.hasBound) {
11785 try {
11786 bumpServiceExecutingLocked(s, "unbind");
11787 updateOomAdjLocked(s.app);
11788 b.intent.hasBound = false;
11789 // Assume the client doesn't want to know about a rebind;
11790 // we will deal with that later if it asks for one.
11791 b.intent.doRebind = false;
11792 s.app.thread.scheduleUnbindService(s, b.intent.intent.getIntent());
11793 } catch (Exception e) {
11794 Slog.w(TAG, "Exception when unbinding service " + s.shortName, e);
11795 serviceDoneExecutingLocked(s, true);
11796 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011797 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011798
11799 if ((c.flags&Context.BIND_AUTO_CREATE) != 0) {
11800 bringDownServiceLocked(s, false);
11801 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011802 }
11803 }
11804
11805 public boolean unbindService(IServiceConnection connection) {
11806 synchronized (this) {
11807 IBinder binder = connection.asBinder();
Joe Onorato8a9b2202010-02-26 18:56:32 -080011808 if (DEBUG_SERVICE) Slog.v(TAG, "unbindService: conn=" + binder);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011809 ArrayList<ConnectionRecord> clist = mServiceConnections.get(binder);
11810 if (clist == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011811 Slog.w(TAG, "Unbind failed: could not find connection for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011812 + connection.asBinder());
11813 return false;
11814 }
11815
11816 final long origId = Binder.clearCallingIdentity();
11817
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011818 while (clist.size() > 0) {
11819 ConnectionRecord r = clist.get(0);
11820 removeConnectionLocked(r, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011821
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011822 if (r.binding.service.app != null) {
11823 // This could have made the service less important.
11824 updateOomAdjLocked(r.binding.service.app);
11825 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011826 }
11827
11828 Binder.restoreCallingIdentity(origId);
11829 }
11830
11831 return true;
11832 }
11833
11834 public void publishService(IBinder token, Intent intent, IBinder service) {
11835 // Refuse possible leaked file descriptors
11836 if (intent != null && intent.hasFileDescriptors() == true) {
11837 throw new IllegalArgumentException("File descriptors passed in Intent");
11838 }
11839
11840 synchronized(this) {
11841 if (!(token instanceof ServiceRecord)) {
11842 throw new IllegalArgumentException("Invalid service token");
11843 }
11844 ServiceRecord r = (ServiceRecord)token;
11845
11846 final long origId = Binder.clearCallingIdentity();
11847
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011848 if (DEBUG_SERVICE) Slog.v(TAG, "PUBLISHING " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011849 + " " + intent + ": " + service);
11850 if (r != null) {
11851 Intent.FilterComparison filter
11852 = new Intent.FilterComparison(intent);
11853 IntentBindRecord b = r.bindings.get(filter);
11854 if (b != null && !b.received) {
11855 b.binder = service;
11856 b.requested = true;
11857 b.received = true;
11858 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011859 Iterator<ArrayList<ConnectionRecord>> it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011860 = r.connections.values().iterator();
11861 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011862 ArrayList<ConnectionRecord> clist = it.next();
11863 for (int i=0; i<clist.size(); i++) {
11864 ConnectionRecord c = clist.get(i);
11865 if (!filter.equals(c.binding.intent.intent)) {
11866 if (DEBUG_SERVICE) Slog.v(
11867 TAG, "Not publishing to: " + c);
11868 if (DEBUG_SERVICE) Slog.v(
11869 TAG, "Bound intent: " + c.binding.intent.intent);
11870 if (DEBUG_SERVICE) Slog.v(
11871 TAG, "Published intent: " + intent);
11872 continue;
11873 }
11874 if (DEBUG_SERVICE) Slog.v(TAG, "Publishing to: " + c);
11875 try {
11876 c.conn.connected(r.name, service);
11877 } catch (Exception e) {
11878 Slog.w(TAG, "Failure sending service " + r.name +
11879 " to connection " + c.conn.asBinder() +
11880 " (in " + c.binding.client.processName + ")", e);
11881 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011882 }
11883 }
11884 }
11885 }
11886
11887 serviceDoneExecutingLocked(r, mStoppingServices.contains(r));
11888
11889 Binder.restoreCallingIdentity(origId);
11890 }
11891 }
11892 }
11893
11894 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
11895 // Refuse possible leaked file descriptors
11896 if (intent != null && intent.hasFileDescriptors() == true) {
11897 throw new IllegalArgumentException("File descriptors passed in Intent");
11898 }
11899
11900 synchronized(this) {
11901 if (!(token instanceof ServiceRecord)) {
11902 throw new IllegalArgumentException("Invalid service token");
11903 }
11904 ServiceRecord r = (ServiceRecord)token;
11905
11906 final long origId = Binder.clearCallingIdentity();
11907
11908 if (r != null) {
11909 Intent.FilterComparison filter
11910 = new Intent.FilterComparison(intent);
11911 IntentBindRecord b = r.bindings.get(filter);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011912 if (DEBUG_SERVICE) Slog.v(TAG, "unbindFinished in " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011913 + " at " + b + ": apps="
11914 + (b != null ? b.apps.size() : 0));
Per Edelberg78f9fff2010-08-30 20:01:35 +020011915
11916 boolean inStopping = mStoppingServices.contains(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011917 if (b != null) {
Per Edelberg78f9fff2010-08-30 20:01:35 +020011918 if (b.apps.size() > 0 && !inStopping) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011919 // Applications have already bound since the last
11920 // unbind, so just rebind right here.
11921 requestServiceBindingLocked(r, b, true);
11922 } else {
11923 // Note to tell the service the next time there is
11924 // a new client.
11925 b.doRebind = true;
11926 }
11927 }
11928
Per Edelberg78f9fff2010-08-30 20:01:35 +020011929 serviceDoneExecutingLocked(r, inStopping);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011930
11931 Binder.restoreCallingIdentity(origId);
11932 }
11933 }
11934 }
11935
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011936 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011937 synchronized(this) {
11938 if (!(token instanceof ServiceRecord)) {
11939 throw new IllegalArgumentException("Invalid service token");
11940 }
11941 ServiceRecord r = (ServiceRecord)token;
11942 boolean inStopping = mStoppingServices.contains(token);
11943 if (r != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011944 if (r != token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011945 Slog.w(TAG, "Done executing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011946 + " with incorrect token: given " + token
11947 + ", expected " + r);
11948 return;
11949 }
11950
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011951 if (type == 1) {
11952 // This is a call from a service start... take care of
11953 // book-keeping.
11954 r.callStart = true;
11955 switch (res) {
11956 case Service.START_STICKY_COMPATIBILITY:
11957 case Service.START_STICKY: {
11958 // We are done with the associated start arguments.
11959 r.findDeliveredStart(startId, true);
11960 // Don't stop if killed.
11961 r.stopIfKilled = false;
11962 break;
11963 }
11964 case Service.START_NOT_STICKY: {
11965 // We are done with the associated start arguments.
11966 r.findDeliveredStart(startId, true);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011967 if (r.getLastStartId() == startId) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011968 // There is no more work, and this service
11969 // doesn't want to hang around if killed.
11970 r.stopIfKilled = true;
11971 }
11972 break;
11973 }
11974 case Service.START_REDELIVER_INTENT: {
11975 // We'll keep this item until they explicitly
11976 // call stop for it, but keep track of the fact
11977 // that it was delivered.
11978 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
11979 if (si != null) {
11980 si.deliveryCount = 0;
11981 si.doneExecutingCount++;
11982 // Don't stop if killed.
11983 r.stopIfKilled = true;
11984 }
11985 break;
11986 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011987 case Service.START_TASK_REMOVED_COMPLETE: {
11988 // Special processing for onTaskRemoved(). Don't
11989 // impact normal onStartCommand() processing.
11990 r.findDeliveredStart(startId, true);
11991 break;
11992 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011993 default:
11994 throw new IllegalArgumentException(
11995 "Unknown service start result: " + res);
11996 }
11997 if (res == Service.START_STICKY_COMPATIBILITY) {
11998 r.callStart = false;
11999 }
12000 }
Amith Yamasani742a6712011-05-04 14:49:28 -070012001 if (DEBUG_MU)
12002 Slog.v(TAG_MU, "before serviceDontExecutingLocked, uid="
12003 + Binder.getOrigCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012004 final long origId = Binder.clearCallingIdentity();
12005 serviceDoneExecutingLocked(r, inStopping);
12006 Binder.restoreCallingIdentity(origId);
12007 } else {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012008 Slog.w(TAG, "Done executing unknown service from pid "
12009 + Binder.getCallingPid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012010 }
12011 }
12012 }
12013
12014 public void serviceDoneExecutingLocked(ServiceRecord r, boolean inStopping) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012015 if (DEBUG_SERVICE) Slog.v(TAG, "<<< DONE EXECUTING " + r
12016 + ": nesting=" + r.executeNesting
12017 + ", inStopping=" + inStopping + ", app=" + r.app);
Dianne Hackborn287952c2010-09-22 22:34:31 -070012018 else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG, "<<< DONE EXECUTING " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012019 r.executeNesting--;
12020 if (r.executeNesting <= 0 && r.app != null) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012021 if (DEBUG_SERVICE) Slog.v(TAG,
12022 "Nesting at 0 of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012023 r.app.executingServices.remove(r);
12024 if (r.app.executingServices.size() == 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012025 if (DEBUG_SERVICE || DEBUG_SERVICE_EXECUTING) Slog.v(TAG,
12026 "No more executingServices of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012027 mHandler.removeMessages(SERVICE_TIMEOUT_MSG, r.app);
12028 }
12029 if (inStopping) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012030 if (DEBUG_SERVICE) Slog.v(TAG,
12031 "doneExecuting remove stopping " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012032 mStoppingServices.remove(r);
Mattias Petersson3996b412010-10-27 09:32:51 +020012033 r.bindings.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012034 }
12035 updateOomAdjLocked(r.app);
12036 }
12037 }
12038
12039 void serviceTimeout(ProcessRecord proc) {
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012040 String anrMessage = null;
12041
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012042 synchronized(this) {
12043 if (proc.executingServices.size() == 0 || proc.thread == null) {
12044 return;
12045 }
12046 long maxTime = SystemClock.uptimeMillis() - SERVICE_TIMEOUT;
12047 Iterator<ServiceRecord> it = proc.executingServices.iterator();
12048 ServiceRecord timeout = null;
12049 long nextTime = 0;
12050 while (it.hasNext()) {
12051 ServiceRecord sr = it.next();
12052 if (sr.executingStart < maxTime) {
12053 timeout = sr;
12054 break;
12055 }
12056 if (sr.executingStart > nextTime) {
12057 nextTime = sr.executingStart;
12058 }
12059 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012060 if (timeout != null && mLruProcesses.contains(proc)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012061 Slog.w(TAG, "Timeout executing service: " + timeout);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012062 anrMessage = "Executing service " + timeout.shortName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012063 } else {
12064 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
12065 msg.obj = proc;
12066 mHandler.sendMessageAtTime(msg, nextTime+SERVICE_TIMEOUT);
12067 }
12068 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012069
12070 if (anrMessage != null) {
12071 appNotResponding(proc, null, null, anrMessage);
12072 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012073 }
12074
12075 // =========================================================
Christopher Tate181fafa2009-05-14 11:12:14 -070012076 // BACKUP AND RESTORE
12077 // =========================================================
12078
12079 // Cause the target app to be launched if necessary and its backup agent
12080 // instantiated. The backup agent will invoke backupAgentCreated() on the
12081 // activity manager to announce its creation.
12082 public boolean bindBackupAgent(ApplicationInfo app, int backupMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012083 if (DEBUG_BACKUP) Slog.v(TAG, "startBackupAgent: app=" + app + " mode=" + backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070012084 enforceCallingPermission("android.permission.BACKUP", "startBackupAgent");
12085
12086 synchronized(this) {
12087 // !!! TODO: currently no check here that we're already bound
12088 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
12089 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
12090 synchronized (stats) {
12091 ss = stats.getServiceStatsLocked(app.uid, app.packageName, app.name);
12092 }
12093
Dianne Hackborne7f97212011-02-24 14:40:20 -080012094 // Backup agent is now in use, its package can't be stopped.
12095 try {
12096 AppGlobals.getPackageManager().setPackageStoppedState(
12097 app.packageName, false);
12098 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080012099 } catch (IllegalArgumentException e) {
12100 Slog.w(TAG, "Failed trying to unstop package "
12101 + app.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080012102 }
12103
Christopher Tate181fafa2009-05-14 11:12:14 -070012104 BackupRecord r = new BackupRecord(ss, app, backupMode);
Christopher Tate4a627c72011-04-01 14:43:32 -070012105 ComponentName hostingName = (backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL)
12106 ? new ComponentName(app.packageName, app.backupAgentName)
12107 : new ComponentName("android", "FullBackupAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -070012108 // startProcessLocked() returns existing proc's record if it's already running
12109 ProcessRecord proc = startProcessLocked(app.processName, app,
Dianne Hackborna0c283e2012-02-09 10:47:01 -080012110 false, 0, "backup", hostingName, false, false);
Christopher Tate181fafa2009-05-14 11:12:14 -070012111 if (proc == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012112 Slog.e(TAG, "Unable to start backup agent process " + r);
Christopher Tate181fafa2009-05-14 11:12:14 -070012113 return false;
12114 }
12115
12116 r.app = proc;
12117 mBackupTarget = r;
12118 mBackupAppName = app.packageName;
12119
Christopher Tate6fa95972009-06-05 18:43:55 -070012120 // Try not to kill the process during backup
12121 updateOomAdjLocked(proc);
12122
Christopher Tate181fafa2009-05-14 11:12:14 -070012123 // If the process is already attached, schedule the creation of the backup agent now.
12124 // If it is not yet live, this will be done when it attaches to the framework.
12125 if (proc.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012126 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc already running: " + proc);
Christopher Tate181fafa2009-05-14 11:12:14 -070012127 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040012128 proc.thread.scheduleCreateBackupAgent(app,
12129 compatibilityInfoForPackageLocked(app), backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070012130 } catch (RemoteException e) {
Christopher Tate436344a2009-09-30 16:17:37 -070012131 // Will time out on the backup manager side
Christopher Tate181fafa2009-05-14 11:12:14 -070012132 }
12133 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012134 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc not running, waiting for attach");
Christopher Tate181fafa2009-05-14 11:12:14 -070012135 }
12136 // Invariants: at this point, the target app process exists and the application
12137 // is either already running or in the process of coming up. mBackupTarget and
12138 // mBackupAppName describe the app, so that when it binds back to the AM we
12139 // know that it's scheduled for a backup-agent operation.
12140 }
12141
12142 return true;
12143 }
12144
12145 // A backup agent has just come up
12146 public void backupAgentCreated(String agentPackageName, IBinder agent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012147 if (DEBUG_BACKUP) Slog.v(TAG, "backupAgentCreated: " + agentPackageName
Christopher Tate181fafa2009-05-14 11:12:14 -070012148 + " = " + agent);
12149
12150 synchronized(this) {
12151 if (!agentPackageName.equals(mBackupAppName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012152 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
Christopher Tate181fafa2009-05-14 11:12:14 -070012153 return;
12154 }
Dianne Hackborn06740692010-09-22 22:46:21 -070012155 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012156
Dianne Hackborn06740692010-09-22 22:46:21 -070012157 long oldIdent = Binder.clearCallingIdentity();
12158 try {
12159 IBackupManager bm = IBackupManager.Stub.asInterface(
12160 ServiceManager.getService(Context.BACKUP_SERVICE));
12161 bm.agentConnected(agentPackageName, agent);
12162 } catch (RemoteException e) {
12163 // can't happen; the backup manager service is local
12164 } catch (Exception e) {
12165 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: ");
12166 e.printStackTrace();
12167 } finally {
12168 Binder.restoreCallingIdentity(oldIdent);
Christopher Tate181fafa2009-05-14 11:12:14 -070012169 }
12170 }
12171
12172 // done with this agent
12173 public void unbindBackupAgent(ApplicationInfo appInfo) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012174 if (DEBUG_BACKUP) Slog.v(TAG, "unbindBackupAgent: " + appInfo);
Christopher Tate8a27f922009-06-26 11:49:18 -070012175 if (appInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012176 Slog.w(TAG, "unbind backup agent for null app");
Christopher Tate8a27f922009-06-26 11:49:18 -070012177 return;
12178 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012179
12180 synchronized(this) {
Christopher Tate8a27f922009-06-26 11:49:18 -070012181 if (mBackupAppName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012182 Slog.w(TAG, "Unbinding backup agent with no active backup");
Christopher Tate8a27f922009-06-26 11:49:18 -070012183 return;
12184 }
12185
Christopher Tate181fafa2009-05-14 11:12:14 -070012186 if (!mBackupAppName.equals(appInfo.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012187 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
Christopher Tate181fafa2009-05-14 11:12:14 -070012188 return;
12189 }
12190
Christopher Tate6fa95972009-06-05 18:43:55 -070012191 ProcessRecord proc = mBackupTarget.app;
12192 mBackupTarget = null;
12193 mBackupAppName = null;
12194
12195 // Not backing this app up any more; reset its OOM adjustment
12196 updateOomAdjLocked(proc);
12197
Christopher Tatec7b31e32009-06-10 15:49:30 -070012198 // If the app crashed during backup, 'thread' will be null here
12199 if (proc.thread != null) {
12200 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040012201 proc.thread.scheduleDestroyBackupAgent(appInfo,
12202 compatibilityInfoForPackageLocked(appInfo));
Christopher Tatec7b31e32009-06-10 15:49:30 -070012203 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012204 Slog.e(TAG, "Exception when unbinding backup agent:");
Christopher Tatec7b31e32009-06-10 15:49:30 -070012205 e.printStackTrace();
12206 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012207 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012208 }
12209 }
12210 // =========================================================
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012211 // BROADCASTS
12212 // =========================================================
12213
Josh Bartel7f208742010-02-25 11:01:44 -060012214 private final List getStickiesLocked(String action, IntentFilter filter,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012215 List cur) {
12216 final ContentResolver resolver = mContext.getContentResolver();
12217 final ArrayList<Intent> list = mStickyBroadcasts.get(action);
12218 if (list == null) {
12219 return cur;
12220 }
12221 int N = list.size();
12222 for (int i=0; i<N; i++) {
12223 Intent intent = list.get(i);
12224 if (filter.match(resolver, intent, true, TAG) >= 0) {
12225 if (cur == null) {
12226 cur = new ArrayList<Intent>();
12227 }
12228 cur.add(intent);
12229 }
12230 }
12231 return cur;
12232 }
12233
Christopher Tatef46723b2012-01-26 14:19:24 -080012234 boolean isPendingBroadcastProcessLocked(int pid) {
12235 return mFgBroadcastQueue.isPendingBroadcastProcessLocked(pid)
12236 || mBgBroadcastQueue.isPendingBroadcastProcessLocked(pid);
12237 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012238
Christopher Tatef46723b2012-01-26 14:19:24 -080012239 void skipPendingBroadcastLocked(int pid) {
12240 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
12241 for (BroadcastQueue queue : mBroadcastQueues) {
12242 queue.skipPendingBroadcastLocked(pid);
12243 }
12244 }
12245
12246 // The app just attached; send any pending broadcasts that it should receive
12247 boolean sendPendingBroadcastsLocked(ProcessRecord app) {
12248 boolean didSomething = false;
12249 for (BroadcastQueue queue : mBroadcastQueues) {
12250 didSomething |= queue.sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012251 }
Christopher Tatef46723b2012-01-26 14:19:24 -080012252 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012253 }
12254
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012255 public Intent registerReceiver(IApplicationThread caller, String callerPackage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012256 IIntentReceiver receiver, IntentFilter filter, String permission) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012257 enforceNotIsolatedCaller("registerReceiver");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012258 synchronized(this) {
12259 ProcessRecord callerApp = null;
12260 if (caller != null) {
12261 callerApp = getRecordForAppLocked(caller);
12262 if (callerApp == null) {
12263 throw new SecurityException(
12264 "Unable to find app for caller " + caller
12265 + " (pid=" + Binder.getCallingPid()
12266 + ") when registering receiver " + receiver);
12267 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012268 if (callerApp.info.uid != Process.SYSTEM_UID &&
12269 !callerApp.pkgList.contains(callerPackage)) {
12270 throw new SecurityException("Given caller package " + callerPackage
12271 + " is not running in process " + callerApp);
12272 }
12273 } else {
12274 callerPackage = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012275 }
12276
12277 List allSticky = null;
12278
12279 // Look for any matching sticky broadcasts...
12280 Iterator actions = filter.actionsIterator();
12281 if (actions != null) {
12282 while (actions.hasNext()) {
12283 String action = (String)actions.next();
Josh Bartel7f208742010-02-25 11:01:44 -060012284 allSticky = getStickiesLocked(action, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012285 }
12286 } else {
Josh Bartel7f208742010-02-25 11:01:44 -060012287 allSticky = getStickiesLocked(null, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012288 }
12289
12290 // The first sticky in the list is returned directly back to
12291 // the client.
12292 Intent sticky = allSticky != null ? (Intent)allSticky.get(0) : null;
12293
Joe Onorato8a9b2202010-02-26 18:56:32 -080012294 if (DEBUG_BROADCAST) Slog.v(TAG, "Register receiver " + filter
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012295 + ": " + sticky);
12296
12297 if (receiver == null) {
12298 return sticky;
12299 }
12300
12301 ReceiverList rl
12302 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
12303 if (rl == null) {
12304 rl = new ReceiverList(this, callerApp,
12305 Binder.getCallingPid(),
12306 Binder.getCallingUid(), receiver);
12307 if (rl.app != null) {
12308 rl.app.receivers.add(rl);
12309 } else {
12310 try {
12311 receiver.asBinder().linkToDeath(rl, 0);
12312 } catch (RemoteException e) {
12313 return sticky;
12314 }
12315 rl.linkedToDeath = true;
12316 }
12317 mRegisteredReceivers.put(receiver.asBinder(), rl);
12318 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012319 BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage, permission);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012320 rl.add(bf);
12321 if (!bf.debugCheck()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012322 Slog.w(TAG, "==> For Dynamic broadast");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012323 }
12324 mReceiverResolver.addFilter(bf);
12325
12326 // Enqueue broadcasts for all existing stickies that match
12327 // this filter.
12328 if (allSticky != null) {
12329 ArrayList receivers = new ArrayList();
12330 receivers.add(bf);
12331
12332 int N = allSticky.size();
12333 for (int i=0; i<N; i++) {
12334 Intent intent = (Intent)allSticky.get(i);
Christopher Tatef46723b2012-01-26 14:19:24 -080012335 BroadcastQueue queue = broadcastQueueForIntent(intent);
12336 BroadcastRecord r = new BroadcastRecord(queue, intent, null,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012337 null, -1, -1, null, receivers, null, 0, null, null,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012338 false, true, true);
Christopher Tatef46723b2012-01-26 14:19:24 -080012339 queue.enqueueParallelBroadcastLocked(r);
12340 queue.scheduleBroadcastsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012341 }
12342 }
12343
12344 return sticky;
12345 }
12346 }
12347
12348 public void unregisterReceiver(IIntentReceiver receiver) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012349 if (DEBUG_BROADCAST) Slog.v(TAG, "Unregister receiver: " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012350
Christopher Tatef46723b2012-01-26 14:19:24 -080012351 final long origId = Binder.clearCallingIdentity();
12352 try {
12353 boolean doTrim = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012354
Christopher Tatef46723b2012-01-26 14:19:24 -080012355 synchronized(this) {
12356 ReceiverList rl
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012357 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
Christopher Tatef46723b2012-01-26 14:19:24 -080012358 if (rl != null) {
12359 if (rl.curBroadcast != null) {
12360 BroadcastRecord r = rl.curBroadcast;
12361 final boolean doNext = finishReceiverLocked(
12362 receiver.asBinder(), r.resultCode, r.resultData,
12363 r.resultExtras, r.resultAbort, true);
12364 if (doNext) {
12365 doTrim = true;
12366 r.queue.processNextBroadcast(false);
12367 }
12368 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012369
Christopher Tatef46723b2012-01-26 14:19:24 -080012370 if (rl.app != null) {
12371 rl.app.receivers.remove(rl);
12372 }
12373 removeReceiverLocked(rl);
12374 if (rl.linkedToDeath) {
12375 rl.linkedToDeath = false;
12376 rl.receiver.asBinder().unlinkToDeath(rl, 0);
12377 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012378 }
12379 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012380
Christopher Tatef46723b2012-01-26 14:19:24 -080012381 // If we actually concluded any broadcasts, we might now be able
12382 // to trim the recipients' apps from our working set
12383 if (doTrim) {
12384 trimApplications();
12385 return;
12386 }
12387
12388 } finally {
12389 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012390 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012391 }
12392
12393 void removeReceiverLocked(ReceiverList rl) {
12394 mRegisteredReceivers.remove(rl.receiver.asBinder());
12395 int N = rl.size();
12396 for (int i=0; i<N; i++) {
12397 mReceiverResolver.removeFilter(rl.get(i));
12398 }
12399 }
12400
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012401 private final void sendPackageBroadcastLocked(int cmd, String[] packages) {
12402 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
12403 ProcessRecord r = mLruProcesses.get(i);
12404 if (r.thread != null) {
12405 try {
12406 r.thread.dispatchPackageBroadcast(cmd, packages);
12407 } catch (RemoteException ex) {
12408 }
12409 }
12410 }
12411 }
12412
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012413 private final int broadcastIntentLocked(ProcessRecord callerApp,
12414 String callerPackage, Intent intent, String resolvedType,
12415 IIntentReceiver resultTo, int resultCode, String resultData,
12416 Bundle map, String requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070012417 boolean ordered, boolean sticky, int callingPid, int callingUid,
12418 int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012419 intent = new Intent(intent);
12420
Dianne Hackborne7f97212011-02-24 14:40:20 -080012421 // By default broadcasts do not go to stopped apps.
12422 intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
12423
Joe Onorato8a9b2202010-02-26 18:56:32 -080012424 if (DEBUG_BROADCAST_LIGHT) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012425 TAG, (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
12426 + " ordered=" + ordered);
12427 if ((resultTo != null) && !ordered) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012428 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012429 }
12430
12431 // Handle special intents: if this broadcast is from the package
12432 // manager about a package being removed, we need to remove all of
12433 // its activities from the history stack.
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012434 final boolean uidRemoved = Intent.ACTION_UID_REMOVED.equals(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012435 intent.getAction());
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012436 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())
12437 || Intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction())
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080012438 || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012439 || uidRemoved) {
12440 if (checkComponentPermission(
12441 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080012442 callingPid, callingUid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012443 == PackageManager.PERMISSION_GRANTED) {
12444 if (uidRemoved) {
12445 final Bundle intentExtras = intent.getExtras();
12446 final int uid = intentExtras != null
12447 ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
12448 if (uid >= 0) {
12449 BatteryStatsImpl bs = mBatteryStatsService.getActiveStatistics();
12450 synchronized (bs) {
12451 bs.removeUidStatsLocked(uid);
12452 }
12453 }
12454 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012455 // If resources are unvailble just force stop all
12456 // those packages and flush the attribute cache as well.
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080012457 if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012458 String list[] = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
12459 if (list != null && (list.length > 0)) {
12460 for (String pkg : list) {
Christopher Tate3dacd842011-08-19 14:56:15 -070012461 forceStopPackageLocked(pkg, -1, false, true, true, false);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012462 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012463 sendPackageBroadcastLocked(
12464 IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE, list);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012465 }
12466 } else {
12467 Uri data = intent.getData();
12468 String ssp;
12469 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
12470 if (!intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false)) {
12471 forceStopPackageLocked(ssp,
Christopher Tate3dacd842011-08-19 14:56:15 -070012472 intent.getIntExtra(Intent.EXTRA_UID, -1), false, true, true, false);
Dianne Hackbornde7faf62009-06-30 13:27:30 -070012473 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012474 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012475 sendPackageBroadcastLocked(IApplicationThread.PACKAGE_REMOVED,
12476 new String[] {ssp});
12477 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012478 }
12479 }
12480 }
12481 } else {
12482 String msg = "Permission Denial: " + intent.getAction()
12483 + " broadcast from " + callerPackage + " (pid=" + callingPid
12484 + ", uid=" + callingUid + ")"
12485 + " requires "
12486 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012487 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012488 throw new SecurityException(msg);
12489 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012490
12491 // Special case for adding a package: by default turn on compatibility
12492 // mode.
12493 } else if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -070012494 Uri data = intent.getData();
12495 String ssp;
12496 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
12497 mCompatModePackages.handlePackageAddedLocked(ssp,
12498 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false));
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012499 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012500 }
12501
12502 /*
12503 * If this is the time zone changed action, queue up a message that will reset the timezone
12504 * of all currently running processes. This message will get queued up before the broadcast
12505 * happens.
12506 */
12507 if (intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) {
12508 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
12509 }
12510
Robert Greenwalt03595d02010-11-02 14:08:23 -070012511 if (intent.ACTION_CLEAR_DNS_CACHE.equals(intent.getAction())) {
12512 mHandler.sendEmptyMessage(CLEAR_DNS_CACHE);
12513 }
12514
Robert Greenwalt434203a2010-10-11 16:00:27 -070012515 if (Proxy.PROXY_CHANGE_ACTION.equals(intent.getAction())) {
12516 ProxyProperties proxy = intent.getParcelableExtra("proxy");
12517 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY, proxy));
12518 }
12519
Dianne Hackborn854060af2009-07-09 18:14:31 -070012520 /*
12521 * Prevent non-system code (defined here to be non-persistent
12522 * processes) from sending protected broadcasts.
12523 */
12524 if (callingUid == Process.SYSTEM_UID || callingUid == Process.PHONE_UID
12525 || callingUid == Process.SHELL_UID || callingUid == 0) {
12526 // Always okay.
12527 } else if (callerApp == null || !callerApp.persistent) {
12528 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012529 if (AppGlobals.getPackageManager().isProtectedBroadcast(
Dianne Hackborn854060af2009-07-09 18:14:31 -070012530 intent.getAction())) {
12531 String msg = "Permission Denial: not allowed to send broadcast "
12532 + intent.getAction() + " from pid="
12533 + callingPid + ", uid=" + callingUid;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012534 Slog.w(TAG, msg);
Dianne Hackborn854060af2009-07-09 18:14:31 -070012535 throw new SecurityException(msg);
12536 }
12537 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012538 Slog.w(TAG, "Remote exception", e);
Dianne Hackborna4972e92012-03-14 10:38:05 -070012539 return ActivityManager.BROADCAST_SUCCESS;
Dianne Hackborn854060af2009-07-09 18:14:31 -070012540 }
12541 }
12542
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012543 // Add to the sticky list if requested.
12544 if (sticky) {
12545 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
12546 callingPid, callingUid)
12547 != PackageManager.PERMISSION_GRANTED) {
12548 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
12549 + callingPid + ", uid=" + callingUid
12550 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012551 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012552 throw new SecurityException(msg);
12553 }
12554 if (requiredPermission != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012555 Slog.w(TAG, "Can't broadcast sticky intent " + intent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012556 + " and enforce permission " + requiredPermission);
Dianne Hackborna4972e92012-03-14 10:38:05 -070012557 return ActivityManager.BROADCAST_STICKY_CANT_HAVE_PERMISSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012558 }
12559 if (intent.getComponent() != null) {
12560 throw new SecurityException(
12561 "Sticky broadcasts can't target a specific component");
12562 }
12563 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
12564 if (list == null) {
12565 list = new ArrayList<Intent>();
12566 mStickyBroadcasts.put(intent.getAction(), list);
12567 }
12568 int N = list.size();
12569 int i;
12570 for (i=0; i<N; i++) {
12571 if (intent.filterEquals(list.get(i))) {
12572 // This sticky already exists, replace it.
12573 list.set(i, new Intent(intent));
12574 break;
12575 }
12576 }
12577 if (i >= N) {
12578 list.add(new Intent(intent));
12579 }
12580 }
12581
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012582 // Figure out who all will receive this broadcast.
12583 List receivers = null;
12584 List<BroadcastFilter> registeredReceivers = null;
12585 try {
12586 if (intent.getComponent() != null) {
12587 // Broadcast is going to one specific receiver class...
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012588 ActivityInfo ai = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -070012589 getReceiverInfo(intent.getComponent(), STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012590 if (ai != null) {
12591 receivers = new ArrayList();
12592 ResolveInfo ri = new ResolveInfo();
Amith Yamasani742a6712011-05-04 14:49:28 -070012593 ri.activityInfo = getActivityInfoForUser(ai, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012594 receivers.add(ri);
12595 }
12596 } else {
Amith Yamasani742a6712011-05-04 14:49:28 -070012597 // TODO: Apply userId
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012598 // Need to resolve the intent to interested receivers...
12599 if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
12600 == 0) {
12601 receivers =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012602 AppGlobals.getPackageManager().queryIntentReceivers(
Dianne Hackborn1655be42009-05-08 14:29:01 -070012603 intent, resolvedType, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012604 }
Mihai Preda074edef2009-05-18 17:13:31 +020012605 registeredReceivers = mReceiverResolver.queryIntent(intent, resolvedType, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012606 }
12607 } catch (RemoteException ex) {
12608 // pm is in same process, this will never happen.
12609 }
12610
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012611 final boolean replacePending =
12612 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
12613
Joe Onorato8a9b2202010-02-26 18:56:32 -080012614 if (DEBUG_BROADCAST) Slog.v(TAG, "Enqueing broadcast: " + intent.getAction()
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012615 + " replacePending=" + replacePending);
12616
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012617 int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
12618 if (!ordered && NR > 0) {
12619 // If we are not serializing this broadcast, then send the
12620 // registered receivers separately so they don't wait for the
12621 // components to be launched.
Christopher Tatef46723b2012-01-26 14:19:24 -080012622 final BroadcastQueue queue = broadcastQueueForIntent(intent);
12623 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012624 callerPackage, callingPid, callingUid, requiredPermission,
12625 registeredReceivers, resultTo, resultCode, resultData, map,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012626 ordered, sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012627 if (DEBUG_BROADCAST) Slog.v(
Christopher Tatef46723b2012-01-26 14:19:24 -080012628 TAG, "Enqueueing parallel broadcast " + r);
12629 final boolean replaced = replacePending && queue.replaceParallelBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012630 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012631 queue.enqueueParallelBroadcastLocked(r);
12632 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012633 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012634 registeredReceivers = null;
12635 NR = 0;
12636 }
12637
12638 // Merge into one list.
12639 int ir = 0;
12640 if (receivers != null) {
12641 // A special case for PACKAGE_ADDED: do not allow the package
12642 // being added to see this broadcast. This prevents them from
12643 // using this as a back door to get run as soon as they are
12644 // installed. Maybe in the future we want to have a special install
12645 // broadcast or such for apps, but we'd like to deliberately make
12646 // this decision.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012647 String skipPackages[] = null;
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012648 if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
12649 || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
12650 || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012651 Uri data = intent.getData();
12652 if (data != null) {
12653 String pkgName = data.getSchemeSpecificPart();
12654 if (pkgName != null) {
12655 skipPackages = new String[] { pkgName };
12656 }
12657 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012658 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012659 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
The Android Open Source Project10592532009-03-18 17:39:46 -070012660 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012661 if (skipPackages != null && (skipPackages.length > 0)) {
12662 for (String skipPackage : skipPackages) {
12663 if (skipPackage != null) {
12664 int NT = receivers.size();
12665 for (int it=0; it<NT; it++) {
12666 ResolveInfo curt = (ResolveInfo)receivers.get(it);
12667 if (curt.activityInfo.packageName.equals(skipPackage)) {
12668 receivers.remove(it);
12669 it--;
12670 NT--;
12671 }
12672 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012673 }
12674 }
12675 }
12676
12677 int NT = receivers != null ? receivers.size() : 0;
12678 int it = 0;
12679 ResolveInfo curt = null;
12680 BroadcastFilter curr = null;
12681 while (it < NT && ir < NR) {
12682 if (curt == null) {
12683 curt = (ResolveInfo)receivers.get(it);
12684 }
12685 if (curr == null) {
12686 curr = registeredReceivers.get(ir);
12687 }
12688 if (curr.getPriority() >= curt.priority) {
12689 // Insert this broadcast record into the final list.
12690 receivers.add(it, curr);
12691 ir++;
12692 curr = null;
12693 it++;
12694 NT++;
12695 } else {
12696 // Skip to the next ResolveInfo in the final list.
12697 it++;
12698 curt = null;
12699 }
12700 }
12701 }
12702 while (ir < NR) {
12703 if (receivers == null) {
12704 receivers = new ArrayList();
12705 }
12706 receivers.add(registeredReceivers.get(ir));
12707 ir++;
12708 }
12709
12710 if ((receivers != null && receivers.size() > 0)
12711 || resultTo != null) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012712 BroadcastQueue queue = broadcastQueueForIntent(intent);
12713 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012714 callerPackage, callingPid, callingUid, requiredPermission,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012715 receivers, resultTo, resultCode, resultData, map, ordered,
12716 sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012717 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012718 TAG, "Enqueueing ordered broadcast " + r
Christopher Tatef46723b2012-01-26 14:19:24 -080012719 + ": prev had " + queue.mOrderedBroadcasts.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012720 if (DEBUG_BROADCAST) {
12721 int seq = r.intent.getIntExtra("seq", -1);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012722 Slog.i(TAG, "Enqueueing broadcast " + r.intent.getAction() + " seq=" + seq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012723 }
Christopher Tatef46723b2012-01-26 14:19:24 -080012724 boolean replaced = replacePending && queue.replaceOrderedBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012725 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012726 queue.enqueueOrderedBroadcastLocked(r);
12727 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012728 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012729 }
12730
Dianne Hackborna4972e92012-03-14 10:38:05 -070012731 return ActivityManager.BROADCAST_SUCCESS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012732 }
12733
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012734 final Intent verifyBroadcastLocked(Intent intent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012735 // Refuse possible leaked file descriptors
12736 if (intent != null && intent.hasFileDescriptors() == true) {
12737 throw new IllegalArgumentException("File descriptors passed in Intent");
12738 }
12739
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012740 int flags = intent.getFlags();
12741
12742 if (!mProcessesReady) {
12743 // if the caller really truly claims to know what they're doing, go
12744 // ahead and allow the broadcast without launching any receivers
12745 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
12746 intent = new Intent(intent);
12747 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
12748 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
12749 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
12750 + " before boot completion");
12751 throw new IllegalStateException("Cannot broadcast before boot completed");
12752 }
12753 }
12754
12755 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
12756 throw new IllegalArgumentException(
12757 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
12758 }
12759
12760 return intent;
12761 }
12762
12763 public final int broadcastIntent(IApplicationThread caller,
12764 Intent intent, String resolvedType, IIntentReceiver resultTo,
12765 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070012766 String requiredPermission, boolean serialized, boolean sticky, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012767 enforceNotIsolatedCaller("broadcastIntent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012768 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012769 intent = verifyBroadcastLocked(intent);
Dianne Hackborn9acc0302009-08-25 00:27:12 -070012770
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012771 final ProcessRecord callerApp = getRecordForAppLocked(caller);
12772 final int callingPid = Binder.getCallingPid();
12773 final int callingUid = Binder.getCallingUid();
12774 final long origId = Binder.clearCallingIdentity();
12775 int res = broadcastIntentLocked(callerApp,
12776 callerApp != null ? callerApp.info.packageName : null,
12777 intent, resolvedType, resultTo,
Amith Yamasani742a6712011-05-04 14:49:28 -070012778 resultCode, resultData, map, requiredPermission, serialized, sticky,
12779 callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012780 Binder.restoreCallingIdentity(origId);
12781 return res;
12782 }
12783 }
12784
12785 int broadcastIntentInPackage(String packageName, int uid,
12786 Intent intent, String resolvedType, IIntentReceiver resultTo,
12787 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070012788 String requiredPermission, boolean serialized, boolean sticky, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012789 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012790 intent = verifyBroadcastLocked(intent);
12791
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012792 final long origId = Binder.clearCallingIdentity();
12793 int res = broadcastIntentLocked(null, packageName, intent, resolvedType,
12794 resultTo, resultCode, resultData, map, requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070012795 serialized, sticky, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012796 Binder.restoreCallingIdentity(origId);
12797 return res;
12798 }
12799 }
12800
Amith Yamasani742a6712011-05-04 14:49:28 -070012801 // TODO: Use the userId; maybe mStickyBroadcasts need to be tied to the user.
12802 public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012803 // Refuse possible leaked file descriptors
12804 if (intent != null && intent.hasFileDescriptors() == true) {
12805 throw new IllegalArgumentException("File descriptors passed in Intent");
12806 }
12807
12808 synchronized(this) {
12809 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
12810 != PackageManager.PERMISSION_GRANTED) {
12811 String msg = "Permission Denial: unbroadcastIntent() from pid="
12812 + Binder.getCallingPid()
12813 + ", uid=" + Binder.getCallingUid()
12814 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012815 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012816 throw new SecurityException(msg);
12817 }
12818 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
12819 if (list != null) {
12820 int N = list.size();
12821 int i;
12822 for (i=0; i<N; i++) {
12823 if (intent.filterEquals(list.get(i))) {
12824 list.remove(i);
12825 break;
12826 }
12827 }
12828 }
12829 }
12830 }
12831
12832 private final boolean finishReceiverLocked(IBinder receiver, int resultCode,
12833 String resultData, Bundle resultExtras, boolean resultAbort,
12834 boolean explicit) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012835 final BroadcastRecord r = broadcastRecordForReceiverLocked(receiver);
12836 if (r == null) {
12837 Slog.w(TAG, "finishReceiver called but not found on queue");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012838 return false;
12839 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012840
Christopher Tatef46723b2012-01-26 14:19:24 -080012841 return r.queue.finishReceiverLocked(r, resultCode, resultData, resultExtras, resultAbort,
12842 explicit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012843 }
12844
12845 public void finishReceiver(IBinder who, int resultCode, String resultData,
12846 Bundle resultExtras, boolean resultAbort) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012847 if (DEBUG_BROADCAST) Slog.v(TAG, "Finish receiver: " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012848
12849 // Refuse possible leaked file descriptors
12850 if (resultExtras != null && resultExtras.hasFileDescriptors()) {
12851 throw new IllegalArgumentException("File descriptors passed in Bundle");
12852 }
12853
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012854 final long origId = Binder.clearCallingIdentity();
Christopher Tatef46723b2012-01-26 14:19:24 -080012855 try {
12856 boolean doNext = false;
12857 BroadcastRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012858
Christopher Tatef46723b2012-01-26 14:19:24 -080012859 synchronized(this) {
12860 r = broadcastRecordForReceiverLocked(who);
12861 if (r != null) {
12862 doNext = r.queue.finishReceiverLocked(r, resultCode,
12863 resultData, resultExtras, resultAbort, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012864 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012865 }
Jeff Brown4d94a762010-09-23 11:33:28 -070012866
Christopher Tatef46723b2012-01-26 14:19:24 -080012867 if (doNext) {
12868 r.queue.processNextBroadcast(false);
12869 }
12870 trimApplications();
12871 } finally {
12872 Binder.restoreCallingIdentity(origId);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012873 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012874 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012875
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012876 // =========================================================
12877 // INSTRUMENTATION
12878 // =========================================================
12879
12880 public boolean startInstrumentation(ComponentName className,
12881 String profileFile, int flags, Bundle arguments,
12882 IInstrumentationWatcher watcher) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012883 enforceNotIsolatedCaller("startInstrumentation");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012884 // Refuse possible leaked file descriptors
12885 if (arguments != null && arguments.hasFileDescriptors()) {
12886 throw new IllegalArgumentException("File descriptors passed in Bundle");
12887 }
12888
12889 synchronized(this) {
12890 InstrumentationInfo ii = null;
12891 ApplicationInfo ai = null;
12892 try {
12893 ii = mContext.getPackageManager().getInstrumentationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070012894 className, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012895 ai = mContext.getPackageManager().getApplicationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070012896 ii.targetPackage, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012897 } catch (PackageManager.NameNotFoundException e) {
12898 }
12899 if (ii == null) {
12900 reportStartInstrumentationFailure(watcher, className,
12901 "Unable to find instrumentation info for: " + className);
12902 return false;
12903 }
12904 if (ai == null) {
12905 reportStartInstrumentationFailure(watcher, className,
12906 "Unable to find instrumentation target package: " + ii.targetPackage);
12907 return false;
12908 }
12909
12910 int match = mContext.getPackageManager().checkSignatures(
12911 ii.targetPackage, ii.packageName);
12912 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
12913 String msg = "Permission Denial: starting instrumentation "
12914 + className + " from pid="
12915 + Binder.getCallingPid()
12916 + ", uid=" + Binder.getCallingPid()
12917 + " not allowed because package " + ii.packageName
12918 + " does not have a signature matching the target "
12919 + ii.targetPackage;
12920 reportStartInstrumentationFailure(watcher, className, msg);
12921 throw new SecurityException(msg);
12922 }
12923
12924 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -070012925 // Instrumentation can kill and relaunch even persistent processes
12926 forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080012927 ProcessRecord app = addAppLocked(ai, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012928 app.instrumentationClass = className;
Dianne Hackborn1655be42009-05-08 14:29:01 -070012929 app.instrumentationInfo = ai;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012930 app.instrumentationProfileFile = profileFile;
12931 app.instrumentationArguments = arguments;
12932 app.instrumentationWatcher = watcher;
12933 app.instrumentationResultClass = className;
12934 Binder.restoreCallingIdentity(origId);
12935 }
12936
12937 return true;
12938 }
12939
12940 /**
12941 * Report errors that occur while attempting to start Instrumentation. Always writes the
12942 * error to the logs, but if somebody is watching, send the report there too. This enables
12943 * the "am" command to report errors with more information.
12944 *
12945 * @param watcher The IInstrumentationWatcher. Null if there isn't one.
12946 * @param cn The component name of the instrumentation.
12947 * @param report The error report.
12948 */
12949 private void reportStartInstrumentationFailure(IInstrumentationWatcher watcher,
12950 ComponentName cn, String report) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012951 Slog.w(TAG, report);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012952 try {
12953 if (watcher != null) {
12954 Bundle results = new Bundle();
12955 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
12956 results.putString("Error", report);
12957 watcher.instrumentationStatus(cn, -1, results);
12958 }
12959 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012960 Slog.w(TAG, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012961 }
12962 }
12963
12964 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
12965 if (app.instrumentationWatcher != null) {
12966 try {
12967 // NOTE: IInstrumentationWatcher *must* be oneway here
12968 app.instrumentationWatcher.instrumentationFinished(
12969 app.instrumentationClass,
12970 resultCode,
12971 results);
12972 } catch (RemoteException e) {
12973 }
12974 }
12975 app.instrumentationWatcher = null;
12976 app.instrumentationClass = null;
Dianne Hackborn1655be42009-05-08 14:29:01 -070012977 app.instrumentationInfo = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012978 app.instrumentationProfileFile = null;
12979 app.instrumentationArguments = null;
12980
Christopher Tate3dacd842011-08-19 14:56:15 -070012981 forceStopPackageLocked(app.processName, -1, false, false, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012982 }
12983
12984 public void finishInstrumentation(IApplicationThread target,
12985 int resultCode, Bundle results) {
12986 // Refuse possible leaked file descriptors
12987 if (results != null && results.hasFileDescriptors()) {
12988 throw new IllegalArgumentException("File descriptors passed in Intent");
12989 }
12990
12991 synchronized(this) {
12992 ProcessRecord app = getRecordForAppLocked(target);
12993 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012994 Slog.w(TAG, "finishInstrumentation: no app for " + target);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012995 return;
12996 }
12997 final long origId = Binder.clearCallingIdentity();
12998 finishInstrumentationLocked(app, resultCode, results);
12999 Binder.restoreCallingIdentity(origId);
13000 }
13001 }
13002
13003 // =========================================================
13004 // CONFIGURATION
13005 // =========================================================
13006
13007 public ConfigurationInfo getDeviceConfigurationInfo() {
13008 ConfigurationInfo config = new ConfigurationInfo();
13009 synchronized (this) {
13010 config.reqTouchScreen = mConfiguration.touchscreen;
13011 config.reqKeyboardType = mConfiguration.keyboard;
13012 config.reqNavigation = mConfiguration.navigation;
Dianne Hackbornfae76f52009-07-16 13:41:23 -070013013 if (mConfiguration.navigation == Configuration.NAVIGATION_DPAD
13014 || mConfiguration.navigation == Configuration.NAVIGATION_TRACKBALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013015 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
13016 }
Dianne Hackbornfae76f52009-07-16 13:41:23 -070013017 if (mConfiguration.keyboard != Configuration.KEYBOARD_UNDEFINED
13018 && mConfiguration.keyboard != Configuration.KEYBOARD_NOKEYS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013019 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
13020 }
Jack Palevichb90d28c2009-07-22 15:35:24 -070013021 config.reqGlEsVersion = GL_ES_VERSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013022 }
13023 return config;
13024 }
13025
13026 public Configuration getConfiguration() {
13027 Configuration ci;
13028 synchronized(this) {
13029 ci = new Configuration(mConfiguration);
13030 }
13031 return ci;
13032 }
13033
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013034 public void updatePersistentConfiguration(Configuration values) {
13035 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
13036 "updateConfiguration()");
13037 enforceCallingPermission(android.Manifest.permission.WRITE_SETTINGS,
13038 "updateConfiguration()");
13039 if (values == null) {
13040 throw new NullPointerException("Configuration must not be null");
13041 }
13042
13043 synchronized(this) {
13044 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn813075a62011-11-14 17:45:19 -080013045 updateConfigurationLocked(values, null, true, false);
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013046 Binder.restoreCallingIdentity(origId);
13047 }
13048 }
13049
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013050 public void updateConfiguration(Configuration values) {
13051 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
13052 "updateConfiguration()");
13053
13054 synchronized(this) {
13055 if (values == null && mWindowManager != null) {
13056 // sentinel: fetch the current configuration from the window manager
13057 values = mWindowManager.computeNewConfiguration();
13058 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013059
13060 if (mWindowManager != null) {
13061 mProcessList.applyDisplaySize(mWindowManager);
13062 }
13063
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013064 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013065 if (values != null) {
13066 Settings.System.clearConfiguration(values);
13067 }
Dianne Hackborn813075a62011-11-14 17:45:19 -080013068 updateConfigurationLocked(values, null, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013069 Binder.restoreCallingIdentity(origId);
13070 }
13071 }
13072
13073 /**
13074 * Do either or both things: (1) change the current configuration, and (2)
13075 * make sure the given activity is running with the (now) current
13076 * configuration. Returns true if the activity has been left running, or
13077 * false if <var>starting</var> is being destroyed to match the new
13078 * configuration.
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013079 * @param persistent TODO
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013080 */
Dianne Hackborna573f6a2012-02-09 16:12:18 -080013081 boolean updateConfigurationLocked(Configuration values,
Dianne Hackborn813075a62011-11-14 17:45:19 -080013082 ActivityRecord starting, boolean persistent, boolean initLocale) {
Mike Lockwood3a74bd32011-08-12 13:55:22 -070013083 // do nothing if we are headless
13084 if (mHeadless) return true;
13085
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013086 int changes = 0;
13087
13088 boolean kept = true;
13089
13090 if (values != null) {
13091 Configuration newConfig = new Configuration(mConfiguration);
13092 changes = newConfig.updateFrom(values);
13093 if (changes != 0) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013094 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013095 Slog.i(TAG, "Updating configuration to: " + values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013096 }
13097
Doug Zongker2bec3d42009-12-04 12:52:44 -080013098 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013099
Dianne Hackborn813075a62011-11-14 17:45:19 -080013100 if (values.locale != null && !initLocale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013101 saveLocaleLocked(values.locale,
13102 !values.locale.equals(mConfiguration.locale),
13103 values.userSetLocale);
13104 }
13105
Dianne Hackborne36d6e22010-02-17 19:46:25 -080013106 mConfigurationSeq++;
13107 if (mConfigurationSeq <= 0) {
13108 mConfigurationSeq = 1;
13109 }
13110 newConfig.seq = mConfigurationSeq;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013111 mConfiguration = newConfig;
Joe Onorato8a9b2202010-02-26 18:56:32 -080013112 Slog.i(TAG, "Config changed: " + newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013113
13114 final Configuration configCopy = new Configuration(mConfiguration);
Joe Onorato54a4a412011-11-02 20:50:08 -070013115
13116 // TODO: If our config changes, should we auto dismiss any currently
13117 // showing dialogs?
13118 mShowDialogs = shouldShowDialogs(newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013119
Dianne Hackborn826d17c2009-11-12 12:55:51 -080013120 AttributeCache ac = AttributeCache.instance();
13121 if (ac != null) {
Dianne Hackborn813075a62011-11-14 17:45:19 -080013122 ac.updateConfiguration(configCopy);
Dianne Hackborn826d17c2009-11-12 12:55:51 -080013123 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013124
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070013125 // Make sure all resources in our process are updated
13126 // right now, so that anyone who is going to retrieve
13127 // resource values after we return will be sure to get
13128 // the new ones. This is especially important during
13129 // boot, where the first config change needs to guarantee
13130 // all resources have that config before following boot
13131 // code is executed.
Dianne Hackborn813075a62011-11-14 17:45:19 -080013132 mSystemThread.applyConfigurationToResources(configCopy);
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070013133
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013134 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080013135 Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013136 msg.obj = new Configuration(configCopy);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080013137 mHandler.sendMessage(msg);
13138 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013139
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013140 for (int i=mLruProcesses.size()-1; i>=0; i--) {
13141 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013142 try {
13143 if (app.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013144 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending to proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013145 + app.processName + " new config " + mConfiguration);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013146 app.thread.scheduleConfigurationChanged(configCopy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013147 }
13148 } catch (Exception e) {
13149 }
13150 }
13151 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080013152 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
13153 | Intent.FLAG_RECEIVER_REPLACE_PENDING);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013154 broadcastIntentLocked(null, null, intent, null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070013155 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080013156 if ((changes&ActivityInfo.CONFIG_LOCALE) != 0) {
13157 broadcastIntentLocked(null, null,
13158 new Intent(Intent.ACTION_LOCALE_CHANGED),
13159 null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070013160 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080013161 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013162 }
13163 }
13164
13165 if (changes != 0 && starting == null) {
13166 // If the configuration changed, and the caller is not already
13167 // in the process of starting an activity, then find the top
13168 // activity to check if its configuration needs to change.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013169 starting = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013170 }
13171
13172 if (starting != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013173 kept = mMainStack.ensureActivityConfigurationLocked(starting, changes);
Dianne Hackborn5f4d6432010-12-21 20:40:11 -080013174 // And we need to make sure at this point that all other activities
13175 // are made visible with the correct configuration.
13176 mMainStack.ensureActivitiesVisibleLocked(starting, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013177 }
13178
Dianne Hackborne36d6e22010-02-17 19:46:25 -080013179 if (values != null && mWindowManager != null) {
13180 mWindowManager.setNewConfiguration(mConfiguration);
13181 }
13182
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013183 return kept;
13184 }
Joe Onorato54a4a412011-11-02 20:50:08 -070013185
13186 /**
13187 * Decide based on the configuration whether we should shouw the ANR,
13188 * crash, etc dialogs. The idea is that if there is no affordnace to
13189 * press the on-screen buttons, we shouldn't show the dialog.
13190 *
13191 * A thought: SystemUI might also want to get told about this, the Power
13192 * dialog / global actions also might want different behaviors.
13193 */
13194 private static final boolean shouldShowDialogs(Configuration config) {
13195 return !(config.keyboard == Configuration.KEYBOARD_NOKEYS
13196 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH);
13197 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013198
13199 /**
13200 * Save the locale. You must be inside a synchronized (this) block.
13201 */
13202 private void saveLocaleLocked(Locale l, boolean isDiff, boolean isPersist) {
13203 if(isDiff) {
13204 SystemProperties.set("user.language", l.getLanguage());
13205 SystemProperties.set("user.region", l.getCountry());
13206 }
13207
13208 if(isPersist) {
13209 SystemProperties.set("persist.sys.language", l.getLanguage());
13210 SystemProperties.set("persist.sys.country", l.getCountry());
13211 SystemProperties.set("persist.sys.localevar", l.getVariant());
13212 }
13213 }
13214
13215 // =========================================================
13216 // LIFETIME MANAGEMENT
13217 // =========================================================
13218
Christopher Tatef46723b2012-01-26 14:19:24 -080013219 // Returns which broadcast queue the app is the current [or imminent] receiver
13220 // on, or 'null' if the app is not an active broadcast recipient.
13221 private BroadcastQueue isReceivingBroadcast(ProcessRecord app) {
13222 BroadcastRecord r = app.curReceiver;
13223 if (r != null) {
13224 return r.queue;
13225 }
13226
13227 // It's not the current receiver, but it might be starting up to become one
13228 synchronized (this) {
13229 for (BroadcastQueue queue : mBroadcastQueues) {
13230 r = queue.mPendingBroadcast;
13231 if (r != null && r.curApp == app) {
13232 // found it; report which queue it's in
13233 return queue;
13234 }
13235 }
13236 }
13237
13238 return null;
13239 }
13240
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013241 private final int computeOomAdjLocked(ProcessRecord app, int hiddenAdj,
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013242 ProcessRecord TOP_APP, boolean recursed, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013243 if (mAdjSeq == app.adjSeq) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013244 // This adjustment has already been computed. If we are calling
13245 // from the top, we may have already computed our adjustment with
13246 // an earlier hidden adjustment that isn't really for us... if
13247 // so, use the new hidden adjustment.
13248 if (!recursed && app.hidden) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013249 app.curAdj = app.curRawAdj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013250 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013251 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013252 }
13253
13254 if (app.thread == null) {
13255 app.adjSeq = mAdjSeq;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013256 app.curSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013257 return (app.curAdj=ProcessList.HIDDEN_APP_MAX_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013258 }
13259
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013260 app.adjTypeCode = ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN;
13261 app.adjSource = null;
13262 app.adjTarget = null;
13263 app.empty = false;
13264 app.hidden = false;
13265
13266 final int activitiesSize = app.activities.size();
13267
Dianne Hackborn7d608422011-08-07 16:24:18 -070013268 if (app.maxAdj <= ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013269 // The max adjustment doesn't allow this app to be anything
13270 // below foreground, so it is not worth doing work for it.
13271 app.adjType = "fixed";
13272 app.adjSeq = mAdjSeq;
13273 app.curRawAdj = app.maxAdj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013274 app.foregroundActivities = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013275 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013276 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013277 // System process can do UI, and when they do we want to have
13278 // them trim their memory after the user leaves the UI. To
13279 // facilitate this, here we need to determine whether or not it
13280 // is currently showing UI.
13281 app.systemNoUi = true;
13282 if (app == TOP_APP) {
13283 app.systemNoUi = false;
13284 } else if (activitiesSize > 0) {
13285 for (int j = 0; j < activitiesSize; j++) {
13286 final ActivityRecord r = app.activities.get(j);
13287 if (r.visible) {
13288 app.systemNoUi = false;
13289 break;
13290 }
13291 }
13292 }
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013293 return (app.curAdj=app.maxAdj);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013294 }
13295
13296 final boolean hadForegroundActivities = app.foregroundActivities;
13297
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013298 app.foregroundActivities = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013299 app.keeping = false;
13300 app.systemNoUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013301
The Android Open Source Project4df24232009-03-05 14:34:35 -080013302 // Determine the importance of the process, starting with most
13303 // important to least, and assign an appropriate OOM adjustment.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013304 int adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013305 int schedGroup;
Christopher Tatef46723b2012-01-26 14:19:24 -080013306 BroadcastQueue queue;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013307 if (app == TOP_APP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013308 // The last app on the list is the foreground app.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013309 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013310 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013311 app.adjType = "top-activity";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013312 app.foregroundActivities = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013313 } else if (app.instrumentationClass != null) {
13314 // Don't want to kill running instrumentation.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013315 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013316 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013317 app.adjType = "instrumentation";
Christopher Tatef46723b2012-01-26 14:19:24 -080013318 } else if ((queue = isReceivingBroadcast(app)) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013319 // An app that is currently receiving a broadcast also
Christopher Tatef46723b2012-01-26 14:19:24 -080013320 // counts as being in the foreground for OOM killer purposes.
13321 // It's placed in a sched group based on the nature of the
13322 // broadcast as reflected by which queue it's active in.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013323 adj = ProcessList.FOREGROUND_APP_ADJ;
Christopher Tatef46723b2012-01-26 14:19:24 -080013324 schedGroup = (queue == mFgBroadcastQueue)
13325 ? Process.THREAD_GROUP_DEFAULT : Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013326 app.adjType = "broadcast";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013327 } else if (app.executingServices.size() > 0) {
13328 // An app that is currently executing a service callback also
13329 // counts as being in the foreground.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013330 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013331 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013332 app.adjType = "exec-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013333 } else if (activitiesSize > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013334 // This app is in the background with paused activities.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013335 // We inspect activities to potentially upgrade adjustment further below.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013336 adj = hiddenAdj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013337 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013338 app.hidden = true;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013339 app.adjType = "bg-activities";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013340 } else {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013341 // A very not-needed process. If this is lower in the lru list,
13342 // we will push it in to the empty bucket.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013343 adj = hiddenAdj;
13344 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013345 app.hidden = true;
13346 app.empty = true;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013347 app.adjType = "bg-empty";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013348 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013349
13350 // Examine all activities if not already foreground.
13351 if (!app.foregroundActivities && activitiesSize > 0) {
13352 for (int j = 0; j < activitiesSize; j++) {
13353 final ActivityRecord r = app.activities.get(j);
13354 if (r.visible) {
13355 // App has a visible activity; only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013356 if (adj > ProcessList.VISIBLE_APP_ADJ) {
13357 adj = ProcessList.VISIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013358 app.adjType = "visible";
13359 }
13360 schedGroup = Process.THREAD_GROUP_DEFAULT;
13361 app.hidden = false;
13362 app.foregroundActivities = true;
13363 break;
13364 } else if (r.state == ActivityState.PAUSING || r.state == ActivityState.PAUSED
13365 || r.state == ActivityState.STOPPING) {
13366 // Only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013367 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13368 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013369 app.adjType = "stopping";
13370 }
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -080013371 app.hidden = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013372 app.foregroundActivities = true;
13373 }
13374 }
13375 }
13376
Dianne Hackborn7d608422011-08-07 16:24:18 -070013377 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013378 if (app.foregroundServices) {
13379 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013380 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013381 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013382 app.adjType = "foreground-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013383 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013384 } else if (app.forcingToForeground != null) {
13385 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013386 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013387 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013388 app.adjType = "force-foreground";
13389 app.adjSource = app.forcingToForeground;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013390 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013391 }
13392 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013393
Dianne Hackborn7d608422011-08-07 16:24:18 -070013394 if (adj > ProcessList.HEAVY_WEIGHT_APP_ADJ && app == mHeavyWeightProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013395 // We don't want to kill the current heavy-weight process.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013396 adj = ProcessList.HEAVY_WEIGHT_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013397 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013398 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013399 app.adjType = "heavy";
13400 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013401
Dianne Hackborn7d608422011-08-07 16:24:18 -070013402 if (adj > ProcessList.HOME_APP_ADJ && app == mHomeProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013403 // This process is hosting what we currently consider to be the
13404 // home app, so we don't want to let it go into the background.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013405 adj = ProcessList.HOME_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013406 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013407 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013408 app.adjType = "home";
13409 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013410
Dianne Hackbornf35fe232011-11-01 19:25:20 -070013411 if (adj > ProcessList.PREVIOUS_APP_ADJ && app == mPreviousProcess
13412 && app.activities.size() > 0) {
13413 // This was the previous process that showed UI to the user.
13414 // We want to try to keep it around more aggressively, to give
13415 // a good experience around switching between two apps.
13416 adj = ProcessList.PREVIOUS_APP_ADJ;
13417 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
13418 app.hidden = false;
13419 app.adjType = "previous";
13420 }
13421
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013422 if (false) Slog.i(TAG, "OOM " + app + ": initial adj=" + adj
13423 + " reason=" + app.adjType);
13424
The Android Open Source Project4df24232009-03-05 14:34:35 -080013425 // By default, we use the computed adjustment. It may be changed if
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013426 // there are applications dependent on our services or providers, but
13427 // this gives us a baseline and makes sure we don't get into an
13428 // infinite recursion.
13429 app.adjSeq = mAdjSeq;
13430 app.curRawAdj = adj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013431
Christopher Tate6fa95972009-06-05 18:43:55 -070013432 if (mBackupTarget != null && app == mBackupTarget.app) {
13433 // If possible we want to avoid killing apps while they're being backed up
Dianne Hackborn7d608422011-08-07 16:24:18 -070013434 if (adj > ProcessList.BACKUP_APP_ADJ) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013435 if (DEBUG_BACKUP) Slog.v(TAG, "oom BACKUP_APP_ADJ for " + app);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013436 adj = ProcessList.BACKUP_APP_ADJ;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013437 app.adjType = "backup";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013438 app.hidden = false;
Christopher Tate6fa95972009-06-05 18:43:55 -070013439 }
13440 }
13441
Dianne Hackborn7d608422011-08-07 16:24:18 -070013442 if (app.services.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013443 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013444 final long now = SystemClock.uptimeMillis();
13445 // This process is more important if the top activity is
13446 // bound to the service.
Dianne Hackborn860755f2010-06-03 18:47:52 -070013447 Iterator<ServiceRecord> jt = app.services.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013448 while (jt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013449 ServiceRecord s = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013450 if (s.startRequested) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013451 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013452 // If this process has shown some UI, let it immediately
13453 // go to the LRU list because it may be pretty heavy with
13454 // UI stuff. We'll tag it with a label just to help
13455 // debug and understand what is going on.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013456 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013457 app.adjType = "started-bg-ui-services";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013458 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013459 } else {
13460 if (now < (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
13461 // This service has seen some activity within
13462 // recent memory, so we will keep its process ahead
13463 // of the background processes.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013464 if (adj > ProcessList.SERVICE_ADJ) {
13465 adj = ProcessList.SERVICE_ADJ;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013466 app.adjType = "started-services";
13467 app.hidden = false;
13468 }
13469 }
13470 // If we have let the service slide into the background
13471 // state, still have some text describing what it is doing
13472 // even though the service no longer has an impact.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013473 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013474 app.adjType = "started-bg-services";
13475 }
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080013476 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013477 // Don't kill this process because it is doing work; it
13478 // has said it is doing work.
13479 app.keeping = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013480 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013481 if (s.connections.size() > 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013482 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013483 Iterator<ArrayList<ConnectionRecord>> kt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013484 = s.connections.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013485 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013486 ArrayList<ConnectionRecord> clist = kt.next();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013487 for (int i=0; i<clist.size() && adj > ProcessList.FOREGROUND_APP_ADJ; i++) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013488 // XXX should compute this based on the max of
13489 // all connected clients.
13490 ConnectionRecord cr = clist.get(i);
13491 if (cr.binding.client == app) {
13492 // Binding to ourself is not interesting.
13493 continue;
13494 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013495 if ((cr.flags&Context.BIND_WAIVE_PRIORITY) == 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013496 ProcessRecord client = cr.binding.client;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013497 int clientAdj = adj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013498 int myHiddenAdj = hiddenAdj;
13499 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013500 if (client.hiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013501 myHiddenAdj = client.hiddenAdj;
13502 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013503 myHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013504 }
13505 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013506 clientAdj = computeOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013507 client, myHiddenAdj, TOP_APP, true, doingAll);
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013508 String adjType = null;
13509 if ((cr.flags&Context.BIND_ALLOW_OOM_MANAGEMENT) != 0) {
13510 // Not doing bind OOM management, so treat
13511 // this guy more like a started service.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013512 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013513 // If this process has shown some UI, let it immediately
13514 // go to the LRU list because it may be pretty heavy with
13515 // UI stuff. We'll tag it with a label just to help
13516 // debug and understand what is going on.
13517 if (adj > clientAdj) {
13518 adjType = "bound-bg-ui-services";
13519 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013520 app.hidden = false;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013521 clientAdj = adj;
13522 } else {
13523 if (now >= (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
13524 // This service has not seen activity within
13525 // recent memory, so allow it to drop to the
13526 // LRU list if there is no other reason to keep
13527 // it around. We'll also tag it with a label just
13528 // to help debug and undertand what is going on.
13529 if (adj > clientAdj) {
13530 adjType = "bound-bg-services";
13531 }
13532 clientAdj = adj;
13533 }
13534 }
13535 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013536 if (adj > clientAdj) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013537 // If this process has recently shown UI, and
13538 // the process that is binding to it is less
13539 // important than being visible, then we don't
13540 // care about the binding as much as we care
13541 // about letting this process get into the LRU
13542 // list to be killed and restarted if needed for
13543 // memory.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013544 if (app.hasShownUi && app != mHomeProcess
13545 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013546 adjType = "bound-bg-ui-services";
13547 } else {
13548 if ((cr.flags&(Context.BIND_ABOVE_CLIENT
13549 |Context.BIND_IMPORTANT)) != 0) {
13550 adj = clientAdj;
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070013551 } else if ((cr.flags&Context.BIND_NOT_VISIBLE) != 0
13552 && clientAdj < ProcessList.PERCEPTIBLE_APP_ADJ
13553 && adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13554 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13555 } else if (clientAdj > ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013556 adj = clientAdj;
13557 } else {
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070013558 app.pendingUiClean = true;
13559 if (adj > ProcessList.VISIBLE_APP_ADJ) {
13560 adj = ProcessList.VISIBLE_APP_ADJ;
13561 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013562 }
13563 if (!client.hidden) {
13564 app.hidden = false;
13565 }
13566 if (client.keeping) {
13567 app.keeping = true;
13568 }
13569 adjType = "service";
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013570 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013571 }
13572 if (adjType != null) {
13573 app.adjType = adjType;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013574 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13575 .REASON_SERVICE_IN_USE;
13576 app.adjSource = cr.binding.client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013577 app.adjSourceOom = clientAdj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013578 app.adjTarget = s.name;
13579 }
13580 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
13581 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
13582 schedGroup = Process.THREAD_GROUP_DEFAULT;
13583 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013584 }
13585 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013586 if ((cr.flags&Context.BIND_ADJUST_WITH_ACTIVITY) != 0) {
13587 ActivityRecord a = cr.activity;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013588 if (a != null && adj > ProcessList.FOREGROUND_APP_ADJ &&
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013589 (a.visible || a.state == ActivityState.RESUMED
13590 || a.state == ActivityState.PAUSING)) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013591 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013592 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
13593 schedGroup = Process.THREAD_GROUP_DEFAULT;
13594 }
13595 app.hidden = false;
13596 app.adjType = "service";
13597 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13598 .REASON_SERVICE_IN_USE;
13599 app.adjSource = a;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013600 app.adjSourceOom = adj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013601 app.adjTarget = s.name;
13602 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013603 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013604 }
13605 }
13606 }
13607 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013608
Dianne Hackborn287952c2010-09-22 22:34:31 -070013609 // Finally, if this process has active services running in it, we
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013610 // would like to avoid killing it unless it would prevent the current
13611 // application from running. By default we put the process in
13612 // with the rest of the background processes; as we scan through
13613 // its services we may bump it up from there.
13614 if (adj > hiddenAdj) {
13615 adj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013616 app.hidden = false;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013617 app.adjType = "bg-services";
13618 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013619 }
13620
Dianne Hackborn7d608422011-08-07 16:24:18 -070013621 if (app.pubProviders.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013622 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013623 Iterator<ContentProviderRecord> jt = app.pubProviders.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013624 while (jt.hasNext() && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013625 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013626 ContentProviderRecord cpr = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013627 if (cpr.clients.size() != 0) {
13628 Iterator<ProcessRecord> kt = cpr.clients.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013629 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013630 ProcessRecord client = kt.next();
The Android Open Source Project10592532009-03-18 17:39:46 -070013631 if (client == app) {
13632 // Being our own client is not interesting.
13633 continue;
13634 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013635 int myHiddenAdj = hiddenAdj;
13636 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013637 if (client.hiddenAdj > ProcessList.FOREGROUND_APP_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013638 myHiddenAdj = client.hiddenAdj;
13639 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013640 myHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013641 }
13642 }
13643 int clientAdj = computeOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013644 client, myHiddenAdj, TOP_APP, true, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013645 if (adj > clientAdj) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013646 if (app.hasShownUi && app != mHomeProcess
13647 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013648 app.adjType = "bg-ui-provider";
13649 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013650 adj = clientAdj > ProcessList.FOREGROUND_APP_ADJ
13651 ? clientAdj : ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013652 app.adjType = "provider";
13653 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013654 if (!client.hidden) {
13655 app.hidden = false;
13656 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013657 if (client.keeping) {
13658 app.keeping = true;
13659 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070013660 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13661 .REASON_PROVIDER_IN_USE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013662 app.adjSource = client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013663 app.adjSourceOom = clientAdj;
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070013664 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013665 }
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013666 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
13667 schedGroup = Process.THREAD_GROUP_DEFAULT;
13668 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013669 }
13670 }
13671 // If the provider has external (non-framework) process
13672 // dependencies, ensure that its adjustment is at least
13673 // FOREGROUND_APP_ADJ.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080013674 if (cpr.hasExternalProcessHandles()) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013675 if (adj > ProcessList.FOREGROUND_APP_ADJ) {
13676 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013677 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013678 app.hidden = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013679 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013680 app.adjType = "provider";
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070013681 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013682 }
13683 }
13684 }
13685 }
13686
13687 app.curRawAdj = adj;
13688
Joe Onorato8a9b2202010-02-26 18:56:32 -080013689 //Slog.i(TAG, "OOM ADJ " + app + ": pid=" + app.pid +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013690 // " adj=" + adj + " curAdj=" + app.curAdj + " maxAdj=" + app.maxAdj);
13691 if (adj > app.maxAdj) {
13692 adj = app.maxAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013693 if (app.maxAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013694 schedGroup = Process.THREAD_GROUP_DEFAULT;
13695 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013696 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013697 if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070013698 app.keeping = true;
13699 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013700
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013701 if (app.hasAboveClient) {
13702 // If this process has bound to any services with BIND_ABOVE_CLIENT,
13703 // then we need to drop its adjustment to be lower than the service's
13704 // in order to honor the request. We want to drop it by one adjustment
13705 // level... but there is special meaning applied to various levels so
13706 // we will skip some of them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013707 if (adj < ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013708 // System process will not get dropped, ever
Dianne Hackborn7d608422011-08-07 16:24:18 -070013709 } else if (adj < ProcessList.VISIBLE_APP_ADJ) {
13710 adj = ProcessList.VISIBLE_APP_ADJ;
13711 } else if (adj < ProcessList.PERCEPTIBLE_APP_ADJ) {
13712 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13713 } else if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
13714 adj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013715 } else if (adj < ProcessList.HIDDEN_APP_MAX_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013716 adj++;
13717 }
13718 }
13719
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013720 if (adj == ProcessList.SERVICE_ADJ) {
13721 if (doingAll) {
13722 app.serviceb = mNewNumServiceProcs > (mNumServiceProcs/3);
13723 mNewNumServiceProcs++;
13724 }
13725 if (app.serviceb) {
13726 adj = ProcessList.SERVICE_B_ADJ;
13727 }
13728 } else {
13729 app.serviceb = false;
13730 }
13731
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013732 app.curAdj = adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013733 app.curSchedGroup = schedGroup;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013734
13735 if (hadForegroundActivities != app.foregroundActivities) {
Jeff Sharkey287bd832011-05-28 19:36:26 -070013736 mHandler.obtainMessage(DISPATCH_FOREGROUND_ACTIVITIES_CHANGED, app.pid, app.info.uid,
13737 app.foregroundActivities).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013738 }
13739
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013740 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013741 }
13742
13743 /**
13744 * Ask a given process to GC right now.
13745 */
13746 final void performAppGcLocked(ProcessRecord app) {
13747 try {
13748 app.lastRequestedGc = SystemClock.uptimeMillis();
13749 if (app.thread != null) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013750 if (app.reportLowMemory) {
13751 app.reportLowMemory = false;
13752 app.thread.scheduleLowMemory();
13753 } else {
13754 app.thread.processInBackground();
13755 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013756 }
13757 } catch (Exception e) {
13758 // whatever.
13759 }
13760 }
13761
13762 /**
13763 * Returns true if things are idle enough to perform GCs.
13764 */
Josh Bartel7f208742010-02-25 11:01:44 -060013765 private final boolean canGcNowLocked() {
Christopher Tatef46723b2012-01-26 14:19:24 -080013766 boolean processingBroadcasts = false;
13767 for (BroadcastQueue q : mBroadcastQueues) {
13768 if (q.mParallelBroadcasts.size() != 0 || q.mOrderedBroadcasts.size() != 0) {
13769 processingBroadcasts = true;
13770 }
13771 }
13772 return !processingBroadcasts
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013773 && (mSleeping || (mMainStack.mResumedActivity != null &&
13774 mMainStack.mResumedActivity.idle));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013775 }
13776
13777 /**
13778 * Perform GCs on all processes that are waiting for it, but only
13779 * if things are idle.
13780 */
13781 final void performAppGcsLocked() {
13782 final int N = mProcessesToGc.size();
13783 if (N <= 0) {
13784 return;
13785 }
Josh Bartel7f208742010-02-25 11:01:44 -060013786 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013787 while (mProcessesToGc.size() > 0) {
13788 ProcessRecord proc = mProcessesToGc.remove(0);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013789 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013790 if ((proc.lastRequestedGc+GC_MIN_INTERVAL)
13791 <= SystemClock.uptimeMillis()) {
13792 // To avoid spamming the system, we will GC processes one
13793 // at a time, waiting a few seconds between each.
13794 performAppGcLocked(proc);
13795 scheduleAppGcsLocked();
13796 return;
13797 } else {
13798 // It hasn't been long enough since we last GCed this
13799 // process... put it in the list to wait for its time.
13800 addProcessToGcListLocked(proc);
13801 break;
13802 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013803 }
13804 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013805
13806 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013807 }
13808 }
13809
13810 /**
13811 * If all looks good, perform GCs on all processes waiting for them.
13812 */
13813 final void performAppGcsIfAppropriateLocked() {
Josh Bartel7f208742010-02-25 11:01:44 -060013814 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013815 performAppGcsLocked();
13816 return;
13817 }
13818 // Still not idle, wait some more.
13819 scheduleAppGcsLocked();
13820 }
13821
13822 /**
13823 * Schedule the execution of all pending app GCs.
13824 */
13825 final void scheduleAppGcsLocked() {
13826 mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013827
13828 if (mProcessesToGc.size() > 0) {
13829 // Schedule a GC for the time to the next process.
13830 ProcessRecord proc = mProcessesToGc.get(0);
13831 Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG);
13832
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013833 long when = proc.lastRequestedGc + GC_MIN_INTERVAL;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013834 long now = SystemClock.uptimeMillis();
13835 if (when < (now+GC_TIMEOUT)) {
13836 when = now + GC_TIMEOUT;
13837 }
13838 mHandler.sendMessageAtTime(msg, when);
13839 }
13840 }
13841
13842 /**
13843 * Add a process to the array of processes waiting to be GCed. Keeps the
13844 * list in sorted order by the last GC time. The process can't already be
13845 * on the list.
13846 */
13847 final void addProcessToGcListLocked(ProcessRecord proc) {
13848 boolean added = false;
13849 for (int i=mProcessesToGc.size()-1; i>=0; i--) {
13850 if (mProcessesToGc.get(i).lastRequestedGc <
13851 proc.lastRequestedGc) {
13852 added = true;
13853 mProcessesToGc.add(i+1, proc);
13854 break;
13855 }
13856 }
13857 if (!added) {
13858 mProcessesToGc.add(0, proc);
13859 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013860 }
13861
13862 /**
13863 * Set up to ask a process to GC itself. This will either do it
13864 * immediately, or put it on the list of processes to gc the next
13865 * time things are idle.
13866 */
13867 final void scheduleAppGcLocked(ProcessRecord app) {
13868 long now = SystemClock.uptimeMillis();
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013869 if ((app.lastRequestedGc+GC_MIN_INTERVAL) > now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013870 return;
13871 }
13872 if (!mProcessesToGc.contains(app)) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013873 addProcessToGcListLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013874 scheduleAppGcsLocked();
13875 }
13876 }
13877
Dianne Hackborn287952c2010-09-22 22:34:31 -070013878 final void checkExcessivePowerUsageLocked(boolean doKills) {
13879 updateCpuStatsNow();
13880
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013881 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013882 boolean doWakeKills = doKills;
13883 boolean doCpuKills = doKills;
13884 if (mLastPowerCheckRealtime == 0) {
13885 doWakeKills = false;
13886 }
13887 if (mLastPowerCheckUptime == 0) {
13888 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013889 }
13890 if (stats.isScreenOn()) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070013891 doWakeKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013892 }
13893 final long curRealtime = SystemClock.elapsedRealtime();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013894 final long realtimeSince = curRealtime - mLastPowerCheckRealtime;
13895 final long curUptime = SystemClock.uptimeMillis();
13896 final long uptimeSince = curUptime - mLastPowerCheckUptime;
13897 mLastPowerCheckRealtime = curRealtime;
13898 mLastPowerCheckUptime = curUptime;
13899 if (realtimeSince < WAKE_LOCK_MIN_CHECK_DURATION) {
13900 doWakeKills = false;
13901 }
13902 if (uptimeSince < CPU_MIN_CHECK_DURATION) {
13903 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013904 }
13905 int i = mLruProcesses.size();
13906 while (i > 0) {
13907 i--;
13908 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013909 if (!app.keeping) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013910 long wtime;
13911 synchronized (stats) {
13912 wtime = stats.getProcessWakeTime(app.info.uid,
13913 app.pid, curRealtime);
13914 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013915 long wtimeUsed = wtime - app.lastWakeTime;
13916 long cputimeUsed = app.curCpuTime - app.lastCpuTime;
13917 if (DEBUG_POWER) {
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013918 StringBuilder sb = new StringBuilder(128);
13919 sb.append("Wake for ");
13920 app.toShortString(sb);
13921 sb.append(": over ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013922 TimeUtils.formatDuration(realtimeSince, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013923 sb.append(" used ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013924 TimeUtils.formatDuration(wtimeUsed, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013925 sb.append(" (");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013926 sb.append((wtimeUsed*100)/realtimeSince);
13927 sb.append("%)");
13928 Slog.i(TAG, sb.toString());
13929 sb.setLength(0);
13930 sb.append("CPU for ");
13931 app.toShortString(sb);
13932 sb.append(": over ");
13933 TimeUtils.formatDuration(uptimeSince, sb);
13934 sb.append(" used ");
13935 TimeUtils.formatDuration(cputimeUsed, sb);
13936 sb.append(" (");
13937 sb.append((cputimeUsed*100)/uptimeSince);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013938 sb.append("%)");
13939 Slog.i(TAG, sb.toString());
13940 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013941 // If a process has held a wake lock for more
13942 // than 50% of the time during this period,
13943 // that sounds pad. Kill!
Dianne Hackborn287952c2010-09-22 22:34:31 -070013944 if (doWakeKills && realtimeSince > 0
13945 && ((wtimeUsed*100)/realtimeSince) >= 50) {
13946 synchronized (stats) {
13947 stats.reportExcessiveWakeLocked(app.info.uid, app.processName,
13948 realtimeSince, wtimeUsed);
13949 }
13950 Slog.w(TAG, "Excessive wake lock in " + app.processName
13951 + " (pid " + app.pid + "): held " + wtimeUsed
13952 + " during " + realtimeSince);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013953 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13954 app.processName, app.setAdj, "excessive wake lock");
13955 Process.killProcessQuiet(app.pid);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013956 } else if (doCpuKills && uptimeSince > 0
13957 && ((cputimeUsed*100)/uptimeSince) >= 50) {
13958 synchronized (stats) {
13959 stats.reportExcessiveCpuLocked(app.info.uid, app.processName,
13960 uptimeSince, cputimeUsed);
13961 }
13962 Slog.w(TAG, "Excessive CPU in " + app.processName
13963 + " (pid " + app.pid + "): used " + cputimeUsed
13964 + " during " + uptimeSince);
13965 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13966 app.processName, app.setAdj, "excessive cpu");
13967 Process.killProcessQuiet(app.pid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013968 } else {
13969 app.lastWakeTime = wtime;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013970 app.lastCpuTime = app.curCpuTime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013971 }
13972 }
13973 }
13974 }
13975
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013976 private final boolean updateOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013977 ProcessRecord app, int hiddenAdj, ProcessRecord TOP_APP, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013978 app.hiddenAdj = hiddenAdj;
13979
13980 if (app.thread == null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013981 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013982 }
13983
Dianne Hackborn287952c2010-09-22 22:34:31 -070013984 final boolean wasKeeping = app.keeping;
13985
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013986 boolean success = true;
13987
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013988 computeOomAdjLocked(app, hiddenAdj, TOP_APP, false, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013989
Jeff Brown10e89712011-07-08 18:52:57 -070013990 if (app.curRawAdj != app.setRawAdj) {
Dianne Hackborn905577f2011-09-07 18:31:28 -070013991 if (false) {
13992 // Removing for now. Forcing GCs is not so useful anymore
13993 // with Dalvik, and the new memory level hint facility is
13994 // better for what we need to do these days.
13995 if (app.curRawAdj > ProcessList.FOREGROUND_APP_ADJ
13996 && app.setRawAdj <= ProcessList.FOREGROUND_APP_ADJ) {
13997 // If this app is transitioning from foreground to
13998 // non-foreground, have it do a gc.
13999 scheduleAppGcLocked(app);
14000 } else if (app.curRawAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
14001 && app.setRawAdj < ProcessList.HIDDEN_APP_MIN_ADJ) {
14002 // Likewise do a gc when an app is moving in to the
14003 // background (such as a service stopping).
14004 scheduleAppGcLocked(app);
14005 }
Jeff Brown10e89712011-07-08 18:52:57 -070014006 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070014007
Jeff Brown10e89712011-07-08 18:52:57 -070014008 if (wasKeeping && !app.keeping) {
14009 // This app is no longer something we want to keep. Note
14010 // its current wake lock time to later know to kill it if
14011 // it is not behaving well.
14012 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
14013 synchronized (stats) {
14014 app.lastWakeTime = stats.getProcessWakeTime(app.info.uid,
14015 app.pid, SystemClock.elapsedRealtime());
14016 }
14017 app.lastCpuTime = app.curCpuTime;
14018 }
14019
14020 app.setRawAdj = app.curRawAdj;
14021 }
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014022
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014023 if (app.curAdj != app.setAdj) {
14024 if (Process.setOomAdj(app.pid, app.curAdj)) {
Dianne Hackbornbbb09ac2011-11-30 11:31:29 -080014025 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014026 TAG, "Set " + app.pid + " " + app.processName +
14027 " adj " + app.curAdj + ": " + app.adjType);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014028 app.setAdj = app.curAdj;
Jeff Brown10e89712011-07-08 18:52:57 -070014029 } else {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014030 success = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014031 Slog.w(TAG, "Failed setting oom adj of " + app + " to " + app.curAdj);
Jeff Brown10e89712011-07-08 18:52:57 -070014032 }
14033 }
14034 if (app.setSchedGroup != app.curSchedGroup) {
14035 app.setSchedGroup = app.curSchedGroup;
14036 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
14037 "Setting process group of " + app.processName
14038 + " to " + app.curSchedGroup);
14039 if (app.waitingToKill != null &&
14040 app.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
14041 Slog.i(TAG, "Killing " + app.toShortString() + ": " + app.waitingToKill);
14042 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14043 app.processName, app.setAdj, app.waitingToKill);
14044 Process.killProcessQuiet(app.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014045 success = false;
Jeff Brown10e89712011-07-08 18:52:57 -070014046 } else {
14047 if (true) {
14048 long oldId = Binder.clearCallingIdentity();
14049 try {
14050 Process.setProcessGroup(app.pid, app.curSchedGroup);
14051 } catch (Exception e) {
14052 Slog.w(TAG, "Failed setting process group of " + app.pid
14053 + " to " + app.curSchedGroup);
14054 e.printStackTrace();
14055 } finally {
14056 Binder.restoreCallingIdentity(oldId);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014057 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014058 } else {
Jeff Brown10e89712011-07-08 18:52:57 -070014059 if (app.thread != null) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070014060 try {
Jeff Brown10e89712011-07-08 18:52:57 -070014061 app.thread.setSchedulingGroup(app.curSchedGroup);
14062 } catch (RemoteException e) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070014063 }
14064 }
14065 }
14066 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014067 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014068 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014069 }
14070
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014071 private final ActivityRecord resumedAppLocked() {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014072 ActivityRecord resumedActivity = mMainStack.mResumedActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014073 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -080014074 resumedActivity = mMainStack.mPausingActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014075 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014076 resumedActivity = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014077 }
14078 }
14079 return resumedActivity;
14080 }
14081
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014082 private final boolean updateOomAdjLocked(ProcessRecord app) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014083 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014084 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
14085 int curAdj = app.curAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070014086 final boolean wasHidden = curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
14087 && curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014088
14089 mAdjSeq++;
14090
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014091 boolean success = updateOomAdjLocked(app, app.hiddenAdj, TOP_APP, false);
Dianne Hackborn7d608422011-08-07 16:24:18 -070014092 final boolean nowHidden = app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
14093 && app.curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014094 if (nowHidden != wasHidden) {
14095 // Changed to/from hidden state, so apps after it in the LRU
14096 // list may also be changed.
14097 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014098 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014099 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014100 }
14101
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014102 final void updateOomAdjLocked() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014103 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014104 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
14105
14106 if (false) {
14107 RuntimeException e = new RuntimeException();
14108 e.fillInStackTrace();
Joe Onorato8a9b2202010-02-26 18:56:32 -080014109 Slog.i(TAG, "updateOomAdj: top=" + TOP_ACT, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014110 }
14111
14112 mAdjSeq++;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014113 mNewNumServiceProcs = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014114
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014115 // Let's determine how many processes we have running vs.
14116 // how many slots we have for background processes; we may want
14117 // to put multiple processes in a slot of there are enough of
14118 // them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014119 int numSlots = ProcessList.HIDDEN_APP_MAX_ADJ - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014120 int factor = (mLruProcesses.size()-4)/numSlots;
14121 if (factor < 1) factor = 1;
14122 int step = 0;
Dianne Hackborn8633e682010-04-22 16:03:41 -070014123 int numHidden = 0;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014124
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014125 // First update the OOM adjustment for each of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014126 // application processes based on their current state.
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014127 int i = mLruProcesses.size();
Dianne Hackborn7d608422011-08-07 16:24:18 -070014128 int curHiddenAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014129 while (i > 0) {
14130 i--;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014131 ProcessRecord app = mLruProcesses.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080014132 //Slog.i(TAG, "OOM " + app + ": cur hidden=" + curHiddenAdj);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014133 updateOomAdjLocked(app, curHiddenAdj, TOP_APP, true);
14134 if (curHiddenAdj < ProcessList.HIDDEN_APP_MAX_ADJ
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014135 && app.curAdj == curHiddenAdj) {
14136 step++;
14137 if (step >= factor) {
14138 step = 0;
14139 curHiddenAdj++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014140 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014141 }
14142 if (!app.killedBackground) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070014143 if (app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014144 numHidden++;
14145 if (numHidden > mProcessLimit) {
14146 Slog.i(TAG, "No longer want " + app.processName
14147 + " (pid " + app.pid + "): hidden #" + numHidden);
14148 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14149 app.processName, app.setAdj, "too many background");
14150 app.killedBackground = true;
14151 Process.killProcessQuiet(app.pid);
Dianne Hackborn8633e682010-04-22 16:03:41 -070014152 }
14153 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -080014154 if (!app.killedBackground && app.isolated && app.services.size() <= 0) {
14155 // If this is an isolated process, and there are no
14156 // services running in it, then the process is no longer
14157 // needed. We agressively kill these because we can by
14158 // definition not re-use the same process again, and it is
14159 // good to avoid having whatever code was running in them
14160 // left sitting around after no longer needed.
14161 Slog.i(TAG, "Isolated process " + app.processName
14162 + " (pid " + app.pid + ") no longer needed");
14163 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14164 app.processName, app.setAdj, "isolated not needed");
14165 app.killedBackground = true;
14166 Process.killProcessQuiet(app.pid);
14167 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014168 }
14169 }
14170
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014171 mNumServiceProcs = mNewNumServiceProcs;
14172
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014173 // Now determine the memory trimming level of background processes.
14174 // Unfortunately we need to start at the back of the list to do this
14175 // properly. We only do this if the number of background apps we
14176 // are managing to keep around is less than half the maximum we desire;
14177 // if we are keeping a good number around, we'll let them use whatever
14178 // memory they want.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014179 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/2)) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014180 final int N = mLruProcesses.size();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080014181 factor = numHidden/3;
14182 int minFactor = 2;
14183 if (mHomeProcess != null) minFactor++;
14184 if (mPreviousProcess != null) minFactor++;
14185 if (factor < minFactor) factor = minFactor;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014186 step = 0;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014187 int fgTrimLevel;
14188 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/5)) {
14189 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL;
14190 } else if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/3)) {
14191 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW;
14192 } else {
14193 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE;
14194 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014195 int curLevel = ComponentCallbacks2.TRIM_MEMORY_COMPLETE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014196 for (i=0; i<N; i++) {
14197 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080014198 if (app.curAdj >= ProcessList.HOME_APP_ADJ
14199 && app.curAdj != ProcessList.SERVICE_B_ADJ
14200 && !app.killedBackground) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014201 if (app.trimMemoryLevel < curLevel && app.thread != null) {
14202 try {
14203 app.thread.scheduleTrimMemory(curLevel);
14204 } catch (RemoteException e) {
14205 }
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080014206 if (false) {
14207 // For now we won't do this; our memory trimming seems
14208 // to be good enough at this point that destroying
14209 // activities causes more harm than good.
14210 if (curLevel >= ComponentCallbacks2.TRIM_MEMORY_COMPLETE
14211 && app != mHomeProcess && app != mPreviousProcess) {
14212 // For these apps we will also finish their activities
14213 // to help them free memory.
14214 mMainStack.destroyActivitiesLocked(app, false, "trim");
14215 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014216 }
14217 }
14218 app.trimMemoryLevel = curLevel;
14219 step++;
14220 if (step >= factor) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014221 step = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014222 switch (curLevel) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014223 case ComponentCallbacks2.TRIM_MEMORY_COMPLETE:
14224 curLevel = ComponentCallbacks2.TRIM_MEMORY_MODERATE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014225 break;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014226 case ComponentCallbacks2.TRIM_MEMORY_MODERATE:
14227 curLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014228 break;
14229 }
14230 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070014231 } else if (app.curAdj == ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014232 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014233 && app.thread != null) {
14234 try {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014235 app.thread.scheduleTrimMemory(
14236 ComponentCallbacks2.TRIM_MEMORY_BACKGROUND);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014237 } catch (RemoteException e) {
14238 }
14239 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014240 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014241 } else {
14242 if ((app.curAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
14243 && app.pendingUiClean) {
14244 // If this application is now in the background and it
14245 // had done UI, then give it the special trim level to
14246 // have it free UI resources.
14247 final int level = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
14248 if (app.trimMemoryLevel < level && app.thread != null) {
14249 try {
14250 app.thread.scheduleTrimMemory(level);
14251 } catch (RemoteException e) {
14252 }
14253 }
14254 app.pendingUiClean = false;
14255 }
14256 if (app.trimMemoryLevel < fgTrimLevel && app.thread != null) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014257 try {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014258 app.thread.scheduleTrimMemory(fgTrimLevel);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014259 } catch (RemoteException e) {
14260 }
14261 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014262 app.trimMemoryLevel = fgTrimLevel;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014263 }
14264 }
14265 } else {
14266 final int N = mLruProcesses.size();
14267 for (i=0; i<N; i++) {
14268 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -070014269 if ((app.curAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014270 && app.pendingUiClean) {
14271 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
14272 && app.thread != null) {
14273 try {
14274 app.thread.scheduleTrimMemory(
14275 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
14276 } catch (RemoteException e) {
14277 }
14278 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014279 app.pendingUiClean = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014280 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014281 app.trimMemoryLevel = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014282 }
14283 }
14284
14285 if (mAlwaysFinishActivities) {
Dianne Hackborn28695e02011-11-02 21:59:51 -070014286 mMainStack.destroyActivitiesLocked(null, false, "always-finish");
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014287 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014288 }
14289
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014290 final void trimApplications() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014291 synchronized (this) {
14292 int i;
14293
14294 // First remove any unused application processes whose package
14295 // has been removed.
14296 for (i=mRemovedProcesses.size()-1; i>=0; i--) {
14297 final ProcessRecord app = mRemovedProcesses.get(i);
14298 if (app.activities.size() == 0
14299 && app.curReceiver == null && app.services.size() == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080014300 Slog.i(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014301 TAG, "Exiting empty application process "
14302 + app.processName + " ("
14303 + (app.thread != null ? app.thread.asBinder() : null)
14304 + ")\n");
14305 if (app.pid > 0 && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070014306 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14307 app.processName, app.setAdj, "empty");
14308 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014309 } else {
14310 try {
14311 app.thread.scheduleExit();
14312 } catch (Exception e) {
14313 // Ignore exceptions.
14314 }
14315 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070014316 cleanUpApplicationRecordLocked(app, false, true, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014317 mRemovedProcesses.remove(i);
14318
14319 if (app.persistent) {
14320 if (app.persistent) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080014321 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014322 }
14323 }
14324 }
14325 }
14326
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014327 // Now update the oom adj for all processes.
14328 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014329 }
14330 }
14331
14332 /** This method sends the specified signal to each of the persistent apps */
14333 public void signalPersistentProcesses(int sig) throws RemoteException {
14334 if (sig != Process.SIGNAL_USR1) {
14335 throw new SecurityException("Only SIGNAL_USR1 is allowed");
14336 }
14337
14338 synchronized (this) {
14339 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
14340 != PackageManager.PERMISSION_GRANTED) {
14341 throw new SecurityException("Requires permission "
14342 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
14343 }
14344
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014345 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
14346 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014347 if (r.thread != null && r.persistent) {
14348 Process.sendSignal(r.pid, sig);
14349 }
14350 }
14351 }
14352 }
14353
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014354 private void stopProfilerLocked(ProcessRecord proc, String path, int profileType) {
14355 if (proc == null || proc == mProfileProc) {
14356 proc = mProfileProc;
14357 path = mProfileFile;
14358 profileType = mProfileType;
14359 clearProfilerLocked();
14360 }
14361 if (proc == null) {
14362 return;
14363 }
14364 try {
14365 proc.thread.profilerControl(false, path, null, profileType);
14366 } catch (RemoteException e) {
14367 throw new IllegalStateException("Process disappeared");
14368 }
14369 }
14370
14371 private void clearProfilerLocked() {
14372 if (mProfileFd != null) {
14373 try {
14374 mProfileFd.close();
14375 } catch (IOException e) {
14376 }
14377 }
14378 mProfileApp = null;
14379 mProfileProc = null;
14380 mProfileFile = null;
14381 mProfileType = 0;
14382 mAutoStopProfiler = false;
14383 }
14384
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014385 public boolean profileControl(String process, boolean start,
Romain Guy7eabe552011-07-21 14:56:34 -070014386 String path, ParcelFileDescriptor fd, int profileType) throws RemoteException {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014387
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014388 try {
14389 synchronized (this) {
14390 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14391 // its own permission.
14392 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14393 != PackageManager.PERMISSION_GRANTED) {
14394 throw new SecurityException("Requires permission "
14395 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014396 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014397
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014398 if (start && fd == null) {
14399 throw new IllegalArgumentException("null fd");
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 ProcessRecord proc = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014403 if (process != null) {
14404 try {
14405 int pid = Integer.parseInt(process);
14406 synchronized (mPidsSelfLocked) {
14407 proc = mPidsSelfLocked.get(pid);
14408 }
14409 } catch (NumberFormatException e) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014410 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014411
14412 if (proc == null) {
14413 HashMap<String, SparseArray<ProcessRecord>> all
14414 = mProcessNames.getMap();
14415 SparseArray<ProcessRecord> procs = all.get(process);
14416 if (procs != null && procs.size() > 0) {
14417 proc = procs.valueAt(0);
14418 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014419 }
14420 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014421
14422 if (start && (proc == null || proc.thread == null)) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014423 throw new IllegalArgumentException("Unknown process: " + process);
14424 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014425
14426 if (start) {
14427 stopProfilerLocked(null, null, 0);
14428 setProfileApp(proc.info, proc.processName, path, fd, false);
14429 mProfileProc = proc;
14430 mProfileType = profileType;
14431 try {
14432 fd = fd.dup();
14433 } catch (IOException e) {
14434 fd = null;
14435 }
14436 proc.thread.profilerControl(start, path, fd, profileType);
14437 fd = null;
14438 mProfileFd = null;
14439 } else {
14440 stopProfilerLocked(proc, path, profileType);
14441 if (fd != null) {
14442 try {
14443 fd.close();
14444 } catch (IOException e) {
14445 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014446 }
14447 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014448
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014449 return true;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014450 }
14451 } catch (RemoteException e) {
14452 throw new IllegalStateException("Process disappeared");
14453 } finally {
14454 if (fd != null) {
14455 try {
14456 fd.close();
14457 } catch (IOException e) {
14458 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014459 }
14460 }
14461 }
Andy McFadden824c5102010-07-09 16:26:57 -070014462
14463 public boolean dumpHeap(String process, boolean managed,
14464 String path, ParcelFileDescriptor fd) throws RemoteException {
14465
14466 try {
14467 synchronized (this) {
14468 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14469 // its own permission (same as profileControl).
14470 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14471 != PackageManager.PERMISSION_GRANTED) {
14472 throw new SecurityException("Requires permission "
14473 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
14474 }
14475
14476 if (fd == null) {
14477 throw new IllegalArgumentException("null fd");
14478 }
14479
14480 ProcessRecord proc = null;
14481 try {
14482 int pid = Integer.parseInt(process);
14483 synchronized (mPidsSelfLocked) {
14484 proc = mPidsSelfLocked.get(pid);
14485 }
14486 } catch (NumberFormatException e) {
14487 }
14488
14489 if (proc == null) {
14490 HashMap<String, SparseArray<ProcessRecord>> all
14491 = mProcessNames.getMap();
14492 SparseArray<ProcessRecord> procs = all.get(process);
14493 if (procs != null && procs.size() > 0) {
14494 proc = procs.valueAt(0);
14495 }
14496 }
14497
14498 if (proc == null || proc.thread == null) {
14499 throw new IllegalArgumentException("Unknown process: " + process);
14500 }
14501
Dianne Hackbornf02e57b2011-03-01 22:21:04 -080014502 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
14503 if (!isDebuggable) {
Andy McFadden824c5102010-07-09 16:26:57 -070014504 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
14505 throw new SecurityException("Process not debuggable: " + proc);
14506 }
14507 }
14508
14509 proc.thread.dumpHeap(managed, path, fd);
14510 fd = null;
14511 return true;
14512 }
14513 } catch (RemoteException e) {
14514 throw new IllegalStateException("Process disappeared");
14515 } finally {
14516 if (fd != null) {
14517 try {
14518 fd.close();
14519 } catch (IOException e) {
14520 }
14521 }
14522 }
14523 }
14524
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014525 /** In this method we try to acquire our lock to make sure that we have not deadlocked */
14526 public void monitor() {
14527 synchronized (this) { }
14528 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014529
Dianne Hackborna573f6a2012-02-09 16:12:18 -080014530 void onCoreSettingsChange(Bundle settings) {
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014531 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
14532 ProcessRecord processRecord = mLruProcesses.get(i);
14533 try {
14534 if (processRecord.thread != null) {
14535 processRecord.thread.setCoreSettings(settings);
14536 }
14537 } catch (RemoteException re) {
14538 /* ignore */
14539 }
14540 }
14541 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014542
14543 // Multi-user methods
14544
Amith Yamasani742a6712011-05-04 14:49:28 -070014545 private int mCurrentUserId;
14546 private SparseIntArray mLoggedInUsers = new SparseIntArray(5);
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014547 private ArrayList<UserListener> mUserListeners = new ArrayList<UserListener>(3);
14548
14549 public interface UserListener {
14550 public void onUserChanged(int userId);
14551
14552 public void onUserAdded(int userId);
14553
14554 public void onUserRemoved(int userId);
14555
14556 public void onUserLoggedOut(int userId);
14557 }
14558
14559 public void addUserListener(UserListener listener) {
14560 synchronized (this) {
14561 if (!mUserListeners.contains(listener)) {
14562 mUserListeners.add(listener);
14563 }
14564 }
14565 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014566
14567 public boolean switchUser(int userId) {
14568 final int callingUid = Binder.getCallingUid();
14569 if (callingUid != 0 && callingUid != Process.myUid()) {
14570 Slog.e(TAG, "Trying to switch user from unauthorized app");
14571 return false;
14572 }
14573 if (mCurrentUserId == userId)
14574 return true;
14575
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014576 ArrayList<UserListener> listeners;
14577
Amith Yamasani742a6712011-05-04 14:49:28 -070014578 synchronized (this) {
14579 // Check if user is already logged in, otherwise check if user exists first before
14580 // adding to the list of logged in users.
14581 if (mLoggedInUsers.indexOfKey(userId) < 0) {
14582 if (!userExists(userId)) {
14583 return false;
14584 }
14585 mLoggedInUsers.append(userId, userId);
14586 }
14587
14588 mCurrentUserId = userId;
14589 boolean haveActivities = mMainStack.switchUser(userId);
14590 if (!haveActivities) {
14591 startHomeActivityLocked(userId);
14592 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014593
14594 listeners = (ArrayList<UserListener>) mUserListeners.clone();
14595 }
14596 // Inform the listeners
14597 for (UserListener listener : listeners) {
14598 listener.onUserChanged(userId);
Amith Yamasani742a6712011-05-04 14:49:28 -070014599 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014600 return true;
14601 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014602
14603 private boolean userExists(int userId) {
14604 try {
14605 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
14606 for (UserInfo user : users) {
14607 if (user.id == userId) {
14608 return true;
14609 }
14610 }
14611 } catch (RemoteException re) {
14612 // Won't happen, in same process
14613 }
14614
14615 return false;
14616 }
14617
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014618 private void checkValidCaller(int uid, int userId) {
14619 if (UserId.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) return;
14620
14621 throw new SecurityException("Caller uid=" + uid
14622 + " is not privileged to communicate with user=" + userId);
14623 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014624
14625 private int applyUserId(int uid, int userId) {
14626 return UserId.getUid(userId, uid);
14627 }
14628
14629 private ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080014630 if (info == null) return null;
Amith Yamasani742a6712011-05-04 14:49:28 -070014631 ApplicationInfo newInfo = new ApplicationInfo(info);
14632 newInfo.uid = applyUserId(info.uid, userId);
14633 if (newInfo.uid >= Process.FIRST_APPLICATION_UID) {
14634 newInfo.dataDir = USER_DATA_DIR + userId + "/"
14635 + info.packageName;
14636 }
14637 return newInfo;
14638 }
14639
14640 ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080014641 if (aInfo == null || aInfo.applicationInfo.uid < Process.FIRST_APPLICATION_UID
Amith Yamasani742a6712011-05-04 14:49:28 -070014642 || userId < 1) {
14643 return aInfo;
14644 }
14645
14646 ActivityInfo info = new ActivityInfo(aInfo);
14647 info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId);
14648 return info;
14649 }
14650
14651 static class ServiceMap {
14652
14653 private final SparseArray<HashMap<ComponentName, ServiceRecord>> mServicesByNamePerUser
14654 = new SparseArray<HashMap<ComponentName, ServiceRecord>>();
14655 private final SparseArray<HashMap<Intent.FilterComparison, ServiceRecord>>
14656 mServicesByIntentPerUser = new SparseArray<
14657 HashMap<Intent.FilterComparison, ServiceRecord>>();
14658
14659 ServiceRecord getServiceByName(ComponentName name, int callingUser) {
14660 // TODO: Deal with global services
14661 if (DEBUG_MU)
14662 Slog.v(TAG_MU, "getServiceByName(" + name + "), callingUser = " + callingUser);
14663 return getServices(callingUser).get(name);
14664 }
14665
14666 ServiceRecord getServiceByName(ComponentName name) {
14667 return getServiceByName(name, -1);
14668 }
14669
14670 ServiceRecord getServiceByIntent(Intent.FilterComparison filter, int callingUser) {
14671 // TODO: Deal with global services
14672 if (DEBUG_MU)
14673 Slog.v(TAG_MU, "getServiceByIntent(" + filter + "), callingUser = " + callingUser);
14674 return getServicesByIntent(callingUser).get(filter);
14675 }
14676
14677 ServiceRecord getServiceByIntent(Intent.FilterComparison filter) {
14678 return getServiceByIntent(filter, -1);
14679 }
14680
14681 void putServiceByName(ComponentName name, int callingUser, ServiceRecord value) {
14682 // TODO: Deal with global services
14683 getServices(callingUser).put(name, value);
14684 }
14685
14686 void putServiceByIntent(Intent.FilterComparison filter, int callingUser,
14687 ServiceRecord value) {
14688 // TODO: Deal with global services
14689 getServicesByIntent(callingUser).put(filter, value);
14690 }
14691
14692 void removeServiceByName(ComponentName name, int callingUser) {
14693 // TODO: Deal with global services
14694 ServiceRecord removed = getServices(callingUser).remove(name);
14695 if (DEBUG_MU)
14696 Slog.v(TAG, "removeServiceByName user=" + callingUser + " name=" + name
14697 + " removed=" + removed);
14698 }
14699
14700 void removeServiceByIntent(Intent.FilterComparison filter, int callingUser) {
14701 // TODO: Deal with global services
14702 ServiceRecord removed = getServicesByIntent(callingUser).remove(filter);
14703 if (DEBUG_MU)
14704 Slog.v(TAG_MU, "removeServiceByIntent user=" + callingUser + " intent=" + filter
14705 + " removed=" + removed);
14706 }
14707
14708 Collection<ServiceRecord> getAllServices(int callingUser) {
14709 // TODO: Deal with global services
14710 return getServices(callingUser).values();
14711 }
14712
14713 private HashMap<ComponentName, ServiceRecord> getServices(int callingUser) {
14714 HashMap map = mServicesByNamePerUser.get(callingUser);
14715 if (map == null) {
14716 map = new HashMap<ComponentName, ServiceRecord>();
14717 mServicesByNamePerUser.put(callingUser, map);
14718 }
14719 return map;
14720 }
14721
14722 private HashMap<Intent.FilterComparison, ServiceRecord> getServicesByIntent(
14723 int callingUser) {
14724 HashMap map = mServicesByIntentPerUser.get(callingUser);
14725 if (map == null) {
14726 map = new HashMap<Intent.FilterComparison, ServiceRecord>();
14727 mServicesByIntentPerUser.put(callingUser, map);
14728 }
14729 return map;
14730 }
14731 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014732}