blob: 6f89f6eab6b31cce7a0ac7555d8639ea8c242ff4 [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;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113import android.util.EventLog;
Dianne Hackborn905577f2011-09-07 18:31:28 -0700114import android.util.Pair;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800115import android.util.Slog;
Joe Onorato5d3bea62010-03-01 13:44:29 -0800116import android.util.Log;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800117import android.util.PrintWriterPrinter;
118import android.util.SparseArray;
Amith Yamasani742a6712011-05-04 14:49:28 -0700119import android.util.SparseIntArray;
Dianne Hackborn1ebccf52010-08-15 13:04:34 -0700120import android.util.TimeUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800121import android.view.Gravity;
122import android.view.LayoutInflater;
123import android.view.View;
124import android.view.WindowManager;
125import android.view.WindowManagerPolicy;
126
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700127import java.io.BufferedInputStream;
128import java.io.BufferedOutputStream;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700129import java.io.BufferedReader;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700130import java.io.DataInputStream;
131import java.io.DataOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800132import java.io.File;
133import java.io.FileDescriptor;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700134import java.io.FileInputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800135import java.io.FileNotFoundException;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700136import java.io.FileOutputStream;
Jacek Surazskif5b9c722009-05-18 12:09:59 +0200137import java.io.IOException;
Dan Egnora455d192010-03-12 08:52:28 -0800138import java.io.InputStreamReader;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800139import java.io.PrintWriter;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700140import java.io.StringWriter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800141import java.lang.IllegalStateException;
142import java.lang.ref.WeakReference;
143import java.util.ArrayList;
Amith Yamasani742a6712011-05-04 14:49:28 -0700144import java.util.Collection;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700145import java.util.Collections;
146import java.util.Comparator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800147import java.util.HashMap;
148import java.util.HashSet;
149import java.util.Iterator;
150import java.util.List;
151import java.util.Locale;
152import java.util.Map;
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -0700153import java.util.Set;
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700154import java.util.concurrent.atomic.AtomicBoolean;
155import java.util.concurrent.atomic.AtomicLong;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800156
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700157public final class ActivityManagerService extends ActivityManagerNative
158 implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
Amith Yamasani742a6712011-05-04 14:49:28 -0700159 private static final String USER_DATA_DIR = "/data/user/";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800160 static final String TAG = "ActivityManager";
Amith Yamasani742a6712011-05-04 14:49:28 -0700161 static final String TAG_MU = "ActivityManagerServiceMU";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800162 static final boolean DEBUG = false;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400163 static final boolean localLOGV = DEBUG;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800164 static final boolean DEBUG_SWITCH = localLOGV || false;
165 static final boolean DEBUG_TASKS = localLOGV || false;
166 static final boolean DEBUG_PAUSE = localLOGV || false;
167 static final boolean DEBUG_OOM_ADJ = localLOGV || false;
168 static final boolean DEBUG_TRANSITION = localLOGV || false;
169 static final boolean DEBUG_BROADCAST = localLOGV || false;
Christopher Tatef46723b2012-01-26 14:19:24 -0800170 static final boolean DEBUG_BACKGROUND_BROADCAST = DEBUG_BROADCAST || false;
Dianne Hackborn82f3f002009-06-16 18:49:05 -0700171 static final boolean DEBUG_BROADCAST_LIGHT = DEBUG_BROADCAST || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800172 static final boolean DEBUG_SERVICE = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700173 static final boolean DEBUG_SERVICE_EXECUTING = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800174 static final boolean DEBUG_VISBILITY = localLOGV || false;
175 static final boolean DEBUG_PROCESSES = localLOGV || false;
Dianne Hackborna1e989b2009-09-01 19:54:29 -0700176 static final boolean DEBUG_PROVIDER = localLOGV || false;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800177 static final boolean DEBUG_URI_PERMISSION = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800178 static final boolean DEBUG_USER_LEAVING = localLOGV || false;
The Android Open Source Project10592532009-03-18 17:39:46 -0700179 static final boolean DEBUG_RESULTS = localLOGV || false;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -0700180 static final boolean DEBUG_BACKUP = localLOGV || false;
Dianne Hackborndc6b6352009-09-30 14:20:09 -0700181 static final boolean DEBUG_CONFIGURATION = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700182 static final boolean DEBUG_POWER = localLOGV || false;
183 static final boolean DEBUG_POWER_QUICK = DEBUG_POWER || false;
Amith Yamasani742a6712011-05-04 14:49:28 -0700184 static final boolean DEBUG_MU = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800185 static final boolean VALIDATE_TOKENS = false;
186 static final boolean SHOW_ACTIVITY_START_TIME = true;
187
188 // Control over CPU and battery monitoring.
189 static final long BATTERY_STATS_TIME = 30*60*1000; // write battery stats every 30 minutes.
190 static final boolean MONITOR_CPU_USAGE = true;
191 static final long MONITOR_CPU_MIN_TIME = 5*1000; // don't sample cpu less than every 5 seconds.
192 static final long MONITOR_CPU_MAX_TIME = 0x0fffffff; // wait possibly forever for next cpu sample.
193 static final boolean MONITOR_THREAD_CPU_USAGE = false;
194
Dianne Hackborn1655be42009-05-08 14:29:01 -0700195 // The flags that are set for all calls we make to the package manager.
Dianne Hackborn11b822d2009-07-21 20:03:02 -0700196 static final int STOCK_PM_FLAGS = PackageManager.GET_SHARED_LIBRARY_FILES;
Dianne Hackborn1655be42009-05-08 14:29:01 -0700197
Dianne Hackbornf02e57b2011-03-01 22:21:04 -0800198 private static final String SYSTEM_DEBUGGABLE = "ro.debuggable";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800199
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800200 // Maximum number of recent tasks that we can remember.
201 static final int MAX_RECENT_TASKS = 20;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700202
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700203 // Amount of time after a call to stopAppSwitches() during which we will
204 // prevent further untrusted switches from happening.
205 static final long APP_SWITCH_DELAY_TIME = 5*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800206
207 // How long we wait for a launched process to attach to the activity manager
208 // before we decide it's never going to come up for real.
209 static final int PROC_START_TIMEOUT = 10*1000;
210
Jeff Brown3f9dd282011-07-08 20:02:19 -0700211 // How long we wait for a launched process to attach to the activity manager
212 // before we decide it's never going to come up for real, when the process was
213 // started with a wrapper for instrumentation (such as Valgrind) because it
214 // could take much longer than usual.
215 static final int PROC_START_TIMEOUT_WITH_WRAPPER = 300*1000;
216
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800217 // How long to wait after going idle before forcing apps to GC.
218 static final int GC_TIMEOUT = 5*1000;
219
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700220 // The minimum amount of time between successive GC requests for a process.
221 static final int GC_MIN_INTERVAL = 60*1000;
222
Dianne Hackborn287952c2010-09-22 22:34:31 -0700223 // The rate at which we check for apps using excessive power -- 15 mins.
224 static final int POWER_CHECK_DELAY = (DEBUG_POWER_QUICK ? 2 : 15) * 60*1000;
225
226 // The minimum sample duration we will allow before deciding we have
227 // enough data on wake locks to start killing things.
228 static final int WAKE_LOCK_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
229
230 // The minimum sample duration we will allow before deciding we have
231 // enough data on CPU usage to start killing things.
232 static final int CPU_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700233
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800234 // How long we allow a receiver to run before giving up on it.
Christopher Tatef46723b2012-01-26 14:19:24 -0800235 static final int BROADCAST_FG_TIMEOUT = 10*1000;
236 static final int BROADCAST_BG_TIMEOUT = 60*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800237
238 // How long we wait for a service to finish executing.
239 static final int SERVICE_TIMEOUT = 20*1000;
240
241 // How long a service needs to be running until restarting its process
242 // is no longer considered to be a relaunch of the service.
243 static final int SERVICE_RESTART_DURATION = 5*1000;
244
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700245 // How long a service needs to be running until it will start back at
246 // SERVICE_RESTART_DURATION after being killed.
247 static final int SERVICE_RESET_RUN_DURATION = 60*1000;
248
249 // Multiplying factor to increase restart duration time by, for each time
250 // a service is killed before it has run for SERVICE_RESET_RUN_DURATION.
251 static final int SERVICE_RESTART_DURATION_FACTOR = 4;
252
253 // The minimum amount of time between restarting services that we allow.
254 // That is, when multiple services are restarting, we won't allow each
255 // to restart less than this amount of time from the last one.
256 static final int SERVICE_MIN_RESTART_TIME_BETWEEN = 10*1000;
257
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800258 // Maximum amount of time for there to be no activity on a service before
259 // we consider it non-essential and allow its process to go on the
260 // LRU background list.
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700261 static final int MAX_SERVICE_INACTIVITY = 30*60*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800262
263 // How long we wait until we timeout on key dispatching.
264 static final int KEY_DISPATCHING_TIMEOUT = 5*1000;
265
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800266 // How long we wait until we timeout on key dispatching during instrumentation.
267 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT = 60*1000;
268
Dan Egnor42471dd2010-01-07 17:25:22 -0800269 static final int MY_PID = Process.myPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800270
271 static final String[] EMPTY_STRING_ARRAY = new String[0];
272
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700273 public ActivityStack mMainStack;
Mike Lockwood3a74bd32011-08-12 13:55:22 -0700274
275 private final boolean mHeadless;
276
Joe Onorato54a4a412011-11-02 20:50:08 -0700277 // Whether we should show our dialogs (ANR, crash, etc) or just perform their
278 // default actuion automatically. Important for devices without direct input
279 // devices.
280 private boolean mShowDialogs = true;
281
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800282 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700283 * Description of a request to start a new activity, which has been held
284 * due to app switches being disabled.
285 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700286 static class PendingActivityLaunch {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700287 ActivityRecord r;
288 ActivityRecord sourceRecord;
Dianne Hackborna4972e92012-03-14 10:38:05 -0700289 int startFlags;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700290 }
291
292 final ArrayList<PendingActivityLaunch> mPendingActivityLaunches
293 = new ArrayList<PendingActivityLaunch>();
294
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800295
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800296 BroadcastQueue mFgBroadcastQueue;
297 BroadcastQueue mBgBroadcastQueue;
Christopher Tatef46723b2012-01-26 14:19:24 -0800298 // Convenient for easy iteration over the queues. Foreground is first
299 // so that dispatch of foreground broadcasts gets precedence.
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800300 final BroadcastQueue[] mBroadcastQueues = new BroadcastQueue[2];
Christopher Tatef46723b2012-01-26 14:19:24 -0800301
302 BroadcastQueue broadcastQueueForIntent(Intent intent) {
303 final boolean isFg = (intent.getFlags() & Intent.FLAG_RECEIVER_FOREGROUND) != 0;
304 if (DEBUG_BACKGROUND_BROADCAST) {
305 Slog.i(TAG, "Broadcast intent " + intent + " on "
306 + (isFg ? "foreground" : "background")
307 + " queue");
308 }
309 return (isFg) ? mFgBroadcastQueue : mBgBroadcastQueue;
310 }
311
312 BroadcastRecord broadcastRecordForReceiverLocked(IBinder receiver) {
313 for (BroadcastQueue queue : mBroadcastQueues) {
314 BroadcastRecord r = queue.getMatchingOrderedReceiver(receiver);
315 if (r != null) {
316 return r;
317 }
318 }
319 return null;
320 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800321
322 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800323 * Activity we have told the window manager to have key focus.
324 */
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700325 ActivityRecord mFocusedActivity = null;
Dianne Hackbornbfe319e2009-09-21 00:34:05 -0700326 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800327 * List of intents that were used to start the most recent tasks.
328 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700329 final ArrayList<TaskRecord> mRecentTasks = new ArrayList<TaskRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800330
331 /**
Dianne Hackborn7d608422011-08-07 16:24:18 -0700332 * Process management.
333 */
334 final ProcessList mProcessList = new ProcessList();
335
336 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800337 * All of the applications we currently have running organized by name.
338 * The keys are strings of the application package name (as
339 * returned by the package manager), and the keys are ApplicationRecord
340 * objects.
341 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700342 final ProcessMap<ProcessRecord> mProcessNames = new ProcessMap<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800343
344 /**
Dianne Hackborna0c283e2012-02-09 10:47:01 -0800345 * The currently running isolated processes.
346 */
347 final SparseArray<ProcessRecord> mIsolatedProcesses = new SparseArray<ProcessRecord>();
348
349 /**
350 * Counter for assigning isolated process uids, to avoid frequently reusing the
351 * same ones.
352 */
353 int mNextIsolatedProcessUid = 0;
354
355 /**
Dianne Hackborn860755f2010-06-03 18:47:52 -0700356 * The currently running heavy-weight process, if any.
357 */
358 ProcessRecord mHeavyWeightProcess = null;
359
360 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800361 * The last time that various processes have crashed.
362 */
363 final ProcessMap<Long> mProcessCrashTimes = new ProcessMap<Long>();
364
365 /**
366 * Set of applications that we consider to be bad, and will reject
367 * incoming broadcasts from (which the user has no control over).
368 * Processes are added to this set when they have crashed twice within
369 * a minimum amount of time; they are removed from it when they are
370 * later restarted (hopefully due to some user action). The value is the
371 * time it was added to the list.
372 */
373 final ProcessMap<Long> mBadProcesses = new ProcessMap<Long>();
374
375 /**
376 * All of the processes we currently have running organized by pid.
377 * The keys are the pid running the application.
378 *
379 * <p>NOTE: This object is protected by its own lock, NOT the global
380 * activity manager lock!
381 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700382 final SparseArray<ProcessRecord> mPidsSelfLocked = new SparseArray<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800383
384 /**
385 * All of the processes that have been forced to be foreground. The key
386 * is the pid of the caller who requested it (we hold a death
387 * link on it).
388 */
389 abstract class ForegroundToken implements IBinder.DeathRecipient {
390 int pid;
391 IBinder token;
392 }
393 final SparseArray<ForegroundToken> mForegroundProcesses
394 = new SparseArray<ForegroundToken>();
395
396 /**
397 * List of records for processes that someone had tried to start before the
398 * system was ready. We don't start them at that point, but ensure they
399 * are started by the time booting is complete.
400 */
401 final ArrayList<ProcessRecord> mProcessesOnHold
402 = new ArrayList<ProcessRecord>();
403
404 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800405 * List of persistent applications that are in the process
406 * of being started.
407 */
408 final ArrayList<ProcessRecord> mPersistentStartingProcesses
409 = new ArrayList<ProcessRecord>();
410
411 /**
412 * Processes that are being forcibly torn down.
413 */
414 final ArrayList<ProcessRecord> mRemovedProcesses
415 = new ArrayList<ProcessRecord>();
416
417 /**
418 * List of running applications, sorted by recent usage.
419 * The first entry in the list is the least recently used.
420 * It contains ApplicationRecord objects. This list does NOT include
421 * any persistent application records (since we never want to exit them).
422 */
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800423 final ArrayList<ProcessRecord> mLruProcesses
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800424 = new ArrayList<ProcessRecord>();
425
426 /**
427 * List of processes that should gc as soon as things are idle.
428 */
429 final ArrayList<ProcessRecord> mProcessesToGc
430 = new ArrayList<ProcessRecord>();
431
432 /**
The Android Open Source Project4df24232009-03-05 14:34:35 -0800433 * This is the process holding what we currently consider to be
434 * the "home" activity.
435 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700436 ProcessRecord mHomeProcess;
The Android Open Source Project4df24232009-03-05 14:34:35 -0800437
438 /**
Dianne Hackbornf35fe232011-11-01 19:25:20 -0700439 * This is the process holding the activity the user last visited that
440 * is in a different process from the one they are currently in.
441 */
442 ProcessRecord mPreviousProcess;
Dianne Hackborn50685602011-12-01 12:23:37 -0800443
444 /**
445 * The time at which the previous process was last visible.
446 */
447 long mPreviousProcessVisibleTime;
448
Dianne Hackbornf35fe232011-11-01 19:25:20 -0700449 /**
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400450 * Packages that the user has asked to have run in screen size
451 * compatibility mode instead of filling the screen.
452 */
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -0700453 final CompatModePackages mCompatModePackages;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400454
455 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800456 * Set of PendingResultRecord objects that are currently active.
457 */
458 final HashSet mPendingResultRecords = new HashSet();
459
460 /**
461 * Set of IntentSenderRecord objects that are currently active.
462 */
463 final HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>> mIntentSenderRecords
464 = new HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>>();
465
466 /**
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -0800467 * Fingerprints (hashCode()) of stack traces that we've
Brad Fitzpatrick143666f2010-06-14 12:40:21 -0700468 * already logged DropBox entries for. Guarded by itself. If
469 * something (rogue user app) forces this over
470 * MAX_DUP_SUPPRESSED_STACKS entries, the contents are cleared.
471 */
472 private final HashSet<Integer> mAlreadyLoggedViolatedStacks = new HashSet<Integer>();
473 private static final int MAX_DUP_SUPPRESSED_STACKS = 5000;
474
475 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -0700476 * Strict Mode background batched logging state.
477 *
478 * The string buffer is guarded by itself, and its lock is also
479 * used to determine if another batched write is already
480 * in-flight.
481 */
482 private final StringBuilder mStrictModeBuffer = new StringBuilder();
483
484 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800485 * Keeps track of all IIntentReceivers that have been registered for
486 * broadcasts. Hash keys are the receiver IBinder, hash value is
487 * a ReceiverList.
488 */
489 final HashMap mRegisteredReceivers = new HashMap();
490
491 /**
492 * Resolver for broadcast intents to registered receivers.
493 * Holds BroadcastFilter (subclass of IntentFilter).
494 */
495 final IntentResolver<BroadcastFilter, BroadcastFilter> mReceiverResolver
496 = new IntentResolver<BroadcastFilter, BroadcastFilter>() {
497 @Override
498 protected boolean allowFilterResult(
499 BroadcastFilter filter, List<BroadcastFilter> dest) {
500 IBinder target = filter.receiverList.receiver.asBinder();
501 for (int i=dest.size()-1; i>=0; i--) {
502 if (dest.get(i).receiverList.receiver.asBinder() == target) {
503 return false;
504 }
505 }
506 return true;
507 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700508
509 @Override
510 protected String packageForFilter(BroadcastFilter filter) {
511 return filter.packageName;
512 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800513 };
514
515 /**
516 * State of all active sticky broadcasts. Keys are the action of the
517 * sticky Intent, values are an ArrayList of all broadcasted intents with
518 * that action (which should usually be one).
519 */
520 final HashMap<String, ArrayList<Intent>> mStickyBroadcasts =
521 new HashMap<String, ArrayList<Intent>>();
522
Amith Yamasani742a6712011-05-04 14:49:28 -0700523 final ServiceMap mServiceMap = new ServiceMap();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800524
525 /**
526 * All currently bound service connections. Keys are the IBinder of
527 * the client's IServiceConnection.
528 */
Dianne Hackborn43d9ac82010-08-25 15:06:25 -0700529 final HashMap<IBinder, ArrayList<ConnectionRecord>> mServiceConnections
530 = new HashMap<IBinder, ArrayList<ConnectionRecord>>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800531
532 /**
533 * List of services that we have been asked to start,
534 * but haven't yet been able to. It is used to hold start requests
535 * while waiting for their corresponding application thread to get
536 * going.
537 */
538 final ArrayList<ServiceRecord> mPendingServices
539 = new ArrayList<ServiceRecord>();
540
541 /**
542 * List of services that are scheduled to restart following a crash.
543 */
544 final ArrayList<ServiceRecord> mRestartingServices
545 = new ArrayList<ServiceRecord>();
546
547 /**
548 * List of services that are in the process of being stopped.
549 */
550 final ArrayList<ServiceRecord> mStoppingServices
551 = new ArrayList<ServiceRecord>();
552
553 /**
Christopher Tate181fafa2009-05-14 11:12:14 -0700554 * Backup/restore process management
555 */
556 String mBackupAppName = null;
557 BackupRecord mBackupTarget = null;
558
559 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800560 * List of PendingThumbnailsRecord objects of clients who are still
561 * waiting to receive all of the thumbnails for a task.
562 */
563 final ArrayList mPendingThumbnails = new ArrayList();
564
565 /**
566 * List of HistoryRecord objects that have been finished and must
567 * still report back to a pending thumbnail receiver.
568 */
569 final ArrayList mCancelledThumbnails = new ArrayList();
570
Amith Yamasani742a6712011-05-04 14:49:28 -0700571 final ProviderMap mProviderMap = new ProviderMap();
572
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800573 /**
574 * List of content providers who have clients waiting for them. The
575 * application is currently being launched and the provider will be
576 * removed from this list once it is published.
577 */
Dianne Hackborn860755f2010-06-03 18:47:52 -0700578 final ArrayList<ContentProviderRecord> mLaunchingProviders
579 = new ArrayList<ContentProviderRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800580
581 /**
582 * Global set of specific Uri permissions that have been granted.
583 */
584 final private SparseArray<HashMap<Uri, UriPermission>> mGrantedUriPermissions
585 = new SparseArray<HashMap<Uri, UriPermission>>();
586
Svetoslav Ganov54d068e2011-03-02 12:58:40 -0800587 CoreSettingsObserver mCoreSettingsObserver;
588
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800589 /**
590 * Thread-local storage used to carry caller permissions over through
591 * indirect content-provider access.
592 * @see #ActivityManagerService.openContentUri()
593 */
594 private class Identity {
595 public int pid;
596 public int uid;
597
598 Identity(int _pid, int _uid) {
599 pid = _pid;
600 uid = _uid;
601 }
602 }
Amith Yamasani742a6712011-05-04 14:49:28 -0700603
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800604 private static ThreadLocal<Identity> sCallerIdentity = new ThreadLocal<Identity>();
605
606 /**
607 * All information we have collected about the runtime performance of
608 * any user id that can impact battery performance.
609 */
610 final BatteryStatsService mBatteryStatsService;
611
612 /**
613 * information about component usage
614 */
615 final UsageStatsService mUsageStatsService;
616
617 /**
618 * Current configuration information. HistoryRecord objects are given
619 * a reference to this object to indicate which configuration they are
620 * currently running in, so this object must be kept immutable.
621 */
622 Configuration mConfiguration = new Configuration();
623
624 /**
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800625 * Current sequencing integer of the configuration, for skipping old
626 * configurations.
627 */
628 int mConfigurationSeq = 0;
629
630 /**
Jack Palevichb90d28c2009-07-22 15:35:24 -0700631 * Hardware-reported OpenGLES version.
632 */
633 final int GL_ES_VERSION;
634
635 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800636 * List of initialization arguments to pass to all processes when binding applications to them.
637 * For example, references to the commonly used services.
638 */
639 HashMap<String, IBinder> mAppBindArgs;
640
641 /**
Dianne Hackbornf210d6b2009-04-13 18:42:49 -0700642 * Temporary to avoid allocations. Protected by main lock.
643 */
644 final StringBuilder mStringBuilder = new StringBuilder(256);
645
646 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800647 * Used to control how we initialize the service.
648 */
649 boolean mStartRunning = false;
650 ComponentName mTopComponent;
651 String mTopAction;
652 String mTopData;
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700653 boolean mProcessesReady = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800654 boolean mSystemReady = false;
655 boolean mBooting = false;
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700656 boolean mWaitingUpdate = false;
657 boolean mDidUpdate = false;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700658 boolean mOnBattery = false;
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700659 boolean mLaunchWarningShown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800660
661 Context mContext;
662
663 int mFactoryTest;
664
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -0700665 boolean mCheckedForSetup;
666
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800667 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700668 * The time at which we will allow normal application switches again,
669 * after a call to {@link #stopAppSwitches()}.
670 */
671 long mAppSwitchesAllowedTime;
672
673 /**
674 * This is set to true after the first switch after mAppSwitchesAllowedTime
675 * is set; any switches after that will clear the time.
676 */
677 boolean mDidAppSwitch;
678
679 /**
Dianne Hackborn287952c2010-09-22 22:34:31 -0700680 * Last time (in realtime) at which we checked for power usage.
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700681 */
Dianne Hackborn287952c2010-09-22 22:34:31 -0700682 long mLastPowerCheckRealtime;
683
684 /**
685 * Last time (in uptime) at which we checked for power usage.
686 */
687 long mLastPowerCheckUptime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700688
689 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800690 * Set while we are wanting to sleep, to prevent any
691 * activities from being started/resumed.
692 */
693 boolean mSleeping = false;
694
695 /**
Dianne Hackborn55280a92009-05-07 15:53:46 -0700696 * Set if we are shutting down the system, similar to sleeping.
697 */
698 boolean mShuttingDown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800699
700 /**
701 * Task identifier that activities are currently being started
702 * in. Incremented each time a new task is created.
703 * todo: Replace this with a TokenSpace class that generates non-repeating
704 * integers that won't wrap.
705 */
706 int mCurTask = 1;
707
708 /**
709 * Current sequence id for oom_adj computation traversal.
710 */
711 int mAdjSeq = 0;
712
713 /**
Dianne Hackborn906497c2010-05-10 15:57:38 -0700714 * Current sequence id for process LRU updating.
715 */
716 int mLruSeq = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800717
718 /**
Dianne Hackborne02c88a2011-10-28 13:58:15 -0700719 * Keep track of the number of service processes we last found, to
720 * determine on the next iteration which should be B services.
721 */
722 int mNumServiceProcs = 0;
723 int mNewNumServiceProcs = 0;
724
725 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800726 * System monitoring: number of processes that died since the last
727 * N procs were started.
728 */
729 int[] mProcDeaths = new int[20];
730
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700731 /**
732 * This is set if we had to do a delayed dexopt of an app before launching
733 * it, to increasing the ANR timeouts in that case.
734 */
735 boolean mDidDexOpt;
736
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800737 String mDebugApp = null;
738 boolean mWaitForDebugger = false;
739 boolean mDebugTransient = false;
740 String mOrigDebugApp = null;
741 boolean mOrigWaitForDebugger = false;
742 boolean mAlwaysFinishActivities = false;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700743 IActivityController mController = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700744 String mProfileApp = null;
745 ProcessRecord mProfileProc = null;
746 String mProfileFile;
747 ParcelFileDescriptor mProfileFd;
748 int mProfileType = 0;
749 boolean mAutoStopProfiler = false;
Siva Velusamy92a8b222012-03-09 16:24:04 -0800750 String mOpenGlTraceApp = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800751
Jeff Sharkeya4620792011-05-20 15:29:23 -0700752 final RemoteCallbackList<IProcessObserver> mProcessObservers
753 = new RemoteCallbackList<IProcessObserver>();
754
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800755 /**
756 * Callback of last caller to {@link #requestPss}.
757 */
758 Runnable mRequestPssCallback;
759
760 /**
761 * Remaining processes for which we are waiting results from the last
762 * call to {@link #requestPss}.
763 */
764 final ArrayList<ProcessRecord> mRequestPssList
765 = new ArrayList<ProcessRecord>();
766
767 /**
768 * Runtime statistics collection thread. This object's lock is used to
769 * protect all related state.
770 */
771 final Thread mProcessStatsThread;
772
773 /**
774 * Used to collect process stats when showing not responding dialog.
775 * Protected by mProcessStatsThread.
776 */
777 final ProcessStats mProcessStats = new ProcessStats(
778 MONITOR_THREAD_CPU_USAGE);
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700779 final AtomicLong mLastCpuTime = new AtomicLong(0);
780 final AtomicBoolean mProcessStatsMutexFree = new AtomicBoolean(true);
781
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800782 long mLastWriteTime = 0;
783
784 /**
785 * Set to true after the system has finished booting.
786 */
787 boolean mBooted = false;
788
Dianne Hackborn7d608422011-08-07 16:24:18 -0700789 int mProcessLimit = ProcessList.MAX_HIDDEN_APPS;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700790 int mProcessLimitOverride = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800791
792 WindowManagerService mWindowManager;
793
794 static ActivityManagerService mSelf;
795 static ActivityThread mSystemThread;
796
797 private final class AppDeathRecipient implements IBinder.DeathRecipient {
798 final ProcessRecord mApp;
799 final int mPid;
800 final IApplicationThread mAppThread;
801
802 AppDeathRecipient(ProcessRecord app, int pid,
803 IApplicationThread thread) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800804 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800805 TAG, "New death recipient " + this
806 + " for thread " + thread.asBinder());
807 mApp = app;
808 mPid = pid;
809 mAppThread = thread;
810 }
811
812 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800813 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800814 TAG, "Death received in " + this
815 + " for thread " + mAppThread.asBinder());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800816 synchronized(ActivityManagerService.this) {
817 appDiedLocked(mApp, mPid, mAppThread);
818 }
819 }
820 }
821
822 static final int SHOW_ERROR_MSG = 1;
823 static final int SHOW_NOT_RESPONDING_MSG = 2;
824 static final int SHOW_FACTORY_ERROR_MSG = 3;
825 static final int UPDATE_CONFIGURATION_MSG = 4;
826 static final int GC_BACKGROUND_PROCESSES_MSG = 5;
827 static final int WAIT_FOR_DEBUGGER_MSG = 6;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800828 static final int SERVICE_TIMEOUT_MSG = 12;
829 static final int UPDATE_TIME_ZONE = 13;
830 static final int SHOW_UID_ERROR_MSG = 14;
831 static final int IM_FEELING_LUCKY_MSG = 15;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800832 static final int PROC_START_TIMEOUT_MSG = 20;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700833 static final int DO_PENDING_ACTIVITY_LAUNCHES_MSG = 21;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -0700834 static final int KILL_APPLICATION_MSG = 22;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800835 static final int FINALIZE_PENDING_INTENT_MSG = 23;
Dianne Hackborn860755f2010-06-03 18:47:52 -0700836 static final int POST_HEAVY_NOTIFICATION_MSG = 24;
837 static final int CANCEL_HEAVY_NOTIFICATION_MSG = 25;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700838 static final int SHOW_STRICT_MODE_VIOLATION_MSG = 26;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700839 static final int CHECK_EXCESSIVE_WAKE_LOCKS_MSG = 27;
Robert Greenwalt03595d02010-11-02 14:08:23 -0700840 static final int CLEAR_DNS_CACHE = 28;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700841 static final int UPDATE_HTTP_PROXY = 29;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700842 static final int SHOW_COMPAT_MODE_DIALOG_MSG = 30;
Dianne Hackborn36f80f32011-05-31 18:26:45 -0700843 static final int DISPATCH_FOREGROUND_ACTIVITIES_CHANGED = 31;
844 static final int DISPATCH_PROCESS_DIED = 32;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700845 static final int REPORT_MEM_USAGE = 33;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800846
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800847 static final int FIRST_ACTIVITY_STACK_MSG = 100;
848 static final int FIRST_BROADCAST_QUEUE_MSG = 200;
849 static final int FIRST_COMPAT_MODE_MSG = 300;
850
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800851 AlertDialog mUidAlert;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700852 CompatModeDialog mCompatModeDialog;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700853 long mLastMemUsageReportTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800854
855 final Handler mHandler = new Handler() {
856 //public Handler() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800857 // if (localLOGV) Slog.v(TAG, "Handler started!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800858 //}
859
860 public void handleMessage(Message msg) {
861 switch (msg.what) {
862 case SHOW_ERROR_MSG: {
863 HashMap data = (HashMap) msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800864 synchronized (ActivityManagerService.this) {
865 ProcessRecord proc = (ProcessRecord)data.get("app");
866 if (proc != null && proc.crashDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800867 Slog.e(TAG, "App already has crash dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800868 return;
869 }
870 AppErrorResult res = (AppErrorResult) data.get("result");
Joe Onorato54a4a412011-11-02 20:50:08 -0700871 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Dan Egnorb7f03672009-12-09 16:22:32 -0800872 Dialog d = new AppErrorDialog(mContext, res, proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800873 d.show();
874 proc.crashDialog = d;
875 } else {
876 // The device is asleep, so just pretend that the user
877 // saw a crash dialog and hit "force quit".
878 res.set(0);
879 }
880 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700881
882 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800883 } break;
884 case SHOW_NOT_RESPONDING_MSG: {
885 synchronized (ActivityManagerService.this) {
886 HashMap data = (HashMap) msg.obj;
887 ProcessRecord proc = (ProcessRecord)data.get("app");
888 if (proc != null && proc.anrDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800889 Slog.e(TAG, "App already has anr dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800890 return;
891 }
The Android Open Source Project4df24232009-03-05 14:34:35 -0800892
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700893 Intent intent = new Intent("android.intent.action.ANR");
894 if (!mProcessesReady) {
Christopher Tatef46723b2012-01-26 14:19:24 -0800895 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
896 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700897 }
898 broadcastIntentLocked(null, null, intent,
The Android Open Source Project4df24232009-03-05 14:34:35 -0800899 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -0700900 false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
The Android Open Source Project4df24232009-03-05 14:34:35 -0800901
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800902 Dialog d = new AppNotRespondingDialog(ActivityManagerService.this,
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700903 mContext, proc, (ActivityRecord)data.get("activity"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800904 d.show();
905 proc.anrDialog = d;
906 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700907
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700908 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800909 } break;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700910 case SHOW_STRICT_MODE_VIOLATION_MSG: {
911 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj;
912 synchronized (ActivityManagerService.this) {
913 ProcessRecord proc = (ProcessRecord) data.get("app");
914 if (proc == null) {
915 Slog.e(TAG, "App not found when showing strict mode dialog.");
916 break;
917 }
918 if (proc.crashDialog != null) {
919 Slog.e(TAG, "App already has strict mode dialog: " + proc);
920 return;
921 }
922 AppErrorResult res = (AppErrorResult) data.get("result");
Joe Onorato54a4a412011-11-02 20:50:08 -0700923 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700924 Dialog d = new StrictModeViolationDialog(mContext, res, proc);
925 d.show();
926 proc.crashDialog = d;
927 } else {
928 // The device is asleep, so just pretend that the user
929 // saw a crash dialog and hit "force quit".
930 res.set(0);
931 }
932 }
933 ensureBootCompleted();
934 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800935 case SHOW_FACTORY_ERROR_MSG: {
936 Dialog d = new FactoryErrorDialog(
937 mContext, msg.getData().getCharSequence("msg"));
938 d.show();
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700939 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800940 } break;
941 case UPDATE_CONFIGURATION_MSG: {
942 final ContentResolver resolver = mContext.getContentResolver();
943 Settings.System.putConfiguration(resolver, (Configuration)msg.obj);
944 } break;
945 case GC_BACKGROUND_PROCESSES_MSG: {
946 synchronized (ActivityManagerService.this) {
947 performAppGcsIfAppropriateLocked();
948 }
949 } break;
950 case WAIT_FOR_DEBUGGER_MSG: {
951 synchronized (ActivityManagerService.this) {
952 ProcessRecord app = (ProcessRecord)msg.obj;
953 if (msg.arg1 != 0) {
954 if (!app.waitedForDebugger) {
955 Dialog d = new AppWaitingForDebuggerDialog(
956 ActivityManagerService.this,
957 mContext, app);
958 app.waitDialog = d;
959 app.waitedForDebugger = true;
960 d.show();
961 }
962 } else {
963 if (app.waitDialog != null) {
964 app.waitDialog.dismiss();
965 app.waitDialog = null;
966 }
967 }
968 }
969 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800970 case SERVICE_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700971 if (mDidDexOpt) {
972 mDidDexOpt = false;
973 Message nmsg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
974 nmsg.obj = msg.obj;
975 mHandler.sendMessageDelayed(nmsg, SERVICE_TIMEOUT);
976 return;
977 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800978 serviceTimeout((ProcessRecord)msg.obj);
979 } break;
980 case UPDATE_TIME_ZONE: {
981 synchronized (ActivityManagerService.this) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800982 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
983 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800984 if (r.thread != null) {
985 try {
986 r.thread.updateTimeZone();
987 } catch (RemoteException ex) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800988 Slog.w(TAG, "Failed to update time zone for: " + r.info.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800989 }
990 }
991 }
992 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700993 } break;
Robert Greenwalt03595d02010-11-02 14:08:23 -0700994 case CLEAR_DNS_CACHE: {
995 synchronized (ActivityManagerService.this) {
996 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
997 ProcessRecord r = mLruProcesses.get(i);
998 if (r.thread != null) {
999 try {
1000 r.thread.clearDnsCache();
1001 } catch (RemoteException ex) {
1002 Slog.w(TAG, "Failed to clear dns cache for: " + r.info.processName);
1003 }
1004 }
1005 }
1006 }
1007 } break;
Robert Greenwalt434203a2010-10-11 16:00:27 -07001008 case UPDATE_HTTP_PROXY: {
1009 ProxyProperties proxy = (ProxyProperties)msg.obj;
1010 String host = "";
1011 String port = "";
1012 String exclList = "";
1013 if (proxy != null) {
1014 host = proxy.getHost();
1015 port = Integer.toString(proxy.getPort());
1016 exclList = proxy.getExclusionList();
1017 }
1018 synchronized (ActivityManagerService.this) {
1019 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1020 ProcessRecord r = mLruProcesses.get(i);
1021 if (r.thread != null) {
1022 try {
1023 r.thread.setHttpProxy(host, port, exclList);
1024 } catch (RemoteException ex) {
1025 Slog.w(TAG, "Failed to update http proxy for: " +
1026 r.info.processName);
1027 }
1028 }
1029 }
1030 }
1031 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001032 case SHOW_UID_ERROR_MSG: {
Joe Onorato54a4a412011-11-02 20:50:08 -07001033 String title = "System UIDs Inconsistent";
1034 String text = "UIDs on the system are inconsistent, you need to wipe your"
1035 + " data partition or your device will be unstable.";
1036 Log.e(TAG, title + ": " + text);
1037 if (mShowDialogs) {
1038 // XXX This is a temporary dialog, no need to localize.
1039 AlertDialog d = new BaseErrorDialog(mContext);
1040 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
1041 d.setCancelable(false);
1042 d.setTitle(title);
1043 d.setMessage(text);
1044 d.setButton(DialogInterface.BUTTON_POSITIVE, "I'm Feeling Lucky",
1045 mHandler.obtainMessage(IM_FEELING_LUCKY_MSG));
1046 mUidAlert = d;
1047 d.show();
1048 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001049 } break;
1050 case IM_FEELING_LUCKY_MSG: {
1051 if (mUidAlert != null) {
1052 mUidAlert.dismiss();
1053 mUidAlert = null;
1054 }
1055 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001056 case PROC_START_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001057 if (mDidDexOpt) {
1058 mDidDexOpt = false;
1059 Message nmsg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
1060 nmsg.obj = msg.obj;
1061 mHandler.sendMessageDelayed(nmsg, PROC_START_TIMEOUT);
1062 return;
1063 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001064 ProcessRecord app = (ProcessRecord)msg.obj;
1065 synchronized (ActivityManagerService.this) {
1066 processStartTimedOutLocked(app);
1067 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001068 } break;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07001069 case DO_PENDING_ACTIVITY_LAUNCHES_MSG: {
1070 synchronized (ActivityManagerService.this) {
1071 doPendingActivityLaunchesLocked(true);
1072 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001073 } break;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001074 case KILL_APPLICATION_MSG: {
1075 synchronized (ActivityManagerService.this) {
1076 int uid = msg.arg1;
1077 boolean restart = (msg.arg2 == 1);
1078 String pkg = (String) msg.obj;
Christopher Tate3dacd842011-08-19 14:56:15 -07001079 forceStopPackageLocked(pkg, uid, restart, false, true, false);
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001080 }
1081 } break;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001082 case FINALIZE_PENDING_INTENT_MSG: {
1083 ((PendingIntentRecord)msg.obj).completeFinalize();
1084 } break;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001085 case POST_HEAVY_NOTIFICATION_MSG: {
1086 INotificationManager inm = NotificationManager.getService();
1087 if (inm == null) {
1088 return;
1089 }
1090
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001091 ActivityRecord root = (ActivityRecord)msg.obj;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001092 ProcessRecord process = root.app;
1093 if (process == null) {
1094 return;
1095 }
1096
1097 try {
1098 Context context = mContext.createPackageContext(process.info.packageName, 0);
1099 String text = mContext.getString(R.string.heavy_weight_notification,
1100 context.getApplicationInfo().loadLabel(context.getPackageManager()));
1101 Notification notification = new Notification();
1102 notification.icon = com.android.internal.R.drawable.stat_sys_adb; //context.getApplicationInfo().icon;
1103 notification.when = 0;
1104 notification.flags = Notification.FLAG_ONGOING_EVENT;
1105 notification.tickerText = text;
1106 notification.defaults = 0; // please be quiet
1107 notification.sound = null;
1108 notification.vibrate = null;
1109 notification.setLatestEventInfo(context, text,
1110 mContext.getText(R.string.heavy_weight_notification_detail),
1111 PendingIntent.getActivity(mContext, 0, root.intent,
1112 PendingIntent.FLAG_CANCEL_CURRENT));
1113
1114 try {
1115 int[] outId = new int[1];
1116 inm.enqueueNotification("android", R.string.heavy_weight_notification,
1117 notification, outId);
1118 } catch (RuntimeException e) {
1119 Slog.w(ActivityManagerService.TAG,
1120 "Error showing notification for heavy-weight app", e);
1121 } catch (RemoteException e) {
1122 }
1123 } catch (NameNotFoundException e) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07001124 Slog.w(TAG, "Unable to create context for heavy notification", e);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001125 }
1126 } break;
1127 case CANCEL_HEAVY_NOTIFICATION_MSG: {
1128 INotificationManager inm = NotificationManager.getService();
1129 if (inm == null) {
1130 return;
1131 }
1132 try {
1133 inm.cancelNotification("android",
1134 R.string.heavy_weight_notification);
1135 } catch (RuntimeException e) {
1136 Slog.w(ActivityManagerService.TAG,
1137 "Error canceling notification for service", e);
1138 } catch (RemoteException e) {
1139 }
1140 } break;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001141 case CHECK_EXCESSIVE_WAKE_LOCKS_MSG: {
1142 synchronized (ActivityManagerService.this) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001143 checkExcessivePowerUsageLocked(true);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07001144 removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001145 Message nmsg = obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
1146 sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001147 }
1148 } break;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001149 case SHOW_COMPAT_MODE_DIALOG_MSG: {
1150 synchronized (ActivityManagerService.this) {
1151 ActivityRecord ar = (ActivityRecord)msg.obj;
1152 if (mCompatModeDialog != null) {
1153 if (mCompatModeDialog.mAppInfo.packageName.equals(
1154 ar.info.applicationInfo.packageName)) {
1155 return;
1156 }
1157 mCompatModeDialog.dismiss();
1158 mCompatModeDialog = null;
1159 }
Dianne Hackborn29478262011-06-07 15:44:22 -07001160 if (ar != null && false) {
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001161 if (mCompatModePackages.getPackageAskCompatModeLocked(
1162 ar.packageName)) {
1163 int mode = mCompatModePackages.computeCompatModeLocked(
1164 ar.info.applicationInfo);
1165 if (mode == ActivityManager.COMPAT_MODE_DISABLED
1166 || mode == ActivityManager.COMPAT_MODE_ENABLED) {
1167 mCompatModeDialog = new CompatModeDialog(
1168 ActivityManagerService.this, mContext,
1169 ar.info.applicationInfo);
1170 mCompatModeDialog.show();
1171 }
1172 }
1173 }
1174 }
Dianne Hackborn36f80f32011-05-31 18:26:45 -07001175 break;
1176 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001177 case DISPATCH_FOREGROUND_ACTIVITIES_CHANGED: {
Jeff Sharkey287bd832011-05-28 19:36:26 -07001178 final int pid = msg.arg1;
1179 final int uid = msg.arg2;
1180 final boolean foregroundActivities = (Boolean) msg.obj;
1181 dispatchForegroundActivitiesChanged(pid, uid, foregroundActivities);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001182 break;
1183 }
1184 case DISPATCH_PROCESS_DIED: {
Jeff Sharkey287bd832011-05-28 19:36:26 -07001185 final int pid = msg.arg1;
1186 final int uid = msg.arg2;
1187 dispatchProcessDied(pid, uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001188 break;
1189 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001190 case REPORT_MEM_USAGE: {
1191 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
1192 if (!isDebuggable) {
1193 return;
1194 }
1195 synchronized (ActivityManagerService.this) {
1196 long now = SystemClock.uptimeMillis();
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001197 if (now < (mLastMemUsageReportTime+5*60*1000)) {
1198 // Don't report more than every 5 minutes to somewhat
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001199 // avoid spamming.
1200 return;
1201 }
1202 mLastMemUsageReportTime = now;
1203 }
1204 Thread thread = new Thread() {
1205 @Override public void run() {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001206 StringBuilder dropBuilder = new StringBuilder(1024);
1207 StringBuilder logBuilder = new StringBuilder(1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -08001208 StringWriter oomSw = new StringWriter();
1209 PrintWriter oomPw = new PrintWriter(oomSw);
1210 StringWriter catSw = new StringWriter();
1211 PrintWriter catPw = new PrintWriter(catSw);
1212 String[] emptyArgs = new String[] { };
1213 StringBuilder tag = new StringBuilder(128);
1214 StringBuilder stack = new StringBuilder(128);
1215 tag.append("Low on memory -- ");
1216 dumpApplicationMemoryUsage(null, oomPw, " ", emptyArgs, true, catPw,
1217 tag, stack);
1218 dropBuilder.append(stack);
1219 dropBuilder.append('\n');
1220 dropBuilder.append('\n');
1221 String oomString = oomSw.toString();
1222 dropBuilder.append(oomString);
1223 dropBuilder.append('\n');
1224 logBuilder.append(oomString);
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001225 try {
1226 java.lang.Process proc = Runtime.getRuntime().exec(new String[] {
1227 "procrank", });
1228 final InputStreamReader converter = new InputStreamReader(
1229 proc.getInputStream());
1230 BufferedReader in = new BufferedReader(converter);
1231 String line;
1232 while (true) {
1233 line = in.readLine();
1234 if (line == null) {
1235 break;
1236 }
1237 if (line.length() > 0) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001238 logBuilder.append(line);
1239 logBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001240 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001241 dropBuilder.append(line);
1242 dropBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001243 }
1244 converter.close();
1245 } catch (IOException e) {
1246 }
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001247 synchronized (ActivityManagerService.this) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08001248 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001249 dumpProcessesLocked(null, catPw, emptyArgs, 0, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001250 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001251 dumpServicesLocked(null, catPw, emptyArgs, 0, false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001252 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001253 dumpActivitiesLocked(null, catPw, emptyArgs, 0, false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001254 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001255 dropBuilder.append(catSw.toString());
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001256 addErrorToDropBox("lowmem", null, "system_server", null,
1257 null, tag.toString(), dropBuilder.toString(), null, null);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001258 Slog.i(TAG, logBuilder.toString());
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001259 synchronized (ActivityManagerService.this) {
1260 long now = SystemClock.uptimeMillis();
1261 if (mLastMemUsageReportTime < now) {
1262 mLastMemUsageReportTime = now;
1263 }
1264 }
1265 }
1266 };
1267 thread.start();
1268 break;
1269 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001270 }
1271 }
1272 };
1273
1274 public static void setSystemProcess() {
1275 try {
1276 ActivityManagerService m = mSelf;
1277
Dianne Hackborna573f6a2012-02-09 16:12:18 -08001278 ServiceManager.addService("activity", m, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001279 ServiceManager.addService("meminfo", new MemBinder(m));
Chet Haase9c1e23b2011-03-24 10:51:31 -07001280 ServiceManager.addService("gfxinfo", new GraphicsBinder(m));
Jeff Brown6754ba22011-12-14 20:20:01 -08001281 ServiceManager.addService("dbinfo", new DbBinder(m));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001282 if (MONITOR_CPU_USAGE) {
1283 ServiceManager.addService("cpuinfo", new CpuBinder(m));
1284 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001285 ServiceManager.addService("permission", new PermissionController(m));
1286
1287 ApplicationInfo info =
1288 mSelf.mContext.getPackageManager().getApplicationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -07001289 "android", STOCK_PM_FLAGS);
Mike Cleron432b7132009-09-24 15:28:29 -07001290 mSystemThread.installSystemApplicationInfo(info);
1291
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001292 synchronized (mSelf) {
1293 ProcessRecord app = mSelf.newProcessRecordLocked(
1294 mSystemThread.getApplicationThread(), info,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001295 info.processName, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001296 app.persistent = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08001297 app.pid = MY_PID;
Dianne Hackborn7d608422011-08-07 16:24:18 -07001298 app.maxAdj = ProcessList.SYSTEM_ADJ;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001299 mSelf.mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001300 synchronized (mSelf.mPidsSelfLocked) {
1301 mSelf.mPidsSelfLocked.put(app.pid, app);
1302 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001303 mSelf.updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001304 }
1305 } catch (PackageManager.NameNotFoundException e) {
1306 throw new RuntimeException(
1307 "Unable to find android system package", e);
1308 }
1309 }
1310
1311 public void setWindowManager(WindowManagerService wm) {
1312 mWindowManager = wm;
1313 }
1314
1315 public static final Context main(int factoryTest) {
1316 AThread thr = new AThread();
1317 thr.start();
1318
1319 synchronized (thr) {
1320 while (thr.mService == null) {
1321 try {
1322 thr.wait();
1323 } catch (InterruptedException e) {
1324 }
1325 }
1326 }
1327
1328 ActivityManagerService m = thr.mService;
1329 mSelf = m;
1330 ActivityThread at = ActivityThread.systemMain();
1331 mSystemThread = at;
1332 Context context = at.getSystemContext();
Dianne Hackborn247fe742011-01-08 17:25:57 -08001333 context.setTheme(android.R.style.Theme_Holo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001334 m.mContext = context;
1335 m.mFactoryTest = factoryTest;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001336 m.mMainStack = new ActivityStack(m, context, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001337
1338 m.mBatteryStatsService.publish(context);
1339 m.mUsageStatsService.publish(context);
1340
1341 synchronized (thr) {
1342 thr.mReady = true;
1343 thr.notifyAll();
1344 }
1345
1346 m.startRunning(null, null, null, null);
1347
1348 return context;
1349 }
1350
1351 public static ActivityManagerService self() {
1352 return mSelf;
1353 }
1354
1355 static class AThread extends Thread {
1356 ActivityManagerService mService;
1357 boolean mReady = false;
1358
1359 public AThread() {
1360 super("ActivityManager");
1361 }
1362
1363 public void run() {
1364 Looper.prepare();
1365
1366 android.os.Process.setThreadPriority(
1367 android.os.Process.THREAD_PRIORITY_FOREGROUND);
Christopher Tate160edb32010-06-30 17:46:30 -07001368 android.os.Process.setCanSelfBackground(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001369
1370 ActivityManagerService m = new ActivityManagerService();
1371
1372 synchronized (this) {
1373 mService = m;
1374 notifyAll();
1375 }
1376
1377 synchronized (this) {
1378 while (!mReady) {
1379 try {
1380 wait();
1381 } catch (InterruptedException e) {
1382 }
1383 }
1384 }
1385
Brad Fitzpatrickec062f62010-11-03 09:56:54 -07001386 // For debug builds, log event loop stalls to dropbox for analysis.
1387 if (StrictMode.conditionallyEnableDebugLogging()) {
1388 Slog.i(TAG, "Enabled StrictMode logging for AThread's Looper");
1389 }
1390
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001391 Looper.loop();
1392 }
1393 }
1394
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001395 static class MemBinder extends Binder {
1396 ActivityManagerService mActivityManagerService;
1397 MemBinder(ActivityManagerService activityManagerService) {
1398 mActivityManagerService = activityManagerService;
1399 }
1400
1401 @Override
1402 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001403 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1404 != PackageManager.PERMISSION_GRANTED) {
1405 pw.println("Permission Denial: can't dump meminfo from from pid="
1406 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1407 + " without permission " + android.Manifest.permission.DUMP);
1408 return;
1409 }
1410
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001411 mActivityManagerService.dumpApplicationMemoryUsage(fd, pw, " ", args,
Dianne Hackborn672342c2011-11-29 11:29:02 -08001412 false, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001413 }
1414 }
1415
Chet Haase9c1e23b2011-03-24 10:51:31 -07001416 static class GraphicsBinder extends Binder {
1417 ActivityManagerService mActivityManagerService;
1418 GraphicsBinder(ActivityManagerService activityManagerService) {
1419 mActivityManagerService = activityManagerService;
1420 }
1421
1422 @Override
1423 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001424 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1425 != PackageManager.PERMISSION_GRANTED) {
1426 pw.println("Permission Denial: can't dump gfxinfo from from pid="
1427 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1428 + " without permission " + android.Manifest.permission.DUMP);
1429 return;
1430 }
1431
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001432 mActivityManagerService.dumpGraphicsHardwareUsage(fd, pw, args);
Chet Haase9c1e23b2011-03-24 10:51:31 -07001433 }
1434 }
1435
Jeff Brown6754ba22011-12-14 20:20:01 -08001436 static class DbBinder extends Binder {
1437 ActivityManagerService mActivityManagerService;
1438 DbBinder(ActivityManagerService activityManagerService) {
1439 mActivityManagerService = activityManagerService;
1440 }
1441
1442 @Override
1443 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1444 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1445 != PackageManager.PERMISSION_GRANTED) {
1446 pw.println("Permission Denial: can't dump dbinfo from from pid="
1447 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1448 + " without permission " + android.Manifest.permission.DUMP);
1449 return;
1450 }
1451
1452 mActivityManagerService.dumpDbInfo(fd, pw, args);
1453 }
1454 }
1455
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001456 static class CpuBinder extends Binder {
1457 ActivityManagerService mActivityManagerService;
1458 CpuBinder(ActivityManagerService activityManagerService) {
1459 mActivityManagerService = activityManagerService;
1460 }
1461
1462 @Override
1463 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001464 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1465 != PackageManager.PERMISSION_GRANTED) {
1466 pw.println("Permission Denial: can't dump cpuinfo from from pid="
1467 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1468 + " without permission " + android.Manifest.permission.DUMP);
1469 return;
1470 }
1471
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001472 synchronized (mActivityManagerService.mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07001473 pw.print(mActivityManagerService.mProcessStats.printCurrentLoad());
1474 pw.print(mActivityManagerService.mProcessStats.printCurrentState(
1475 SystemClock.uptimeMillis()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001476 }
1477 }
1478 }
1479
1480 private ActivityManagerService() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001481 Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
Dianne Hackborn2c6c5e62009-10-08 17:55:49 -07001482
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001483 mFgBroadcastQueue = new BroadcastQueue(this, "foreground", BROADCAST_FG_TIMEOUT);
1484 mBgBroadcastQueue = new BroadcastQueue(this, "background", BROADCAST_BG_TIMEOUT);
1485 mBroadcastQueues[0] = mFgBroadcastQueue;
1486 mBroadcastQueues[1] = mBgBroadcastQueue;
1487
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001488 File dataDir = Environment.getDataDirectory();
1489 File systemDir = new File(dataDir, "system");
1490 systemDir.mkdirs();
1491 mBatteryStatsService = new BatteryStatsService(new File(
1492 systemDir, "batterystats.bin").toString());
1493 mBatteryStatsService.getActiveStatistics().readLocked();
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001494 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
Dianne Hackborn287952c2010-09-22 22:34:31 -07001495 mOnBattery = DEBUG_POWER ? true
1496 : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001497 mBatteryStatsService.getActiveStatistics().setCallback(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001498
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001499 mUsageStatsService = new UsageStatsService(new File(
Dianne Hackborn6447ca32009-04-07 19:50:08 -07001500 systemDir, "usagestats").toString());
Mike Lockwood3a74bd32011-08-12 13:55:22 -07001501 mHeadless = "1".equals(SystemProperties.get("ro.config.headless", "0"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001502
Jack Palevichb90d28c2009-07-22 15:35:24 -07001503 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",
1504 ConfigurationInfo.GL_ES_VERSION_UNDEFINED);
1505
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001506 mConfiguration.setToDefaults();
1507 mConfiguration.locale = Locale.getDefault();
Dianne Hackborn813075a62011-11-14 17:45:19 -08001508 mConfigurationSeq = mConfiguration.seq = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001509 mProcessStats.init();
1510
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07001511 mCompatModePackages = new CompatModePackages(this, systemDir);
1512
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001513 // Add ourself to the Watchdog monitors.
1514 Watchdog.getInstance().addMonitor(this);
1515
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001516 mProcessStatsThread = new Thread("ProcessStats") {
1517 public void run() {
1518 while (true) {
1519 try {
1520 try {
1521 synchronized(this) {
1522 final long now = SystemClock.uptimeMillis();
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001523 long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001524 long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001525 //Slog.i(TAG, "Cpu delay=" + nextCpuDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001526 // + ", write delay=" + nextWriteDelay);
1527 if (nextWriteDelay < nextCpuDelay) {
1528 nextCpuDelay = nextWriteDelay;
1529 }
1530 if (nextCpuDelay > 0) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001531 mProcessStatsMutexFree.set(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001532 this.wait(nextCpuDelay);
1533 }
1534 }
1535 } catch (InterruptedException e) {
1536 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001537 updateCpuStatsNow();
1538 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001539 Slog.e(TAG, "Unexpected exception collecting process stats", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001540 }
1541 }
1542 }
1543 };
1544 mProcessStatsThread.start();
1545 }
1546
1547 @Override
1548 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1549 throws RemoteException {
1550 try {
1551 return super.onTransact(code, data, reply, flags);
1552 } catch (RuntimeException e) {
1553 // The activity manager only throws security exceptions, so let's
1554 // log all others.
1555 if (!(e instanceof SecurityException)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001556 Slog.e(TAG, "Activity Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001557 }
1558 throw e;
1559 }
1560 }
1561
1562 void updateCpuStats() {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001563 final long now = SystemClock.uptimeMillis();
1564 if (mLastCpuTime.get() >= now - MONITOR_CPU_MIN_TIME) {
1565 return;
1566 }
1567 if (mProcessStatsMutexFree.compareAndSet(true, false)) {
1568 synchronized (mProcessStatsThread) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001569 mProcessStatsThread.notify();
1570 }
1571 }
1572 }
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001573
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001574 void updateCpuStatsNow() {
1575 synchronized (mProcessStatsThread) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001576 mProcessStatsMutexFree.set(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001577 final long now = SystemClock.uptimeMillis();
1578 boolean haveNewCpuStats = false;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07001579
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001580 if (MONITOR_CPU_USAGE &&
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001581 mLastCpuTime.get() < (now-MONITOR_CPU_MIN_TIME)) {
1582 mLastCpuTime.set(now);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001583 haveNewCpuStats = true;
1584 mProcessStats.update();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001585 //Slog.i(TAG, mProcessStats.printCurrentState());
1586 //Slog.i(TAG, "Total CPU usage: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001587 // + mProcessStats.getTotalCpuPercent() + "%");
1588
Joe Onorato8a9b2202010-02-26 18:56:32 -08001589 // Slog the cpu usage if the property is set.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001590 if ("true".equals(SystemProperties.get("events.cpu"))) {
1591 int user = mProcessStats.getLastUserTime();
1592 int system = mProcessStats.getLastSystemTime();
1593 int iowait = mProcessStats.getLastIoWaitTime();
1594 int irq = mProcessStats.getLastIrqTime();
1595 int softIrq = mProcessStats.getLastSoftIrqTime();
1596 int idle = mProcessStats.getLastIdleTime();
1597
1598 int total = user + system + iowait + irq + softIrq + idle;
1599 if (total == 0) total = 1;
1600
Doug Zongker2bec3d42009-12-04 12:52:44 -08001601 EventLog.writeEvent(EventLogTags.CPU,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001602 ((user+system+iowait+irq+softIrq) * 100) / total,
1603 (user * 100) / total,
1604 (system * 100) / total,
1605 (iowait * 100) / total,
1606 (irq * 100) / total,
1607 (softIrq * 100) / total);
1608 }
1609 }
1610
Amith Yamasanie43530a2009-08-21 13:11:37 -07001611 long[] cpuSpeedTimes = mProcessStats.getLastCpuSpeedTimes();
Amith Yamasani819f9282009-06-24 23:18:15 -07001612 final BatteryStatsImpl bstats = mBatteryStatsService.getActiveStatistics();
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001613 synchronized(bstats) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001614 synchronized(mPidsSelfLocked) {
1615 if (haveNewCpuStats) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001616 if (mOnBattery) {
1617 int perc = bstats.startAddingCpuLocked();
1618 int totalUTime = 0;
1619 int totalSTime = 0;
Dianne Hackborn287952c2010-09-22 22:34:31 -07001620 final int N = mProcessStats.countStats();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001621 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001622 ProcessStats.Stats st = mProcessStats.getStats(i);
1623 if (!st.working) {
1624 continue;
1625 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001626 ProcessRecord pr = mPidsSelfLocked.get(st.pid);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001627 int otherUTime = (st.rel_utime*perc)/100;
1628 int otherSTime = (st.rel_stime*perc)/100;
1629 totalUTime += otherUTime;
1630 totalSTime += otherSTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001631 if (pr != null) {
1632 BatteryStatsImpl.Uid.Proc ps = pr.batteryStats;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001633 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1634 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001635 ps.addSpeedStepTimes(cpuSpeedTimes);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001636 pr.curCpuTime += (st.rel_utime+st.rel_stime) * 10;
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001637 } else {
1638 BatteryStatsImpl.Uid.Proc ps =
Amith Yamasani819f9282009-06-24 23:18:15 -07001639 bstats.getProcessStatsLocked(st.name, st.pid);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001640 if (ps != null) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001641 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1642 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001643 ps.addSpeedStepTimes(cpuSpeedTimes);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001644 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001645 }
1646 }
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001647 bstats.finishAddingCpuLocked(perc, totalUTime,
1648 totalSTime, cpuSpeedTimes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001649 }
1650 }
1651 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001652
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001653 if (mLastWriteTime < (now-BATTERY_STATS_TIME)) {
1654 mLastWriteTime = now;
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001655 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001656 }
1657 }
1658 }
1659 }
1660
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001661 @Override
1662 public void batteryNeedsCpuUpdate() {
1663 updateCpuStatsNow();
1664 }
1665
1666 @Override
1667 public void batteryPowerChanged(boolean onBattery) {
1668 // When plugging in, update the CPU stats first before changing
1669 // the plug state.
1670 updateCpuStatsNow();
1671 synchronized (this) {
1672 synchronized(mPidsSelfLocked) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001673 mOnBattery = DEBUG_POWER ? true : onBattery;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001674 }
1675 }
1676 }
1677
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001678 /**
1679 * Initialize the application bind args. These are passed to each
1680 * process when the bindApplication() IPC is sent to the process. They're
1681 * lazily setup to make sure the services are running when they're asked for.
1682 */
1683 private HashMap<String, IBinder> getCommonServicesLocked() {
1684 if (mAppBindArgs == null) {
1685 mAppBindArgs = new HashMap<String, IBinder>();
1686
1687 // Setup the application init args
1688 mAppBindArgs.put("package", ServiceManager.getService("package"));
1689 mAppBindArgs.put("window", ServiceManager.getService("window"));
1690 mAppBindArgs.put(Context.ALARM_SERVICE,
1691 ServiceManager.getService(Context.ALARM_SERVICE));
1692 }
1693 return mAppBindArgs;
1694 }
1695
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001696 final void setFocusedActivityLocked(ActivityRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001697 if (mFocusedActivity != r) {
1698 mFocusedActivity = r;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001699 if (r != null) {
1700 mWindowManager.setFocusedApp(r.appToken, true);
1701 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001702 }
1703 }
1704
Dianne Hackborn906497c2010-05-10 15:57:38 -07001705 private final void updateLruProcessInternalLocked(ProcessRecord app,
1706 boolean oomAdj, boolean updateActivityTime, int bestPos) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001707 // put it on the LRU to keep track of when it should be exited.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001708 int lrui = mLruProcesses.indexOf(app);
1709 if (lrui >= 0) mLruProcesses.remove(lrui);
1710
1711 int i = mLruProcesses.size()-1;
1712 int skipTop = 0;
1713
Dianne Hackborn906497c2010-05-10 15:57:38 -07001714 app.lruSeq = mLruSeq;
1715
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001716 // compute the new weight for this process.
1717 if (updateActivityTime) {
1718 app.lastActivityTime = SystemClock.uptimeMillis();
1719 }
1720 if (app.activities.size() > 0) {
1721 // If this process has activities, we more strongly want to keep
1722 // it around.
1723 app.lruWeight = app.lastActivityTime;
1724 } else if (app.pubProviders.size() > 0) {
1725 // If this process contains content providers, we want to keep
1726 // it a little more strongly.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001727 app.lruWeight = app.lastActivityTime - ProcessList.CONTENT_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001728 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001729 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001730 } else {
1731 // If this process doesn't have activities, we less strongly
1732 // want to keep it around, and generally want to avoid getting
1733 // in front of any very recently used activities.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001734 app.lruWeight = app.lastActivityTime - ProcessList.EMPTY_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001735 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001736 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001737 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001738
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001739 while (i >= 0) {
1740 ProcessRecord p = mLruProcesses.get(i);
1741 // If this app shouldn't be in front of the first N background
1742 // apps, then skip over that many that are currently hidden.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001743 if (skipTop > 0 && p.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001744 skipTop--;
1745 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001746 if (p.lruWeight <= app.lruWeight || i < bestPos) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001747 mLruProcesses.add(i+1, app);
1748 break;
1749 }
1750 i--;
1751 }
1752 if (i < 0) {
1753 mLruProcesses.add(0, app);
1754 }
1755
Dianne Hackborn906497c2010-05-10 15:57:38 -07001756 // If the app is currently using a content provider or service,
1757 // bump those processes as well.
1758 if (app.connections.size() > 0) {
1759 for (ConnectionRecord cr : app.connections) {
1760 if (cr.binding != null && cr.binding.service != null
1761 && cr.binding.service.app != null
1762 && cr.binding.service.app.lruSeq != mLruSeq) {
1763 updateLruProcessInternalLocked(cr.binding.service.app, oomAdj,
1764 updateActivityTime, i+1);
1765 }
1766 }
1767 }
1768 if (app.conProviders.size() > 0) {
1769 for (ContentProviderRecord cpr : app.conProviders.keySet()) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07001770 if (cpr.proc != null && cpr.proc.lruSeq != mLruSeq) {
1771 updateLruProcessInternalLocked(cpr.proc, oomAdj,
Dianne Hackborn906497c2010-05-10 15:57:38 -07001772 updateActivityTime, i+1);
1773 }
1774 }
1775 }
1776
Joe Onorato8a9b2202010-02-26 18:56:32 -08001777 //Slog.i(TAG, "Putting proc to front: " + app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001778 if (oomAdj) {
1779 updateOomAdjLocked();
1780 }
1781 }
1782
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001783 final void updateLruProcessLocked(ProcessRecord app,
Dianne Hackborn906497c2010-05-10 15:57:38 -07001784 boolean oomAdj, boolean updateActivityTime) {
1785 mLruSeq++;
1786 updateLruProcessInternalLocked(app, oomAdj, updateActivityTime, 0);
1787 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001788
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001789 final ProcessRecord getProcessRecordLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001790 String processName, int uid) {
1791 if (uid == Process.SYSTEM_UID) {
1792 // The system gets to run in any process. If there are multiple
1793 // processes with the same uid, just pick the first (this
1794 // should never happen).
1795 SparseArray<ProcessRecord> procs = mProcessNames.getMap().get(
1796 processName);
1797 return procs != null ? procs.valueAt(0) : null;
1798 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001799 // uid = applyUserId(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001800 ProcessRecord proc = mProcessNames.get(processName, uid);
1801 return proc;
1802 }
1803
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001804 void ensurePackageDexOpt(String packageName) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001805 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001806 try {
1807 if (pm.performDexOpt(packageName)) {
1808 mDidDexOpt = true;
1809 }
1810 } catch (RemoteException e) {
1811 }
1812 }
1813
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001814 boolean isNextTransitionForward() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001815 int transit = mWindowManager.getPendingAppTransition();
1816 return transit == WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
1817 || transit == WindowManagerPolicy.TRANSIT_TASK_OPEN
1818 || transit == WindowManagerPolicy.TRANSIT_TASK_TO_FRONT;
1819 }
1820
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001821 final ProcessRecord startProcessLocked(String processName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001822 ApplicationInfo info, boolean knownToBeDead, int intentFlags,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001823 String hostingType, ComponentName hostingName, boolean allowWhileBooting,
1824 boolean isolated) {
1825 ProcessRecord app;
1826 if (!isolated) {
1827 app = getProcessRecordLocked(processName, info.uid);
1828 } else {
1829 // If this is an isolated process, it can't re-use an existing process.
1830 app = null;
1831 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001832 // We don't have to do anything more if:
1833 // (1) There is an existing application record; and
1834 // (2) The caller doesn't think it is dead, OR there is no thread
1835 // object attached to it so we know it couldn't have crashed; and
1836 // (3) There is a pid assigned to it, so it is either starting or
1837 // already running.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001838 if (DEBUG_PROCESSES) Slog.v(TAG, "startProcess: name=" + processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001839 + " app=" + app + " knownToBeDead=" + knownToBeDead
1840 + " thread=" + (app != null ? app.thread : null)
1841 + " pid=" + (app != null ? app.pid : -1));
Magnus Edlund7bb25812010-02-24 15:45:06 +01001842 if (app != null && app.pid > 0) {
1843 if (!knownToBeDead || app.thread == null) {
Dianne Hackborn20cb56e2010-03-04 00:58:29 -08001844 // We already have the app running, or are waiting for it to
1845 // come up (we have a pid but not yet its thread), so keep it.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001846 if (DEBUG_PROCESSES) Slog.v(TAG, "App already running: " + app);
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001847 // If this is a new package in the process, add the package to the list
1848 app.addPackage(info.packageName);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001849 return app;
1850 } else {
1851 // An application record is attached to a previous process,
1852 // clean it up now.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001853 if (DEBUG_PROCESSES) Slog.v(TAG, "App died: " + app);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07001854 handleAppDiedLocked(app, true, true);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001855 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001856 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01001857
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001858 String hostingNameStr = hostingName != null
1859 ? hostingName.flattenToShortString() : null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001860
1861 if (!isolated) {
1862 if ((intentFlags&Intent.FLAG_FROM_BACKGROUND) != 0) {
1863 // If we are in the background, then check to see if this process
1864 // is bad. If so, we will just silently fail.
1865 if (mBadProcesses.get(info.processName, info.uid) != null) {
1866 if (DEBUG_PROCESSES) Slog.v(TAG, "Bad process: " + info.uid
1867 + "/" + info.processName);
1868 return null;
1869 }
1870 } else {
1871 // When the user is explicitly starting a process, then clear its
1872 // crash count so that we won't make it bad until they see at
1873 // least one crash dialog again, and make the process good again
1874 // if it had been bad.
1875 if (DEBUG_PROCESSES) Slog.v(TAG, "Clearing bad process: " + info.uid
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001876 + "/" + info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001877 mProcessCrashTimes.remove(info.processName, info.uid);
1878 if (mBadProcesses.get(info.processName, info.uid) != null) {
1879 EventLog.writeEvent(EventLogTags.AM_PROC_GOOD, info.uid,
1880 info.processName);
1881 mBadProcesses.remove(info.processName, info.uid);
1882 if (app != null) {
1883 app.bad = false;
1884 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001885 }
1886 }
1887 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001888
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001889 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001890 app = newProcessRecordLocked(null, info, processName, isolated);
1891 if (app == null) {
1892 Slog.w(TAG, "Failed making new process record for "
1893 + processName + "/" + info.uid + " isolated=" + isolated);
1894 return null;
1895 }
1896 mProcessNames.put(processName, app.uid, app);
1897 if (isolated) {
1898 mIsolatedProcesses.put(app.uid, app);
1899 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001900 } else {
1901 // If this is a new package in the process, add the package to the list
1902 app.addPackage(info.packageName);
1903 }
1904
1905 // If the system is not ready yet, then hold off on starting this
1906 // process until it is.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001907 if (!mProcessesReady
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001908 && !isAllowedWhileBooting(info)
1909 && !allowWhileBooting) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001910 if (!mProcessesOnHold.contains(app)) {
1911 mProcessesOnHold.add(app);
1912 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001913 if (DEBUG_PROCESSES) Slog.v(TAG, "System not ready, putting on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001914 return app;
1915 }
1916
1917 startProcessLocked(app, hostingType, hostingNameStr);
1918 return (app.pid != 0) ? app : null;
1919 }
1920
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001921 boolean isAllowedWhileBooting(ApplicationInfo ai) {
1922 return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0;
1923 }
1924
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001925 private final void startProcessLocked(ProcessRecord app,
1926 String hostingType, String hostingNameStr) {
1927 if (app.pid > 0 && app.pid != MY_PID) {
1928 synchronized (mPidsSelfLocked) {
1929 mPidsSelfLocked.remove(app.pid);
1930 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
1931 }
1932 app.pid = 0;
1933 }
1934
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001935 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
1936 "startProcessLocked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001937 mProcessesOnHold.remove(app);
1938
1939 updateCpuStats();
1940
1941 System.arraycopy(mProcDeaths, 0, mProcDeaths, 1, mProcDeaths.length-1);
1942 mProcDeaths[0] = 0;
1943
1944 try {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001945 int uid = app.uid;
Amith Yamasani742a6712011-05-04 14:49:28 -07001946
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001947 int[] gids = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001948 if (!app.isolated) {
1949 try {
1950 gids = mContext.getPackageManager().getPackageGids(
1951 app.info.packageName);
1952 } catch (PackageManager.NameNotFoundException e) {
1953 Slog.w(TAG, "Unable to retrieve gids", e);
1954 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001955 }
1956 if (mFactoryTest != SystemServer.FACTORY_TEST_OFF) {
1957 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
1958 && mTopComponent != null
1959 && app.processName.equals(mTopComponent.getPackageName())) {
1960 uid = 0;
1961 }
1962 if (mFactoryTest == SystemServer.FACTORY_TEST_HIGH_LEVEL
1963 && (app.info.flags&ApplicationInfo.FLAG_FACTORY_TEST) != 0) {
1964 uid = 0;
1965 }
1966 }
1967 int debugFlags = 0;
1968 if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
1969 debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;
Elliott Hughesfa36aee2011-06-17 14:39:41 -07001970 // Also turn on CheckJNI for debuggable apps. It's quite
1971 // awkward to turn on otherwise.
1972 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001973 }
Ben Cheng6c0afff2010-02-14 16:18:56 -08001974 // Run the app in safe mode if its manifest requests so or the
1975 // system is booted in safe mode.
1976 if ((app.info.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0 ||
1977 Zygote.systemInSafeMode == true) {
Ben Cheng23085b72010-02-08 16:06:32 -08001978 debugFlags |= Zygote.DEBUG_ENABLE_SAFEMODE;
1979 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001980 if ("1".equals(SystemProperties.get("debug.checkjni"))) {
1981 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
1982 }
Elliott Hughesae07ecf2011-07-06 17:33:27 -07001983 if ("1".equals(SystemProperties.get("debug.jni.logging"))) {
1984 debugFlags |= Zygote.DEBUG_ENABLE_JNI_LOGGING;
1985 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001986 if ("1".equals(SystemProperties.get("debug.assert"))) {
1987 debugFlags |= Zygote.DEBUG_ENABLE_ASSERT;
1988 }
Jeff Brown3f9dd282011-07-08 20:02:19 -07001989
1990 // Start the process. It will either succeed and return a result containing
1991 // the PID of the new process, or else throw a RuntimeException.
1992 Process.ProcessStartResult startResult = Process.start("android.app.ActivityThread",
Elliott Hughese1dfcb72011-07-08 11:08:07 -07001993 app.processName, uid, uid, gids, debugFlags,
1994 app.info.targetSdkVersion, null);
Jeff Brown3f9dd282011-07-08 20:02:19 -07001995
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001996 BatteryStatsImpl bs = app.batteryStats.getBatteryStats();
1997 synchronized (bs) {
1998 if (bs.isOnBattery()) {
1999 app.batteryStats.incStartsLocked();
2000 }
2001 }
2002
Jeff Brown3f9dd282011-07-08 20:02:19 -07002003 EventLog.writeEvent(EventLogTags.AM_PROC_START, startResult.pid, uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002004 app.processName, hostingType,
2005 hostingNameStr != null ? hostingNameStr : "");
2006
2007 if (app.persistent) {
Jeff Brown3f9dd282011-07-08 20:02:19 -07002008 Watchdog.getInstance().processStarted(app.processName, startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002009 }
2010
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07002011 StringBuilder buf = mStringBuilder;
2012 buf.setLength(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002013 buf.append("Start proc ");
2014 buf.append(app.processName);
2015 buf.append(" for ");
2016 buf.append(hostingType);
2017 if (hostingNameStr != null) {
2018 buf.append(" ");
2019 buf.append(hostingNameStr);
2020 }
2021 buf.append(": pid=");
Jeff Brown3f9dd282011-07-08 20:02:19 -07002022 buf.append(startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002023 buf.append(" uid=");
2024 buf.append(uid);
2025 buf.append(" gids={");
2026 if (gids != null) {
2027 for (int gi=0; gi<gids.length; gi++) {
2028 if (gi != 0) buf.append(", ");
2029 buf.append(gids[gi]);
2030
2031 }
2032 }
2033 buf.append("}");
Joe Onorato8a9b2202010-02-26 18:56:32 -08002034 Slog.i(TAG, buf.toString());
Jeff Brown3f9dd282011-07-08 20:02:19 -07002035 app.pid = startResult.pid;
2036 app.usingWrapper = startResult.usingWrapper;
2037 app.removed = false;
2038 synchronized (mPidsSelfLocked) {
2039 this.mPidsSelfLocked.put(startResult.pid, app);
2040 Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
2041 msg.obj = app;
2042 mHandler.sendMessageDelayed(msg, startResult.usingWrapper
2043 ? PROC_START_TIMEOUT_WITH_WRAPPER : PROC_START_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002044 }
2045 } catch (RuntimeException e) {
2046 // XXX do better error recovery.
2047 app.pid = 0;
Joe Onorato8a9b2202010-02-26 18:56:32 -08002048 Slog.e(TAG, "Failure starting process " + app.processName, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002049 }
2050 }
2051
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002052 void updateUsageStats(ActivityRecord resumedComponent, boolean resumed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002053 if (resumed) {
2054 mUsageStatsService.noteResumeComponent(resumedComponent.realActivity);
2055 } else {
2056 mUsageStatsService.notePauseComponent(resumedComponent.realActivity);
2057 }
2058 }
2059
Amith Yamasani742a6712011-05-04 14:49:28 -07002060 boolean startHomeActivityLocked(int userId) {
Mike Lockwooda8f767a2011-08-31 14:32:37 -04002061 if (mHeadless) {
2062 // Added because none of the other calls to ensureBootCompleted seem to fire
2063 // when running headless.
2064 ensureBootCompleted();
2065 return false;
2066 }
2067
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002068 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2069 && mTopAction == null) {
2070 // We are running in factory test mode, but unable to find
2071 // the factory test app, so just sit around displaying the
2072 // error message and don't try to start anything.
2073 return false;
2074 }
2075 Intent intent = new Intent(
2076 mTopAction,
2077 mTopData != null ? Uri.parse(mTopData) : null);
2078 intent.setComponent(mTopComponent);
2079 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
2080 intent.addCategory(Intent.CATEGORY_HOME);
2081 }
2082 ActivityInfo aInfo =
2083 intent.resolveActivityInfo(mContext.getPackageManager(),
2084 STOCK_PM_FLAGS);
2085 if (aInfo != null) {
2086 intent.setComponent(new ComponentName(
2087 aInfo.applicationInfo.packageName, aInfo.name));
2088 // Don't do this if the home app is currently being
2089 // instrumented.
Amith Yamasani742a6712011-05-04 14:49:28 -07002090 aInfo = new ActivityInfo(aInfo);
2091 aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002092 ProcessRecord app = getProcessRecordLocked(aInfo.processName,
2093 aInfo.applicationInfo.uid);
2094 if (app == null || app.instrumentationClass == null) {
2095 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002096 mMainStack.startActivityLocked(null, intent, null, aInfo,
2097 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002098 }
2099 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002100
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002101 return true;
2102 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002103
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002104 /**
2105 * Starts the "new version setup screen" if appropriate.
2106 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002107 void startSetupActivityLocked() {
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002108 // Only do this once per boot.
2109 if (mCheckedForSetup) {
2110 return;
2111 }
2112
2113 // We will show this screen if the current one is a different
2114 // version than the last one shown, and we are not running in
2115 // low-level factory test mode.
2116 final ContentResolver resolver = mContext.getContentResolver();
2117 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL &&
2118 Settings.Secure.getInt(resolver,
2119 Settings.Secure.DEVICE_PROVISIONED, 0) != 0) {
2120 mCheckedForSetup = true;
2121
2122 // See if we should be showing the platform update setup UI.
2123 Intent intent = new Intent(Intent.ACTION_UPGRADE_SETUP);
2124 List<ResolveInfo> ris = mSelf.mContext.getPackageManager()
2125 .queryIntentActivities(intent, PackageManager.GET_META_DATA);
2126
2127 // We don't allow third party apps to replace this.
2128 ResolveInfo ri = null;
2129 for (int i=0; ris != null && i<ris.size(); i++) {
2130 if ((ris.get(i).activityInfo.applicationInfo.flags
2131 & ApplicationInfo.FLAG_SYSTEM) != 0) {
2132 ri = ris.get(i);
2133 break;
2134 }
2135 }
2136
2137 if (ri != null) {
2138 String vers = ri.activityInfo.metaData != null
2139 ? ri.activityInfo.metaData.getString(Intent.METADATA_SETUP_VERSION)
2140 : null;
2141 if (vers == null && ri.activityInfo.applicationInfo.metaData != null) {
2142 vers = ri.activityInfo.applicationInfo.metaData.getString(
2143 Intent.METADATA_SETUP_VERSION);
2144 }
2145 String lastVers = Settings.Secure.getString(
2146 resolver, Settings.Secure.LAST_SETUP_SHOWN);
2147 if (vers != null && !vers.equals(lastVers)) {
2148 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2149 intent.setComponent(new ComponentName(
2150 ri.activityInfo.packageName, ri.activityInfo.name));
Dianne Hackborna4972e92012-03-14 10:38:05 -07002151 mMainStack.startActivityLocked(null, intent, null, ri.activityInfo,
2152 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002153 }
2154 }
2155 }
2156 }
2157
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002158 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002159 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002160 }
2161
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002162 void enforceNotIsolatedCaller(String caller) {
2163 if (UserId.isIsolated(Binder.getCallingUid())) {
2164 throw new SecurityException("Isolated process not allowed to call " + caller);
2165 }
2166 }
2167
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002168 public int getFrontActivityScreenCompatMode() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002169 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002170 synchronized (this) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002171 return mCompatModePackages.getFrontActivityScreenCompatModeLocked();
2172 }
2173 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002174
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002175 public void setFrontActivityScreenCompatMode(int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002176 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2177 "setFrontActivityScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002178 synchronized (this) {
2179 mCompatModePackages.setFrontActivityScreenCompatModeLocked(mode);
2180 }
2181 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002182
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002183 public int getPackageScreenCompatMode(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002184 enforceNotIsolatedCaller("getPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002185 synchronized (this) {
2186 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
2187 }
2188 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002189
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002190 public void setPackageScreenCompatMode(String packageName, int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002191 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2192 "setPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002193 synchronized (this) {
2194 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002195 }
2196 }
2197
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002198 public boolean getPackageAskScreenCompat(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002199 enforceNotIsolatedCaller("getPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002200 synchronized (this) {
2201 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
2202 }
2203 }
2204
2205 public void setPackageAskScreenCompat(String packageName, boolean ask) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002206 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2207 "setPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002208 synchronized (this) {
2209 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
2210 }
2211 }
2212
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002213 void reportResumedActivityLocked(ActivityRecord r) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002214 //Slog.i(TAG, "**** REPORT RESUME: " + r);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002215
2216 final int identHash = System.identityHashCode(r);
2217 updateUsageStats(r, true);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002218 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002219
Jeff Sharkeya4620792011-05-20 15:29:23 -07002220 private void dispatchForegroundActivitiesChanged(int pid, int uid, boolean foregroundActivities) {
2221 int i = mProcessObservers.beginBroadcast();
2222 while (i > 0) {
2223 i--;
2224 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2225 if (observer != null) {
2226 try {
2227 observer.onForegroundActivitiesChanged(pid, uid, foregroundActivities);
2228 } catch (RemoteException e) {
2229 }
2230 }
2231 }
2232 mProcessObservers.finishBroadcast();
2233 }
2234
2235 private void dispatchProcessDied(int pid, int uid) {
2236 int i = mProcessObservers.beginBroadcast();
2237 while (i > 0) {
2238 i--;
2239 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2240 if (observer != null) {
2241 try {
2242 observer.onProcessDied(pid, uid);
2243 } catch (RemoteException e) {
2244 }
2245 }
2246 }
2247 mProcessObservers.finishBroadcast();
2248 }
2249
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002250 final void doPendingActivityLaunchesLocked(boolean doResume) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002251 final int N = mPendingActivityLaunches.size();
2252 if (N <= 0) {
2253 return;
2254 }
2255 for (int i=0; i<N; i++) {
2256 PendingActivityLaunch pal = mPendingActivityLaunches.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002257 mMainStack.startActivityUncheckedLocked(pal.r, pal.sourceRecord,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002258 pal.startFlags, doResume && i == (N-1));
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002259 }
2260 mPendingActivityLaunches.clear();
2261 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002262
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002263 public final int startActivity(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002264 Intent intent, String resolvedType, IBinder resultTo,
2265 String resultWho, int requestCode, int startFlags,
2266 String profileFile, ParcelFileDescriptor profileFd, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002267 enforceNotIsolatedCaller("startActivity");
Amith Yamasani742a6712011-05-04 14:49:28 -07002268 int userId = 0;
2269 if (intent.getCategories() != null && intent.getCategories().contains(Intent.CATEGORY_HOME)) {
2270 // Requesting home, set the identity to the current user
2271 // HACK!
2272 userId = mCurrentUserId;
2273 } else {
2274 // TODO: Fix this in a better way - calls coming from SystemUI should probably carry
2275 // the current user's userId
2276 if (Binder.getCallingUid() < Process.FIRST_APPLICATION_UID) {
2277 userId = 0;
2278 } else {
2279 userId = Binder.getOrigCallingUser();
2280 }
2281 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002282 return mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002283 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
2284 null, null, options, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002285 }
2286
2287 public final WaitResult startActivityAndWait(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002288 Intent intent, String resolvedType, IBinder resultTo,
2289 String resultWho, int requestCode, int startFlags, String profileFile,
2290 ParcelFileDescriptor profileFd, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002291 enforceNotIsolatedCaller("startActivityAndWait");
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002292 WaitResult res = new WaitResult();
Amith Yamasani742a6712011-05-04 14:49:28 -07002293 int userId = Binder.getOrigCallingUser();
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002294 mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002295 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
2296 res, null, options, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002297 return res;
2298 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08002299
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002300 public final int startActivityWithConfig(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002301 Intent intent, String resolvedType, IBinder resultTo,
2302 String resultWho, int requestCode, int startFlags, Configuration config,
2303 Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002304 enforceNotIsolatedCaller("startActivityWithConfig");
Amith Yamasani742a6712011-05-04 14:49:28 -07002305 int ret = mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002306 resultTo, resultWho, requestCode, startFlags,
2307 null, null, null, config, options, Binder.getOrigCallingUser());
Amith Yamasani742a6712011-05-04 14:49:28 -07002308 return ret;
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002309 }
2310
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002311 public int startActivityIntentSender(IApplicationThread caller,
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002312 IntentSender intent, Intent fillInIntent, String resolvedType,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002313 IBinder resultTo, String resultWho, int requestCode,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002314 int flagsMask, int flagsValues, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002315 enforceNotIsolatedCaller("startActivityIntentSender");
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002316 // Refuse possible leaked file descriptors
2317 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
2318 throw new IllegalArgumentException("File descriptors passed in Intent");
2319 }
2320
2321 IIntentSender sender = intent.getTarget();
2322 if (!(sender instanceof PendingIntentRecord)) {
2323 throw new IllegalArgumentException("Bad PendingIntent object");
2324 }
2325
2326 PendingIntentRecord pir = (PendingIntentRecord)sender;
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002327
2328 synchronized (this) {
2329 // If this is coming from the currently resumed activity, it is
2330 // effectively saying that app switches are allowed at this point.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002331 if (mMainStack.mResumedActivity != null
2332 && mMainStack.mResumedActivity.info.applicationInfo.uid ==
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002333 Binder.getCallingUid()) {
2334 mAppSwitchesAllowedTime = 0;
2335 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002336 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002337 int ret = pir.sendInner(0, fillInIntent, resolvedType, null, null,
2338 resultTo, resultWho, requestCode, flagsMask, flagsValues, options);
Amith Yamasani742a6712011-05-04 14:49:28 -07002339 return ret;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002340 }
2341
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002342 public boolean startNextMatchingActivity(IBinder callingActivity,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002343 Intent intent, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002344 // Refuse possible leaked file descriptors
2345 if (intent != null && intent.hasFileDescriptors() == true) {
2346 throw new IllegalArgumentException("File descriptors passed in Intent");
2347 }
2348
2349 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002350 ActivityRecord r = mMainStack.isInStackLocked(callingActivity);
2351 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002352 return false;
2353 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002354 if (r.app == null || r.app.thread == null) {
2355 // The caller is not running... d'oh!
2356 return false;
2357 }
2358 intent = new Intent(intent);
2359 // The caller is not allowed to change the data.
2360 intent.setDataAndType(r.intent.getData(), r.intent.getType());
2361 // And we are resetting to find the next component...
2362 intent.setComponent(null);
2363
2364 ActivityInfo aInfo = null;
2365 try {
2366 List<ResolveInfo> resolves =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002367 AppGlobals.getPackageManager().queryIntentActivities(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002368 intent, r.resolvedType,
Dianne Hackborn1655be42009-05-08 14:29:01 -07002369 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002370
2371 // Look for the original activity in the list...
2372 final int N = resolves != null ? resolves.size() : 0;
2373 for (int i=0; i<N; i++) {
2374 ResolveInfo rInfo = resolves.get(i);
2375 if (rInfo.activityInfo.packageName.equals(r.packageName)
2376 && rInfo.activityInfo.name.equals(r.info.name)) {
2377 // We found the current one... the next matching is
2378 // after it.
2379 i++;
2380 if (i<N) {
2381 aInfo = resolves.get(i).activityInfo;
2382 }
2383 break;
2384 }
2385 }
2386 } catch (RemoteException e) {
2387 }
2388
2389 if (aInfo == null) {
2390 // Nobody who is next!
2391 return false;
2392 }
2393
2394 intent.setComponent(new ComponentName(
2395 aInfo.applicationInfo.packageName, aInfo.name));
2396 intent.setFlags(intent.getFlags()&~(
2397 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
2398 Intent.FLAG_ACTIVITY_CLEAR_TOP|
2399 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
2400 Intent.FLAG_ACTIVITY_NEW_TASK));
2401
2402 // Okay now we need to start the new activity, replacing the
2403 // currently running activity. This is a little tricky because
2404 // we want to start the new one as if the current one is finished,
2405 // but not finish the current one first so that there is no flicker.
2406 // And thus...
2407 final boolean wasFinishing = r.finishing;
2408 r.finishing = true;
2409
2410 // Propagate reply information over to the new activity.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002411 final ActivityRecord resultTo = r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002412 final String resultWho = r.resultWho;
2413 final int requestCode = r.requestCode;
2414 r.resultTo = null;
2415 if (resultTo != null) {
2416 resultTo.removeResultsLocked(r, resultWho, requestCode);
2417 }
2418
2419 final long origId = Binder.clearCallingIdentity();
2420 // XXX we are not dealing with propagating grantedUriPermissions...
2421 // those are not yet exposed to user code, so there is no need.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002422 int res = mMainStack.startActivityLocked(r.app.thread, intent,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002423 r.resolvedType, aInfo, resultTo != null ? resultTo.appToken : null,
2424 resultWho, requestCode, -1, r.launchedFromUid, 0,
2425 options, false, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002426 Binder.restoreCallingIdentity(origId);
2427
2428 r.finishing = wasFinishing;
Dianne Hackborna4972e92012-03-14 10:38:05 -07002429 if (res != ActivityManager.START_SUCCESS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002430 return false;
2431 }
2432 return true;
2433 }
2434 }
2435
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002436 public final int startActivityInPackage(int uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002437 Intent intent, String resolvedType, IBinder resultTo,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002438 String resultWho, int requestCode, int startFlags, Bundle options) {
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002439
2440 // This is so super not safe, that only the system (or okay root)
2441 // can do it.
Amith Yamasani742a6712011-05-04 14:49:28 -07002442 int userId = Binder.getOrigCallingUser();
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002443 final int callingUid = Binder.getCallingUid();
2444 if (callingUid != 0 && callingUid != Process.myUid()) {
2445 throw new SecurityException(
2446 "startActivityInPackage only available to the system");
2447 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002448
Amith Yamasani742a6712011-05-04 14:49:28 -07002449 int ret = mMainStack.startActivityMayWait(null, uid, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002450 resultTo, resultWho, requestCode, startFlags,
2451 null, null, null, null, options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002452 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002453 }
2454
2455 public final int startActivities(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002456 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002457 enforceNotIsolatedCaller("startActivities");
Amith Yamasani742a6712011-05-04 14:49:28 -07002458 int ret = mMainStack.startActivities(caller, -1, intents, resolvedTypes, resultTo,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002459 options, Binder.getOrigCallingUser());
Amith Yamasani742a6712011-05-04 14:49:28 -07002460 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002461 }
2462
2463 public final int startActivitiesInPackage(int uid,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002464 Intent[] intents, String[] resolvedTypes, IBinder resultTo,
2465 Bundle options) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002466
2467 // This is so super not safe, that only the system (or okay root)
2468 // can do it.
2469 final int callingUid = Binder.getCallingUid();
2470 if (callingUid != 0 && callingUid != Process.myUid()) {
2471 throw new SecurityException(
2472 "startActivityInPackage only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002473 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002474 int ret = mMainStack.startActivities(null, uid, intents, resolvedTypes, resultTo,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002475 options, UserId.getUserId(uid));
Amith Yamasani742a6712011-05-04 14:49:28 -07002476 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002477 }
2478
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002479 final void addRecentTaskLocked(TaskRecord task) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002480 int N = mRecentTasks.size();
Dianne Hackborn7c0e75e2010-12-21 19:15:40 -08002481 // Quick case: check if the top-most recent task is the same.
2482 if (N > 0 && mRecentTasks.get(0) == task) {
2483 return;
2484 }
2485 // Remove any existing entries that are the same kind of task.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002486 for (int i=0; i<N; i++) {
2487 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07002488 if (task.userId == tr.userId
2489 && ((task.affinity != null && task.affinity.equals(tr.affinity))
2490 || (task.intent != null && task.intent.filterEquals(tr.intent)))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002491 mRecentTasks.remove(i);
2492 i--;
2493 N--;
2494 if (task.intent == null) {
2495 // If the new recent task we are adding is not fully
2496 // specified, then replace it with the existing recent task.
2497 task = tr;
2498 }
2499 }
2500 }
2501 if (N >= MAX_RECENT_TASKS) {
2502 mRecentTasks.remove(N-1);
2503 }
2504 mRecentTasks.add(0, task);
2505 }
2506
2507 public void setRequestedOrientation(IBinder token,
2508 int requestedOrientation) {
2509 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002510 ActivityRecord r = mMainStack.isInStackLocked(token);
2511 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002512 return;
2513 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002514 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornbe707852011-11-11 14:32:10 -08002515 mWindowManager.setAppOrientation(r.appToken, requestedOrientation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002516 Configuration config = mWindowManager.updateOrientationFromAppTokens(
The Android Open Source Project10592532009-03-18 17:39:46 -07002517 mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -08002518 r.mayFreezeScreenLocked(r.app) ? r.appToken : null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002519 if (config != null) {
2520 r.frozenBeforeDestroy = true;
Dianne Hackborn813075a62011-11-14 17:45:19 -08002521 if (!updateConfigurationLocked(config, r, false, false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002522 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002523 }
2524 }
2525 Binder.restoreCallingIdentity(origId);
2526 }
2527 }
2528
2529 public int getRequestedOrientation(IBinder token) {
2530 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002531 ActivityRecord r = mMainStack.isInStackLocked(token);
2532 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002533 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
2534 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08002535 return mWindowManager.getAppOrientation(r.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002536 }
2537 }
2538
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002539 /**
2540 * This is the internal entry point for handling Activity.finish().
2541 *
2542 * @param token The Binder token referencing the Activity we want to finish.
2543 * @param resultCode Result code, if any, from this Activity.
2544 * @param resultData Result data (Intent), if any, from this Activity.
2545 *
Alexey Tarasov83bad3d2009-08-12 15:05:43 +11002546 * @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 -08002547 */
2548 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData) {
2549 // Refuse possible leaked file descriptors
2550 if (resultData != null && resultData.hasFileDescriptors() == true) {
2551 throw new IllegalArgumentException("File descriptors passed in Intent");
2552 }
2553
2554 synchronized(this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002555 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002556 // Find the first activity that is not finishing.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002557 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002558 if (next != null) {
2559 // ask watcher if this is allowed
2560 boolean resumeOK = true;
2561 try {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002562 resumeOK = mController.activityResuming(next.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002563 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002564 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002565 }
2566
2567 if (!resumeOK) {
2568 return false;
2569 }
2570 }
2571 }
2572 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002573 boolean res = mMainStack.requestFinishActivityLocked(token, resultCode,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002574 resultData, "app-request");
2575 Binder.restoreCallingIdentity(origId);
2576 return res;
2577 }
2578 }
2579
Dianne Hackborn860755f2010-06-03 18:47:52 -07002580 public final void finishHeavyWeightApp() {
2581 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2582 != PackageManager.PERMISSION_GRANTED) {
2583 String msg = "Permission Denial: finishHeavyWeightApp() from pid="
2584 + Binder.getCallingPid()
2585 + ", uid=" + Binder.getCallingUid()
2586 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2587 Slog.w(TAG, msg);
2588 throw new SecurityException(msg);
2589 }
2590
2591 synchronized(this) {
2592 if (mHeavyWeightProcess == null) {
2593 return;
2594 }
2595
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002596 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>(
Dianne Hackborn860755f2010-06-03 18:47:52 -07002597 mHeavyWeightProcess.activities);
2598 for (int i=0; i<activities.size(); i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002599 ActivityRecord r = activities.get(i);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002600 if (!r.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002601 int index = mMainStack.indexOfTokenLocked(r.appToken);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002602 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002603 mMainStack.finishActivityLocked(r, index, Activity.RESULT_CANCELED,
Dianne Hackborn860755f2010-06-03 18:47:52 -07002604 null, "finish-heavy");
2605 }
2606 }
2607 }
2608
2609 mHeavyWeightProcess = null;
2610 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
2611 }
2612 }
2613
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002614 public void crashApplication(int uid, int initialPid, String packageName,
2615 String message) {
2616 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2617 != PackageManager.PERMISSION_GRANTED) {
2618 String msg = "Permission Denial: crashApplication() from pid="
2619 + Binder.getCallingPid()
2620 + ", uid=" + Binder.getCallingUid()
2621 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2622 Slog.w(TAG, msg);
2623 throw new SecurityException(msg);
2624 }
2625
2626 synchronized(this) {
2627 ProcessRecord proc = null;
2628
2629 // Figure out which process to kill. We don't trust that initialPid
2630 // still has any relation to current pids, so must scan through the
2631 // list.
2632 synchronized (mPidsSelfLocked) {
2633 for (int i=0; i<mPidsSelfLocked.size(); i++) {
2634 ProcessRecord p = mPidsSelfLocked.valueAt(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002635 if (p.uid != uid) {
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002636 continue;
2637 }
2638 if (p.pid == initialPid) {
2639 proc = p;
2640 break;
2641 }
2642 for (String str : p.pkgList) {
2643 if (str.equals(packageName)) {
2644 proc = p;
2645 }
2646 }
2647 }
2648 }
2649
2650 if (proc == null) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07002651 Slog.w(TAG, "crashApplication: nothing for uid=" + uid
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002652 + " initialPid=" + initialPid
2653 + " packageName=" + packageName);
2654 return;
2655 }
2656
2657 if (proc.thread != null) {
Dianne Hackborn9f531192010-08-04 17:48:03 -07002658 if (proc.pid == Process.myPid()) {
2659 Log.w(TAG, "crashApplication: trying to crash self!");
2660 return;
2661 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002662 long ident = Binder.clearCallingIdentity();
2663 try {
2664 proc.thread.scheduleCrash(message);
2665 } catch (RemoteException e) {
2666 }
2667 Binder.restoreCallingIdentity(ident);
2668 }
2669 }
2670 }
2671
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002672 public final void finishSubActivity(IBinder token, String resultWho,
2673 int requestCode) {
2674 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002675 ActivityRecord self = mMainStack.isInStackLocked(token);
2676 if (self == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002677 return;
2678 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002679
2680 final long origId = Binder.clearCallingIdentity();
2681
2682 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002683 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2684 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002685 if (r.resultTo == self && r.requestCode == requestCode) {
2686 if ((r.resultWho == null && resultWho == null) ||
2687 (r.resultWho != null && r.resultWho.equals(resultWho))) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002688 mMainStack.finishActivityLocked(r, i,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002689 Activity.RESULT_CANCELED, null, "request-sub");
2690 }
2691 }
2692 }
2693
2694 Binder.restoreCallingIdentity(origId);
2695 }
2696 }
2697
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002698 public boolean willActivityBeVisible(IBinder token) {
2699 synchronized(this) {
2700 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002701 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2702 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08002703 if (r.appToken == token) {
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002704 return true;
2705 }
2706 if (r.fullscreen && !r.finishing) {
2707 return false;
2708 }
2709 }
2710 return true;
2711 }
2712 }
2713
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002714 public void overridePendingTransition(IBinder token, String packageName,
2715 int enterAnim, int exitAnim) {
2716 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002717 ActivityRecord self = mMainStack.isInStackLocked(token);
2718 if (self == null) {
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002719 return;
2720 }
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002721
2722 final long origId = Binder.clearCallingIdentity();
2723
2724 if (self.state == ActivityState.RESUMED
2725 || self.state == ActivityState.PAUSING) {
2726 mWindowManager.overridePendingAppTransition(packageName,
2727 enterAnim, exitAnim);
2728 }
2729
2730 Binder.restoreCallingIdentity(origId);
2731 }
2732 }
2733
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002734 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002735 * Main function for removing an existing process from the activity manager
2736 * as a result of that process going away. Clears out all connections
2737 * to the process.
2738 */
2739 private final void handleAppDiedLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002740 boolean restarting, boolean allowRestart) {
2741 cleanUpApplicationRecordLocked(app, restarting, allowRestart, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002742 if (!restarting) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002743 mLruProcesses.remove(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002744 }
2745
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002746 if (mProfileProc == app) {
2747 clearProfilerLocked();
2748 }
2749
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002750 // Just in case...
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002751 if (mMainStack.mPausingActivity != null && mMainStack.mPausingActivity.app == app) {
2752 if (DEBUG_PAUSE) Slog.v(TAG, "App died while pausing: " +mMainStack.mPausingActivity);
2753 mMainStack.mPausingActivity = null;
2754 }
2755 if (mMainStack.mLastPausedActivity != null && mMainStack.mLastPausedActivity.app == app) {
2756 mMainStack.mLastPausedActivity = null;
2757 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002758
2759 // Remove this application's activities from active lists.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002760 mMainStack.removeHistoryRecordsForAppLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002761
2762 boolean atTop = true;
2763 boolean hasVisibleActivities = false;
2764
2765 // Clean out the history list.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002766 int i = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08002767 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002768 TAG, "Removing app " + app + " from history with " + i + " entries");
2769 while (i > 0) {
2770 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002771 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002772 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002773 TAG, "Record #" + i + " " + r + ": app=" + r.app);
2774 if (r.app == app) {
2775 if ((!r.haveState && !r.stateNotNeeded) || r.finishing) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002776 if (ActivityStack.DEBUG_ADD_REMOVE) {
2777 RuntimeException here = new RuntimeException("here");
2778 here.fillInStackTrace();
2779 Slog.i(TAG, "Removing activity " + r + " from stack at " + i
2780 + ": haveState=" + r.haveState
2781 + " stateNotNeeded=" + r.stateNotNeeded
2782 + " finishing=" + r.finishing
2783 + " state=" + r.state, here);
2784 }
2785 if (!r.finishing) {
2786 Slog.w(TAG, "Force removing " + r + ": app died, no saved state");
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -08002787 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
2788 System.identityHashCode(r),
2789 r.task.taskId, r.shortComponentName,
2790 "proc died without state saved");
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002791 }
Dianne Hackborn5c607432012-02-28 14:44:19 -08002792 mMainStack.removeActivityFromHistoryLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002793
2794 } else {
2795 // We have the current state for this activity, so
2796 // it can be restarted later when needed.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002797 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002798 TAG, "Keeping entry, setting app to null");
2799 if (r.visible) {
2800 hasVisibleActivities = true;
2801 }
2802 r.app = null;
2803 r.nowVisible = false;
2804 if (!r.haveState) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002805 if (ActivityStack.DEBUG_SAVED_STATE) Slog.i(TAG,
2806 "App died, clearing saved state of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002807 r.icicle = null;
2808 }
2809 }
2810
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002811 r.stack.cleanUpActivityLocked(r, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002812 }
2813 atTop = false;
2814 }
2815
2816 app.activities.clear();
2817
2818 if (app.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002819 Slog.w(TAG, "Crash of app " + app.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002820 + " running instrumentation " + app.instrumentationClass);
2821 Bundle info = new Bundle();
2822 info.putString("shortMsg", "Process crashed.");
2823 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
2824 }
2825
2826 if (!restarting) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002827 if (!mMainStack.resumeTopActivityLocked(null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002828 // If there was nothing to resume, and we are not already
2829 // restarting this process, but there is a visible activity that
2830 // is hosted by the process... then make sure all visible
2831 // activities are running, taking care of restarting this
2832 // process.
2833 if (hasVisibleActivities) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002834 mMainStack.ensureActivitiesVisibleLocked(null, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002835 }
2836 }
2837 }
2838 }
2839
2840 private final int getLRURecordIndexForAppLocked(IApplicationThread thread) {
2841 IBinder threadBinder = thread.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002842 // Find the application record.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002843 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2844 ProcessRecord rec = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002845 if (rec.thread != null && rec.thread.asBinder() == threadBinder) {
2846 return i;
2847 }
2848 }
2849 return -1;
2850 }
2851
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002852 final ProcessRecord getRecordForAppLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002853 IApplicationThread thread) {
2854 if (thread == null) {
2855 return null;
2856 }
2857
2858 int appIndex = getLRURecordIndexForAppLocked(thread);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002859 return appIndex >= 0 ? mLruProcesses.get(appIndex) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002860 }
2861
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002862 final void appDiedLocked(ProcessRecord app, int pid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002863 IApplicationThread thread) {
2864
2865 mProcDeaths[0]++;
2866
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002867 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
2868 synchronized (stats) {
2869 stats.noteProcessDiedLocked(app.info.uid, pid);
2870 }
2871
Magnus Edlund7bb25812010-02-24 15:45:06 +01002872 // Clean up already done if the process has been re-started.
2873 if (app.pid == pid && app.thread != null &&
2874 app.thread.asBinder() == thread.asBinder()) {
Dianne Hackborn906497c2010-05-10 15:57:38 -07002875 if (!app.killedBackground) {
2876 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
2877 + ") has died.");
2878 }
Doug Zongker2bec3d42009-12-04 12:52:44 -08002879 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002880 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002881 TAG, "Dying app: " + app + ", pid: " + pid
2882 + ", thread: " + thread.asBinder());
2883 boolean doLowMem = app.instrumentationClass == null;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002884 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002885
2886 if (doLowMem) {
2887 // If there are no longer any background processes running,
2888 // and the app that died was not running instrumentation,
2889 // then tell everyone we are now low on memory.
2890 boolean haveBg = false;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002891 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2892 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -07002893 if (rec.thread != null && rec.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002894 haveBg = true;
2895 break;
2896 }
2897 }
2898
2899 if (!haveBg) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002900 EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mLruProcesses.size());
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002901 long now = SystemClock.uptimeMillis();
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002902 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2903 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn36124872009-10-08 16:22:03 -07002904 if (rec != app && rec.thread != null &&
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002905 (rec.lastLowMemory+GC_MIN_INTERVAL) <= now) {
2906 // The low memory report is overriding any current
2907 // state for a GC request. Make sure to do
Dianne Hackborn32907cf2010-06-10 17:50:20 -07002908 // heavy/important/visible/foreground processes first.
Dianne Hackborn7d608422011-08-07 16:24:18 -07002909 if (rec.setAdj <= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002910 rec.lastRequestedGc = 0;
2911 } else {
2912 rec.lastRequestedGc = rec.lastLowMemory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002913 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002914 rec.reportLowMemory = true;
2915 rec.lastLowMemory = now;
2916 mProcessesToGc.remove(rec);
2917 addProcessToGcListLocked(rec);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002918 }
2919 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07002920 mHandler.sendEmptyMessage(REPORT_MEM_USAGE);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002921 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002922 }
2923 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01002924 } else if (app.pid != pid) {
2925 // A new process has already been started.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002926 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
Magnus Edlund7bb25812010-02-24 15:45:06 +01002927 + ") has died and restarted (pid " + app.pid + ").");
Dianne Hackborn28a8c2b2010-03-01 11:30:02 -08002928 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08002929 } else if (DEBUG_PROCESSES) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002930 Slog.d(TAG, "Received spurious death notification for thread "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002931 + thread.asBinder());
2932 }
2933 }
2934
Dan Egnor42471dd2010-01-07 17:25:22 -08002935 /**
2936 * If a stack trace dump file is configured, dump process stack traces.
Christopher Tate6ee412d2010-05-28 12:01:56 -07002937 * @param clearTraces causes the dump file to be erased prior to the new
2938 * traces being written, if true; when false, the new traces will be
2939 * appended to any existing file content.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002940 * @param firstPids of dalvik VM processes to dump stack traces for first
2941 * @param lastPids of dalvik VM processes to dump stack traces for last
Dan Egnor42471dd2010-01-07 17:25:22 -08002942 * @return file containing stack traces, or null if no dump file is configured
2943 */
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002944 public static File dumpStackTraces(boolean clearTraces, ArrayList<Integer> firstPids,
2945 ProcessStats processStats, SparseArray<Boolean> lastPids) {
Dan Egnor42471dd2010-01-07 17:25:22 -08002946 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
2947 if (tracesPath == null || tracesPath.length() == 0) {
2948 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002949 }
Dan Egnor42471dd2010-01-07 17:25:22 -08002950
2951 File tracesFile = new File(tracesPath);
2952 try {
2953 File tracesDir = tracesFile.getParentFile();
2954 if (!tracesDir.exists()) tracesFile.mkdirs();
2955 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
2956
Christopher Tate6ee412d2010-05-28 12:01:56 -07002957 if (clearTraces && tracesFile.exists()) tracesFile.delete();
Dan Egnor42471dd2010-01-07 17:25:22 -08002958 tracesFile.createNewFile();
2959 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
2960 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002961 Slog.w(TAG, "Unable to prepare ANR traces file: " + tracesPath, e);
Dan Egnor42471dd2010-01-07 17:25:22 -08002962 return null;
2963 }
2964
2965 // Use a FileObserver to detect when traces finish writing.
2966 // The order of traces is considered important to maintain for legibility.
2967 FileObserver observer = new FileObserver(tracesPath, FileObserver.CLOSE_WRITE) {
2968 public synchronized void onEvent(int event, String path) { notify(); }
2969 };
2970
2971 try {
2972 observer.startWatching();
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002973
2974 // First collect all of the stacks of the most important pids.
2975 try {
2976 int num = firstPids.size();
2977 for (int i = 0; i < num; i++) {
2978 synchronized (observer) {
2979 Process.sendSignal(firstPids.get(i), Process.SIGNAL_QUIT);
2980 observer.wait(200); // Wait for write-close, give up after 200msec
2981 }
2982 }
2983 } catch (InterruptedException e) {
2984 Log.wtf(TAG, e);
2985 }
2986
2987 // Next measure CPU usage.
2988 if (processStats != null) {
2989 processStats.init();
2990 System.gc();
2991 processStats.update();
2992 try {
2993 synchronized (processStats) {
2994 processStats.wait(500); // measure over 1/2 second.
2995 }
2996 } catch (InterruptedException e) {
2997 }
2998 processStats.update();
2999
3000 // We'll take the stack crawls of just the top apps using CPU.
3001 final int N = processStats.countWorkingStats();
3002 int numProcs = 0;
3003 for (int i=0; i<N && numProcs<5; i++) {
3004 ProcessStats.Stats stats = processStats.getWorkingStats(i);
3005 if (lastPids.indexOfKey(stats.pid) >= 0) {
3006 numProcs++;
3007 try {
3008 synchronized (observer) {
3009 Process.sendSignal(stats.pid, Process.SIGNAL_QUIT);
3010 observer.wait(200); // Wait for write-close, give up after 200msec
3011 }
3012 } catch (InterruptedException e) {
3013 Log.wtf(TAG, e);
3014 }
3015
3016 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003017 }
3018 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003019
3020 return tracesFile;
3021
Dan Egnor42471dd2010-01-07 17:25:22 -08003022 } finally {
3023 observer.stopWatching();
3024 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003025 }
3026
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003027 final void appNotResponding(ProcessRecord app, ActivityRecord activity,
3028 ActivityRecord parent, final String annotation) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003029 ArrayList<Integer> firstPids = new ArrayList<Integer>(5);
3030 SparseArray<Boolean> lastPids = new SparseArray<Boolean>(20);
3031
Dianne Hackborn287952c2010-09-22 22:34:31 -07003032 if (mController != null) {
3033 try {
3034 // 0 == continue, -1 = kill process immediately
3035 int res = mController.appEarlyNotResponding(app.processName, app.pid, annotation);
3036 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3037 } catch (RemoteException e) {
3038 mController = null;
3039 }
3040 }
3041
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003042 long anrTime = SystemClock.uptimeMillis();
3043 if (MONITOR_CPU_USAGE) {
3044 updateCpuStatsNow();
3045 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003046
3047 synchronized (this) {
3048 // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down.
3049 if (mShuttingDown) {
3050 Slog.i(TAG, "During shutdown skipping ANR: " + app + " " + annotation);
3051 return;
3052 } else if (app.notResponding) {
3053 Slog.i(TAG, "Skipping duplicate ANR: " + app + " " + annotation);
3054 return;
3055 } else if (app.crashing) {
3056 Slog.i(TAG, "Crashing app skipping ANR: " + app + " " + annotation);
3057 return;
3058 }
3059
3060 // In case we come through here for the same app before completing
3061 // this one, mark as anring now so we will bail out.
3062 app.notResponding = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08003063
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003064 // Log the ANR to the event log.
3065 EventLog.writeEvent(EventLogTags.AM_ANR, app.pid, app.processName, app.info.flags,
3066 annotation);
Dan Egnor42471dd2010-01-07 17:25:22 -08003067
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003068 // Dump thread traces as quickly as we can, starting with "interesting" processes.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003069 firstPids.add(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003070
3071 int parentPid = app.pid;
3072 if (parent != null && parent.app != null && parent.app.pid > 0) parentPid = parent.app.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003073 if (parentPid != app.pid) firstPids.add(parentPid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003074
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003075 if (MY_PID != app.pid && MY_PID != parentPid) firstPids.add(MY_PID);
Dan Egnor42471dd2010-01-07 17:25:22 -08003076
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003077 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
3078 ProcessRecord r = mLruProcesses.get(i);
3079 if (r != null && r.thread != null) {
3080 int pid = r.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003081 if (pid > 0 && pid != app.pid && pid != parentPid && pid != MY_PID) {
3082 if (r.persistent) {
3083 firstPids.add(pid);
3084 } else {
3085 lastPids.put(pid, Boolean.TRUE);
3086 }
3087 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003088 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003089 }
3090 }
3091
Dan Egnor42471dd2010-01-07 17:25:22 -08003092 // Log the ANR to the main log.
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07003093 StringBuilder info = mStringBuilder;
3094 info.setLength(0);
Dan Egnor42471dd2010-01-07 17:25:22 -08003095 info.append("ANR in ").append(app.processName);
3096 if (activity != null && activity.shortComponentName != null) {
3097 info.append(" (").append(activity.shortComponentName).append(")");
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07003098 }
Eric Rowe6f4f6192010-02-17 18:29:04 -08003099 info.append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003100 if (annotation != null) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003101 info.append("Reason: ").append(annotation).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003102 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003103 if (parent != null && parent != activity) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003104 info.append("Parent: ").append(parent.shortComponentName).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003105 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003106
Dianne Hackborn287952c2010-09-22 22:34:31 -07003107 final ProcessStats processStats = new ProcessStats(true);
3108
3109 File tracesFile = dumpStackTraces(true, firstPids, processStats, lastPids);
3110
Dan Egnor42471dd2010-01-07 17:25:22 -08003111 String cpuInfo = null;
3112 if (MONITOR_CPU_USAGE) {
3113 updateCpuStatsNow();
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003114 synchronized (mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003115 cpuInfo = mProcessStats.printCurrentState(anrTime);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003116 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003117 info.append(processStats.printCurrentLoad());
Dan Egnor42471dd2010-01-07 17:25:22 -08003118 info.append(cpuInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003119 }
3120
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003121 info.append(processStats.printCurrentState(anrTime));
3122
Joe Onorato8a9b2202010-02-26 18:56:32 -08003123 Slog.e(TAG, info.toString());
Dan Egnor42471dd2010-01-07 17:25:22 -08003124 if (tracesFile == null) {
3125 // There is no trace file, so dump (only) the alleged culprit's threads to the log
3126 Process.sendSignal(app.pid, Process.SIGNAL_QUIT);
3127 }
3128
Jeff Sharkeya353d262011-10-28 11:12:06 -07003129 addErrorToDropBox("anr", app, app.processName, activity, parent, annotation,
3130 cpuInfo, tracesFile, null);
Dan Egnor42471dd2010-01-07 17:25:22 -08003131
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003132 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003133 try {
Dan Egnor42471dd2010-01-07 17:25:22 -08003134 // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately
3135 int res = mController.appNotResponding(app.processName, app.pid, info.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003136 if (res != 0) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003137 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3138 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003139 }
3140 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003141 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003142 }
3143 }
3144
Dan Egnor42471dd2010-01-07 17:25:22 -08003145 // Unless configured otherwise, swallow ANRs in background processes & kill the process.
3146 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
3147 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003148
3149 synchronized (this) {
3150 if (!showBackground && !app.isInterestingToUserLocked() && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003151 Slog.w(TAG, "Killing " + app + ": background ANR");
3152 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
3153 app.processName, app.setAdj, "background ANR");
3154 Process.killProcessQuiet(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003155 return;
3156 }
3157
3158 // Set the app's notResponding state, and look up the errorReportReceiver
3159 makeAppNotRespondingLocked(app,
3160 activity != null ? activity.shortComponentName : null,
3161 annotation != null ? "ANR " + annotation : "ANR",
3162 info.toString());
3163
3164 // Bring up the infamous App Not Responding dialog
3165 Message msg = Message.obtain();
3166 HashMap map = new HashMap();
3167 msg.what = SHOW_NOT_RESPONDING_MSG;
3168 msg.obj = map;
3169 map.put("app", app);
3170 if (activity != null) {
3171 map.put("activity", activity);
3172 }
3173
3174 mHandler.sendMessage(msg);
Dan Egnor42471dd2010-01-07 17:25:22 -08003175 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003176 }
3177
Dianne Hackborn0dad3642010-09-09 21:25:35 -07003178 final void showLaunchWarningLocked(final ActivityRecord cur, final ActivityRecord next) {
3179 if (!mLaunchWarningShown) {
3180 mLaunchWarningShown = true;
3181 mHandler.post(new Runnable() {
3182 @Override
3183 public void run() {
3184 synchronized (ActivityManagerService.this) {
3185 final Dialog d = new LaunchWarningWindow(mContext, cur, next);
3186 d.show();
3187 mHandler.postDelayed(new Runnable() {
3188 @Override
3189 public void run() {
3190 synchronized (ActivityManagerService.this) {
3191 d.dismiss();
3192 mLaunchWarningShown = false;
3193 }
3194 }
3195 }, 4000);
3196 }
3197 }
3198 });
3199 }
3200 }
3201
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003202 public boolean clearApplicationUserData(final String packageName,
Amith Yamasani742a6712011-05-04 14:49:28 -07003203 final IPackageDataObserver observer, final int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003204 enforceNotIsolatedCaller("clearApplicationUserData");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003205 int uid = Binder.getCallingUid();
3206 int pid = Binder.getCallingPid();
3207 long callingId = Binder.clearCallingIdentity();
3208 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003209 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003210 int pkgUid = -1;
3211 synchronized(this) {
3212 try {
3213 pkgUid = pm.getPackageUid(packageName);
3214 } catch (RemoteException e) {
3215 }
3216 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003217 Slog.w(TAG, "Invalid packageName:" + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003218 return false;
3219 }
3220 if (uid == pkgUid || checkComponentPermission(
3221 android.Manifest.permission.CLEAR_APP_USER_DATA,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08003222 pid, uid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003223 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003224 forceStopPackageLocked(packageName, pkgUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003225 } else {
3226 throw new SecurityException(pid+" does not have permission:"+
3227 android.Manifest.permission.CLEAR_APP_USER_DATA+" to clear data" +
3228 "for process:"+packageName);
3229 }
3230 }
3231
3232 try {
3233 //clear application user data
3234 pm.clearApplicationUserData(packageName, observer);
3235 Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED,
3236 Uri.fromParts("package", packageName, null));
3237 intent.putExtra(Intent.EXTRA_UID, pkgUid);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003238 broadcastIntentInPackage("android", Process.SYSTEM_UID, intent,
Amith Yamasani742a6712011-05-04 14:49:28 -07003239 null, null, 0, null, null, null, false, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003240 } catch (RemoteException e) {
3241 }
3242 } finally {
3243 Binder.restoreCallingIdentity(callingId);
3244 }
3245 return true;
3246 }
3247
Dianne Hackborn03abb812010-01-04 18:43:19 -08003248 public void killBackgroundProcesses(final String packageName) {
3249 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3250 != PackageManager.PERMISSION_GRANTED &&
3251 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES)
3252 != PackageManager.PERMISSION_GRANTED) {
3253 String msg = "Permission Denial: killBackgroundProcesses() from pid="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003254 + Binder.getCallingPid()
3255 + ", uid=" + Binder.getCallingUid()
Dianne Hackborn03abb812010-01-04 18:43:19 -08003256 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003257 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003258 throw new SecurityException(msg);
3259 }
3260
3261 long callingId = Binder.clearCallingIdentity();
3262 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003263 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003264 int pkgUid = -1;
3265 synchronized(this) {
3266 try {
3267 pkgUid = pm.getPackageUid(packageName);
3268 } catch (RemoteException e) {
3269 }
3270 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003271 Slog.w(TAG, "Invalid packageName: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003272 return;
3273 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003274 killPackageProcessesLocked(packageName, pkgUid,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003275 ProcessList.SERVICE_ADJ, false, true, true, false, "kill background");
3276 }
3277 } finally {
3278 Binder.restoreCallingIdentity(callingId);
3279 }
3280 }
3281
3282 public void killAllBackgroundProcesses() {
3283 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3284 != PackageManager.PERMISSION_GRANTED) {
3285 String msg = "Permission Denial: killAllBackgroundProcesses() from pid="
3286 + Binder.getCallingPid()
3287 + ", uid=" + Binder.getCallingUid()
3288 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
3289 Slog.w(TAG, msg);
3290 throw new SecurityException(msg);
3291 }
3292
3293 long callingId = Binder.clearCallingIdentity();
3294 try {
3295 synchronized(this) {
3296 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
3297 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3298 final int NA = apps.size();
3299 for (int ia=0; ia<NA; ia++) {
3300 ProcessRecord app = apps.valueAt(ia);
3301 if (app.persistent) {
3302 // we don't kill persistent processes
3303 continue;
3304 }
3305 if (app.removed) {
3306 procs.add(app);
3307 } else if (app.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
3308 app.removed = true;
3309 procs.add(app);
3310 }
3311 }
3312 }
3313
3314 int N = procs.size();
3315 for (int i=0; i<N; i++) {
3316 removeProcessLocked(procs.get(i), false, true, "kill all background");
3317 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003318 }
3319 } finally {
3320 Binder.restoreCallingIdentity(callingId);
3321 }
3322 }
3323
3324 public void forceStopPackage(final String packageName) {
3325 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3326 != PackageManager.PERMISSION_GRANTED) {
3327 String msg = "Permission Denial: forceStopPackage() from pid="
3328 + Binder.getCallingPid()
3329 + ", uid=" + Binder.getCallingUid()
3330 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003331 Slog.w(TAG, msg);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003332 throw new SecurityException(msg);
3333 }
Amith Yamasani742a6712011-05-04 14:49:28 -07003334 final int userId = Binder.getOrigCallingUser();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003335 long callingId = Binder.clearCallingIdentity();
3336 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003337 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003338 int pkgUid = -1;
3339 synchronized(this) {
3340 try {
3341 pkgUid = pm.getPackageUid(packageName);
Amith Yamasani742a6712011-05-04 14:49:28 -07003342 // Convert the uid to the one for the calling user
3343 pkgUid = UserId.getUid(userId, pkgUid);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003344 } catch (RemoteException e) {
3345 }
3346 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003347 Slog.w(TAG, "Invalid packageName: " + packageName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003348 return;
3349 }
3350 forceStopPackageLocked(packageName, pkgUid);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003351 try {
3352 pm.setPackageStoppedState(packageName, true);
3353 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08003354 } catch (IllegalArgumentException e) {
3355 Slog.w(TAG, "Failed trying to unstop package "
3356 + packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003357 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003358 }
3359 } finally {
3360 Binder.restoreCallingIdentity(callingId);
3361 }
3362 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003363
3364 /*
3365 * The pkg name and uid have to be specified.
3366 * @see android.app.IActivityManager#killApplicationWithUid(java.lang.String, int)
3367 */
3368 public void killApplicationWithUid(String pkg, int uid) {
3369 if (pkg == null) {
3370 return;
3371 }
3372 // Make sure the uid is valid.
3373 if (uid < 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003374 Slog.w(TAG, "Invalid uid specified for pkg : " + pkg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003375 return;
3376 }
3377 int callerUid = Binder.getCallingUid();
3378 // Only the system server can kill an application
3379 if (callerUid == Process.SYSTEM_UID) {
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07003380 // Post an aysnc message to kill the application
3381 Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG);
3382 msg.arg1 = uid;
3383 msg.arg2 = 0;
3384 msg.obj = pkg;
Suchi Amalapurapud50066f2009-08-18 16:57:41 -07003385 mHandler.sendMessage(msg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003386 } else {
3387 throw new SecurityException(callerUid + " cannot kill pkg: " +
3388 pkg);
3389 }
3390 }
3391
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003392 public void closeSystemDialogs(String reason) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003393 enforceNotIsolatedCaller("closeSystemDialogs");
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003394 Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003395 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003396 if (reason != null) {
3397 intent.putExtra("reason", reason);
3398 }
3399
3400 final int uid = Binder.getCallingUid();
3401 final long origId = Binder.clearCallingIdentity();
3402 synchronized (this) {
Dianne Hackbornffa42482009-09-23 22:20:11 -07003403 mWindowManager.closeSystemDialogs(reason);
3404
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08003405 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003406 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornffa42482009-09-23 22:20:11 -07003407 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003408 r.stack.finishActivityLocked(r, i,
Dianne Hackbornffa42482009-09-23 22:20:11 -07003409 Activity.RESULT_CANCELED, null, "close-sys");
3410 }
3411 }
3412
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003413 broadcastIntentLocked(null, null, intent, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07003414 null, 0, null, null, null, false, false, -1, uid, 0 /* TODO: Verify */);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003415 }
3416 Binder.restoreCallingIdentity(origId);
3417 }
3418
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003419 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids)
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003420 throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003421 enforceNotIsolatedCaller("getProcessMemoryInfo");
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003422 Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length];
3423 for (int i=pids.length-1; i>=0; i--) {
3424 infos[i] = new Debug.MemoryInfo();
3425 Debug.getMemoryInfo(pids[i], infos[i]);
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003426 }
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003427 return infos;
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003428 }
Christopher Tate5e1ab332009-09-01 20:32:49 -07003429
Dianne Hackbornb437e092011-08-05 17:50:29 -07003430 public long[] getProcessPss(int[] pids) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003431 enforceNotIsolatedCaller("getProcessPss");
Dianne Hackbornb437e092011-08-05 17:50:29 -07003432 long[] pss = new long[pids.length];
3433 for (int i=pids.length-1; i>=0; i--) {
3434 pss[i] = Debug.getPss(pids[i]);
3435 }
3436 return pss;
3437 }
3438
Christopher Tate5e1ab332009-09-01 20:32:49 -07003439 public void killApplicationProcess(String processName, int uid) {
3440 if (processName == null) {
3441 return;
3442 }
3443
3444 int callerUid = Binder.getCallingUid();
3445 // Only the system server can kill an application
3446 if (callerUid == Process.SYSTEM_UID) {
3447 synchronized (this) {
3448 ProcessRecord app = getProcessRecordLocked(processName, uid);
Christopher Tate4a627c72011-04-01 14:43:32 -07003449 if (app != null && app.thread != null) {
Christopher Tate5e1ab332009-09-01 20:32:49 -07003450 try {
3451 app.thread.scheduleSuicide();
3452 } catch (RemoteException e) {
3453 // If the other end already died, then our work here is done.
3454 }
3455 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003456 Slog.w(TAG, "Process/uid not found attempting kill of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07003457 + processName + " / " + uid);
3458 }
3459 }
3460 } else {
3461 throw new SecurityException(callerUid + " cannot kill app process: " +
3462 processName);
3463 }
3464 }
3465
Dianne Hackborn03abb812010-01-04 18:43:19 -08003466 private void forceStopPackageLocked(final String packageName, int uid) {
Christopher Tate3dacd842011-08-19 14:56:15 -07003467 forceStopPackageLocked(packageName, uid, false, false, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003468 Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED,
3469 Uri.fromParts("package", packageName, null));
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003470 if (!mProcessesReady) {
3471 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3472 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003473 intent.putExtra(Intent.EXTRA_UID, uid);
3474 broadcastIntentLocked(null, null, intent,
3475 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07003476 false, false,
3477 MY_PID, Process.SYSTEM_UID, UserId.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003478 }
3479
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003480 private final boolean killPackageProcessesLocked(String packageName, int uid,
Christopher Tate3dacd842011-08-19 14:56:15 -07003481 int minOomAdj, boolean callerWillRestart, boolean allowRestart, boolean doit,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003482 boolean evenPersistent, String reason) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003483 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003484
Dianne Hackborn03abb812010-01-04 18:43:19 -08003485 // Remove all processes this package may have touched: all with the
3486 // same UID (except for the system or root user), and all whose name
3487 // matches the package name.
3488 final String procNamePrefix = packageName + ":";
3489 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3490 final int NA = apps.size();
3491 for (int ia=0; ia<NA; ia++) {
3492 ProcessRecord app = apps.valueAt(ia);
Christopher Tate3dacd842011-08-19 14:56:15 -07003493 if (app.persistent && !evenPersistent) {
Christopher Tate064d8422011-07-26 15:38:07 -07003494 // we don't kill persistent processes
3495 continue;
3496 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003497 if (app.removed) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003498 if (doit) {
3499 procs.add(app);
3500 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003501 } else if ((uid > 0 && uid != Process.SYSTEM_UID && app.info.uid == uid)
3502 || app.processName.equals(packageName)
3503 || app.processName.startsWith(procNamePrefix)) {
3504 if (app.setAdj >= minOomAdj) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003505 if (!doit) {
3506 return true;
3507 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003508 app.removed = true;
3509 procs.add(app);
3510 }
3511 }
3512 }
3513 }
3514
3515 int N = procs.size();
3516 for (int i=0; i<N; i++) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003517 removeProcessLocked(procs.get(i), callerWillRestart, allowRestart, reason);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003518 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003519 return N > 0;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003520 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003521
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003522 private final boolean forceStopPackageLocked(String name, int uid,
Christopher Tate3dacd842011-08-19 14:56:15 -07003523 boolean callerWillRestart, boolean purgeCache, boolean doit,
3524 boolean evenPersistent) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003525 int i;
3526 int N;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003527
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003528 if (uid < 0) {
3529 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003530 uid = AppGlobals.getPackageManager().getPackageUid(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003531 } catch (RemoteException e) {
3532 }
3533 }
3534
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003535 if (doit) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003536 Slog.i(TAG, "Force stopping package " + name + " uid=" + uid);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003537
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003538 Iterator<SparseArray<Long>> badApps = mProcessCrashTimes.getMap().values().iterator();
3539 while (badApps.hasNext()) {
3540 SparseArray<Long> ba = badApps.next();
3541 if (ba.get(uid) != null) {
3542 badApps.remove();
3543 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003544 }
3545 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003546
3547 boolean didSomething = killPackageProcessesLocked(name, uid, -100,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003548 callerWillRestart, false, doit, evenPersistent, "force stop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003549
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003550 TaskRecord lastTask = null;
3551 for (i=0; i<mMainStack.mHistory.size(); i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003552 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003553 final boolean samePackage = r.packageName.equals(name);
3554 if ((samePackage || r.task == lastTask)
Christopher Tate3dacd842011-08-19 14:56:15 -07003555 && (r.app == null || evenPersistent || !r.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003556 if (!doit) {
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003557 if (r.finishing) {
3558 // If this activity is just finishing, then it is not
3559 // interesting as far as something to stop.
3560 continue;
3561 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003562 return true;
3563 }
3564 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003565 Slog.i(TAG, " Force finishing activity " + r);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003566 if (samePackage) {
3567 if (r.app != null) {
3568 r.app.removed = true;
3569 }
3570 r.app = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003571 }
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003572 lastTask = r.task;
3573 if (r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
3574 null, "force-stop")) {
3575 i--;
3576 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003577 }
3578 }
3579
3580 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
Amith Yamasani742a6712011-05-04 14:49:28 -07003581 int userId = UserId.getUserId(uid);
3582 for (ServiceRecord service : mServiceMap.getAllServices(userId)) {
Christopher Tate064d8422011-07-26 15:38:07 -07003583 if (service.packageName.equals(name)
Christopher Tate3dacd842011-08-19 14:56:15 -07003584 && (service.app == null || evenPersistent || !service.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003585 if (!doit) {
3586 return true;
3587 }
3588 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003589 Slog.i(TAG, " Force stopping service " + service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003590 if (service.app != null) {
3591 service.app.removed = true;
3592 }
3593 service.app = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003594 service.isolatedProc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003595 services.add(service);
3596 }
3597 }
3598
3599 N = services.size();
3600 for (i=0; i<N; i++) {
3601 bringDownServiceLocked(services.get(i), true);
3602 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003603
3604 ArrayList<ContentProviderRecord> providers = new ArrayList<ContentProviderRecord>();
Amith Yamasani37ce3a82012-02-06 12:04:42 -08003605 for (ContentProviderRecord provider : mProviderMap.getProvidersByClass(-1).values()) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003606 if (provider.info.packageName.equals(name)
3607 && (provider.proc == null || evenPersistent || !provider.proc.persistent)) {
3608 if (!doit) {
3609 return true;
3610 }
3611 didSomething = true;
3612 providers.add(provider);
3613 }
3614 }
3615
3616 N = providers.size();
3617 for (i=0; i<N; i++) {
3618 removeDyingProviderLocked(null, providers.get(i));
3619 }
3620
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003621 if (doit) {
3622 if (purgeCache) {
3623 AttributeCache ac = AttributeCache.instance();
3624 if (ac != null) {
3625 ac.removePackage(name);
3626 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003627 }
Dianne Hackborn38cc8962011-10-13 11:33:55 -07003628 if (mBooted) {
3629 mMainStack.resumeTopActivityLocked(null);
3630 mMainStack.scheduleIdleLocked();
3631 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003632 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003633
3634 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003635 }
3636
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003637 private final boolean removeProcessLocked(ProcessRecord app,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003638 boolean callerWillRestart, boolean allowRestart, String reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003639 final String name = app.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003640 final int uid = app.uid;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003641 if (DEBUG_PROCESSES) Slog.d(
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003642 TAG, "Force removing proc " + app.toShortString() + " (" + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003643 + "/" + uid + ")");
3644
3645 mProcessNames.remove(name, uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003646 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003647 if (mHeavyWeightProcess == app) {
3648 mHeavyWeightProcess = null;
3649 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3650 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003651 boolean needRestart = false;
3652 if (app.pid > 0 && app.pid != MY_PID) {
3653 int pid = app.pid;
3654 synchronized (mPidsSelfLocked) {
3655 mPidsSelfLocked.remove(pid);
3656 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3657 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003658 Slog.i(TAG, "Killing proc " + app.toShortString() + ": " + reason);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003659 handleAppDiedLocked(app, true, allowRestart);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003660 mLruProcesses.remove(app);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003661 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003662
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003663 if (app.persistent && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003664 if (!callerWillRestart) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003665 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003666 } else {
3667 needRestart = true;
3668 }
3669 }
3670 } else {
3671 mRemovedProcesses.add(app);
3672 }
3673
3674 return needRestart;
3675 }
3676
3677 private final void processStartTimedOutLocked(ProcessRecord app) {
3678 final int pid = app.pid;
3679 boolean gone = false;
3680 synchronized (mPidsSelfLocked) {
3681 ProcessRecord knownApp = mPidsSelfLocked.get(pid);
3682 if (knownApp != null && knownApp.thread == null) {
3683 mPidsSelfLocked.remove(pid);
3684 gone = true;
3685 }
3686 }
3687
3688 if (gone) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003689 Slog.w(TAG, "Process " + app + " failed to attach");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003690 EventLog.writeEvent(EventLogTags.AM_PROCESS_START_TIMEOUT, pid, app.uid,
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003691 app.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003692 mProcessNames.remove(app.processName, app.uid);
3693 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003694 if (mHeavyWeightProcess == app) {
3695 mHeavyWeightProcess = null;
3696 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3697 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003698 // Take care of any launching providers waiting for this process.
3699 checkAppInLaunchingProvidersLocked(app, true);
3700 // Take care of any services that are waiting for the process.
3701 for (int i=0; i<mPendingServices.size(); i++) {
3702 ServiceRecord sr = mPendingServices.get(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003703 if ((app.uid == sr.appInfo.uid
3704 && app.processName.equals(sr.processName))
3705 || sr.isolatedProc == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003706 Slog.w(TAG, "Forcing bringing down service: " + sr);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003707 sr.isolatedProc = null;
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003708 mPendingServices.remove(i);
3709 i--;
3710 bringDownServiceLocked(sr, true);
3711 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003712 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003713 EventLog.writeEvent(EventLogTags.AM_KILL, pid,
3714 app.processName, app.setAdj, "start timeout");
3715 Process.killProcessQuiet(pid);
Christopher Tate181fafa2009-05-14 11:12:14 -07003716 if (mBackupTarget != null && mBackupTarget.app.pid == pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003717 Slog.w(TAG, "Unattached app died before backup, skipping");
Christopher Tate181fafa2009-05-14 11:12:14 -07003718 try {
3719 IBackupManager bm = IBackupManager.Stub.asInterface(
3720 ServiceManager.getService(Context.BACKUP_SERVICE));
3721 bm.agentDisconnected(app.info.packageName);
3722 } catch (RemoteException e) {
3723 // Can't happen; the backup manager is local
3724 }
3725 }
Christopher Tatef46723b2012-01-26 14:19:24 -08003726 if (isPendingBroadcastProcessLocked(pid)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003727 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
Christopher Tatef46723b2012-01-26 14:19:24 -08003728 skipPendingBroadcastLocked(pid);
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003729 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003730 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003731 Slog.w(TAG, "Spurious process start timeout - pid not known for " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003732 }
3733 }
3734
3735 private final boolean attachApplicationLocked(IApplicationThread thread,
3736 int pid) {
3737
3738 // Find the application record that is being attached... either via
3739 // the pid if we are running in multiple processes, or just pull the
3740 // next app record if we are emulating process with anonymous threads.
3741 ProcessRecord app;
3742 if (pid != MY_PID && pid >= 0) {
3743 synchronized (mPidsSelfLocked) {
3744 app = mPidsSelfLocked.get(pid);
3745 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003746 } else {
3747 app = null;
3748 }
3749
3750 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003751 Slog.w(TAG, "No pending application record for pid " + pid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003752 + " (IApplicationThread " + thread + "); dropping process");
Doug Zongker2bec3d42009-12-04 12:52:44 -08003753 EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003754 if (pid > 0 && pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003755 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003756 } else {
3757 try {
3758 thread.scheduleExit();
3759 } catch (Exception e) {
3760 // Ignore exceptions.
3761 }
3762 }
3763 return false;
3764 }
3765
3766 // If this application record is still attached to a previous
3767 // process, clean it up now.
3768 if (app.thread != null) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003769 handleAppDiedLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003770 }
3771
3772 // Tell the process all about itself.
3773
Joe Onorato8a9b2202010-02-26 18:56:32 -08003774 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003775 TAG, "Binding process pid " + pid + " to record " + app);
3776
3777 String processName = app.processName;
3778 try {
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07003779 AppDeathRecipient adr = new AppDeathRecipient(
3780 app, pid, thread);
3781 thread.asBinder().linkToDeath(adr, 0);
3782 app.deathRecipient = adr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003783 } catch (RemoteException e) {
3784 app.resetPackageList();
3785 startProcessLocked(app, "link fail", processName);
3786 return false;
3787 }
3788
Doug Zongker2bec3d42009-12-04 12:52:44 -08003789 EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.pid, app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003790
3791 app.thread = thread;
3792 app.curAdj = app.setAdj = -100;
Dianne Hackborn09c916b2009-12-08 14:50:51 -08003793 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
3794 app.setSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003795 app.forcingToForeground = null;
3796 app.foregroundServices = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07003797 app.hasShownUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003798 app.debugging = false;
3799
3800 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3801
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003802 boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003803 List providers = normalMode ? generateApplicationProvidersLocked(app) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003804
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003805 if (!normalMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003806 Slog.i(TAG, "Launching preboot mode app: " + app);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003807 }
3808
Joe Onorato8a9b2202010-02-26 18:56:32 -08003809 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003810 TAG, "New app record " + app
3811 + " thread=" + thread.asBinder() + " pid=" + pid);
3812 try {
3813 int testMode = IApplicationThread.DEBUG_OFF;
3814 if (mDebugApp != null && mDebugApp.equals(processName)) {
3815 testMode = mWaitForDebugger
3816 ? IApplicationThread.DEBUG_WAIT
3817 : IApplicationThread.DEBUG_ON;
3818 app.debugging = true;
3819 if (mDebugTransient) {
3820 mDebugApp = mOrigDebugApp;
3821 mWaitForDebugger = mOrigWaitForDebugger;
3822 }
3823 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003824 String profileFile = app.instrumentationProfileFile;
3825 ParcelFileDescriptor profileFd = null;
3826 boolean profileAutoStop = false;
3827 if (mProfileApp != null && mProfileApp.equals(processName)) {
3828 mProfileProc = app;
3829 profileFile = mProfileFile;
3830 profileFd = mProfileFd;
3831 profileAutoStop = mAutoStopProfiler;
3832 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08003833 boolean enableOpenGlTrace = false;
3834 if (mOpenGlTraceApp != null && mOpenGlTraceApp.equals(processName)) {
3835 enableOpenGlTrace = true;
3836 mOpenGlTraceApp = null;
3837 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003838
Christopher Tate181fafa2009-05-14 11:12:14 -07003839 // If the app is being launched for restore or full backup, set it up specially
3840 boolean isRestrictedBackupMode = false;
3841 if (mBackupTarget != null && mBackupAppName.equals(processName)) {
3842 isRestrictedBackupMode = (mBackupTarget.backupMode == BackupRecord.RESTORE)
Christopher Tate75a99702011-05-18 16:28:19 -07003843 || (mBackupTarget.backupMode == BackupRecord.RESTORE_FULL)
Christopher Tate181fafa2009-05-14 11:12:14 -07003844 || (mBackupTarget.backupMode == BackupRecord.BACKUP_FULL);
3845 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003846
Dianne Hackbornd7f6daa2009-06-22 17:06:35 -07003847 ensurePackageDexOpt(app.instrumentationInfo != null
3848 ? app.instrumentationInfo.packageName
3849 : app.info.packageName);
3850 if (app.instrumentationClass != null) {
3851 ensurePackageDexOpt(app.instrumentationClass.getPackageName());
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003852 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08003853 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Binding proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003854 + processName + " with config " + mConfiguration);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003855 ApplicationInfo appInfo = app.instrumentationInfo != null
3856 ? app.instrumentationInfo : app.info;
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -07003857 app.compat = compatibilityInfoForPackageLocked(appInfo);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003858 if (profileFd != null) {
3859 profileFd = profileFd.dup();
3860 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003861 thread.bindApplication(processName, appInfo, providers,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003862 app.instrumentationClass, profileFile, profileFd, profileAutoStop,
Siva Velusamy92a8b222012-03-09 16:24:04 -08003863 app.instrumentationArguments, app.instrumentationWatcher, testMode,
3864 enableOpenGlTrace, isRestrictedBackupMode || !normalMode, app.persistent,
Dianne Hackborn813075a62011-11-14 17:45:19 -08003865 new Configuration(mConfiguration), app.compat, getCommonServicesLocked(),
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08003866 mCoreSettingsObserver.getCoreSettingsLocked());
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003867 updateLruProcessLocked(app, false, true);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003868 app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003869 } catch (Exception e) {
3870 // todo: Yikes! What should we do? For now we will try to
3871 // start another process, but that could easily get us in
3872 // an infinite loop of restarting processes...
Joe Onorato8a9b2202010-02-26 18:56:32 -08003873 Slog.w(TAG, "Exception thrown during bind!", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003874
3875 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07003876 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003877 startProcessLocked(app, "bind fail", processName);
3878 return false;
3879 }
3880
3881 // Remove this record from the list of starting applications.
3882 mPersistentStartingProcesses.remove(app);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003883 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
3884 "Attach application locked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003885 mProcessesOnHold.remove(app);
3886
3887 boolean badApp = false;
3888 boolean didSomething = false;
3889
3890 // See if the top visible activity is waiting to run in this process...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003891 ActivityRecord hr = mMainStack.topRunningActivityLocked(null);
Christopher Tate04c0af82010-06-07 18:35:20 -07003892 if (hr != null && normalMode) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003893 if (hr.app == null && app.uid == hr.info.applicationInfo.uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003894 && processName.equals(hr.processName)) {
3895 try {
Mike Lockwood3a74bd32011-08-12 13:55:22 -07003896 if (mHeadless) {
3897 Slog.e(TAG, "Starting activities not supported on headless device: " + hr);
3898 } else if (mMainStack.realStartActivityLocked(hr, app, true, true)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003899 didSomething = true;
3900 }
3901 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003902 Slog.w(TAG, "Exception in new application when starting activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003903 + hr.intent.getComponent().flattenToShortString(), e);
3904 badApp = true;
3905 }
3906 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003907 mMainStack.ensureActivitiesVisibleLocked(hr, null, processName, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003908 }
3909 }
3910
3911 // Find any services that should be running in this process...
3912 if (!badApp && mPendingServices.size() > 0) {
3913 ServiceRecord sr = null;
3914 try {
3915 for (int i=0; i<mPendingServices.size(); i++) {
3916 sr = mPendingServices.get(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003917 if (app != sr.isolatedProc && (app.uid != sr.appInfo.uid
3918 || !processName.equals(sr.processName))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003919 continue;
3920 }
3921
3922 mPendingServices.remove(i);
3923 i--;
3924 realStartServiceLocked(sr, app);
3925 didSomething = true;
3926 }
3927 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003928 Slog.w(TAG, "Exception in new application when starting service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003929 + sr.shortName, e);
3930 badApp = true;
3931 }
3932 }
3933
Christopher Tatef46723b2012-01-26 14:19:24 -08003934 // Check if a next-broadcast receiver is in this process...
3935 if (!badApp && isPendingBroadcastProcessLocked(pid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003936 try {
Christopher Tatef46723b2012-01-26 14:19:24 -08003937 didSomething = sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003938 } catch (Exception e) {
Christopher Tatef46723b2012-01-26 14:19:24 -08003939 // If the app died trying to launch the receiver we declare it 'bad'
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003940 badApp = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003941 }
3942 }
3943
Christopher Tate181fafa2009-05-14 11:12:14 -07003944 // Check whether the next backup agent is in this process...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003945 if (!badApp && mBackupTarget != null && mBackupTarget.appInfo.uid == app.uid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003946 if (DEBUG_BACKUP) Slog.v(TAG, "New app is backup target, launching agent for " + app);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003947 ensurePackageDexOpt(mBackupTarget.appInfo.packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07003948 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003949 thread.scheduleCreateBackupAgent(mBackupTarget.appInfo,
3950 compatibilityInfoForPackageLocked(mBackupTarget.appInfo),
3951 mBackupTarget.backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -07003952 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003953 Slog.w(TAG, "Exception scheduling backup agent creation: ");
Christopher Tate181fafa2009-05-14 11:12:14 -07003954 e.printStackTrace();
3955 }
3956 }
3957
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003958 if (badApp) {
3959 // todo: Also need to kill application to deal with all
3960 // kinds of exceptions.
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003961 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003962 return false;
3963 }
3964
3965 if (!didSomething) {
3966 updateOomAdjLocked();
3967 }
3968
3969 return true;
3970 }
3971
3972 public final void attachApplication(IApplicationThread thread) {
3973 synchronized (this) {
3974 int callingPid = Binder.getCallingPid();
3975 final long origId = Binder.clearCallingIdentity();
3976 attachApplicationLocked(thread, callingPid);
3977 Binder.restoreCallingIdentity(origId);
3978 }
3979 }
3980
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003981 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003982 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003983 ActivityRecord r = mMainStack.activityIdleInternal(token, false, config);
3984 if (stopProfiling) {
3985 synchronized (this) {
3986 if (mProfileProc == r.app) {
3987 if (mProfileFd != null) {
3988 try {
3989 mProfileFd.close();
3990 } catch (IOException e) {
3991 }
3992 clearProfilerLocked();
3993 }
3994 }
3995 }
3996 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003997 Binder.restoreCallingIdentity(origId);
3998 }
3999
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004000 void enableScreenAfterBoot() {
Doug Zongker2bec3d42009-12-04 12:52:44 -08004001 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004002 SystemClock.uptimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004003 mWindowManager.enableScreenAfterBoot();
4004 }
4005
Dianne Hackborn661cd522011-08-22 00:26:20 -07004006 public void showBootMessage(final CharSequence msg, final boolean always) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004007 enforceNotIsolatedCaller("showBootMessage");
Dianne Hackborn661cd522011-08-22 00:26:20 -07004008 mWindowManager.showBootMessage(msg, always);
4009 }
4010
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004011 public void dismissKeyguardOnNextActivity() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004012 enforceNotIsolatedCaller("dismissKeyguardOnNextActivity");
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004013 synchronized (this) {
4014 mMainStack.dismissKeyguardOnNextActivityLocked();
4015 }
4016 }
4017
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004018 final void finishBooting() {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004019 IntentFilter pkgFilter = new IntentFilter();
4020 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
4021 pkgFilter.addDataScheme("package");
4022 mContext.registerReceiver(new BroadcastReceiver() {
4023 @Override
4024 public void onReceive(Context context, Intent intent) {
4025 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
4026 if (pkgs != null) {
4027 for (String pkg : pkgs) {
Vairavan Srinivasan61f07652010-07-22 13:36:40 -07004028 synchronized (ActivityManagerService.this) {
Christopher Tate3dacd842011-08-19 14:56:15 -07004029 if (forceStopPackageLocked(pkg, -1, false, false, false, false)) {
Vairavan Srinivasan61f07652010-07-22 13:36:40 -07004030 setResultCode(Activity.RESULT_OK);
4031 return;
4032 }
4033 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004034 }
4035 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004036 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004037 }, pkgFilter);
4038
4039 synchronized (this) {
4040 // Ensure that any processes we had put on hold are now started
4041 // up.
4042 final int NP = mProcessesOnHold.size();
4043 if (NP > 0) {
4044 ArrayList<ProcessRecord> procs =
4045 new ArrayList<ProcessRecord>(mProcessesOnHold);
4046 for (int ip=0; ip<NP; ip++) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004047 if (DEBUG_PROCESSES) Slog.v(TAG, "Starting process on hold: "
4048 + procs.get(ip));
4049 startProcessLocked(procs.get(ip), "on-hold", null);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004050 }
4051 }
4052
4053 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004054 // Start looking for apps that are abusing wake locks.
4055 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07004056 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004057 // Tell anyone interested that we are done booting!
Dianne Hackbornf4c454b2010-08-11 12:47:41 -07004058 SystemProperties.set("sys.boot_completed", "1");
Guang Zhu191713a2012-01-12 12:02:22 -08004059 SystemProperties.set("dev.bootcomplete", "1");
Amith Yamasani742a6712011-05-04 14:49:28 -07004060 /* TODO: Send this to all users that are to be logged in on startup */
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004061 broadcastIntentLocked(null, null,
4062 new Intent(Intent.ACTION_BOOT_COMPLETED, null),
4063 null, null, 0, null, null,
4064 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
Amith Yamasani742a6712011-05-04 14:49:28 -07004065 false, false, MY_PID, Process.SYSTEM_UID, Binder.getOrigCallingUser());
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004066 }
4067 }
4068 }
4069
4070 final void ensureBootCompleted() {
4071 boolean booting;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004072 boolean enableScreen;
4073 synchronized (this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004074 booting = mBooting;
4075 mBooting = false;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004076 enableScreen = !mBooted;
4077 mBooted = true;
4078 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004079
4080 if (booting) {
4081 finishBooting();
4082 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004083
4084 if (enableScreen) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004085 enableScreenAfterBoot();
4086 }
4087 }
4088
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004089 public final void activityPaused(IBinder token) {
4090 final long origId = Binder.clearCallingIdentity();
4091 mMainStack.activityPaused(token, false);
4092 Binder.restoreCallingIdentity(origId);
4093 }
4094
4095 public final void activityStopped(IBinder token, Bundle icicle, Bitmap thumbnail,
4096 CharSequence description) {
4097 if (localLOGV) Slog.v(
4098 TAG, "Activity stopped: token=" + token);
4099
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004100 // Refuse possible leaked file descriptors
4101 if (icicle != null && icicle.hasFileDescriptors()) {
4102 throw new IllegalArgumentException("File descriptors passed in Bundle");
4103 }
4104
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004105 ActivityRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004106
4107 final long origId = Binder.clearCallingIdentity();
4108
4109 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004110 r = mMainStack.isInStackLocked(token);
4111 if (r != null) {
4112 r.stack.activityStoppedLocked(r, icicle, thumbnail, description);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004113 }
4114 }
4115
4116 if (r != null) {
4117 sendPendingThumbnail(r, null, null, null, false);
4118 }
4119
4120 trimApplications();
4121
4122 Binder.restoreCallingIdentity(origId);
4123 }
4124
4125 public final void activityDestroyed(IBinder token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004126 if (DEBUG_SWITCH) Slog.v(TAG, "ACTIVITY DESTROYED: " + token);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004127 mMainStack.activityDestroyed(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004128 }
4129
4130 public String getCallingPackage(IBinder token) {
4131 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004132 ActivityRecord r = getCallingRecordLocked(token);
Dianne Hackborn9bbcb912009-10-20 15:42:38 -07004133 return r != null && r.app != null ? r.info.packageName : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004134 }
4135 }
4136
4137 public ComponentName getCallingActivity(IBinder token) {
4138 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004139 ActivityRecord r = getCallingRecordLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004140 return r != null ? r.intent.getComponent() : null;
4141 }
4142 }
4143
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004144 private ActivityRecord getCallingRecordLocked(IBinder token) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004145 ActivityRecord r = mMainStack.isInStackLocked(token);
4146 if (r == null) {
4147 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004148 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004149 return r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004150 }
4151
4152 public ComponentName getActivityClassForToken(IBinder token) {
4153 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004154 ActivityRecord r = mMainStack.isInStackLocked(token);
4155 if (r == null) {
4156 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004157 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004158 return r.intent.getComponent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004159 }
4160 }
4161
4162 public String getPackageForToken(IBinder token) {
4163 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004164 ActivityRecord r = mMainStack.isInStackLocked(token);
4165 if (r == null) {
4166 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004167 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004168 return r.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004169 }
4170 }
4171
4172 public IIntentSender getIntentSender(int type,
4173 String packageName, IBinder token, String resultWho,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004174 int requestCode, Intent[] intents, String[] resolvedTypes, int flags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004175 enforceNotIsolatedCaller("getIntentSender");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004176 // Refuse possible leaked file descriptors
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004177 if (intents != null) {
4178 if (intents.length < 1) {
4179 throw new IllegalArgumentException("Intents array length must be >= 1");
4180 }
4181 for (int i=0; i<intents.length; i++) {
4182 Intent intent = intents[i];
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004183 if (intent != null) {
4184 if (intent.hasFileDescriptors()) {
4185 throw new IllegalArgumentException("File descriptors passed in Intent");
4186 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07004187 if (type == ActivityManager.INTENT_SENDER_BROADCAST &&
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004188 (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
4189 throw new IllegalArgumentException(
4190 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
4191 }
4192 intents[i] = new Intent(intent);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004193 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004194 }
4195 if (resolvedTypes != null && resolvedTypes.length != intents.length) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004196 throw new IllegalArgumentException(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004197 "Intent array length does not match resolvedTypes length");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004198 }
4199 }
4200
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004201 synchronized(this) {
4202 int callingUid = Binder.getCallingUid();
4203 try {
Jeff Brown10e89712011-07-08 18:52:57 -07004204 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004205 int uid = AppGlobals.getPackageManager()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004206 .getPackageUid(packageName);
Amith Yamasani742a6712011-05-04 14:49:28 -07004207 if (UserId.getAppId(callingUid) != uid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004208 String msg = "Permission Denial: getIntentSender() from pid="
4209 + Binder.getCallingPid()
4210 + ", uid=" + Binder.getCallingUid()
4211 + ", (need uid=" + uid + ")"
4212 + " is not allowed to send as package " + packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004213 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004214 throw new SecurityException(msg);
4215 }
4216 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004217
Amith Yamasani742a6712011-05-04 14:49:28 -07004218 if (DEBUG_MU)
4219 Slog.i(TAG_MU, "Getting intent sender for origCallingUid="
4220 + Binder.getOrigCallingUid());
4221 return getIntentSenderLocked(type, packageName, Binder.getOrigCallingUid(),
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004222 token, resultWho, requestCode, intents, resolvedTypes, flags);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004223
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004224 } catch (RemoteException e) {
4225 throw new SecurityException(e);
4226 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004227 }
4228 }
4229
4230 IIntentSender getIntentSenderLocked(int type,
4231 String packageName, int callingUid, IBinder token, String resultWho,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004232 int requestCode, Intent[] intents, String[] resolvedTypes, int flags) {
Amith Yamasani742a6712011-05-04 14:49:28 -07004233 if (DEBUG_MU)
4234 Slog.v(TAG_MU, "getIntentSenderLocked(): uid=" + callingUid);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004235 ActivityRecord activity = null;
Dianne Hackborna4972e92012-03-14 10:38:05 -07004236 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004237 activity = mMainStack.isInStackLocked(token);
4238 if (activity == null) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004239 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004240 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004241 if (activity.finishing) {
4242 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004243 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004244 }
4245
4246 final boolean noCreate = (flags&PendingIntent.FLAG_NO_CREATE) != 0;
4247 final boolean cancelCurrent = (flags&PendingIntent.FLAG_CANCEL_CURRENT) != 0;
4248 final boolean updateCurrent = (flags&PendingIntent.FLAG_UPDATE_CURRENT) != 0;
4249 flags &= ~(PendingIntent.FLAG_NO_CREATE|PendingIntent.FLAG_CANCEL_CURRENT
4250 |PendingIntent.FLAG_UPDATE_CURRENT);
4251
4252 PendingIntentRecord.Key key = new PendingIntentRecord.Key(
4253 type, packageName, activity, resultWho,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004254 requestCode, intents, resolvedTypes, flags);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004255 WeakReference<PendingIntentRecord> ref;
4256 ref = mIntentSenderRecords.get(key);
4257 PendingIntentRecord rec = ref != null ? ref.get() : null;
4258 if (rec != null) {
4259 if (!cancelCurrent) {
4260 if (updateCurrent) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004261 if (rec.key.requestIntent != null) {
4262 rec.key.requestIntent.replaceExtras(intents != null ? intents[0] : null);
4263 }
4264 if (intents != null) {
4265 intents[intents.length-1] = rec.key.requestIntent;
4266 rec.key.allIntents = intents;
4267 rec.key.allResolvedTypes = resolvedTypes;
4268 } else {
4269 rec.key.allIntents = null;
4270 rec.key.allResolvedTypes = null;
4271 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004272 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004273 return rec;
4274 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004275 rec.canceled = true;
4276 mIntentSenderRecords.remove(key);
4277 }
4278 if (noCreate) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004279 return rec;
4280 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004281 rec = new PendingIntentRecord(this, key, callingUid);
4282 mIntentSenderRecords.put(key, rec.ref);
Dianne Hackborna4972e92012-03-14 10:38:05 -07004283 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004284 if (activity.pendingResults == null) {
4285 activity.pendingResults
4286 = new HashSet<WeakReference<PendingIntentRecord>>();
4287 }
4288 activity.pendingResults.add(rec.ref);
4289 }
4290 return rec;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004291 }
4292
4293 public void cancelIntentSender(IIntentSender sender) {
4294 if (!(sender instanceof PendingIntentRecord)) {
4295 return;
4296 }
4297 synchronized(this) {
4298 PendingIntentRecord rec = (PendingIntentRecord)sender;
4299 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004300 int uid = AppGlobals.getPackageManager()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004301 .getPackageUid(rec.key.packageName);
Amith Yamasani04e0d262012-02-14 11:50:53 -08004302 if (!UserId.isSameApp(uid, Binder.getCallingUid())) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004303 String msg = "Permission Denial: cancelIntentSender() from pid="
4304 + Binder.getCallingPid()
4305 + ", uid=" + Binder.getCallingUid()
4306 + " is not allowed to cancel packges "
4307 + rec.key.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004308 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004309 throw new SecurityException(msg);
4310 }
4311 } catch (RemoteException e) {
4312 throw new SecurityException(e);
4313 }
4314 cancelIntentSenderLocked(rec, true);
4315 }
4316 }
4317
4318 void cancelIntentSenderLocked(PendingIntentRecord rec, boolean cleanActivity) {
4319 rec.canceled = true;
4320 mIntentSenderRecords.remove(rec.key);
4321 if (cleanActivity && rec.key.activity != null) {
4322 rec.key.activity.pendingResults.remove(rec.ref);
4323 }
4324 }
4325
4326 public String getPackageForIntentSender(IIntentSender pendingResult) {
4327 if (!(pendingResult instanceof PendingIntentRecord)) {
4328 return null;
4329 }
Brad Fitzpatrickb213d102010-04-19 11:58:52 -07004330 try {
4331 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4332 return res.key.packageName;
4333 } catch (ClassCastException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004334 }
4335 return null;
4336 }
4337
Dianne Hackborn6c418d52011-06-29 14:05:33 -07004338 public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) {
4339 if (!(pendingResult instanceof PendingIntentRecord)) {
4340 return false;
4341 }
4342 try {
4343 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4344 if (res.key.allIntents == null) {
4345 return false;
4346 }
4347 for (int i=0; i<res.key.allIntents.length; i++) {
4348 Intent intent = res.key.allIntents[i];
4349 if (intent.getPackage() != null && intent.getComponent() != null) {
4350 return false;
4351 }
4352 }
4353 return true;
4354 } catch (ClassCastException e) {
4355 }
4356 return false;
4357 }
4358
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004359 public void setProcessLimit(int max) {
4360 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4361 "setProcessLimit()");
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004362 synchronized (this) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07004363 mProcessLimit = max < 0 ? ProcessList.MAX_HIDDEN_APPS : max;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004364 mProcessLimitOverride = max;
4365 }
4366 trimApplications();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004367 }
4368
4369 public int getProcessLimit() {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004370 synchronized (this) {
4371 return mProcessLimitOverride;
4372 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004373 }
4374
4375 void foregroundTokenDied(ForegroundToken token) {
4376 synchronized (ActivityManagerService.this) {
4377 synchronized (mPidsSelfLocked) {
4378 ForegroundToken cur
4379 = mForegroundProcesses.get(token.pid);
4380 if (cur != token) {
4381 return;
4382 }
4383 mForegroundProcesses.remove(token.pid);
4384 ProcessRecord pr = mPidsSelfLocked.get(token.pid);
4385 if (pr == null) {
4386 return;
4387 }
4388 pr.forcingToForeground = null;
4389 pr.foregroundServices = false;
4390 }
4391 updateOomAdjLocked();
4392 }
4393 }
4394
4395 public void setProcessForeground(IBinder token, int pid, boolean isForeground) {
4396 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4397 "setProcessForeground()");
4398 synchronized(this) {
4399 boolean changed = false;
4400
4401 synchronized (mPidsSelfLocked) {
4402 ProcessRecord pr = mPidsSelfLocked.get(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004403 if (pr == null && isForeground) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004404 Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004405 return;
4406 }
4407 ForegroundToken oldToken = mForegroundProcesses.get(pid);
4408 if (oldToken != null) {
4409 oldToken.token.unlinkToDeath(oldToken, 0);
4410 mForegroundProcesses.remove(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004411 if (pr != null) {
4412 pr.forcingToForeground = null;
4413 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004414 changed = true;
4415 }
4416 if (isForeground && token != null) {
4417 ForegroundToken newToken = new ForegroundToken() {
4418 public void binderDied() {
4419 foregroundTokenDied(this);
4420 }
4421 };
4422 newToken.pid = pid;
4423 newToken.token = token;
4424 try {
4425 token.linkToDeath(newToken, 0);
4426 mForegroundProcesses.put(pid, newToken);
4427 pr.forcingToForeground = token;
4428 changed = true;
4429 } catch (RemoteException e) {
4430 // If the process died while doing this, we will later
4431 // do the cleanup with the process death link.
4432 }
4433 }
4434 }
4435
4436 if (changed) {
4437 updateOomAdjLocked();
4438 }
4439 }
4440 }
4441
4442 // =========================================================
4443 // PERMISSIONS
4444 // =========================================================
4445
4446 static class PermissionController extends IPermissionController.Stub {
4447 ActivityManagerService mActivityManagerService;
4448 PermissionController(ActivityManagerService activityManagerService) {
4449 mActivityManagerService = activityManagerService;
4450 }
4451
4452 public boolean checkPermission(String permission, int pid, int uid) {
4453 return mActivityManagerService.checkPermission(permission, pid,
4454 uid) == PackageManager.PERMISSION_GRANTED;
4455 }
4456 }
4457
4458 /**
4459 * This can be called with or without the global lock held.
4460 */
4461 int checkComponentPermission(String permission, int pid, int uid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004462 int owningUid, boolean exported) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004463 // We might be performing an operation on behalf of an indirect binder
4464 // invocation, e.g. via {@link #openContentUri}. Check and adjust the
4465 // client identity accordingly before proceeding.
4466 Identity tlsIdentity = sCallerIdentity.get();
4467 if (tlsIdentity != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004468 Slog.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004469 + tlsIdentity.pid + "," + tlsIdentity.uid + "}");
4470 uid = tlsIdentity.uid;
4471 pid = tlsIdentity.pid;
4472 }
4473
4474 // Root, system server and our own process get to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07004475 if (uid == 0 || uid == Process.SYSTEM_UID || pid == MY_PID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004476 return PackageManager.PERMISSION_GRANTED;
4477 }
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004478 // Isolated processes don't get any permissions.
4479 if (UserId.isIsolated(uid)) {
4480 return PackageManager.PERMISSION_DENIED;
4481 }
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004482 // If there is a uid that owns whatever is being accessed, it has
4483 // blanket access to it regardless of the permissions it requires.
Amith Yamasani742a6712011-05-04 14:49:28 -07004484 if (owningUid >= 0 && UserId.isSameApp(uid, owningUid)) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004485 return PackageManager.PERMISSION_GRANTED;
4486 }
4487 // If the target is not exported, then nobody else can get to it.
4488 if (!exported) {
4489 Slog.w(TAG, "Permission denied: checkComponentPermission() owningUid=" + owningUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004490 return PackageManager.PERMISSION_DENIED;
4491 }
4492 if (permission == null) {
4493 return PackageManager.PERMISSION_GRANTED;
4494 }
4495 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004496 return AppGlobals.getPackageManager()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004497 .checkUidPermission(permission, uid);
4498 } catch (RemoteException e) {
4499 // Should never happen, but if it does... deny!
Joe Onorato8a9b2202010-02-26 18:56:32 -08004500 Slog.e(TAG, "PackageManager is dead?!?", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004501 }
4502 return PackageManager.PERMISSION_DENIED;
4503 }
4504
4505 /**
4506 * As the only public entry point for permissions checking, this method
4507 * can enforce the semantic that requesting a check on a null global
4508 * permission is automatically denied. (Internally a null permission
4509 * string is used when calling {@link #checkComponentPermission} in cases
4510 * when only uid-based security is needed.)
4511 *
4512 * This can be called with or without the global lock held.
4513 */
4514 public int checkPermission(String permission, int pid, int uid) {
4515 if (permission == null) {
4516 return PackageManager.PERMISSION_DENIED;
4517 }
Amith Yamasani742a6712011-05-04 14:49:28 -07004518 return checkComponentPermission(permission, pid, UserId.getAppId(uid), -1, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004519 }
4520
4521 /**
4522 * Binder IPC calls go through the public entry point.
4523 * This can be called with or without the global lock held.
4524 */
4525 int checkCallingPermission(String permission) {
4526 return checkPermission(permission,
4527 Binder.getCallingPid(),
Amith Yamasani742a6712011-05-04 14:49:28 -07004528 UserId.getAppId(Binder.getCallingUid()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004529 }
4530
4531 /**
4532 * This can be called with or without the global lock held.
4533 */
4534 void enforceCallingPermission(String permission, String func) {
4535 if (checkCallingPermission(permission)
4536 == PackageManager.PERMISSION_GRANTED) {
4537 return;
4538 }
4539
4540 String msg = "Permission Denial: " + func + " from pid="
4541 + Binder.getCallingPid()
4542 + ", uid=" + Binder.getCallingUid()
4543 + " requires " + permission;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004544 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004545 throw new SecurityException(msg);
4546 }
4547
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004548 /**
4549 * Determine if UID is holding permissions required to access {@link Uri} in
4550 * the given {@link ProviderInfo}. Final permission checking is always done
4551 * in {@link ContentProvider}.
4552 */
4553 private final boolean checkHoldingPermissionsLocked(
4554 IPackageManager pm, ProviderInfo pi, Uri uri, int uid, int modeFlags) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004555 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4556 "checkHoldingPermissionsLocked: uri=" + uri + " uid=" + uid);
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004557
4558 if (pi.applicationInfo.uid == uid) {
4559 return true;
4560 } else if (!pi.exported) {
4561 return false;
4562 }
4563
4564 boolean readMet = (modeFlags & Intent.FLAG_GRANT_READ_URI_PERMISSION) == 0;
4565 boolean writeMet = (modeFlags & Intent.FLAG_GRANT_WRITE_URI_PERMISSION) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004566 try {
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004567 // check if target holds top-level <provider> permissions
4568 if (!readMet && pi.readPermission != null
4569 && (pm.checkUidPermission(pi.readPermission, uid) == PERMISSION_GRANTED)) {
4570 readMet = true;
4571 }
4572 if (!writeMet && pi.writePermission != null
4573 && (pm.checkUidPermission(pi.writePermission, uid) == PERMISSION_GRANTED)) {
4574 writeMet = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004575 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004576
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004577 // track if unprotected read/write is allowed; any denied
4578 // <path-permission> below removes this ability
4579 boolean allowDefaultRead = pi.readPermission == null;
4580 boolean allowDefaultWrite = pi.writePermission == null;
Dianne Hackborn48058e82010-09-27 16:53:23 -07004581
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004582 // check if target holds any <path-permission> that match uri
4583 final PathPermission[] pps = pi.pathPermissions;
4584 if (pps != null) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004585 final String path = uri.getPath();
4586 int i = pps.length;
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004587 while (i > 0 && (!readMet || !writeMet)) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004588 i--;
4589 PathPermission pp = pps[i];
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004590 if (pp.match(path)) {
4591 if (!readMet) {
4592 final String pprperm = pp.getReadPermission();
4593 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking read perm for "
4594 + pprperm + " for " + pp.getPath()
4595 + ": match=" + pp.match(path)
4596 + " check=" + pm.checkUidPermission(pprperm, uid));
4597 if (pprperm != null) {
4598 if (pm.checkUidPermission(pprperm, uid) == PERMISSION_GRANTED) {
4599 readMet = true;
4600 } else {
4601 allowDefaultRead = false;
4602 }
4603 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004604 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004605 if (!writeMet) {
4606 final String ppwperm = pp.getWritePermission();
4607 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking write perm "
4608 + ppwperm + " for " + pp.getPath()
4609 + ": match=" + pp.match(path)
4610 + " check=" + pm.checkUidPermission(ppwperm, uid));
4611 if (ppwperm != null) {
4612 if (pm.checkUidPermission(ppwperm, uid) == PERMISSION_GRANTED) {
4613 writeMet = true;
4614 } else {
4615 allowDefaultWrite = false;
4616 }
4617 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004618 }
4619 }
4620 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07004621 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004622
4623 // grant unprotected <provider> read/write, if not blocked by
4624 // <path-permission> above
4625 if (allowDefaultRead) readMet = true;
4626 if (allowDefaultWrite) writeMet = true;
4627
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004628 } catch (RemoteException e) {
4629 return false;
4630 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004631
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004632 return readMet && writeMet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004633 }
4634
4635 private final boolean checkUriPermissionLocked(Uri uri, int uid,
4636 int modeFlags) {
4637 // Root gets to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07004638 if (uid == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004639 return true;
4640 }
4641 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(uid);
4642 if (perms == null) return false;
4643 UriPermission perm = perms.get(uri);
4644 if (perm == null) return false;
4645 return (modeFlags&perm.modeFlags) == modeFlags;
4646 }
4647
4648 public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004649 enforceNotIsolatedCaller("checkUriPermission");
4650
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004651 // Another redirected-binder-call permissions check as in
4652 // {@link checkComponentPermission}.
4653 Identity tlsIdentity = sCallerIdentity.get();
4654 if (tlsIdentity != null) {
4655 uid = tlsIdentity.uid;
4656 pid = tlsIdentity.pid;
4657 }
4658
Amith Yamasani742a6712011-05-04 14:49:28 -07004659 uid = UserId.getAppId(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004660 // Our own process gets to do everything.
4661 if (pid == MY_PID) {
4662 return PackageManager.PERMISSION_GRANTED;
4663 }
4664 synchronized(this) {
4665 return checkUriPermissionLocked(uri, uid, modeFlags)
4666 ? PackageManager.PERMISSION_GRANTED
4667 : PackageManager.PERMISSION_DENIED;
4668 }
4669 }
4670
Dianne Hackborn39792d22010-08-19 18:01:52 -07004671 /**
4672 * Check if the targetPkg can be granted permission to access uri by
4673 * the callingUid using the given modeFlags. Throws a security exception
4674 * if callingUid is not allowed to do this. Returns the uid of the target
4675 * if the URI permission grant should be performed; returns -1 if it is not
4676 * needed (for example targetPkg already has permission to access the URI).
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004677 * If you already know the uid of the target, you can supply it in
4678 * lastTargetUid else set that to -1.
Dianne Hackborn39792d22010-08-19 18:01:52 -07004679 */
4680 int checkGrantUriPermissionLocked(int callingUid, String targetPkg,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004681 Uri uri, int modeFlags, int lastTargetUid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004682 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4683 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4684 if (modeFlags == 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004685 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004686 }
4687
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004688 if (targetPkg != null) {
4689 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4690 "Checking grant " + targetPkg + " permission to " + uri);
4691 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004692
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004693 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004694
4695 // If this is not a content: uri, we can't do anything with it.
4696 if (!ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004697 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004698 "Can't grant URI permission for non-content URI: " + uri);
Dianne Hackborn39792d22010-08-19 18:01:52 -07004699 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004700 }
4701
4702 String name = uri.getAuthority();
4703 ProviderInfo pi = null;
Amith Yamasani742a6712011-05-04 14:49:28 -07004704 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
4705 UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004706 if (cpr != null) {
4707 pi = cpr.info;
4708 } else {
4709 try {
4710 pi = pm.resolveContentProvider(name,
4711 PackageManager.GET_URI_PERMISSION_PATTERNS);
4712 } catch (RemoteException ex) {
4713 }
4714 }
4715 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07004716 Slog.w(TAG, "No content provider found for permission check: " + uri.toSafeString());
Dianne Hackborn39792d22010-08-19 18:01:52 -07004717 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004718 }
4719
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004720 int targetUid = lastTargetUid;
4721 if (targetUid < 0 && targetPkg != null) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004722 try {
4723 targetUid = pm.getPackageUid(targetPkg);
4724 if (targetUid < 0) {
4725 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4726 "Can't grant URI permission no uid for: " + targetPkg);
4727 return -1;
4728 }
4729 } catch (RemoteException ex) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004730 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004731 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004732 }
4733
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004734 if (targetUid >= 0) {
4735 // First... does the target actually need this permission?
4736 if (checkHoldingPermissionsLocked(pm, pi, uri, targetUid, modeFlags)) {
4737 // No need to grant the target this permission.
4738 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4739 "Target " + targetPkg + " already has full permission to " + uri);
4740 return -1;
4741 }
4742 } else {
4743 // First... there is no target package, so can anyone access it?
4744 boolean allowed = pi.exported;
4745 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
4746 if (pi.readPermission != null) {
4747 allowed = false;
4748 }
4749 }
4750 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
4751 if (pi.writePermission != null) {
4752 allowed = false;
4753 }
4754 }
4755 if (allowed) {
4756 return -1;
4757 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004758 }
4759
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004760 // Second... is the provider allowing granting of URI permissions?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004761 if (!pi.grantUriPermissions) {
4762 throw new SecurityException("Provider " + pi.packageName
4763 + "/" + pi.name
4764 + " does not allow granting of Uri permissions (uri "
4765 + uri + ")");
4766 }
4767 if (pi.uriPermissionPatterns != null) {
4768 final int N = pi.uriPermissionPatterns.length;
4769 boolean allowed = false;
4770 for (int i=0; i<N; i++) {
4771 if (pi.uriPermissionPatterns[i] != null
4772 && pi.uriPermissionPatterns[i].match(uri.getPath())) {
4773 allowed = true;
4774 break;
4775 }
4776 }
4777 if (!allowed) {
4778 throw new SecurityException("Provider " + pi.packageName
4779 + "/" + pi.name
4780 + " does not allow granting of permission to path of Uri "
4781 + uri);
4782 }
4783 }
4784
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004785 // Third... does the caller itself have permission to access
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004786 // this uri?
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004787 if (callingUid != Process.myUid()) {
4788 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
4789 if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
4790 throw new SecurityException("Uid " + callingUid
4791 + " does not have permission to uri " + uri);
4792 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004793 }
4794 }
4795
Dianne Hackborn39792d22010-08-19 18:01:52 -07004796 return targetUid;
4797 }
4798
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004799 public int checkGrantUriPermission(int callingUid, String targetPkg,
4800 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004801 enforceNotIsolatedCaller("checkGrantUriPermission");
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004802 synchronized(this) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004803 return checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004804 }
4805 }
4806
Dianne Hackborn39792d22010-08-19 18:01:52 -07004807 void grantUriPermissionUncheckedLocked(int targetUid, String targetPkg,
4808 Uri uri, int modeFlags, UriPermissionOwner owner) {
4809 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4810 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4811 if (modeFlags == 0) {
4812 return;
4813 }
4814
4815 // So here we are: the caller has the assumed permission
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004816 // to the uri, and the target doesn't. Let's now give this to
4817 // the target.
4818
Joe Onorato8a9b2202010-02-26 18:56:32 -08004819 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn39792d22010-08-19 18:01:52 -07004820 "Granting " + targetPkg + "/" + targetUid + " permission to " + uri);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004821
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004822 HashMap<Uri, UriPermission> targetUris
4823 = mGrantedUriPermissions.get(targetUid);
4824 if (targetUris == null) {
4825 targetUris = new HashMap<Uri, UriPermission>();
4826 mGrantedUriPermissions.put(targetUid, targetUris);
4827 }
4828
4829 UriPermission perm = targetUris.get(uri);
4830 if (perm == null) {
4831 perm = new UriPermission(targetUid, uri);
4832 targetUris.put(uri, perm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004833 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07004834
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004835 perm.modeFlags |= modeFlags;
Dianne Hackborn39792d22010-08-19 18:01:52 -07004836 if (owner == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004837 perm.globalModeFlags |= modeFlags;
Vairavan Srinivasan91c12c22011-01-21 18:26:06 -08004838 } else {
4839 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
4840 perm.readOwners.add(owner);
4841 owner.addReadPermission(perm);
4842 }
4843 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
4844 perm.writeOwners.add(owner);
4845 owner.addWritePermission(perm);
4846 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004847 }
4848 }
4849
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004850 void grantUriPermissionLocked(int callingUid, String targetPkg, Uri uri,
4851 int modeFlags, UriPermissionOwner owner) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004852 if (targetPkg == null) {
4853 throw new NullPointerException("targetPkg");
4854 }
4855
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004856 int targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn39792d22010-08-19 18:01:52 -07004857 if (targetUid < 0) {
4858 return;
4859 }
4860
4861 grantUriPermissionUncheckedLocked(targetUid, targetPkg, uri, modeFlags, owner);
4862 }
4863
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004864 static class NeededUriGrants extends ArrayList<Uri> {
4865 final String targetPkg;
4866 final int targetUid;
4867 final int flags;
4868
4869 NeededUriGrants(String _targetPkg, int _targetUid, int _flags) {
4870 targetPkg = _targetPkg;
4871 targetUid = _targetUid;
4872 flags = _flags;
4873 }
4874 }
4875
Dianne Hackborn39792d22010-08-19 18:01:52 -07004876 /**
4877 * Like checkGrantUriPermissionLocked, but takes an Intent.
4878 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004879 NeededUriGrants checkGrantUriPermissionFromIntentLocked(int callingUid,
4880 String targetPkg, Intent intent, int mode, NeededUriGrants needed) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07004881 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004882 "Checking URI perm to data=" + (intent != null ? intent.getData() : null)
4883 + " clip=" + (intent != null ? intent.getClipData() : null)
Dianne Hackbornb424b632010-08-18 15:59:05 -07004884 + " from " + intent + "; flags=0x"
4885 + Integer.toHexString(intent != null ? intent.getFlags() : 0));
4886
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004887 if (targetPkg == null) {
4888 throw new NullPointerException("targetPkg");
4889 }
4890
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004891 if (intent == null) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004892 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004893 }
4894 Uri data = intent.getData();
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004895 ClipData clip = intent.getClipData();
4896 if (data == null && clip == null) {
4897 return null;
Dianne Hackborn39792d22010-08-19 18:01:52 -07004898 }
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004899 if (data != null) {
4900 int target = checkGrantUriPermissionLocked(callingUid, targetPkg, data,
4901 mode, needed != null ? needed.targetUid : -1);
4902 if (target > 0) {
4903 if (needed == null) {
4904 needed = new NeededUriGrants(targetPkg, target, mode);
4905 }
4906 needed.add(data);
4907 }
4908 }
4909 if (clip != null) {
4910 for (int i=0; i<clip.getItemCount(); i++) {
4911 Uri uri = clip.getItemAt(i).getUri();
4912 if (uri != null) {
4913 int target = -1;
4914 target = checkGrantUriPermissionLocked(callingUid, targetPkg, uri,
4915 mode, needed != null ? needed.targetUid : -1);
4916 if (target > 0) {
4917 if (needed == null) {
4918 needed = new NeededUriGrants(targetPkg, target, mode);
4919 }
4920 needed.add(uri);
4921 }
4922 } else {
4923 Intent clipIntent = clip.getItemAt(i).getIntent();
4924 if (clipIntent != null) {
4925 NeededUriGrants newNeeded = checkGrantUriPermissionFromIntentLocked(
4926 callingUid, targetPkg, clipIntent, mode, needed);
4927 if (newNeeded != null) {
4928 needed = newNeeded;
4929 }
4930 }
4931 }
4932 }
4933 }
4934
4935 return needed;
Dianne Hackborn39792d22010-08-19 18:01:52 -07004936 }
4937
4938 /**
4939 * Like grantUriPermissionUncheckedLocked, but takes an Intent.
4940 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004941 void grantUriPermissionUncheckedFromIntentLocked(NeededUriGrants needed,
4942 UriPermissionOwner owner) {
4943 if (needed != null) {
4944 for (int i=0; i<needed.size(); i++) {
4945 grantUriPermissionUncheckedLocked(needed.targetUid, needed.targetPkg,
4946 needed.get(i), needed.flags, owner);
4947 }
4948 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07004949 }
4950
4951 void grantUriPermissionFromIntentLocked(int callingUid,
4952 String targetPkg, Intent intent, UriPermissionOwner owner) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004953 NeededUriGrants needed = checkGrantUriPermissionFromIntentLocked(callingUid, targetPkg,
Dianne Hackbornd9781fe2012-03-08 18:04:18 -08004954 intent, intent != null ? intent.getFlags() : 0, null);
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004955 if (needed == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004956 return;
4957 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07004958
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004959 grantUriPermissionUncheckedFromIntentLocked(needed, owner);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004960 }
4961
4962 public void grantUriPermission(IApplicationThread caller, String targetPkg,
4963 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004964 enforceNotIsolatedCaller("grantUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004965 synchronized(this) {
4966 final ProcessRecord r = getRecordForAppLocked(caller);
4967 if (r == null) {
4968 throw new SecurityException("Unable to find app for caller "
4969 + caller
4970 + " when granting permission to uri " + uri);
4971 }
4972 if (targetPkg == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07004973 throw new IllegalArgumentException("null target");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004974 }
4975 if (uri == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07004976 throw new IllegalArgumentException("null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004977 }
4978
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004979 grantUriPermissionLocked(r.uid, targetPkg, uri, modeFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004980 null);
4981 }
4982 }
4983
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004984 void removeUriPermissionIfNeededLocked(UriPermission perm) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004985 if ((perm.modeFlags&(Intent.FLAG_GRANT_READ_URI_PERMISSION
4986 |Intent.FLAG_GRANT_WRITE_URI_PERMISSION)) == 0) {
4987 HashMap<Uri, UriPermission> perms
4988 = mGrantedUriPermissions.get(perm.uid);
4989 if (perms != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004990 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004991 "Removing " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004992 perms.remove(perm.uri);
4993 if (perms.size() == 0) {
4994 mGrantedUriPermissions.remove(perm.uid);
4995 }
4996 }
4997 }
4998 }
4999
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005000 private void revokeUriPermissionLocked(int callingUid, Uri uri,
5001 int modeFlags) {
5002 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5003 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5004 if (modeFlags == 0) {
5005 return;
5006 }
5007
Joe Onorato8a9b2202010-02-26 18:56:32 -08005008 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005009 "Revoking all granted permissions to " + uri);
5010
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005011 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005012
5013 final String authority = uri.getAuthority();
5014 ProviderInfo pi = null;
Amith Yamasani742a6712011-05-04 14:49:28 -07005015 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority,
5016 UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005017 if (cpr != null) {
5018 pi = cpr.info;
5019 } else {
5020 try {
5021 pi = pm.resolveContentProvider(authority,
5022 PackageManager.GET_URI_PERMISSION_PATTERNS);
5023 } catch (RemoteException ex) {
5024 }
5025 }
5026 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005027 Slog.w(TAG, "No content provider found for permission revoke: " + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005028 return;
5029 }
5030
5031 // Does the caller have this permission on the URI?
Dianne Hackborn48058e82010-09-27 16:53:23 -07005032 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005033 // Right now, if you are not the original owner of the permission,
5034 // you are not allowed to revoke it.
5035 //if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5036 throw new SecurityException("Uid " + callingUid
5037 + " does not have permission to uri " + uri);
5038 //}
5039 }
5040
5041 // Go through all of the permissions and remove any that match.
5042 final List<String> SEGMENTS = uri.getPathSegments();
5043 if (SEGMENTS != null) {
5044 final int NS = SEGMENTS.size();
5045 int N = mGrantedUriPermissions.size();
5046 for (int i=0; i<N; i++) {
5047 HashMap<Uri, UriPermission> perms
5048 = mGrantedUriPermissions.valueAt(i);
5049 Iterator<UriPermission> it = perms.values().iterator();
5050 toploop:
5051 while (it.hasNext()) {
5052 UriPermission perm = it.next();
5053 Uri targetUri = perm.uri;
5054 if (!authority.equals(targetUri.getAuthority())) {
5055 continue;
5056 }
5057 List<String> targetSegments = targetUri.getPathSegments();
5058 if (targetSegments == null) {
5059 continue;
5060 }
5061 if (targetSegments.size() < NS) {
5062 continue;
5063 }
5064 for (int j=0; j<NS; j++) {
5065 if (!SEGMENTS.get(j).equals(targetSegments.get(j))) {
5066 continue toploop;
5067 }
5068 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08005069 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005070 "Revoking " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005071 perm.clearModes(modeFlags);
5072 if (perm.modeFlags == 0) {
5073 it.remove();
5074 }
5075 }
5076 if (perms.size() == 0) {
5077 mGrantedUriPermissions.remove(
5078 mGrantedUriPermissions.keyAt(i));
5079 N--;
5080 i--;
5081 }
5082 }
5083 }
5084 }
5085
5086 public void revokeUriPermission(IApplicationThread caller, Uri uri,
5087 int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005088 enforceNotIsolatedCaller("revokeUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005089 synchronized(this) {
5090 final ProcessRecord r = getRecordForAppLocked(caller);
5091 if (r == null) {
5092 throw new SecurityException("Unable to find app for caller "
5093 + caller
5094 + " when revoking permission to uri " + uri);
5095 }
5096 if (uri == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005097 Slog.w(TAG, "revokeUriPermission: null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005098 return;
5099 }
5100
5101 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5102 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5103 if (modeFlags == 0) {
5104 return;
5105 }
5106
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005107 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005108
5109 final String authority = uri.getAuthority();
5110 ProviderInfo pi = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005111 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005112 if (cpr != null) {
5113 pi = cpr.info;
5114 } else {
5115 try {
5116 pi = pm.resolveContentProvider(authority,
5117 PackageManager.GET_URI_PERMISSION_PATTERNS);
5118 } catch (RemoteException ex) {
5119 }
5120 }
5121 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005122 Slog.w(TAG, "No content provider found for permission revoke: "
5123 + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005124 return;
5125 }
5126
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005127 revokeUriPermissionLocked(r.uid, uri, modeFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005128 }
5129 }
5130
Dianne Hackborn7e269642010-08-25 19:50:20 -07005131 @Override
5132 public IBinder newUriPermissionOwner(String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005133 enforceNotIsolatedCaller("newUriPermissionOwner");
Dianne Hackborn7e269642010-08-25 19:50:20 -07005134 synchronized(this) {
5135 UriPermissionOwner owner = new UriPermissionOwner(this, name);
5136 return owner.getExternalTokenLocked();
5137 }
5138 }
5139
5140 @Override
5141 public void grantUriPermissionFromOwner(IBinder token, int fromUid, String targetPkg,
5142 Uri uri, int modeFlags) {
5143 synchronized(this) {
5144 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5145 if (owner == null) {
5146 throw new IllegalArgumentException("Unknown owner: " + token);
5147 }
5148 if (fromUid != Binder.getCallingUid()) {
5149 if (Binder.getCallingUid() != Process.myUid()) {
5150 // Only system code can grant URI permissions on behalf
5151 // of other users.
5152 throw new SecurityException("nice try");
5153 }
5154 }
5155 if (targetPkg == null) {
5156 throw new IllegalArgumentException("null target");
5157 }
5158 if (uri == null) {
5159 throw new IllegalArgumentException("null uri");
5160 }
5161
5162 grantUriPermissionLocked(fromUid, targetPkg, uri, modeFlags, owner);
5163 }
5164 }
5165
5166 @Override
5167 public void revokeUriPermissionFromOwner(IBinder token, Uri uri, int mode) {
5168 synchronized(this) {
5169 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5170 if (owner == null) {
5171 throw new IllegalArgumentException("Unknown owner: " + token);
5172 }
5173
5174 if (uri == null) {
5175 owner.removeUriPermissionsLocked(mode);
5176 } else {
5177 owner.removeUriPermissionLocked(uri, mode);
5178 }
5179 }
5180 }
5181
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005182 public void showWaitingForDebugger(IApplicationThread who, boolean waiting) {
5183 synchronized (this) {
5184 ProcessRecord app =
5185 who != null ? getRecordForAppLocked(who) : null;
5186 if (app == null) return;
5187
5188 Message msg = Message.obtain();
5189 msg.what = WAIT_FOR_DEBUGGER_MSG;
5190 msg.obj = app;
5191 msg.arg1 = waiting ? 1 : 0;
5192 mHandler.sendMessage(msg);
5193 }
5194 }
5195
5196 public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07005197 final long homeAppMem = mProcessList.getMemLevel(ProcessList.HOME_APP_ADJ);
5198 final long hiddenAppMem = mProcessList.getMemLevel(ProcessList.HIDDEN_APP_MIN_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005199 outInfo.availMem = Process.getFreeMemory();
Dianne Hackborn7d608422011-08-07 16:24:18 -07005200 outInfo.threshold = homeAppMem;
5201 outInfo.lowMemory = outInfo.availMem < (homeAppMem + ((hiddenAppMem-homeAppMem)/2));
5202 outInfo.hiddenAppThreshold = hiddenAppMem;
5203 outInfo.secondaryServerThreshold = mProcessList.getMemLevel(
Dianne Hackborne02c88a2011-10-28 13:58:15 -07005204 ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07005205 outInfo.visibleAppThreshold = mProcessList.getMemLevel(
5206 ProcessList.VISIBLE_APP_ADJ);
5207 outInfo.foregroundAppThreshold = mProcessList.getMemLevel(
5208 ProcessList.FOREGROUND_APP_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005209 }
5210
5211 // =========================================================
5212 // TASK MANAGEMENT
5213 // =========================================================
5214
5215 public List getTasks(int maxNum, int flags,
5216 IThumbnailReceiver receiver) {
5217 ArrayList list = new ArrayList();
5218
5219 PendingThumbnailsRecord pending = null;
5220 IApplicationThread topThumbnail = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005221 ActivityRecord topRecord = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005222
5223 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005224 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005225 TAG, "getTasks: max=" + maxNum + ", flags=" + flags
5226 + ", receiver=" + receiver);
5227
5228 if (checkCallingPermission(android.Manifest.permission.GET_TASKS)
5229 != PackageManager.PERMISSION_GRANTED) {
5230 if (receiver != null) {
5231 // If the caller wants to wait for pending thumbnails,
5232 // it ain't gonna get them.
5233 try {
5234 receiver.finished();
5235 } catch (RemoteException ex) {
5236 }
5237 }
5238 String msg = "Permission Denial: getTasks() from pid="
5239 + Binder.getCallingPid()
5240 + ", uid=" + Binder.getCallingUid()
5241 + " requires " + android.Manifest.permission.GET_TASKS;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005242 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005243 throw new SecurityException(msg);
5244 }
5245
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005246 int pos = mMainStack.mHistory.size()-1;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005247 ActivityRecord next =
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005248 pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005249 ActivityRecord top = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005250 TaskRecord curTask = null;
5251 int numActivities = 0;
5252 int numRunning = 0;
5253 while (pos >= 0 && maxNum > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005254 final ActivityRecord r = next;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005255 pos--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005256 next = pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005257
5258 // Initialize state for next task if needed.
5259 if (top == null ||
5260 (top.state == ActivityState.INITIALIZING
5261 && top.task == r.task)) {
5262 top = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005263 curTask = r.task;
5264 numActivities = numRunning = 0;
5265 }
5266
5267 // Add 'r' into the current task.
5268 numActivities++;
5269 if (r.app != null && r.app.thread != null) {
5270 numRunning++;
5271 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005272
Joe Onorato8a9b2202010-02-26 18:56:32 -08005273 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005274 TAG, r.intent.getComponent().flattenToShortString()
5275 + ": task=" + r.task);
5276
5277 // If the next one is a different task, generate a new
5278 // TaskInfo entry for what we have.
5279 if (next == null || next.task != curTask) {
5280 ActivityManager.RunningTaskInfo ci
5281 = new ActivityManager.RunningTaskInfo();
5282 ci.id = curTask.taskId;
5283 ci.baseActivity = r.intent.getComponent();
5284 ci.topActivity = top.intent.getComponent();
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005285 if (top.thumbHolder != null) {
5286 ci.description = top.thumbHolder.lastDescription;
5287 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005288 ci.numActivities = numActivities;
5289 ci.numRunning = numRunning;
5290 //System.out.println(
5291 // "#" + maxNum + ": " + " descr=" + ci.description);
5292 if (ci.thumbnail == null && receiver != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005293 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005294 TAG, "State=" + top.state + "Idle=" + top.idle
5295 + " app=" + top.app
5296 + " thr=" + (top.app != null ? top.app.thread : null));
5297 if (top.state == ActivityState.RESUMED
5298 || top.state == ActivityState.PAUSING) {
5299 if (top.idle && top.app != null
5300 && top.app.thread != null) {
5301 topRecord = top;
5302 topThumbnail = top.app.thread;
5303 } else {
5304 top.thumbnailNeeded = true;
5305 }
5306 }
5307 if (pending == null) {
5308 pending = new PendingThumbnailsRecord(receiver);
5309 }
5310 pending.pendingRecords.add(top);
5311 }
5312 list.add(ci);
5313 maxNum--;
5314 top = null;
5315 }
5316 }
5317
5318 if (pending != null) {
5319 mPendingThumbnails.add(pending);
5320 }
5321 }
5322
Joe Onorato8a9b2202010-02-26 18:56:32 -08005323 if (localLOGV) Slog.v(TAG, "We have pending thumbnails: " + pending);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005324
5325 if (topThumbnail != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005326 if (localLOGV) Slog.v(TAG, "Requesting top thumbnail");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005327 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08005328 topThumbnail.requestThumbnail(topRecord.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005329 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005330 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005331 sendPendingThumbnail(null, topRecord.appToken, null, null, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005332 }
5333 }
5334
5335 if (pending == null && receiver != null) {
5336 // In this case all thumbnails were available and the client
5337 // is being asked to be told when the remaining ones come in...
5338 // which is unusually, since the top-most currently running
5339 // activity should never have a canned thumbnail! Oh well.
5340 try {
5341 receiver.finished();
5342 } catch (RemoteException ex) {
5343 }
5344 }
5345
5346 return list;
5347 }
5348
5349 public List<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum,
5350 int flags) {
Amith Yamasani742a6712011-05-04 14:49:28 -07005351 final int callingUid = Binder.getCallingUid();
5352 // If it's the system uid asking, then use the current user id.
5353 // TODO: Make sure that there aren't any other legitimate calls from the system uid that
5354 // require the entire list.
5355 final int callingUserId = callingUid == Process.SYSTEM_UID
5356 ? mCurrentUserId : UserId.getUserId(callingUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005357 synchronized (this) {
5358 enforceCallingPermission(android.Manifest.permission.GET_TASKS,
5359 "getRecentTasks()");
5360
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005361 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005362
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005363 final int N = mRecentTasks.size();
5364 ArrayList<ActivityManager.RecentTaskInfo> res
5365 = new ArrayList<ActivityManager.RecentTaskInfo>(
5366 maxNum < N ? maxNum : N);
5367 for (int i=0; i<N && maxNum > 0; i++) {
5368 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005369 // Only add calling user's recent tasks
5370 if (tr.userId != callingUserId) continue;
Dianne Hackborn905577f2011-09-07 18:31:28 -07005371 // Return the entry if desired by the caller. We always return
5372 // the first entry, because callers always expect this to be the
Amith Yamasani742a6712011-05-04 14:49:28 -07005373 // foreground app. We may filter others if the caller has
Dianne Hackborn905577f2011-09-07 18:31:28 -07005374 // not supplied RECENT_WITH_EXCLUDED and there is some reason
5375 // we should exclude the entry.
Amith Yamasani742a6712011-05-04 14:49:28 -07005376
Dianne Hackborn905577f2011-09-07 18:31:28 -07005377 if (i == 0
5378 || ((flags&ActivityManager.RECENT_WITH_EXCLUDED) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005379 || (tr.intent == null)
5380 || ((tr.intent.getFlags()
5381 &Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) == 0)) {
5382 ActivityManager.RecentTaskInfo rti
5383 = new ActivityManager.RecentTaskInfo();
5384 rti.id = tr.numActivities > 0 ? tr.taskId : -1;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005385 rti.persistentId = tr.taskId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005386 rti.baseIntent = new Intent(
5387 tr.intent != null ? tr.intent : tr.affinityIntent);
5388 rti.origActivity = tr.origActivity;
Dianne Hackbornd2835932010-12-13 16:28:46 -08005389 rti.description = tr.lastDescription;
5390
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005391 if ((flags&ActivityManager.RECENT_IGNORE_UNAVAILABLE) != 0) {
5392 // Check whether this activity is currently available.
5393 try {
5394 if (rti.origActivity != null) {
5395 if (pm.getActivityInfo(rti.origActivity, 0) == null) {
5396 continue;
5397 }
5398 } else if (rti.baseIntent != null) {
5399 if (pm.queryIntentActivities(rti.baseIntent,
5400 null, 0) == null) {
5401 continue;
5402 }
5403 }
5404 } catch (RemoteException e) {
5405 // Will never happen.
5406 }
5407 }
5408
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005409 res.add(rti);
5410 maxNum--;
5411 }
5412 }
5413 return res;
5414 }
5415 }
5416
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005417 private TaskRecord taskForIdLocked(int id) {
5418 final int N = mRecentTasks.size();
5419 for (int i=0; i<N; i++) {
5420 TaskRecord tr = mRecentTasks.get(i);
5421 if (tr.taskId == id) {
5422 return tr;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005423 }
5424 }
5425 return null;
5426 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005427
5428 public ActivityManager.TaskThumbnails getTaskThumbnails(int id) {
5429 synchronized (this) {
5430 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
5431 "getTaskThumbnails()");
5432 TaskRecord tr = taskForIdLocked(id);
5433 if (tr != null) {
5434 return mMainStack.getTaskThumbnailsLocked(tr);
5435 }
5436 }
5437 return null;
5438 }
5439
5440 public boolean removeSubTask(int taskId, int subTaskIndex) {
5441 synchronized (this) {
5442 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5443 "removeSubTask()");
5444 long ident = Binder.clearCallingIdentity();
5445 try {
5446 return mMainStack.removeTaskActivitiesLocked(taskId, subTaskIndex) != null;
5447 } finally {
5448 Binder.restoreCallingIdentity(ident);
5449 }
5450 }
5451 }
5452
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005453 private void cleanUpRemovedTaskLocked(ActivityRecord root, boolean killProcesses) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005454 TaskRecord tr = root.task;
5455 Intent baseIntent = new Intent(
5456 tr.intent != null ? tr.intent : tr.affinityIntent);
5457 ComponentName component = baseIntent.getComponent();
5458 if (component == null) {
5459 Slog.w(TAG, "Now component for base intent of task: " + tr);
5460 return;
5461 }
5462
5463 // Find any running services associated with this app.
5464 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
Amith Yamasani742a6712011-05-04 14:49:28 -07005465 for (ServiceRecord sr : mServiceMap.getAllServices(root.userId)) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005466 if (sr.packageName.equals(component.getPackageName())) {
5467 services.add(sr);
5468 }
5469 }
5470
5471 // Take care of any running services associated with the app.
5472 for (int i=0; i<services.size(); i++) {
5473 ServiceRecord sr = services.get(i);
5474 if (sr.startRequested) {
5475 if ((sr.serviceInfo.flags&ServiceInfo.FLAG_STOP_WITH_TASK) != 0) {
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005476 Slog.i(TAG, "Stopping service " + sr.shortName + ": remove task");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005477 stopServiceLocked(sr);
5478 } else {
5479 sr.pendingStarts.add(new ServiceRecord.StartItem(sr, true,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005480 sr.makeNextStartId(), baseIntent, null));
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005481 if (sr.app != null && sr.app.thread != null) {
5482 sendServiceArgsLocked(sr, false);
5483 }
5484 }
5485 }
5486 }
5487
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005488 if (killProcesses) {
5489 // Find any running processes associated with this app.
5490 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
5491 SparseArray<ProcessRecord> appProcs
5492 = mProcessNames.getMap().get(component.getPackageName());
5493 if (appProcs != null) {
5494 for (int i=0; i<appProcs.size(); i++) {
5495 procs.add(appProcs.valueAt(i));
5496 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005497 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005498
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005499 // Kill the running processes.
5500 for (int i=0; i<procs.size(); i++) {
5501 ProcessRecord pr = procs.get(i);
5502 if (pr.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
5503 Slog.i(TAG, "Killing " + pr.toShortString() + ": remove task");
5504 EventLog.writeEvent(EventLogTags.AM_KILL, pr.pid,
5505 pr.processName, pr.setAdj, "remove task");
5506 Process.killProcessQuiet(pr.pid);
5507 } else {
5508 pr.waitingToKill = "remove task";
5509 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005510 }
5511 }
5512 }
5513
5514 public boolean removeTask(int taskId, int flags) {
5515 synchronized (this) {
5516 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5517 "removeTask()");
5518 long ident = Binder.clearCallingIdentity();
5519 try {
5520 ActivityRecord r = mMainStack.removeTaskActivitiesLocked(taskId, -1);
5521 if (r != null) {
5522 mRecentTasks.remove(r.task);
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005523 cleanUpRemovedTaskLocked(r,
5524 (flags&ActivityManager.REMOVE_TASK_KILL_PROCESS) != 0);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005525 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005526 } else {
5527 TaskRecord tr = null;
5528 int i=0;
5529 while (i < mRecentTasks.size()) {
5530 TaskRecord t = mRecentTasks.get(i);
5531 if (t.taskId == taskId) {
5532 tr = t;
5533 break;
5534 }
5535 i++;
5536 }
5537 if (tr != null) {
5538 if (tr.numActivities <= 0) {
5539 // Caller is just removing a recent task that is
5540 // not actively running. That is easy!
5541 mRecentTasks.remove(i);
5542 } else {
5543 Slog.w(TAG, "removeTask: task " + taskId
5544 + " does not have activities to remove, "
5545 + " but numActivities=" + tr.numActivities
5546 + ": " + tr);
5547 }
5548 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005549 }
5550 } finally {
5551 Binder.restoreCallingIdentity(ident);
5552 }
5553 }
5554 return false;
5555 }
Dianne Hackbornd94df452011-02-16 18:53:31 -08005556
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005557 private final int findAffinityTaskTopLocked(int startIndex, String affinity) {
5558 int j;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005559 TaskRecord startTask = ((ActivityRecord)mMainStack.mHistory.get(startIndex)).task;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005560 TaskRecord jt = startTask;
5561
5562 // First look backwards
5563 for (j=startIndex-1; j>=0; j--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005564 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005565 if (r.task != jt) {
5566 jt = r.task;
5567 if (affinity.equals(jt.affinity)) {
5568 return j;
5569 }
5570 }
5571 }
5572
5573 // Now look forwards
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005574 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005575 jt = startTask;
5576 for (j=startIndex+1; j<N; j++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005577 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005578 if (r.task != jt) {
5579 if (affinity.equals(jt.affinity)) {
5580 return j;
5581 }
5582 jt = r.task;
5583 }
5584 }
5585
5586 // Might it be at the top?
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005587 if (affinity.equals(((ActivityRecord)mMainStack.mHistory.get(N-1)).task.affinity)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005588 return N-1;
5589 }
5590
5591 return -1;
5592 }
5593
5594 /**
Dianne Hackbornb06ea702009-07-13 13:07:51 -07005595 * TODO: Add mController hook
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005596 */
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005597 public void moveTaskToFront(int task, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005598 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5599 "moveTaskToFront()");
5600
5601 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005602 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5603 Binder.getCallingUid(), "Task to front")) {
5604 return;
5605 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005606 final long origId = Binder.clearCallingIdentity();
5607 try {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005608 TaskRecord tr = taskForIdLocked(task);
5609 if (tr != null) {
5610 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5611 mMainStack.mUserLeaving = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005612 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005613 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5614 // Caller wants the home activity moved with it. To accomplish this,
5615 // we'll just move the home task to the top first.
5616 mMainStack.moveHomeToFrontLocked();
5617 }
5618 mMainStack.moveTaskToFrontLocked(tr, null);
5619 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005620 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005621 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
5622 ActivityRecord hr = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005623 if (hr.task.taskId == task) {
Dianne Hackbornd94df452011-02-16 18:53:31 -08005624 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5625 mMainStack.mUserLeaving = true;
5626 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005627 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5628 // Caller wants the home activity moved with it. To accomplish this,
5629 // we'll just move the home task to the top first.
5630 mMainStack.moveHomeToFrontLocked();
5631 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005632 mMainStack.moveTaskToFrontLocked(hr.task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005633 return;
5634 }
5635 }
5636 } finally {
5637 Binder.restoreCallingIdentity(origId);
5638 }
5639 }
5640 }
5641
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005642 public void moveTaskToBack(int task) {
5643 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5644 "moveTaskToBack()");
5645
5646 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005647 if (mMainStack.mResumedActivity != null
5648 && mMainStack.mResumedActivity.task.taskId == task) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005649 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5650 Binder.getCallingUid(), "Task to back")) {
5651 return;
5652 }
5653 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005654 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005655 mMainStack.moveTaskToBackLocked(task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005656 Binder.restoreCallingIdentity(origId);
5657 }
5658 }
5659
5660 /**
5661 * Moves an activity, and all of the other activities within the same task, to the bottom
5662 * of the history stack. The activity's order within the task is unchanged.
5663 *
5664 * @param token A reference to the activity we wish to move
5665 * @param nonRoot If false then this only works if the activity is the root
5666 * of a task; if true it will work for any activity in a task.
5667 * @return Returns true if the move completed, false if not.
5668 */
5669 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005670 enforceNotIsolatedCaller("moveActivityTaskToBack");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005671 synchronized(this) {
5672 final long origId = Binder.clearCallingIdentity();
5673 int taskId = getTaskForActivityLocked(token, !nonRoot);
5674 if (taskId >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005675 return mMainStack.moveTaskToBackLocked(taskId, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005676 }
5677 Binder.restoreCallingIdentity(origId);
5678 }
5679 return false;
5680 }
5681
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005682 public void moveTaskBackwards(int task) {
5683 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5684 "moveTaskBackwards()");
5685
5686 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005687 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5688 Binder.getCallingUid(), "Task backwards")) {
5689 return;
5690 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005691 final long origId = Binder.clearCallingIdentity();
5692 moveTaskBackwardsLocked(task);
5693 Binder.restoreCallingIdentity(origId);
5694 }
5695 }
5696
5697 private final void moveTaskBackwardsLocked(int task) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005698 Slog.e(TAG, "moveTaskBackwards not yet implemented!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005699 }
5700
5701 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
5702 synchronized(this) {
5703 return getTaskForActivityLocked(token, onlyRoot);
5704 }
5705 }
5706
5707 int getTaskForActivityLocked(IBinder token, boolean onlyRoot) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005708 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005709 TaskRecord lastTask = null;
5710 for (int i=0; i<N; i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005711 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005712 if (r.appToken == token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005713 if (!onlyRoot || lastTask != r.task) {
5714 return r.task.taskId;
5715 }
5716 return -1;
5717 }
5718 lastTask = r.task;
5719 }
5720
5721 return -1;
5722 }
5723
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005724 // =========================================================
5725 // THUMBNAILS
5726 // =========================================================
5727
5728 public void reportThumbnail(IBinder token,
5729 Bitmap thumbnail, CharSequence description) {
5730 //System.out.println("Report thumbnail for " + token + ": " + thumbnail);
5731 final long origId = Binder.clearCallingIdentity();
5732 sendPendingThumbnail(null, token, thumbnail, description, true);
5733 Binder.restoreCallingIdentity(origId);
5734 }
5735
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005736 final void sendPendingThumbnail(ActivityRecord r, IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005737 Bitmap thumbnail, CharSequence description, boolean always) {
5738 TaskRecord task = null;
5739 ArrayList receivers = null;
5740
5741 //System.out.println("Send pending thumbnail: " + r);
5742
5743 synchronized(this) {
5744 if (r == null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07005745 r = mMainStack.isInStackLocked(token);
5746 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005747 return;
5748 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005749 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005750 if (thumbnail == null && r.thumbHolder != null) {
5751 thumbnail = r.thumbHolder.lastThumbnail;
5752 description = r.thumbHolder.lastDescription;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005753 }
5754 if (thumbnail == null && !always) {
5755 // If there is no thumbnail, and this entry is not actually
5756 // going away, then abort for now and pick up the next
5757 // thumbnail we get.
5758 return;
5759 }
5760 task = r.task;
5761
5762 int N = mPendingThumbnails.size();
5763 int i=0;
5764 while (i<N) {
5765 PendingThumbnailsRecord pr =
5766 (PendingThumbnailsRecord)mPendingThumbnails.get(i);
5767 //System.out.println("Looking in " + pr.pendingRecords);
5768 if (pr.pendingRecords.remove(r)) {
5769 if (receivers == null) {
5770 receivers = new ArrayList();
5771 }
5772 receivers.add(pr);
5773 if (pr.pendingRecords.size() == 0) {
5774 pr.finished = true;
5775 mPendingThumbnails.remove(i);
5776 N--;
5777 continue;
5778 }
5779 }
5780 i++;
5781 }
5782 }
5783
5784 if (receivers != null) {
5785 final int N = receivers.size();
5786 for (int i=0; i<N; i++) {
5787 try {
5788 PendingThumbnailsRecord pr =
5789 (PendingThumbnailsRecord)receivers.get(i);
5790 pr.receiver.newThumbnail(
5791 task != null ? task.taskId : -1, thumbnail, description);
5792 if (pr.finished) {
5793 pr.receiver.finished();
5794 }
5795 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005796 Slog.w(TAG, "Exception thrown when sending thumbnail", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005797 }
5798 }
5799 }
5800 }
5801
5802 // =========================================================
5803 // CONTENT PROVIDERS
5804 // =========================================================
5805
Jeff Brown10e89712011-07-08 18:52:57 -07005806 private final List<ProviderInfo> generateApplicationProvidersLocked(ProcessRecord app) {
5807 List<ProviderInfo> providers = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005808 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005809 providers = AppGlobals.getPackageManager().
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005810 queryContentProviders(app.processName, app.uid,
Dianne Hackborn1655be42009-05-08 14:29:01 -07005811 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005812 } catch (RemoteException ex) {
5813 }
Amith Yamasani742a6712011-05-04 14:49:28 -07005814 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005815 Slog.v(TAG_MU, "generateApplicationProvidersLocked, app.info.uid = " + app.uid);
5816 int userId = app.userId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005817 if (providers != null) {
5818 final int N = providers.size();
5819 for (int i=0; i<N; i++) {
5820 ProviderInfo cpi =
5821 (ProviderInfo)providers.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005822
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07005823 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07005824 ContentProviderRecord cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005825 if (cpr == null) {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08005826 cpr = new ContentProviderRecord(this, cpi, app.info, comp);
Amith Yamasani742a6712011-05-04 14:49:28 -07005827 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005828 }
Amith Yamasani742a6712011-05-04 14:49:28 -07005829 if (DEBUG_MU)
5830 Slog.v(TAG_MU, "generateApplicationProvidersLocked, cpi.uid = " + cpr.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005831 app.pubProviders.put(cpi.name, cpr);
5832 app.addPackage(cpi.applicationInfo.packageName);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07005833 ensurePackageDexOpt(cpi.applicationInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005834 }
5835 }
5836 return providers;
5837 }
5838
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005839 /**
5840 * Check if {@link ProcessRecord} has a possible chance at accessing the
5841 * given {@link ProviderInfo}. Final permission checking is always done
5842 * in {@link ContentProvider}.
5843 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005844 private final String checkContentProviderPermissionLocked(
Dianne Hackbornb424b632010-08-18 15:59:05 -07005845 ProviderInfo cpi, ProcessRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005846 final int callingPid = (r != null) ? r.pid : Binder.getCallingPid();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005847 final int callingUid = (r != null) ? r.uid : Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005848 if (checkComponentPermission(cpi.readPermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005849 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005850 == PackageManager.PERMISSION_GRANTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005851 return null;
5852 }
5853 if (checkComponentPermission(cpi.writePermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005854 cpi.applicationInfo.uid, cpi.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005855 == PackageManager.PERMISSION_GRANTED) {
5856 return null;
5857 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07005858
5859 PathPermission[] pps = cpi.pathPermissions;
5860 if (pps != null) {
5861 int i = pps.length;
5862 while (i > 0) {
5863 i--;
5864 PathPermission pp = pps[i];
5865 if (checkComponentPermission(pp.getReadPermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005866 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005867 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07005868 return null;
5869 }
5870 if (checkComponentPermission(pp.getWritePermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005871 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackborn2af632f2009-07-08 14:56:37 -07005872 == PackageManager.PERMISSION_GRANTED) {
5873 return null;
5874 }
5875 }
5876 }
5877
Dianne Hackbornb424b632010-08-18 15:59:05 -07005878 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(callingUid);
5879 if (perms != null) {
5880 for (Map.Entry<Uri, UriPermission> uri : perms.entrySet()) {
5881 if (uri.getKey().getAuthority().equals(cpi.authority)) {
5882 return null;
5883 }
5884 }
5885 }
5886
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005887 String msg;
5888 if (!cpi.exported) {
5889 msg = "Permission Denial: opening provider " + cpi.name
5890 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
5891 + ", uid=" + callingUid + ") that is not exported from uid "
5892 + cpi.applicationInfo.uid;
5893 } else {
5894 msg = "Permission Denial: opening provider " + cpi.name
5895 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
5896 + ", uid=" + callingUid + ") requires "
5897 + cpi.readPermission + " or " + cpi.writePermission;
5898 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08005899 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005900 return msg;
5901 }
5902
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08005903 boolean incProviderCount(ProcessRecord r, final ContentProviderRecord cpr,
5904 IBinder externalProcessToken) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005905 if (r != null) {
5906 Integer cnt = r.conProviders.get(cpr);
5907 if (DEBUG_PROVIDER) Slog.v(TAG,
5908 "Adding provider requested by "
5909 + r.processName + " from process "
5910 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
5911 + " cnt=" + (cnt == null ? 1 : cnt));
5912 if (cnt == null) {
5913 cpr.clients.add(r);
5914 r.conProviders.put(cpr, new Integer(1));
5915 return true;
5916 } else {
5917 r.conProviders.put(cpr, new Integer(cnt.intValue()+1));
5918 }
5919 } else {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08005920 cpr.addExternalProcessHandleLocked(externalProcessToken);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005921 }
5922 return false;
5923 }
5924
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08005925 boolean decProviderCount(ProcessRecord r, final ContentProviderRecord cpr,
5926 IBinder externalProcessToken) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005927 if (r != null) {
5928 Integer cnt = r.conProviders.get(cpr);
5929 if (DEBUG_PROVIDER) Slog.v(TAG,
5930 "Removing provider requested by "
5931 + r.processName + " from process "
5932 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
5933 + " cnt=" + cnt);
5934 if (cnt == null || cnt.intValue() <= 1) {
5935 cpr.clients.remove(r);
5936 r.conProviders.remove(cpr);
5937 return true;
5938 } else {
5939 r.conProviders.put(cpr, new Integer(cnt.intValue()-1));
5940 }
5941 } else {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08005942 cpr.removeExternalProcessHandleLocked(externalProcessToken);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005943 }
5944 return false;
5945 }
5946
Amith Yamasani742a6712011-05-04 14:49:28 -07005947 private final ContentProviderHolder getContentProviderImpl(IApplicationThread caller,
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08005948 String name, IBinder token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005949 ContentProviderRecord cpr;
5950 ProviderInfo cpi = null;
5951
5952 synchronized(this) {
5953 ProcessRecord r = null;
5954 if (caller != null) {
5955 r = getRecordForAppLocked(caller);
5956 if (r == null) {
5957 throw new SecurityException(
5958 "Unable to find app for caller " + caller
5959 + " (pid=" + Binder.getCallingPid()
5960 + ") when getting content provider " + name);
5961 }
5962 }
5963
5964 // First check if this content provider has been published...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005965 int userId = UserId.getUserId(r != null ? r.uid : Binder.getCallingUid());
Amith Yamasani742a6712011-05-04 14:49:28 -07005966 cpr = mProviderMap.getProviderByName(name, userId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005967 boolean providerRunning = cpr != null;
5968 if (providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005969 cpi = cpr.info;
Dianne Hackbornb424b632010-08-18 15:59:05 -07005970 String msg;
5971 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
5972 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005973 }
5974
5975 if (r != null && cpr.canRunHere(r)) {
5976 // This provider has been published or is in the process
5977 // of being published... but it is also allowed to run
5978 // in the caller's process, so don't make a connection
5979 // and just let the caller instantiate its own instance.
5980 if (cpr.provider != null) {
5981 // don't give caller the provider object, it needs
5982 // to make its own.
5983 cpr = new ContentProviderRecord(cpr);
5984 }
5985 return cpr;
5986 }
5987
5988 final long origId = Binder.clearCallingIdentity();
5989
Dianne Hackborna1e989b2009-09-01 19:54:29 -07005990 // In this case the provider instance already exists, so we can
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005991 // return it right away.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08005992 final boolean countChanged = incProviderCount(r, cpr, token);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005993 if (countChanged) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07005994 if (cpr.proc != null && r.setAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005995 // If this is a perceptible app accessing the provider,
Dianne Hackborn906497c2010-05-10 15:57:38 -07005996 // make sure to count it as being accessed and thus
5997 // back up on the LRU list. This is good because
5998 // content providers are often expensive to start.
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07005999 updateLruProcessLocked(cpr.proc, false, true);
Dianne Hackborn906497c2010-05-10 15:57:38 -07006000 }
Dianne Hackborn6f86c0e2010-05-11 14:20:52 -07006001 }
6002
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006003 if (cpr.proc != null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006004 if (false) {
6005 if (cpr.name.flattenToShortString().equals(
6006 "com.android.providers.calendar/.CalendarProvider2")) {
6007 Slog.v(TAG, "****************** KILLING "
6008 + cpr.name.flattenToShortString());
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006009 Process.killProcess(cpr.proc.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006010 }
6011 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006012 boolean success = updateOomAdjLocked(cpr.proc);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006013 if (DEBUG_PROVIDER) Slog.i(TAG, "Adjust success: " + success);
6014 // NOTE: there is still a race here where a signal could be
6015 // pending on the process even though we managed to update its
6016 // adj level. Not sure what to do about this, but at least
6017 // the race is now smaller.
6018 if (!success) {
6019 // Uh oh... it looks like the provider's process
6020 // has been killed on us. We need to wait for a new
6021 // process to be started, and make sure its death
6022 // doesn't kill our process.
6023 Slog.i(TAG,
6024 "Existing provider " + cpr.name.flattenToShortString()
6025 + " is crashing; detaching " + r);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006026 boolean lastRef = decProviderCount(r, cpr, token);
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006027 appDiedLocked(cpr.proc, cpr.proc.pid, cpr.proc.thread);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006028 if (!lastRef) {
6029 // This wasn't the last ref our process had on
6030 // the provider... we have now been killed, bail.
6031 return null;
6032 }
6033 providerRunning = false;
6034 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006035 }
6036
6037 Binder.restoreCallingIdentity(origId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006038 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006039
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006040 if (!providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006041 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006042 cpi = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07006043 resolveContentProvider(name,
6044 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006045 } catch (RemoteException ex) {
6046 }
6047 if (cpi == null) {
6048 return null;
6049 }
6050
Amith Yamasani742a6712011-05-04 14:49:28 -07006051 cpi.applicationInfo = getAppInfoForUser(cpi.applicationInfo,
6052 Binder.getOrigCallingUser());
6053
Dianne Hackbornb424b632010-08-18 15:59:05 -07006054 String msg;
6055 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6056 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006057 }
6058
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07006059 if (!mProcessesReady && !mDidUpdate && !mWaitingUpdate
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006060 && !cpi.processName.equals("system")) {
6061 // If this content provider does not run in the system
6062 // process, and the system is not yet ready to run other
6063 // processes, then fail fast instead of hanging.
6064 throw new IllegalArgumentException(
6065 "Attempt to launch content provider before system ready");
6066 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006067
6068 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006069 cpr = mProviderMap.getProviderByClass(comp, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006070 final boolean firstClass = cpr == null;
6071 if (firstClass) {
6072 try {
6073 ApplicationInfo ai =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006074 AppGlobals.getPackageManager().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006075 getApplicationInfo(
6076 cpi.applicationInfo.packageName,
Dianne Hackborn1655be42009-05-08 14:29:01 -07006077 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006078 if (ai == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006079 Slog.w(TAG, "No package info for content provider "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006080 + cpi.name);
6081 return null;
6082 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006083 ai = getAppInfoForUser(ai, Binder.getOrigCallingUser());
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006084 cpr = new ContentProviderRecord(this, cpi, ai, comp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006085 } catch (RemoteException ex) {
6086 // pm is in same process, this will never happen.
6087 }
6088 }
6089
6090 if (r != null && cpr.canRunHere(r)) {
6091 // If this is a multiprocess provider, then just return its
6092 // info and allow the caller to instantiate it. Only do
6093 // this if the provider is the same user as the caller's
6094 // process, or can run as root (so can be in any process).
6095 return cpr;
6096 }
6097
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006098 if (DEBUG_PROVIDER) {
6099 RuntimeException e = new RuntimeException("here");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006100 Slog.w(TAG, "LAUNCHING REMOTE PROVIDER (myuid " + r.uid
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006101 + " pruid " + cpr.appInfo.uid + "): " + cpr.info.name, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006102 }
6103
6104 // This is single process, and our app is now connecting to it.
6105 // See if we are already in the process of launching this
6106 // provider.
6107 final int N = mLaunchingProviders.size();
6108 int i;
6109 for (i=0; i<N; i++) {
6110 if (mLaunchingProviders.get(i) == cpr) {
6111 break;
6112 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006113 }
6114
6115 // If the provider is not already being launched, then get it
6116 // started.
6117 if (i >= N) {
6118 final long origId = Binder.clearCallingIdentity();
Dianne Hackborne7f97212011-02-24 14:40:20 -08006119
6120 try {
6121 // Content provider is now in use, its package can't be stopped.
6122 try {
6123 AppGlobals.getPackageManager().setPackageStoppedState(
6124 cpr.appInfo.packageName, false);
6125 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006126 } catch (IllegalArgumentException e) {
6127 Slog.w(TAG, "Failed trying to unstop package "
6128 + cpr.appInfo.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006129 }
6130
6131 ProcessRecord proc = startProcessLocked(cpi.processName,
6132 cpr.appInfo, false, 0, "content provider",
6133 new ComponentName(cpi.applicationInfo.packageName,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006134 cpi.name), false, false);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006135 if (proc == null) {
6136 Slog.w(TAG, "Unable to launch app "
6137 + cpi.applicationInfo.packageName + "/"
6138 + cpi.applicationInfo.uid + " for provider "
6139 + name + ": process is bad");
6140 return null;
6141 }
6142 cpr.launchingApp = proc;
6143 mLaunchingProviders.add(cpr);
6144 } finally {
6145 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006146 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006147 }
6148
6149 // Make sure the provider is published (the same provider class
6150 // may be published under multiple names).
6151 if (firstClass) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006152 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006153 }
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006154
Amith Yamasani742a6712011-05-04 14:49:28 -07006155 mProviderMap.putProviderByName(name, cpr);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006156 incProviderCount(r, cpr, token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006157 }
6158 }
6159
6160 // Wait for the provider to be published...
6161 synchronized (cpr) {
6162 while (cpr.provider == null) {
6163 if (cpr.launchingApp == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006164 Slog.w(TAG, "Unable to launch app "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006165 + cpi.applicationInfo.packageName + "/"
6166 + cpi.applicationInfo.uid + " for provider "
6167 + name + ": launching app became null");
Doug Zongker2bec3d42009-12-04 12:52:44 -08006168 EventLog.writeEvent(EventLogTags.AM_PROVIDER_LOST_PROCESS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006169 cpi.applicationInfo.packageName,
6170 cpi.applicationInfo.uid, name);
6171 return null;
6172 }
6173 try {
Amith Yamasani742a6712011-05-04 14:49:28 -07006174 if (DEBUG_MU) {
6175 Slog.v(TAG_MU, "Waiting to start provider " + cpr + " launchingApp="
6176 + cpr.launchingApp);
6177 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006178 cpr.wait();
6179 } catch (InterruptedException ex) {
6180 }
6181 }
6182 }
6183 return cpr;
6184 }
6185
6186 public final ContentProviderHolder getContentProvider(
6187 IApplicationThread caller, String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006188 enforceNotIsolatedCaller("getContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006189 if (caller == null) {
6190 String msg = "null IApplicationThread when getting content provider "
6191 + name;
Joe Onorato8a9b2202010-02-26 18:56:32 -08006192 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006193 throw new SecurityException(msg);
6194 }
6195
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006196 return getContentProviderImpl(caller, name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006197 }
6198
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006199 public ContentProviderHolder getContentProviderExternal(String name, IBinder token) {
6200 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6201 "Do not have permission in call getContentProviderExternal()");
6202 return getContentProviderExternalUnchecked(name, token);
6203 }
6204
6205 private ContentProviderHolder getContentProviderExternalUnchecked(String name,IBinder token) {
6206 return getContentProviderImpl(null, name, token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006207 }
6208
6209 /**
6210 * Drop a content provider from a ProcessRecord's bookkeeping
6211 * @param cpr
6212 */
6213 public void removeContentProvider(IApplicationThread caller, String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006214 enforceNotIsolatedCaller("removeContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006215 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006216 int userId = UserId.getUserId(Binder.getCallingUid());
6217 ContentProviderRecord cpr = mProviderMap.getProviderByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006218 if(cpr == null) {
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006219 // remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006220 if (DEBUG_PROVIDER) Slog.v(TAG, name +
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006221 " provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006222 return;
6223 }
6224 final ProcessRecord r = getRecordForAppLocked(caller);
6225 if (r == null) {
6226 throw new SecurityException(
6227 "Unable to find app for caller " + caller +
6228 " when removing content provider " + name);
6229 }
6230 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006231 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006232 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp, userId);
6233 if (DEBUG_PROVIDER) Slog.v(TAG, "Removing provider requested by "
6234 + r.info.processName + " from process "
6235 + localCpr.appInfo.processName);
6236 if (localCpr.launchingApp == r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006237 //should not happen. taken care of as a local provider
Joe Onorato8a9b2202010-02-26 18:56:32 -08006238 Slog.w(TAG, "removeContentProvider called on local provider: "
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006239 + cpr.info.name + " in process " + r.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006240 return;
6241 } else {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006242 if (decProviderCount(r, localCpr, null)) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006243 updateOomAdjLocked();
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07006244 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006245 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006246 }
6247 }
6248
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006249 public void removeContentProviderExternal(String name, IBinder token) {
6250 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6251 "Do not have permission in call removeContentProviderExternal()");
6252 removeContentProviderExternalUnchecked(name, token);
6253 }
6254
6255 private void removeContentProviderExternalUnchecked(String name, IBinder token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006256 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006257 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
6258 Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006259 if(cpr == null) {
6260 //remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006261 if(localLOGV) Slog.v(TAG, name+" content provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006262 return;
6263 }
6264
6265 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006266 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006267 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp,
6268 Binder.getOrigCallingUser());
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006269 if (localCpr.hasExternalProcessHandles()) {
6270 if (localCpr.removeExternalProcessHandleLocked(token)) {
6271 updateOomAdjLocked();
6272 } else {
6273 Slog.e(TAG, "Attmpt to remove content provider " + localCpr
6274 + " with no external reference for token: "
6275 + token + ".");
6276 }
6277 } else {
6278 Slog.e(TAG, "Attmpt to remove content provider: " + localCpr
6279 + " with no external references.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006280 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006281 }
6282 }
6283
6284 public final void publishContentProviders(IApplicationThread caller,
6285 List<ContentProviderHolder> providers) {
6286 if (providers == null) {
6287 return;
6288 }
6289
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006290 enforceNotIsolatedCaller("publishContentProviders");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006291 synchronized(this) {
6292 final ProcessRecord r = getRecordForAppLocked(caller);
Amith Yamasani742a6712011-05-04 14:49:28 -07006293 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006294 Slog.v(TAG_MU, "ProcessRecord uid = " + r.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006295 if (r == null) {
6296 throw new SecurityException(
6297 "Unable to find app for caller " + caller
6298 + " (pid=" + Binder.getCallingPid()
6299 + ") when publishing content providers");
6300 }
6301
6302 final long origId = Binder.clearCallingIdentity();
6303
6304 final int N = providers.size();
6305 for (int i=0; i<N; i++) {
6306 ContentProviderHolder src = providers.get(i);
6307 if (src == null || src.info == null || src.provider == null) {
6308 continue;
6309 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07006310 ContentProviderRecord dst = r.pubProviders.get(src.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006311 if (DEBUG_MU)
6312 Slog.v(TAG_MU, "ContentProviderRecord uid = " + dst.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006313 if (dst != null) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006314 ComponentName comp = new ComponentName(dst.info.packageName, dst.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006315 mProviderMap.putProviderByClass(comp, dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006316 String names[] = dst.info.authority.split(";");
6317 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006318 mProviderMap.putProviderByName(names[j], dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006319 }
6320
6321 int NL = mLaunchingProviders.size();
6322 int j;
6323 for (j=0; j<NL; j++) {
6324 if (mLaunchingProviders.get(j) == dst) {
6325 mLaunchingProviders.remove(j);
6326 j--;
6327 NL--;
6328 }
6329 }
6330 synchronized (dst) {
6331 dst.provider = src.provider;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006332 dst.proc = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006333 dst.notifyAll();
6334 }
6335 updateOomAdjLocked(r);
6336 }
6337 }
6338
6339 Binder.restoreCallingIdentity(origId);
6340 }
6341 }
6342
6343 public static final void installSystemProviders() {
Jeff Brown10e89712011-07-08 18:52:57 -07006344 List<ProviderInfo> providers;
Josh Bartel2ecce342010-02-25 10:55:48 -06006345 synchronized (mSelf) {
6346 ProcessRecord app = mSelf.mProcessNames.get("system", Process.SYSTEM_UID);
6347 providers = mSelf.generateApplicationProvidersLocked(app);
Dianne Hackborn5c83a5f2010-03-12 16:46:46 -08006348 if (providers != null) {
6349 for (int i=providers.size()-1; i>=0; i--) {
6350 ProviderInfo pi = (ProviderInfo)providers.get(i);
6351 if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6352 Slog.w(TAG, "Not installing system proc provider " + pi.name
6353 + ": not system .apk");
6354 providers.remove(i);
6355 }
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006356 }
6357 }
6358 }
Josh Bartel2ecce342010-02-25 10:55:48 -06006359 if (providers != null) {
6360 mSystemThread.installSystemProviders(providers);
6361 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08006362
6363 mSelf.mCoreSettingsObserver = new CoreSettingsObserver(mSelf);
Mark Brophyc6350272011-08-05 16:16:39 +01006364
6365 mSelf.mUsageStatsService.monitorPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006366 }
6367
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006368 /**
6369 * Allows app to retrieve the MIME type of a URI without having permission
6370 * to access its content provider.
6371 *
6372 * CTS tests for this functionality can be run with "runtest cts-appsecurity".
6373 *
6374 * Test cases are at cts/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/
6375 * src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java
6376 */
6377 public String getProviderMimeType(Uri uri) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006378 enforceNotIsolatedCaller("getProviderMimeType");
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006379 final String name = uri.getAuthority();
6380 final long ident = Binder.clearCallingIdentity();
6381 ContentProviderHolder holder = null;
6382
6383 try {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006384 holder = getContentProviderExternalUnchecked(name, null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006385 if (holder != null) {
6386 return holder.provider.getType(uri);
6387 }
6388 } catch (RemoteException e) {
6389 Log.w(TAG, "Content provider dead retrieving " + uri, e);
6390 return null;
6391 } finally {
6392 if (holder != null) {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006393 removeContentProviderExternalUnchecked(name, null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006394 }
6395 Binder.restoreCallingIdentity(ident);
6396 }
6397
6398 return null;
6399 }
6400
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006401 // =========================================================
6402 // GLOBAL MANAGEMENT
6403 // =========================================================
6404
6405 final ProcessRecord newProcessRecordLocked(IApplicationThread thread,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006406 ApplicationInfo info, String customProcess, boolean isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006407 String proc = customProcess != null ? customProcess : info.processName;
6408 BatteryStatsImpl.Uid.Proc ps = null;
6409 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006410 int uid = info.uid;
6411 if (isolated) {
6412 int userId = UserId.getUserId(uid);
6413 int stepsLeft = Process.LAST_ISOLATED_UID - Process.FIRST_ISOLATED_UID + 1;
6414 uid = 0;
6415 while (true) {
6416 if (mNextIsolatedProcessUid < Process.FIRST_ISOLATED_UID
6417 || mNextIsolatedProcessUid > Process.LAST_ISOLATED_UID) {
6418 mNextIsolatedProcessUid = Process.FIRST_ISOLATED_UID;
6419 }
6420 uid = UserId.getUid(userId, mNextIsolatedProcessUid);
6421 mNextIsolatedProcessUid++;
6422 if (mIsolatedProcesses.indexOfKey(uid) < 0) {
6423 // No process for this uid, use it.
6424 break;
6425 }
6426 stepsLeft--;
6427 if (stepsLeft <= 0) {
6428 return null;
6429 }
6430 }
6431 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006432 synchronized (stats) {
6433 ps = stats.getProcessStatsLocked(info.uid, proc);
6434 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006435 return new ProcessRecord(ps, thread, info, proc, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006436 }
6437
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006438 final ProcessRecord addAppLocked(ApplicationInfo info, boolean isolated) {
6439 ProcessRecord app;
6440 if (!isolated) {
6441 app = getProcessRecordLocked(info.processName, info.uid);
6442 } else {
6443 app = null;
6444 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006445
6446 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006447 app = newProcessRecordLocked(null, info, null, isolated);
6448 mProcessNames.put(info.processName, app.uid, app);
6449 if (isolated) {
6450 mIsolatedProcesses.put(app.uid, app);
6451 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08006452 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006453 }
6454
Dianne Hackborne7f97212011-02-24 14:40:20 -08006455 // This package really, really can not be stopped.
6456 try {
6457 AppGlobals.getPackageManager().setPackageStoppedState(
6458 info.packageName, false);
6459 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006460 } catch (IllegalArgumentException e) {
6461 Slog.w(TAG, "Failed trying to unstop package "
6462 + info.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006463 }
6464
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006465 if ((info.flags&(ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT))
6466 == (ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT)) {
6467 app.persistent = true;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07006468 app.maxAdj = ProcessList.PERSISTENT_PROC_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006469 }
6470 if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) {
6471 mPersistentStartingProcesses.add(app);
6472 startProcessLocked(app, "added application", app.processName);
6473 }
6474
6475 return app;
6476 }
6477
6478 public void unhandledBack() {
6479 enforceCallingPermission(android.Manifest.permission.FORCE_BACK,
6480 "unhandledBack()");
6481
6482 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006483 int count = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08006484 if (DEBUG_SWITCH) Slog.d(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006485 TAG, "Performing unhandledBack(): stack size = " + count);
6486 if (count > 1) {
6487 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006488 mMainStack.finishActivityLocked((ActivityRecord)mMainStack.mHistory.get(count-1),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006489 count-1, Activity.RESULT_CANCELED, null, "unhandled-back");
6490 Binder.restoreCallingIdentity(origId);
6491 }
6492 }
6493 }
6494
6495 public ParcelFileDescriptor openContentUri(Uri uri) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006496 enforceNotIsolatedCaller("openContentUri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006497 String name = uri.getAuthority();
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006498 ContentProviderHolder cph = getContentProviderExternalUnchecked(name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006499 ParcelFileDescriptor pfd = null;
6500 if (cph != null) {
6501 // We record the binder invoker's uid in thread-local storage before
6502 // going to the content provider to open the file. Later, in the code
6503 // that handles all permissions checks, we look for this uid and use
6504 // that rather than the Activity Manager's own uid. The effect is that
6505 // we do the check against the caller's permissions even though it looks
6506 // to the content provider like the Activity Manager itself is making
6507 // the request.
6508 sCallerIdentity.set(new Identity(
6509 Binder.getCallingPid(), Binder.getCallingUid()));
6510 try {
6511 pfd = cph.provider.openFile(uri, "r");
6512 } catch (FileNotFoundException e) {
6513 // do nothing; pfd will be returned null
6514 } finally {
6515 // Ensure that whatever happens, we clean up the identity state
6516 sCallerIdentity.remove();
6517 }
6518
6519 // We've got the fd now, so we're done with the provider.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006520 removeContentProviderExternalUnchecked(name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006521 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006522 Slog.d(TAG, "Failed to get provider for authority '" + name + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006523 }
6524 return pfd;
6525 }
6526
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006527 // Actually is sleeping or shutting down or whatever else in the future
6528 // is an inactive state.
6529 public boolean isSleeping() {
6530 return mSleeping || mShuttingDown;
6531 }
6532
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006533 public void goingToSleep() {
6534 synchronized(this) {
6535 mSleeping = true;
6536 mWindowManager.setEventDispatching(false);
6537
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006538 mMainStack.stopIfSleepingLocked();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006539
6540 // Initialize the wake times of all processes.
Dianne Hackborn287952c2010-09-22 22:34:31 -07006541 checkExcessivePowerUsageLocked(false);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006542 mHandler.removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
6543 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07006544 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006545 }
6546 }
6547
Dianne Hackborn55280a92009-05-07 15:53:46 -07006548 public boolean shutdown(int timeout) {
6549 if (checkCallingPermission(android.Manifest.permission.SHUTDOWN)
6550 != PackageManager.PERMISSION_GRANTED) {
6551 throw new SecurityException("Requires permission "
6552 + android.Manifest.permission.SHUTDOWN);
6553 }
6554
6555 boolean timedout = false;
6556
6557 synchronized(this) {
6558 mShuttingDown = true;
6559 mWindowManager.setEventDispatching(false);
6560
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006561 if (mMainStack.mResumedActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006562 mMainStack.stopIfSleepingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07006563 final long endTime = System.currentTimeMillis() + timeout;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006564 while (mMainStack.mResumedActivity != null
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08006565 || mMainStack.mPausingActivity != null) {
Dianne Hackborn55280a92009-05-07 15:53:46 -07006566 long delay = endTime - System.currentTimeMillis();
6567 if (delay <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006568 Slog.w(TAG, "Activity manager shutdown timed out");
Dianne Hackborn55280a92009-05-07 15:53:46 -07006569 timedout = true;
6570 break;
6571 }
6572 try {
6573 this.wait();
6574 } catch (InterruptedException e) {
6575 }
6576 }
6577 }
6578 }
6579
6580 mUsageStatsService.shutdown();
6581 mBatteryStatsService.shutdown();
6582
6583 return timedout;
6584 }
6585
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006586 public final void activitySlept(IBinder token) {
6587 if (localLOGV) Slog.v(
6588 TAG, "Activity slept: token=" + token);
6589
6590 ActivityRecord r = null;
6591
6592 final long origId = Binder.clearCallingIdentity();
6593
6594 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006595 r = mMainStack.isInStackLocked(token);
6596 if (r != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006597 mMainStack.activitySleptLocked(r);
6598 }
6599 }
6600
6601 Binder.restoreCallingIdentity(origId);
6602 }
6603
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006604 public void wakingUp() {
6605 synchronized(this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006606 mWindowManager.setEventDispatching(true);
6607 mSleeping = false;
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006608 mMainStack.awakeFromSleepingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006609 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006610 }
6611 }
6612
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006613 public void stopAppSwitches() {
6614 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
6615 != PackageManager.PERMISSION_GRANTED) {
6616 throw new SecurityException("Requires permission "
6617 + android.Manifest.permission.STOP_APP_SWITCHES);
6618 }
6619
6620 synchronized(this) {
6621 mAppSwitchesAllowedTime = SystemClock.uptimeMillis()
6622 + APP_SWITCH_DELAY_TIME;
6623 mDidAppSwitch = false;
6624 mHandler.removeMessages(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
6625 Message msg = mHandler.obtainMessage(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
6626 mHandler.sendMessageDelayed(msg, APP_SWITCH_DELAY_TIME);
6627 }
6628 }
6629
6630 public void resumeAppSwitches() {
6631 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
6632 != PackageManager.PERMISSION_GRANTED) {
6633 throw new SecurityException("Requires permission "
6634 + android.Manifest.permission.STOP_APP_SWITCHES);
6635 }
6636
6637 synchronized(this) {
6638 // Note that we don't execute any pending app switches... we will
6639 // let those wait until either the timeout, or the next start
6640 // activity request.
6641 mAppSwitchesAllowedTime = 0;
6642 }
6643 }
6644
6645 boolean checkAppSwitchAllowedLocked(int callingPid, int callingUid,
6646 String name) {
6647 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
6648 return true;
6649 }
6650
6651 final int perm = checkComponentPermission(
6652 android.Manifest.permission.STOP_APP_SWITCHES, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006653 callingUid, -1, true);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006654 if (perm == PackageManager.PERMISSION_GRANTED) {
6655 return true;
6656 }
6657
Joe Onorato8a9b2202010-02-26 18:56:32 -08006658 Slog.w(TAG, name + " request from " + callingUid + " stopped");
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006659 return false;
6660 }
6661
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006662 public void setDebugApp(String packageName, boolean waitForDebugger,
6663 boolean persistent) {
6664 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
6665 "setDebugApp()");
6666
6667 // Note that this is not really thread safe if there are multiple
6668 // callers into it at the same time, but that's not a situation we
6669 // care about.
6670 if (persistent) {
6671 final ContentResolver resolver = mContext.getContentResolver();
6672 Settings.System.putString(
6673 resolver, Settings.System.DEBUG_APP,
6674 packageName);
6675 Settings.System.putInt(
6676 resolver, Settings.System.WAIT_FOR_DEBUGGER,
6677 waitForDebugger ? 1 : 0);
6678 }
6679
6680 synchronized (this) {
6681 if (!persistent) {
6682 mOrigDebugApp = mDebugApp;
6683 mOrigWaitForDebugger = mWaitForDebugger;
6684 }
6685 mDebugApp = packageName;
6686 mWaitForDebugger = waitForDebugger;
6687 mDebugTransient = !persistent;
6688 if (packageName != null) {
6689 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -07006690 forceStopPackageLocked(packageName, -1, false, false, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006691 Binder.restoreCallingIdentity(origId);
6692 }
6693 }
6694 }
6695
Siva Velusamy92a8b222012-03-09 16:24:04 -08006696 void setOpenGlTraceApp(ApplicationInfo app, String processName) {
6697 synchronized (this) {
6698 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
6699 if (!isDebuggable) {
6700 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
6701 throw new SecurityException("Process not debuggable: " + app.packageName);
6702 }
6703 }
6704
6705 mOpenGlTraceApp = processName;
6706 }
6707 }
6708
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07006709 void setProfileApp(ApplicationInfo app, String processName, String profileFile,
6710 ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
6711 synchronized (this) {
6712 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
6713 if (!isDebuggable) {
6714 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
6715 throw new SecurityException("Process not debuggable: " + app.packageName);
6716 }
6717 }
6718 mProfileApp = processName;
6719 mProfileFile = profileFile;
6720 if (mProfileFd != null) {
6721 try {
6722 mProfileFd.close();
6723 } catch (IOException e) {
6724 }
6725 mProfileFd = null;
6726 }
6727 mProfileFd = profileFd;
6728 mProfileType = 0;
6729 mAutoStopProfiler = autoStopProfiler;
6730 }
6731 }
6732
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006733 public void setAlwaysFinish(boolean enabled) {
6734 enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH,
6735 "setAlwaysFinish()");
6736
6737 Settings.System.putInt(
6738 mContext.getContentResolver(),
6739 Settings.System.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0);
6740
6741 synchronized (this) {
6742 mAlwaysFinishActivities = enabled;
6743 }
6744 }
6745
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006746 public void setActivityController(IActivityController controller) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006747 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006748 "setActivityController()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006749 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006750 mController = controller;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006751 }
6752 }
6753
Dianne Hackborn9327f4f2010-01-29 10:38:29 -08006754 public boolean isUserAMonkey() {
6755 // For now the fact that there is a controller implies
6756 // we have a monkey.
6757 synchronized (this) {
6758 return mController != null;
6759 }
6760 }
6761
Jeff Sharkeya4620792011-05-20 15:29:23 -07006762 public void registerProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08006763 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
6764 "registerProcessObserver()");
6765 synchronized (this) {
6766 mProcessObservers.register(observer);
6767 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07006768 }
6769
6770 public void unregisterProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08006771 synchronized (this) {
6772 mProcessObservers.unregister(observer);
6773 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07006774 }
6775
Daniel Sandler69a48172010-06-23 16:29:36 -04006776 public void setImmersive(IBinder token, boolean immersive) {
6777 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006778 ActivityRecord r = mMainStack.isInStackLocked(token);
6779 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04006780 throw new IllegalArgumentException();
6781 }
Daniel Sandler69a48172010-06-23 16:29:36 -04006782 r.immersive = immersive;
6783 }
6784 }
6785
6786 public boolean isImmersive(IBinder token) {
6787 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006788 ActivityRecord r = mMainStack.isInStackLocked(token);
6789 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04006790 throw new IllegalArgumentException();
6791 }
Daniel Sandler69a48172010-06-23 16:29:36 -04006792 return r.immersive;
6793 }
6794 }
6795
6796 public boolean isTopActivityImmersive() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006797 enforceNotIsolatedCaller("startActivity");
Daniel Sandler69a48172010-06-23 16:29:36 -04006798 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006799 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Daniel Sandler69a48172010-06-23 16:29:36 -04006800 return (r != null) ? r.immersive : false;
6801 }
6802 }
6803
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006804 public final void enterSafeMode() {
6805 synchronized(this) {
6806 // It only makes sense to do this before the system is ready
6807 // and started launching other packages.
6808 if (!mSystemReady) {
6809 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006810 AppGlobals.getPackageManager().enterSafeMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006811 } catch (RemoteException e) {
6812 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006813 }
6814 }
6815 }
6816
Jeff Brownb09abc12011-01-13 21:08:27 -08006817 public final void showSafeModeOverlay() {
6818 View v = LayoutInflater.from(mContext).inflate(
6819 com.android.internal.R.layout.safe_mode, null);
6820 WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
6821 lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
6822 lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
6823 lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
6824 lp.gravity = Gravity.BOTTOM | Gravity.LEFT;
6825 lp.format = v.getBackground().getOpacity();
6826 lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
6827 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
6828 ((WindowManager)mContext.getSystemService(
6829 Context.WINDOW_SERVICE)).addView(v, lp);
6830 }
6831
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006832 public void noteWakeupAlarm(IIntentSender sender) {
6833 if (!(sender instanceof PendingIntentRecord)) {
6834 return;
6835 }
6836 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
6837 synchronized (stats) {
6838 if (mBatteryStatsService.isOnBattery()) {
6839 mBatteryStatsService.enforceCallingPermission();
6840 PendingIntentRecord rec = (PendingIntentRecord)sender;
6841 int MY_UID = Binder.getCallingUid();
6842 int uid = rec.uid == MY_UID ? Process.SYSTEM_UID : rec.uid;
6843 BatteryStatsImpl.Uid.Pkg pkg =
6844 stats.getPackageStatsLocked(uid, rec.key.packageName);
6845 pkg.incWakeupsLocked();
6846 }
6847 }
6848 }
6849
Dianne Hackborn64825172011-03-02 21:32:58 -08006850 public boolean killPids(int[] pids, String pReason, boolean secure) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006851 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006852 throw new SecurityException("killPids only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006853 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006854 String reason = (pReason == null) ? "Unknown" : pReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006855 // XXX Note: don't acquire main activity lock here, because the window
6856 // manager calls in with its locks held.
6857
6858 boolean killed = false;
6859 synchronized (mPidsSelfLocked) {
6860 int[] types = new int[pids.length];
6861 int worstType = 0;
6862 for (int i=0; i<pids.length; i++) {
6863 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
6864 if (proc != null) {
6865 int type = proc.setAdj;
6866 types[i] = type;
6867 if (type > worstType) {
6868 worstType = type;
6869 }
6870 }
6871 }
6872
Dianne Hackborn64825172011-03-02 21:32:58 -08006873 // If the worst oom_adj is somewhere in the hidden proc LRU range,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006874 // then constrain it so we will kill all hidden procs.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07006875 if (worstType < ProcessList.HIDDEN_APP_MAX_ADJ
6876 && worstType > ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07006877 worstType = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006878 }
Dianne Hackborn64825172011-03-02 21:32:58 -08006879
6880 // If this is not a secure call, don't let it kill processes that
6881 // are important.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07006882 if (!secure && worstType < ProcessList.SERVICE_ADJ) {
6883 worstType = ProcessList.SERVICE_ADJ;
Dianne Hackborn64825172011-03-02 21:32:58 -08006884 }
6885
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006886 Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006887 for (int i=0; i<pids.length; i++) {
6888 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
6889 if (proc == null) {
6890 continue;
6891 }
6892 int adj = proc.setAdj;
Dianne Hackborn906497c2010-05-10 15:57:38 -07006893 if (adj >= worstType && !proc.killedBackground) {
Dianne Hackborn8633e682010-04-22 16:03:41 -07006894 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006895 EventLog.writeEvent(EventLogTags.AM_KILL, proc.pid,
6896 proc.processName, adj, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006897 killed = true;
Dianne Hackborn906497c2010-05-10 15:57:38 -07006898 proc.killedBackground = true;
6899 Process.killProcessQuiet(pids[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006900 }
6901 }
6902 }
6903 return killed;
6904 }
6905
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006906 public final void startRunning(String pkg, String cls, String action,
6907 String data) {
6908 synchronized(this) {
6909 if (mStartRunning) {
6910 return;
6911 }
6912 mStartRunning = true;
6913 mTopComponent = pkg != null && cls != null
6914 ? new ComponentName(pkg, cls) : null;
6915 mTopAction = action != null ? action : Intent.ACTION_MAIN;
6916 mTopData = data;
6917 if (!mSystemReady) {
6918 return;
6919 }
6920 }
6921
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07006922 systemReady(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006923 }
6924
6925 private void retrieveSettings() {
6926 final ContentResolver resolver = mContext.getContentResolver();
6927 String debugApp = Settings.System.getString(
6928 resolver, Settings.System.DEBUG_APP);
6929 boolean waitForDebugger = Settings.System.getInt(
6930 resolver, Settings.System.WAIT_FOR_DEBUGGER, 0) != 0;
6931 boolean alwaysFinishActivities = Settings.System.getInt(
6932 resolver, Settings.System.ALWAYS_FINISH_ACTIVITIES, 0) != 0;
6933
6934 Configuration configuration = new Configuration();
6935 Settings.System.getConfiguration(resolver, configuration);
6936
6937 synchronized (this) {
6938 mDebugApp = mOrigDebugApp = debugApp;
6939 mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger;
6940 mAlwaysFinishActivities = alwaysFinishActivities;
6941 // This happens before any activities are started, so we can
6942 // change mConfiguration in-place.
Dianne Hackborn813075a62011-11-14 17:45:19 -08006943 updateConfigurationLocked(configuration, null, false, true);
Joe Onorato8a9b2202010-02-26 18:56:32 -08006944 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Initial config: " + mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006945 }
6946 }
6947
6948 public boolean testIsSystemReady() {
6949 // no need to synchronize(this) just to read & return the value
6950 return mSystemReady;
6951 }
6952
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006953 private static File getCalledPreBootReceiversFile() {
6954 File dataDir = Environment.getDataDirectory();
6955 File systemDir = new File(dataDir, "system");
6956 File fname = new File(systemDir, "called_pre_boots.dat");
6957 return fname;
6958 }
Dianne Hackborn661cd522011-08-22 00:26:20 -07006959
6960 static final int LAST_DONE_VERSION = 10000;
6961
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006962 private static ArrayList<ComponentName> readLastDonePreBootReceivers() {
6963 ArrayList<ComponentName> lastDoneReceivers = new ArrayList<ComponentName>();
6964 File file = getCalledPreBootReceiversFile();
6965 FileInputStream fis = null;
6966 try {
6967 fis = new FileInputStream(file);
6968 DataInputStream dis = new DataInputStream(new BufferedInputStream(fis, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07006969 int fvers = dis.readInt();
6970 if (fvers == LAST_DONE_VERSION) {
6971 String vers = dis.readUTF();
6972 String codename = dis.readUTF();
6973 String build = dis.readUTF();
6974 if (android.os.Build.VERSION.RELEASE.equals(vers)
6975 && android.os.Build.VERSION.CODENAME.equals(codename)
6976 && android.os.Build.VERSION.INCREMENTAL.equals(build)) {
6977 int num = dis.readInt();
6978 while (num > 0) {
6979 num--;
6980 String pkg = dis.readUTF();
6981 String cls = dis.readUTF();
6982 lastDoneReceivers.add(new ComponentName(pkg, cls));
6983 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006984 }
6985 }
6986 } catch (FileNotFoundException e) {
6987 } catch (IOException e) {
6988 Slog.w(TAG, "Failure reading last done pre-boot receivers", e);
6989 } finally {
6990 if (fis != null) {
6991 try {
6992 fis.close();
6993 } catch (IOException e) {
6994 }
6995 }
6996 }
6997 return lastDoneReceivers;
6998 }
6999
7000 private static void writeLastDonePreBootReceivers(ArrayList<ComponentName> list) {
7001 File file = getCalledPreBootReceiversFile();
7002 FileOutputStream fos = null;
7003 DataOutputStream dos = null;
7004 try {
7005 Slog.i(TAG, "Writing new set of last done pre-boot receivers...");
7006 fos = new FileOutputStream(file);
7007 dos = new DataOutputStream(new BufferedOutputStream(fos, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007008 dos.writeInt(LAST_DONE_VERSION);
7009 dos.writeUTF(android.os.Build.VERSION.RELEASE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007010 dos.writeUTF(android.os.Build.VERSION.CODENAME);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007011 dos.writeUTF(android.os.Build.VERSION.INCREMENTAL);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007012 dos.writeInt(list.size());
7013 for (int i=0; i<list.size(); i++) {
7014 dos.writeUTF(list.get(i).getPackageName());
7015 dos.writeUTF(list.get(i).getClassName());
7016 }
7017 } catch (IOException e) {
7018 Slog.w(TAG, "Failure writing last done pre-boot receivers", e);
7019 file.delete();
7020 } finally {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07007021 FileUtils.sync(fos);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007022 if (dos != null) {
7023 try {
7024 dos.close();
7025 } catch (IOException e) {
7026 // TODO Auto-generated catch block
7027 e.printStackTrace();
7028 }
7029 }
7030 }
7031 }
7032
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007033 public void systemReady(final Runnable goingCallback) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007034 synchronized(this) {
7035 if (mSystemReady) {
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007036 if (goingCallback != null) goingCallback.run();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007037 return;
7038 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007039
7040 // Check to see if there are any update receivers to run.
7041 if (!mDidUpdate) {
7042 if (mWaitingUpdate) {
7043 return;
7044 }
7045 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
7046 List<ResolveInfo> ris = null;
7047 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007048 ris = AppGlobals.getPackageManager().queryIntentReceivers(
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007049 intent, null, 0);
7050 } catch (RemoteException e) {
7051 }
7052 if (ris != null) {
7053 for (int i=ris.size()-1; i>=0; i--) {
7054 if ((ris.get(i).activityInfo.applicationInfo.flags
7055 &ApplicationInfo.FLAG_SYSTEM) == 0) {
7056 ris.remove(i);
7057 }
7058 }
7059 intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007060
7061 ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers();
7062
7063 final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007064 for (int i=0; i<ris.size(); i++) {
7065 ActivityInfo ai = ris.get(i).activityInfo;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007066 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7067 if (lastDoneReceivers.contains(comp)) {
7068 ris.remove(i);
7069 i--;
7070 }
7071 }
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07007072
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007073 for (int i=0; i<ris.size(); i++) {
7074 ActivityInfo ai = ris.get(i).activityInfo;
7075 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7076 doneReceivers.add(comp);
7077 intent.setComponent(comp);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007078 IIntentReceiver finisher = null;
Dianne Hackbornd6847842010-01-12 18:14:19 -08007079 if (i == ris.size()-1) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007080 finisher = new IIntentReceiver.Stub() {
7081 public void performReceive(Intent intent, int resultCode,
Dianne Hackborn68d881c2009-10-05 13:58:17 -07007082 String data, Bundle extras, boolean ordered,
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007083 boolean sticky) {
7084 // The raw IIntentReceiver interface is called
7085 // with the AM lock held, so redispatch to
7086 // execute our code without the lock.
7087 mHandler.post(new Runnable() {
7088 public void run() {
7089 synchronized (ActivityManagerService.this) {
7090 mDidUpdate = true;
7091 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007092 writeLastDonePreBootReceivers(doneReceivers);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007093 showBootMessage(mContext.getText(
7094 R.string.android_upgrading_complete),
7095 false);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007096 systemReady(goingCallback);
7097 }
7098 });
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007099 }
7100 };
7101 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08007102 Slog.i(TAG, "Sending system update to: " + intent.getComponent());
Amith Yamasani742a6712011-05-04 14:49:28 -07007103 /* TODO: Send this to all users */
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007104 broadcastIntentLocked(null, null, intent, null, finisher,
Amith Yamasani742a6712011-05-04 14:49:28 -07007105 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID,
Amith Yamasanic600e21f2012-02-14 16:08:07 -08007106 0 /* UserId zero */);
Dianne Hackbornd6847842010-01-12 18:14:19 -08007107 if (finisher != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007108 mWaitingUpdate = true;
7109 }
7110 }
7111 }
7112 if (mWaitingUpdate) {
7113 return;
7114 }
7115 mDidUpdate = true;
7116 }
7117
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007118 mSystemReady = true;
7119 if (!mStartRunning) {
7120 return;
7121 }
7122 }
7123
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007124 ArrayList<ProcessRecord> procsToKill = null;
7125 synchronized(mPidsSelfLocked) {
7126 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
7127 ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7128 if (!isAllowedWhileBooting(proc.info)){
7129 if (procsToKill == null) {
7130 procsToKill = new ArrayList<ProcessRecord>();
7131 }
7132 procsToKill.add(proc);
7133 }
7134 }
7135 }
7136
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007137 synchronized(this) {
7138 if (procsToKill != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007139 for (int i=procsToKill.size()-1; i>=0; i--) {
7140 ProcessRecord proc = procsToKill.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007141 Slog.i(TAG, "Removing system update proc: " + proc);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007142 removeProcessLocked(proc, true, false, "system update done");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007143 }
7144 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007145
7146 // Now that we have cleaned up any update processes, we
7147 // are ready to start launching real processes and know that
7148 // we won't trample on them any more.
7149 mProcessesReady = true;
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007150 }
7151
Joe Onorato8a9b2202010-02-26 18:56:32 -08007152 Slog.i(TAG, "System now ready");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007153 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007154 SystemClock.uptimeMillis());
7155
7156 synchronized(this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007157 // Make sure we have no pre-ready processes sitting around.
7158
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007159 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
7160 ResolveInfo ri = mContext.getPackageManager()
7161 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST),
Dianne Hackborn1655be42009-05-08 14:29:01 -07007162 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007163 CharSequence errorMsg = null;
7164 if (ri != null) {
7165 ActivityInfo ai = ri.activityInfo;
7166 ApplicationInfo app = ai.applicationInfo;
7167 if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7168 mTopAction = Intent.ACTION_FACTORY_TEST;
7169 mTopData = null;
7170 mTopComponent = new ComponentName(app.packageName,
7171 ai.name);
7172 } else {
7173 errorMsg = mContext.getResources().getText(
7174 com.android.internal.R.string.factorytest_not_system);
7175 }
7176 } else {
7177 errorMsg = mContext.getResources().getText(
7178 com.android.internal.R.string.factorytest_no_action);
7179 }
7180 if (errorMsg != null) {
7181 mTopAction = null;
7182 mTopData = null;
7183 mTopComponent = null;
7184 Message msg = Message.obtain();
7185 msg.what = SHOW_FACTORY_ERROR_MSG;
7186 msg.getData().putCharSequence("msg", errorMsg);
7187 mHandler.sendMessage(msg);
7188 }
7189 }
7190 }
7191
7192 retrieveSettings();
7193
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007194 if (goingCallback != null) goingCallback.run();
7195
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007196 synchronized (this) {
7197 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
7198 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007199 List apps = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07007200 getPersistentApplications(STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007201 if (apps != null) {
7202 int N = apps.size();
7203 int i;
7204 for (i=0; i<N; i++) {
7205 ApplicationInfo info
7206 = (ApplicationInfo)apps.get(i);
7207 if (info != null &&
7208 !info.packageName.equals("android")) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007209 addAppLocked(info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007210 }
7211 }
7212 }
7213 } catch (RemoteException ex) {
7214 // pm is in same process, this will never happen.
7215 }
7216 }
7217
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007218 // Start up initial activity.
7219 mBooting = true;
7220
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007221 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007222 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007223 Message msg = Message.obtain();
7224 msg.what = SHOW_UID_ERROR_MSG;
7225 mHandler.sendMessage(msg);
7226 }
7227 } catch (RemoteException e) {
7228 }
7229
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007230 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007231 }
7232 }
7233
Dan Egnorb7f03672009-12-09 16:22:32 -08007234 private boolean makeAppCrashingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007235 String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007236 app.crashing = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007237 app.crashingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007238 ActivityManager.ProcessErrorStateInfo.CRASHED, null, shortMsg, longMsg, stackTrace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007239 startAppProblemLocked(app);
7240 app.stopFreezingAllLocked();
7241 return handleAppCrashLocked(app);
7242 }
7243
Dan Egnorb7f03672009-12-09 16:22:32 -08007244 private void makeAppNotRespondingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007245 String activity, String shortMsg, String longMsg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007246 app.notResponding = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007247 app.notRespondingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007248 ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING,
7249 activity, shortMsg, longMsg, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007250 startAppProblemLocked(app);
7251 app.stopFreezingAllLocked();
7252 }
7253
7254 /**
7255 * Generate a process error record, suitable for attachment to a ProcessRecord.
7256 *
7257 * @param app The ProcessRecord in which the error occurred.
7258 * @param condition Crashing, Application Not Responding, etc. Values are defined in
7259 * ActivityManager.AppErrorStateInfo
Dan Egnor60d87622009-12-16 16:32:58 -08007260 * @param activity The activity associated with the crash, if known.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007261 * @param shortMsg Short message describing the crash.
7262 * @param longMsg Long message describing the crash.
Dan Egnorb7f03672009-12-09 16:22:32 -08007263 * @param stackTrace Full crash stack trace, may be null.
7264 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007265 * @return Returns a fully-formed AppErrorStateInfo record.
7266 */
7267 private ActivityManager.ProcessErrorStateInfo generateProcessError(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007268 int condition, String activity, String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007269 ActivityManager.ProcessErrorStateInfo report = new ActivityManager.ProcessErrorStateInfo();
Dan Egnorb7f03672009-12-09 16:22:32 -08007270
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007271 report.condition = condition;
7272 report.processName = app.processName;
7273 report.pid = app.pid;
7274 report.uid = app.info.uid;
Dan Egnor60d87622009-12-16 16:32:58 -08007275 report.tag = activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007276 report.shortMsg = shortMsg;
7277 report.longMsg = longMsg;
Dan Egnorb7f03672009-12-09 16:22:32 -08007278 report.stackTrace = stackTrace;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007279
7280 return report;
7281 }
7282
Dan Egnor42471dd2010-01-07 17:25:22 -08007283 void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007284 synchronized (this) {
7285 app.crashing = false;
7286 app.crashingReport = null;
7287 app.notResponding = false;
7288 app.notRespondingReport = null;
7289 if (app.anrDialog == fromDialog) {
7290 app.anrDialog = null;
7291 }
7292 if (app.waitDialog == fromDialog) {
7293 app.waitDialog = null;
7294 }
7295 if (app.pid > 0 && app.pid != MY_PID) {
Dan Egnor42471dd2010-01-07 17:25:22 -08007296 handleAppCrashLocked(app);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007297 Slog.i(ActivityManagerService.TAG, "Killing " + app + ": user's request");
Dianne Hackborn8633e682010-04-22 16:03:41 -07007298 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
7299 app.processName, app.setAdj, "user's request after error");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007300 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007301 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007302 }
7303 }
Dan Egnor42471dd2010-01-07 17:25:22 -08007304
Dan Egnorb7f03672009-12-09 16:22:32 -08007305 private boolean handleAppCrashLocked(ProcessRecord app) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007306 long now = SystemClock.uptimeMillis();
7307
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007308 Long crashTime;
7309 if (!app.isolated) {
7310 crashTime = mProcessCrashTimes.get(app.info.processName, app.uid);
7311 } else {
7312 crashTime = null;
7313 }
Dianne Hackborn7d608422011-08-07 16:24:18 -07007314 if (crashTime != null && now < crashTime+ProcessList.MIN_CRASH_INTERVAL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007315 // This process loses!
Joe Onorato8a9b2202010-02-26 18:56:32 -08007316 Slog.w(TAG, "Process " + app.info.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007317 + " has crashed too many times: killing!");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007318 EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007319 app.info.processName, app.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007320 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
7321 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007322 if (r.app == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007323 Slog.w(TAG, " Force finishing activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007324 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007325 r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED, null, "crashed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007326 }
7327 }
7328 if (!app.persistent) {
7329 // We don't want to start this process again until the user
7330 // explicitly does so... but for persistent process, we really
7331 // need to keep it running. If a persistent process is actually
7332 // repeatedly crashing, then badness for everyone.
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007333 EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007334 app.info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007335 if (!app.isolated) {
7336 // XXX We don't have a way to mark isolated processes
7337 // as bad, since they don't have a peristent identity.
7338 mBadProcesses.put(app.info.processName, app.uid, now);
7339 mProcessCrashTimes.remove(app.info.processName, app.uid);
7340 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007341 app.bad = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007342 app.removed = true;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07007343 // Don't let services in this process be restarted and potentially
7344 // annoy the user repeatedly. Unless it is persistent, since those
7345 // processes run critical code.
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007346 removeProcessLocked(app, false, false, "crash");
Dianne Hackborncb44d962011-03-10 17:02:27 -08007347 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007348 return false;
7349 }
Dianne Hackborncb44d962011-03-10 17:02:27 -08007350 mMainStack.resumeTopActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007351 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007352 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007353 if (r.app == app) {
7354 // If the top running activity is from this crashing
7355 // process, then terminate it to avoid getting in a loop.
7356 Slog.w(TAG, " Force finishing activity "
7357 + r.intent.getComponent().flattenToShortString());
Dianne Hackbornbe707852011-11-11 14:32:10 -08007358 int index = mMainStack.indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007359 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007360 Activity.RESULT_CANCELED, null, "crashed");
Dianne Hackborn070783f2010-12-29 16:46:28 -08007361 // Also terminate any activities below it that aren't yet
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007362 // stopped, to avoid a situation where one will get
7363 // re-start our crashing activity once it gets resumed again.
7364 index--;
7365 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007366 r = (ActivityRecord)mMainStack.mHistory.get(index);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007367 if (r.state == ActivityState.RESUMED
7368 || r.state == ActivityState.PAUSING
7369 || r.state == ActivityState.PAUSED) {
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08007370 if (!r.isHomeActivity || mHomeProcess != r.app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007371 Slog.w(TAG, " Force finishing activity "
7372 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007373 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007374 Activity.RESULT_CANCELED, null, "crashed");
7375 }
7376 }
7377 }
7378 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007379 }
7380
7381 // Bump up the crash count of any services currently running in the proc.
7382 if (app.services.size() != 0) {
7383 // Any services running in the application need to be placed
7384 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -07007385 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007386 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07007387 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007388 sr.crashCount++;
7389 }
7390 }
Mattias Larssona4fd0072010-06-22 22:37:03 +02007391
7392 // If the crashing process is what we consider to be the "home process" and it has been
7393 // replaced by a third-party app, clear the package preferred activities from packages
7394 // with a home activity running in the process to prevent a repeatedly crashing app
7395 // from blocking the user to manually clear the list.
7396 if (app == mHomeProcess && mHomeProcess.activities.size() > 0
7397 && (mHomeProcess.info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
7398 Iterator it = mHomeProcess.activities.iterator();
7399 while (it.hasNext()) {
Jean-Baptiste Queru5ea89f72010-07-30 09:30:31 -07007400 ActivityRecord r = (ActivityRecord)it.next();
Mattias Larssona4fd0072010-06-22 22:37:03 +02007401 if (r.isHomeActivity) {
7402 Log.i(TAG, "Clearing package preferred activities from " + r.packageName);
7403 try {
7404 ActivityThread.getPackageManager()
7405 .clearPackagePreferredActivities(r.packageName);
7406 } catch (RemoteException c) {
7407 // pm is in same process, this will never happen.
7408 }
7409 }
7410 }
7411 }
7412
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007413 if (!app.isolated) {
7414 // XXX Can't keep track of crash times for isolated processes,
7415 // because they don't have a perisistent identity.
7416 mProcessCrashTimes.put(app.info.processName, app.uid, now);
7417 }
7418
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007419 return true;
7420 }
7421
7422 void startAppProblemLocked(ProcessRecord app) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08007423 app.errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver(
7424 mContext, app.info.packageName, app.info.flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007425 skipCurrentReceiverLocked(app);
7426 }
7427
7428 void skipCurrentReceiverLocked(ProcessRecord app) {
Christopher Tatef46723b2012-01-26 14:19:24 -08007429 for (BroadcastQueue queue : mBroadcastQueues) {
7430 queue.skipCurrentReceiverLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007431 }
7432 }
7433
Dan Egnor60d87622009-12-16 16:32:58 -08007434 /**
7435 * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes.
7436 * The application process will exit immediately after this call returns.
7437 * @param app object of the crashing app, null for the system server
7438 * @param crashInfo describing the exception
7439 */
7440 public void handleApplicationCrash(IBinder app, ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007441 ProcessRecord r = findAppProcess(app, "Crash");
Jeff Sharkeya353d262011-10-28 11:12:06 -07007442 final String processName = app == null ? "system_server"
7443 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08007444
7445 EventLog.writeEvent(EventLogTags.AM_CRASH, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07007446 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08007447 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08007448 crashInfo.exceptionClassName,
7449 crashInfo.exceptionMessage,
7450 crashInfo.throwFileName,
7451 crashInfo.throwLineNumber);
7452
Jeff Sharkeya353d262011-10-28 11:12:06 -07007453 addErrorToDropBox("crash", r, processName, null, null, null, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08007454
7455 crashApplication(r, crashInfo);
7456 }
7457
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007458 public void handleApplicationStrictModeViolation(
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007459 IBinder app,
7460 int violationMask,
7461 StrictMode.ViolationInfo info) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007462 ProcessRecord r = findAppProcess(app, "StrictMode");
7463 if (r == null) {
7464 return;
7465 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007466
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007467 if ((violationMask & StrictMode.PENALTY_DROPBOX) != 0) {
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08007468 Integer stackFingerprint = info.hashCode();
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007469 boolean logIt = true;
7470 synchronized (mAlreadyLoggedViolatedStacks) {
7471 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) {
7472 logIt = false;
7473 // TODO: sub-sample into EventLog for these, with
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007474 // the info.durationMillis? Then we'd get
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007475 // the relative pain numbers, without logging all
7476 // the stack traces repeatedly. We'd want to do
7477 // likewise in the client code, which also does
7478 // dup suppression, before the Binder call.
7479 } else {
7480 if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) {
7481 mAlreadyLoggedViolatedStacks.clear();
7482 }
7483 mAlreadyLoggedViolatedStacks.add(stackFingerprint);
7484 }
7485 }
7486 if (logIt) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007487 logStrictModeViolationToDropBox(r, info);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007488 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007489 }
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007490
7491 if ((violationMask & StrictMode.PENALTY_DIALOG) != 0) {
7492 AppErrorResult result = new AppErrorResult();
7493 synchronized (this) {
7494 final long origId = Binder.clearCallingIdentity();
7495
7496 Message msg = Message.obtain();
7497 msg.what = SHOW_STRICT_MODE_VIOLATION_MSG;
7498 HashMap<String, Object> data = new HashMap<String, Object>();
7499 data.put("result", result);
7500 data.put("app", r);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007501 data.put("violationMask", violationMask);
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007502 data.put("info", info);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007503 msg.obj = data;
7504 mHandler.sendMessage(msg);
7505
7506 Binder.restoreCallingIdentity(origId);
7507 }
7508 int res = result.get();
Dianne Hackbornb424b632010-08-18 15:59:05 -07007509 Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007510 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007511 }
7512
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007513 // Depending on the policy in effect, there could be a bunch of
7514 // these in quick succession so we try to batch these together to
7515 // minimize disk writes, number of dropbox entries, and maximize
7516 // compression, by having more fewer, larger records.
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007517 private void logStrictModeViolationToDropBox(
7518 ProcessRecord process,
7519 StrictMode.ViolationInfo info) {
7520 if (info == null) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007521 return;
7522 }
7523 final boolean isSystemApp = process == null ||
7524 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM |
7525 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07007526 final String processName = process == null ? "unknown" : process.processName;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007527 final String dropboxTag = isSystemApp ? "system_app_strictmode" : "data_app_strictmode";
7528 final DropBoxManager dbox = (DropBoxManager)
7529 mContext.getSystemService(Context.DROPBOX_SERVICE);
7530
7531 // Exit early if the dropbox isn't configured to accept this report type.
7532 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
7533
7534 boolean bufferWasEmpty;
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007535 boolean needsFlush;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007536 final StringBuilder sb = isSystemApp ? mStrictModeBuffer : new StringBuilder(1024);
7537 synchronized (sb) {
7538 bufferWasEmpty = sb.length() == 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07007539 appendDropBoxProcessHeaders(process, processName, sb);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007540 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
7541 sb.append("System-App: ").append(isSystemApp).append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007542 sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n");
7543 if (info.violationNumThisLoop != 0) {
7544 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n");
7545 }
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07007546 if (info.numAnimationsRunning != 0) {
7547 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n");
7548 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07007549 if (info.broadcastIntentAction != null) {
7550 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n");
7551 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08007552 if (info.durationMillis != -1) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007553 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n");
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007554 }
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08007555 if (info.numInstances != -1) {
7556 sb.append("Instance-Count: ").append(info.numInstances).append("\n");
7557 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08007558 if (info.tags != null) {
7559 for (String tag : info.tags) {
7560 sb.append("Span-Tag: ").append(tag).append("\n");
7561 }
7562 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007563 sb.append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007564 if (info.crashInfo != null && info.crashInfo.stackTrace != null) {
7565 sb.append(info.crashInfo.stackTrace);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007566 }
7567 sb.append("\n");
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007568
7569 // Only buffer up to ~64k. Various logging bits truncate
7570 // things at 128k.
7571 needsFlush = (sb.length() > 64 * 1024);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007572 }
7573
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007574 // Flush immediately if the buffer's grown too large, or this
7575 // is a non-system app. Non-system apps are isolated with a
7576 // different tag & policy and not batched.
7577 //
7578 // Batching is useful during internal testing with
7579 // StrictMode settings turned up high. Without batching,
7580 // thousands of separate files could be created on boot.
7581 if (!isSystemApp || needsFlush) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007582 new Thread("Error dump: " + dropboxTag) {
7583 @Override
7584 public void run() {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007585 String report;
7586 synchronized (sb) {
7587 report = sb.toString();
7588 sb.delete(0, sb.length());
7589 sb.trimToSize();
7590 }
7591 if (report.length() != 0) {
7592 dbox.addText(dropboxTag, report);
7593 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007594 }
7595 }.start();
7596 return;
7597 }
7598
7599 // System app batching:
7600 if (!bufferWasEmpty) {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007601 // An existing dropbox-writing thread is outstanding, so
7602 // we don't need to start it up. The existing thread will
7603 // catch the buffer appends we just did.
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007604 return;
7605 }
7606
7607 // Worker thread to both batch writes and to avoid blocking the caller on I/O.
7608 // (After this point, we shouldn't access AMS internal data structures.)
7609 new Thread("Error dump: " + dropboxTag) {
7610 @Override
7611 public void run() {
7612 // 5 second sleep to let stacks arrive and be batched together
7613 try {
7614 Thread.sleep(5000); // 5 seconds
7615 } catch (InterruptedException e) {}
7616
7617 String errorReport;
7618 synchronized (mStrictModeBuffer) {
7619 errorReport = mStrictModeBuffer.toString();
7620 if (errorReport.length() == 0) {
7621 return;
7622 }
7623 mStrictModeBuffer.delete(0, mStrictModeBuffer.length());
7624 mStrictModeBuffer.trimToSize();
7625 }
7626 dbox.addText(dropboxTag, errorReport);
7627 }
7628 }.start();
7629 }
7630
Dan Egnor60d87622009-12-16 16:32:58 -08007631 /**
7632 * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors.
7633 * @param app object of the crashing app, null for the system server
7634 * @param tag reported by the caller
7635 * @param crashInfo describing the context of the error
7636 * @return true if the process should exit immediately (WTF is fatal)
7637 */
7638 public boolean handleApplicationWtf(IBinder app, String tag,
Dan Egnorb7f03672009-12-09 16:22:32 -08007639 ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007640 ProcessRecord r = findAppProcess(app, "WTF");
Jeff Sharkeya353d262011-10-28 11:12:06 -07007641 final String processName = app == null ? "system_server"
7642 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08007643
7644 EventLog.writeEvent(EventLogTags.AM_WTF, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07007645 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08007646 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08007647 tag, crashInfo.exceptionMessage);
7648
Jeff Sharkeya353d262011-10-28 11:12:06 -07007649 addErrorToDropBox("wtf", r, processName, null, null, tag, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08007650
Dianne Hackborn1ab43772011-03-15 14:38:02 -07007651 if (r != null && r.pid != Process.myPid() &&
7652 Settings.Secure.getInt(mContext.getContentResolver(),
7653 Settings.Secure.WTF_IS_FATAL, 0) != 0) {
Dan Egnor60d87622009-12-16 16:32:58 -08007654 crashApplication(r, crashInfo);
7655 return true;
7656 } else {
7657 return false;
7658 }
7659 }
7660
7661 /**
7662 * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit})
7663 * @return the corresponding {@link ProcessRecord} object, or null if none could be found
7664 */
Dianne Hackborncb44d962011-03-10 17:02:27 -08007665 private ProcessRecord findAppProcess(IBinder app, String reason) {
Dan Egnor60d87622009-12-16 16:32:58 -08007666 if (app == null) {
7667 return null;
7668 }
7669
7670 synchronized (this) {
7671 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
7672 final int NA = apps.size();
7673 for (int ia=0; ia<NA; ia++) {
7674 ProcessRecord p = apps.valueAt(ia);
7675 if (p.thread != null && p.thread.asBinder() == app) {
7676 return p;
7677 }
7678 }
7679 }
7680
Dianne Hackborncb44d962011-03-10 17:02:27 -08007681 Slog.w(TAG, "Can't find mystery application for " + reason
7682 + " from pid=" + Binder.getCallingPid()
7683 + " uid=" + Binder.getCallingUid() + ": " + app);
Dan Egnor60d87622009-12-16 16:32:58 -08007684 return null;
7685 }
7686 }
7687
7688 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007689 * Utility function for addErrorToDropBox and handleStrictModeViolation's logging
7690 * to append various headers to the dropbox log text.
Dan Egnor60d87622009-12-16 16:32:58 -08007691 */
Jeff Sharkeya353d262011-10-28 11:12:06 -07007692 private void appendDropBoxProcessHeaders(ProcessRecord process, String processName,
7693 StringBuilder sb) {
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08007694 // Watchdog thread ends up invoking this function (with
7695 // a null ProcessRecord) to add the stack file to dropbox.
7696 // Do not acquire a lock on this (am) in such cases, as it
7697 // could cause a potential deadlock, if and when watchdog
7698 // is invoked due to unavailability of lock on am and it
7699 // would prevent watchdog from killing system_server.
7700 if (process == null) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07007701 sb.append("Process: ").append(processName).append("\n");
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08007702 return;
7703 }
Brad Fitzpatrick1e02d362010-09-10 09:19:50 -07007704 // Note: ProcessRecord 'process' is guarded by the service
7705 // instance. (notably process.pkgList, which could otherwise change
7706 // concurrently during execution of this method)
7707 synchronized (this) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07007708 sb.append("Process: ").append(processName).append("\n");
Dan Egnora455d192010-03-12 08:52:28 -08007709 int flags = process.info.flags;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007710 IPackageManager pm = AppGlobals.getPackageManager();
Dan Egnora455d192010-03-12 08:52:28 -08007711 sb.append("Flags: 0x").append(Integer.toString(flags, 16)).append("\n");
7712 for (String pkg : process.pkgList) {
7713 sb.append("Package: ").append(pkg);
Dan Egnor42471dd2010-01-07 17:25:22 -08007714 try {
Dan Egnora455d192010-03-12 08:52:28 -08007715 PackageInfo pi = pm.getPackageInfo(pkg, 0);
7716 if (pi != null) {
7717 sb.append(" v").append(pi.versionCode);
7718 if (pi.versionName != null) {
7719 sb.append(" (").append(pi.versionName).append(")");
7720 }
7721 }
7722 } catch (RemoteException e) {
7723 Slog.e(TAG, "Error getting package info: " + pkg, e);
Dan Egnor60d87622009-12-16 16:32:58 -08007724 }
Dan Egnora455d192010-03-12 08:52:28 -08007725 sb.append("\n");
Dan Egnor60d87622009-12-16 16:32:58 -08007726 }
Dan Egnora455d192010-03-12 08:52:28 -08007727 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007728 }
7729
7730 private static String processClass(ProcessRecord process) {
7731 if (process == null || process.pid == MY_PID) {
7732 return "system_server";
7733 } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
7734 return "system_app";
7735 } else {
7736 return "data_app";
7737 }
7738 }
7739
7740 /**
7741 * Write a description of an error (crash, WTF, ANR) to the drop box.
7742 * @param eventType to include in the drop box tag ("crash", "wtf", etc.)
7743 * @param process which caused the error, null means the system server
7744 * @param activity which triggered the error, null if unknown
7745 * @param parent activity related to the error, null if unknown
7746 * @param subject line related to the error, null if absent
7747 * @param report in long form describing the error, null if absent
7748 * @param logFile to include in the report, null if none
7749 * @param crashInfo giving an application stack trace, null if absent
7750 */
7751 public void addErrorToDropBox(String eventType,
Jeff Sharkeya353d262011-10-28 11:12:06 -07007752 ProcessRecord process, String processName, ActivityRecord activity,
7753 ActivityRecord parent, String subject,
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007754 final String report, final File logFile,
7755 final ApplicationErrorReport.CrashInfo crashInfo) {
7756 // NOTE -- this must never acquire the ActivityManagerService lock,
7757 // otherwise the watchdog may be prevented from resetting the system.
7758
7759 final String dropboxTag = processClass(process) + "_" + eventType;
7760 final DropBoxManager dbox = (DropBoxManager)
7761 mContext.getSystemService(Context.DROPBOX_SERVICE);
7762
7763 // Exit early if the dropbox isn't configured to accept this report type.
7764 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
7765
7766 final StringBuilder sb = new StringBuilder(1024);
Jeff Sharkeya353d262011-10-28 11:12:06 -07007767 appendDropBoxProcessHeaders(process, processName, sb);
Dan Egnora455d192010-03-12 08:52:28 -08007768 if (activity != null) {
7769 sb.append("Activity: ").append(activity.shortComponentName).append("\n");
7770 }
7771 if (parent != null && parent.app != null && parent.app.pid != process.pid) {
7772 sb.append("Parent-Process: ").append(parent.app.processName).append("\n");
7773 }
7774 if (parent != null && parent != activity) {
7775 sb.append("Parent-Activity: ").append(parent.shortComponentName).append("\n");
7776 }
7777 if (subject != null) {
7778 sb.append("Subject: ").append(subject).append("\n");
7779 }
7780 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
Christian Lindeberg03d2ca62010-09-28 14:52:20 +02007781 if (Debug.isDebuggerConnected()) {
7782 sb.append("Debugger: Connected\n");
7783 }
Dan Egnora455d192010-03-12 08:52:28 -08007784 sb.append("\n");
7785
7786 // Do the rest in a worker thread to avoid blocking the caller on I/O
7787 // (After this point, we shouldn't access AMS internal data structures.)
7788 Thread worker = new Thread("Error dump: " + dropboxTag) {
7789 @Override
7790 public void run() {
7791 if (report != null) {
7792 sb.append(report);
7793 }
7794 if (logFile != null) {
7795 try {
7796 sb.append(FileUtils.readTextFile(logFile, 128 * 1024, "\n\n[[TRUNCATED]]"));
7797 } catch (IOException e) {
7798 Slog.e(TAG, "Error reading " + logFile, e);
7799 }
7800 }
7801 if (crashInfo != null && crashInfo.stackTrace != null) {
7802 sb.append(crashInfo.stackTrace);
7803 }
7804
7805 String setting = Settings.Secure.ERROR_LOGCAT_PREFIX + dropboxTag;
7806 int lines = Settings.Secure.getInt(mContext.getContentResolver(), setting, 0);
7807 if (lines > 0) {
7808 sb.append("\n");
7809
7810 // Merge several logcat streams, and take the last N lines
7811 InputStreamReader input = null;
7812 try {
7813 java.lang.Process logcat = new ProcessBuilder("/system/bin/logcat",
7814 "-v", "time", "-b", "events", "-b", "system", "-b", "main",
7815 "-t", String.valueOf(lines)).redirectErrorStream(true).start();
7816
7817 try { logcat.getOutputStream().close(); } catch (IOException e) {}
7818 try { logcat.getErrorStream().close(); } catch (IOException e) {}
7819 input = new InputStreamReader(logcat.getInputStream());
7820
7821 int num;
7822 char[] buf = new char[8192];
7823 while ((num = input.read(buf)) > 0) sb.append(buf, 0, num);
7824 } catch (IOException e) {
7825 Slog.e(TAG, "Error running logcat", e);
7826 } finally {
7827 if (input != null) try { input.close(); } catch (IOException e) {}
7828 }
7829 }
7830
7831 dbox.addText(dropboxTag, sb.toString());
Dan Egnor60d87622009-12-16 16:32:58 -08007832 }
Dan Egnora455d192010-03-12 08:52:28 -08007833 };
7834
7835 if (process == null || process.pid == MY_PID) {
7836 worker.run(); // We may be about to die -- need to run this synchronously
7837 } else {
7838 worker.start();
Dan Egnor60d87622009-12-16 16:32:58 -08007839 }
7840 }
7841
7842 /**
7843 * Bring up the "unexpected error" dialog box for a crashing app.
7844 * Deal with edge cases (intercepts from instrumented applications,
7845 * ActivityController, error intent receivers, that sort of thing).
7846 * @param r the application crashing
7847 * @param crashInfo describing the failure
7848 */
7849 private void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) {
Dan Egnorb7f03672009-12-09 16:22:32 -08007850 long timeMillis = System.currentTimeMillis();
7851 String shortMsg = crashInfo.exceptionClassName;
7852 String longMsg = crashInfo.exceptionMessage;
7853 String stackTrace = crashInfo.stackTrace;
7854 if (shortMsg != null && longMsg != null) {
7855 longMsg = shortMsg + ": " + longMsg;
7856 } else if (shortMsg != null) {
7857 longMsg = shortMsg;
7858 }
7859
Dan Egnor60d87622009-12-16 16:32:58 -08007860 AppErrorResult result = new AppErrorResult();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007861 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007862 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007863 try {
7864 String name = r != null ? r.processName : null;
7865 int pid = r != null ? r.pid : Binder.getCallingPid();
Dan Egnor60d87622009-12-16 16:32:58 -08007866 if (!mController.appCrashed(name, pid,
Dan Egnorb7f03672009-12-09 16:22:32 -08007867 shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007868 Slog.w(TAG, "Force-killing crashed app " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007869 + " at watcher's request");
7870 Process.killProcess(pid);
Dan Egnorb7f03672009-12-09 16:22:32 -08007871 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007872 }
7873 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007874 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007875 }
7876 }
7877
7878 final long origId = Binder.clearCallingIdentity();
7879
7880 // If this process is running instrumentation, finish it.
7881 if (r != null && r.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007882 Slog.w(TAG, "Error in app " + r.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007883 + " running instrumentation " + r.instrumentationClass + ":");
Joe Onorato8a9b2202010-02-26 18:56:32 -08007884 if (shortMsg != null) Slog.w(TAG, " " + shortMsg);
7885 if (longMsg != null) Slog.w(TAG, " " + longMsg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007886 Bundle info = new Bundle();
7887 info.putString("shortMsg", shortMsg);
7888 info.putString("longMsg", longMsg);
7889 finishInstrumentationLocked(r, Activity.RESULT_CANCELED, info);
7890 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08007891 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007892 }
7893
Dan Egnor60d87622009-12-16 16:32:58 -08007894 // If we can't identify the process or it's already exceeded its crash quota,
7895 // quit right away without showing a crash dialog.
7896 if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007897 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08007898 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007899 }
7900
7901 Message msg = Message.obtain();
7902 msg.what = SHOW_ERROR_MSG;
7903 HashMap data = new HashMap();
7904 data.put("result", result);
7905 data.put("app", r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007906 msg.obj = data;
7907 mHandler.sendMessage(msg);
7908
7909 Binder.restoreCallingIdentity(origId);
7910 }
7911
7912 int res = result.get();
7913
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007914 Intent appErrorIntent = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007915 synchronized (this) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007916 if (r != null && !r.isolated) {
7917 // XXX Can't keep track of crash time for isolated processes,
7918 // since they don't have a persistent identity.
7919 mProcessCrashTimes.put(r.info.processName, r.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007920 SystemClock.uptimeMillis());
7921 }
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007922 if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) {
Dan Egnorb7f03672009-12-09 16:22:32 -08007923 appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007924 }
7925 }
7926
7927 if (appErrorIntent != null) {
7928 try {
7929 mContext.startActivity(appErrorIntent);
7930 } catch (ActivityNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007931 Slog.w(TAG, "bug report receiver dissappeared", e);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007932 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007933 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007934 }
Dan Egnorb7f03672009-12-09 16:22:32 -08007935
7936 Intent createAppErrorIntentLocked(ProcessRecord r,
7937 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
7938 ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007939 if (report == null) {
7940 return null;
7941 }
7942 Intent result = new Intent(Intent.ACTION_APP_ERROR);
7943 result.setComponent(r.errorReportReceiver);
7944 result.putExtra(Intent.EXTRA_BUG_REPORT, report);
7945 result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
7946 return result;
7947 }
7948
Dan Egnorb7f03672009-12-09 16:22:32 -08007949 private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r,
7950 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007951 if (r.errorReportReceiver == null) {
7952 return null;
7953 }
7954
7955 if (!r.crashing && !r.notResponding) {
7956 return null;
7957 }
7958
Dan Egnorb7f03672009-12-09 16:22:32 -08007959 ApplicationErrorReport report = new ApplicationErrorReport();
7960 report.packageName = r.info.packageName;
7961 report.installerPackageName = r.errorReportReceiver.getPackageName();
7962 report.processName = r.processName;
7963 report.time = timeMillis;
Jacek Surazskie0ee6ef2010-01-07 16:23:03 +01007964 report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007965
Dan Egnorb7f03672009-12-09 16:22:32 -08007966 if (r.crashing) {
7967 report.type = ApplicationErrorReport.TYPE_CRASH;
7968 report.crashInfo = crashInfo;
7969 } else if (r.notResponding) {
7970 report.type = ApplicationErrorReport.TYPE_ANR;
7971 report.anrInfo = new ApplicationErrorReport.AnrInfo();
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007972
Dan Egnorb7f03672009-12-09 16:22:32 -08007973 report.anrInfo.activity = r.notRespondingReport.tag;
7974 report.anrInfo.cause = r.notRespondingReport.shortMsg;
7975 report.anrInfo.info = r.notRespondingReport.longMsg;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007976 }
7977
Dan Egnorb7f03672009-12-09 16:22:32 -08007978 return report;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007979 }
7980
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007981 public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08007982 enforceNotIsolatedCaller("getProcessesInErrorState");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007983 // assume our apps are happy - lazy create the list
7984 List<ActivityManager.ProcessErrorStateInfo> errList = null;
7985
7986 synchronized (this) {
7987
7988 // iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08007989 for (int i=mLruProcesses.size()-1; i>=0; i--) {
7990 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007991 if ((app.thread != null) && (app.crashing || app.notResponding)) {
7992 // This one's in trouble, so we'll generate a report for it
7993 // crashes are higher priority (in case there's a crash *and* an anr)
7994 ActivityManager.ProcessErrorStateInfo report = null;
7995 if (app.crashing) {
7996 report = app.crashingReport;
7997 } else if (app.notResponding) {
7998 report = app.notRespondingReport;
7999 }
8000
8001 if (report != null) {
8002 if (errList == null) {
8003 errList = new ArrayList<ActivityManager.ProcessErrorStateInfo>(1);
8004 }
8005 errList.add(report);
8006 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008007 Slog.w(TAG, "Missing app error report, app = " + app.processName +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008008 " crashing = " + app.crashing +
8009 " notResponding = " + app.notResponding);
8010 }
8011 }
8012 }
8013 }
8014
8015 return errList;
8016 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07008017
8018 static int oomAdjToImportance(int adj, ActivityManager.RunningAppProcessInfo currApp) {
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008019 if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008020 if (currApp != null) {
8021 currApp.lru = adj - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
8022 }
8023 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008024 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
8025 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008026 } else if (adj >= ProcessList.HOME_APP_ADJ) {
8027 if (currApp != null) {
8028 currApp.lru = 0;
8029 }
8030 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008031 } else if (adj >= ProcessList.SERVICE_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008032 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
8033 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
8034 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
8035 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
8036 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
8037 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
8038 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
8039 } else {
8040 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
8041 }
8042 }
8043
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008044 private void fillInProcMemInfo(ProcessRecord app,
8045 ActivityManager.RunningAppProcessInfo outInfo) {
8046 outInfo.pid = app.pid;
8047 outInfo.uid = app.info.uid;
8048 if (mHeavyWeightProcess == app) {
8049 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_CANT_SAVE_STATE;
8050 }
8051 if (app.persistent) {
8052 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_PERSISTENT;
8053 }
8054 outInfo.lastTrimLevel = app.trimMemoryLevel;
8055 int adj = app.curAdj;
8056 outInfo.importance = oomAdjToImportance(adj, outInfo);
8057 outInfo.importanceReasonCode = app.adjTypeCode;
8058 }
8059
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008060 public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008061 enforceNotIsolatedCaller("getRunningAppProcesses");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008062 // Lazy instantiation of list
8063 List<ActivityManager.RunningAppProcessInfo> runList = null;
8064 synchronized (this) {
8065 // Iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008066 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8067 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008068 if ((app.thread != null) && (!app.crashing && !app.notResponding)) {
8069 // Generate process state info for running application
8070 ActivityManager.RunningAppProcessInfo currApp =
8071 new ActivityManager.RunningAppProcessInfo(app.processName,
8072 app.pid, app.getPackageList());
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008073 fillInProcMemInfo(app, currApp);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008074 if (app.adjSource instanceof ProcessRecord) {
8075 currApp.importanceReasonPid = ((ProcessRecord)app.adjSource).pid;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008076 currApp.importanceReasonImportance = oomAdjToImportance(
8077 app.adjSourceOom, null);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008078 } else if (app.adjSource instanceof ActivityRecord) {
8079 ActivityRecord r = (ActivityRecord)app.adjSource;
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008080 if (r.app != null) currApp.importanceReasonPid = r.app.pid;
8081 }
8082 if (app.adjTarget instanceof ComponentName) {
8083 currApp.importanceReasonComponent = (ComponentName)app.adjTarget;
8084 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08008085 //Slog.v(TAG, "Proc " + app.processName + ": imp=" + currApp.importance
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008086 // + " lru=" + currApp.lru);
8087 if (runList == null) {
8088 runList = new ArrayList<ActivityManager.RunningAppProcessInfo>();
8089 }
8090 runList.add(currApp);
8091 }
8092 }
8093 }
8094 return runList;
8095 }
8096
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008097 public List<ApplicationInfo> getRunningExternalApplications() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008098 enforceNotIsolatedCaller("getRunningExternalApplications");
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008099 List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses();
8100 List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>();
8101 if (runningApps != null && runningApps.size() > 0) {
8102 Set<String> extList = new HashSet<String>();
8103 for (ActivityManager.RunningAppProcessInfo app : runningApps) {
8104 if (app.pkgList != null) {
8105 for (String pkg : app.pkgList) {
8106 extList.add(pkg);
8107 }
8108 }
8109 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008110 IPackageManager pm = AppGlobals.getPackageManager();
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008111 for (String pkg : extList) {
8112 try {
8113 ApplicationInfo info = pm.getApplicationInfo(pkg, 0);
8114 if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
8115 retList.add(info);
8116 }
8117 } catch (RemoteException e) {
8118 }
8119 }
8120 }
8121 return retList;
8122 }
8123
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008124 @Override
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008125 public void getMyMemoryState(ActivityManager.RunningAppProcessInfo outInfo) {
8126 enforceNotIsolatedCaller("getMyMemoryState");
8127 synchronized (this) {
8128 ProcessRecord proc;
8129 synchronized (mPidsSelfLocked) {
8130 proc = mPidsSelfLocked.get(Binder.getCallingPid());
8131 }
8132 fillInProcMemInfo(proc, outInfo);
8133 }
8134 }
8135
8136 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008137 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008138 if (checkCallingPermission(android.Manifest.permission.DUMP)
8139 != PackageManager.PERMISSION_GRANTED) {
8140 pw.println("Permission Denial: can't dump ActivityManager from from pid="
8141 + Binder.getCallingPid()
8142 + ", uid=" + Binder.getCallingUid()
8143 + " without permission "
8144 + android.Manifest.permission.DUMP);
8145 return;
8146 }
8147
8148 boolean dumpAll = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008149 boolean dumpClient = false;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008150 String dumpPackage = null;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008151
8152 int opti = 0;
8153 while (opti < args.length) {
8154 String opt = args[opti];
8155 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
8156 break;
8157 }
8158 opti++;
8159 if ("-a".equals(opt)) {
8160 dumpAll = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008161 } else if ("-c".equals(opt)) {
8162 dumpClient = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008163 } else if ("-h".equals(opt)) {
8164 pw.println("Activity manager dump options:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008165 pw.println(" [-a] [-c] [-h] [cmd] ...");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008166 pw.println(" cmd may be one of:");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008167 pw.println(" a[ctivities]: activity stack state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008168 pw.println(" b[roadcasts] [PACKAGE_NAME]: broadcast state");
8169 pw.println(" i[ntents] [PACKAGE_NAME]: pending intent state");
8170 pw.println(" p[rocesses] [PACKAGE_NAME]: process state");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008171 pw.println(" o[om]: out of memory management");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008172 pw.println(" prov[iders] [COMP_SPEC ...]: content provider state");
Marco Nelissen18cb2872011-11-15 11:19:53 -08008173 pw.println(" provider [COMP_SPEC]: provider client-side state");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008174 pw.println(" s[ervices] [COMP_SPEC ...]: service state");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008175 pw.println(" service [COMP_SPEC]: service client-side state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008176 pw.println(" package [PACKAGE_NAME]: all state related to given package");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008177 pw.println(" all: dump all activities");
8178 pw.println(" top: dump the top activity");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008179 pw.println(" cmd may also be a COMP_SPEC to dump activities.");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008180 pw.println(" COMP_SPEC may be a component name (com.foo/.myApp),");
8181 pw.println(" a partial substring in a component name, a");
8182 pw.println(" hex object identifier.");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008183 pw.println(" -a: include all available server state.");
8184 pw.println(" -c: include client state.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008185 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008186 } else {
8187 pw.println("Unknown argument: " + opt + "; use -h for help");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008188 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008189 }
8190
8191 // Is the caller requesting to dump a particular piece of data?
8192 if (opti < args.length) {
8193 String cmd = args[opti];
8194 opti++;
8195 if ("activities".equals(cmd) || "a".equals(cmd)) {
8196 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008197 dumpActivitiesLocked(fd, pw, args, opti, true, dumpClient, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008198 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008199 return;
8200 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008201 String[] newArgs;
8202 String name;
8203 if (opti >= args.length) {
8204 name = null;
8205 newArgs = EMPTY_STRING_ARRAY;
8206 } else {
8207 name = args[opti];
8208 opti++;
8209 newArgs = new String[args.length - opti];
8210 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8211 args.length - opti);
8212 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008213 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008214 dumpBroadcastsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008215 }
8216 return;
8217 } else if ("intents".equals(cmd) || "i".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008218 String[] newArgs;
8219 String name;
8220 if (opti >= args.length) {
8221 name = null;
8222 newArgs = EMPTY_STRING_ARRAY;
8223 } else {
8224 name = args[opti];
8225 opti++;
8226 newArgs = new String[args.length - opti];
8227 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8228 args.length - opti);
8229 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008230 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008231 dumpPendingIntentsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008232 }
8233 return;
8234 } else if ("processes".equals(cmd) || "p".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008235 String[] newArgs;
8236 String name;
8237 if (opti >= args.length) {
8238 name = null;
8239 newArgs = EMPTY_STRING_ARRAY;
8240 } else {
8241 name = args[opti];
8242 opti++;
8243 newArgs = new String[args.length - opti];
8244 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8245 args.length - opti);
8246 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008247 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008248 dumpProcessesLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008249 }
8250 return;
Dianne Hackborn287952c2010-09-22 22:34:31 -07008251 } else if ("oom".equals(cmd) || "o".equals(cmd)) {
8252 synchronized (this) {
8253 dumpOomLocked(fd, pw, args, opti, true);
8254 }
8255 return;
Marco Nelissen18cb2872011-11-15 11:19:53 -08008256 } else if ("provider".equals(cmd)) {
8257 String[] newArgs;
8258 String name;
8259 if (opti >= args.length) {
8260 name = null;
8261 newArgs = EMPTY_STRING_ARRAY;
8262 } else {
8263 name = args[opti];
8264 opti++;
8265 newArgs = new String[args.length - opti];
8266 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
8267 }
8268 if (!dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) {
8269 pw.println("No providers match: " + name);
8270 pw.println("Use -h for help.");
8271 }
8272 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008273 } else if ("providers".equals(cmd) || "prov".equals(cmd)) {
8274 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008275 dumpProvidersLocked(fd, pw, args, opti, true, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008276 }
8277 return;
8278 } else if ("service".equals(cmd)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008279 String[] newArgs;
8280 String name;
8281 if (opti >= args.length) {
8282 name = null;
8283 newArgs = EMPTY_STRING_ARRAY;
8284 } else {
8285 name = args[opti];
8286 opti++;
8287 newArgs = new String[args.length - opti];
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008288 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8289 args.length - opti);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008290 }
8291 if (!dumpService(fd, pw, name, newArgs, 0, dumpAll)) {
8292 pw.println("No services match: " + name);
8293 pw.println("Use -h for help.");
8294 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008295 return;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008296 } else if ("package".equals(cmd)) {
8297 String[] newArgs;
8298 if (opti >= args.length) {
8299 pw.println("package: no package name specified");
8300 pw.println("Use -h for help.");
8301 return;
8302 } else {
8303 dumpPackage = args[opti];
8304 opti++;
8305 newArgs = new String[args.length - opti];
8306 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8307 args.length - opti);
8308 args = newArgs;
8309 opti = 0;
8310 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008311 } else if ("services".equals(cmd) || "s".equals(cmd)) {
8312 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008313 dumpServicesLocked(fd, pw, args, opti, true, dumpClient, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008314 }
8315 return;
Dianne Hackborn625ac272010-09-17 18:29:22 -07008316 } else {
8317 // Dumping a single activity?
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008318 if (!dumpActivity(fd, pw, cmd, args, opti, dumpAll)) {
8319 pw.println("Bad activity command, or no activities match: " + cmd);
8320 pw.println("Use -h for help.");
Dianne Hackborn625ac272010-09-17 18:29:22 -07008321 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08008322 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008323 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008324 }
8325
8326 // No piece of data specified, dump everything.
8327 synchronized (this) {
8328 boolean needSep;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008329 needSep = dumpPendingIntentsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008330 if (needSep) {
8331 pw.println(" ");
8332 }
8333 if (dumpAll) {
8334 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008335 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008336 needSep = dumpBroadcastsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008337 if (needSep) {
8338 pw.println(" ");
8339 }
8340 if (dumpAll) {
8341 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008342 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008343 needSep = dumpProvidersLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008344 if (needSep) {
8345 pw.println(" ");
8346 }
8347 if (dumpAll) {
8348 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008349 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008350 needSep = dumpServicesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008351 if (needSep) {
8352 pw.println(" ");
8353 }
8354 if (dumpAll) {
8355 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008356 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008357 needSep = dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008358 if (needSep) {
8359 pw.println(" ");
8360 }
8361 if (dumpAll) {
8362 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008363 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008364 dumpProcessesLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008365 }
8366 }
8367
8368 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008369 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008370 pw.println("ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
8371 pw.println(" Main stack:");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008372 dumpHistoryList(fd, pw, mMainStack.mHistory, " ", "Hist", true, !dumpAll, dumpClient,
8373 dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008374 pw.println(" ");
8375 pw.println(" Running activities (most recent first):");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008376 dumpHistoryList(fd, pw, mMainStack.mLRUActivities, " ", "Run", false, !dumpAll, false,
8377 dumpPackage);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008378 if (mMainStack.mWaitingVisibleActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008379 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008380 pw.println(" Activities waiting for another to become visible:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008381 dumpHistoryList(fd, pw, mMainStack.mWaitingVisibleActivities, " ", "Wait", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008382 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008383 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008384 if (mMainStack.mStoppingActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008385 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008386 pw.println(" Activities waiting to stop:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008387 dumpHistoryList(fd, pw, mMainStack.mStoppingActivities, " ", "Stop", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008388 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008389 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008390 if (mMainStack.mGoingToSleepActivities.size() > 0) {
8391 pw.println(" ");
8392 pw.println(" Activities waiting to sleep:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008393 dumpHistoryList(fd, pw, mMainStack.mGoingToSleepActivities, " ", "Sleep", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008394 !dumpAll, false, dumpPackage);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008395 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008396 if (mMainStack.mFinishingActivities.size() > 0) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008397 pw.println(" ");
8398 pw.println(" Activities waiting to finish:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008399 dumpHistoryList(fd, pw, mMainStack.mFinishingActivities, " ", "Fin", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008400 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008401 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008402
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008403 pw.println(" ");
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08008404 if (mMainStack.mPausingActivity != null) {
8405 pw.println(" mPausingActivity: " + mMainStack.mPausingActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008406 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008407 pw.println(" mResumedActivity: " + mMainStack.mResumedActivity);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008408 pw.println(" mFocusedActivity: " + mFocusedActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008409 if (dumpAll) {
8410 pw.println(" mLastPausedActivity: " + mMainStack.mLastPausedActivity);
8411 pw.println(" mSleepTimeout: " + mMainStack.mSleepTimeout);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07008412 pw.println(" mDismissKeyguardOnNextActivity: "
8413 + mMainStack.mDismissKeyguardOnNextActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008414 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008415
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008416 if (mRecentTasks.size() > 0) {
8417 pw.println();
8418 pw.println(" Recent tasks:");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008419
8420 final int N = mRecentTasks.size();
8421 for (int i=0; i<N; i++) {
8422 TaskRecord tr = mRecentTasks.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008423 if (dumpPackage != null) {
8424 if (tr.realActivity == null ||
8425 !dumpPackage.equals(tr.realActivity)) {
8426 continue;
8427 }
8428 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008429 pw.print(" * Recent #"); pw.print(i); pw.print(": ");
8430 pw.println(tr);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008431 if (dumpAll) {
8432 mRecentTasks.get(i).dump(pw, " ");
8433 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008434 }
8435 }
8436
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008437 if (dumpAll) {
8438 pw.println(" ");
8439 pw.println(" mCurTask: " + mCurTask);
8440 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008441
8442 return true;
8443 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008444
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008445 boolean dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008446 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008447 boolean needSep = false;
8448 int numPers = 0;
8449
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008450 pw.println("ACTIVITY MANAGER RUNNING PROCESSES (dumpsys activity processes)");
8451
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008452 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008453 for (SparseArray<ProcessRecord> procs : mProcessNames.getMap().values()) {
8454 final int NA = procs.size();
8455 for (int ia=0; ia<NA; ia++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008456 ProcessRecord r = procs.valueAt(ia);
8457 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8458 continue;
8459 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008460 if (!needSep) {
8461 pw.println(" All known processes:");
8462 needSep = true;
8463 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008464 pw.print(r.persistent ? " *PERS*" : " *APP*");
8465 pw.print(" UID "); pw.print(procs.keyAt(ia));
8466 pw.print(" "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008467 r.dump(pw, " ");
8468 if (r.persistent) {
8469 numPers++;
8470 }
8471 }
8472 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008473 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008474
8475 if (mIsolatedProcesses.size() > 0) {
8476 if (needSep) pw.println(" ");
8477 needSep = true;
8478 pw.println(" Isolated process list (sorted by uid):");
8479 for (int i=0; i<mIsolatedProcesses.size(); i++) {
8480 ProcessRecord r = mIsolatedProcesses.valueAt(i);
8481 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8482 continue;
8483 }
8484 pw.println(String.format("%sIsolated #%2d: %s",
8485 " ", i, r.toString()));
8486 }
8487 }
8488
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008489 if (mLruProcesses.size() > 0) {
8490 if (needSep) pw.println(" ");
8491 needSep = true;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008492 pw.println(" Process LRU list (sorted by oom_adj):");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008493 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008494 "Proc", "PERS", false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008495 needSep = true;
8496 }
8497
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008498 if (dumpAll) {
8499 synchronized (mPidsSelfLocked) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008500 boolean printed = false;
8501 for (int i=0; i<mPidsSelfLocked.size(); i++) {
8502 ProcessRecord r = mPidsSelfLocked.valueAt(i);
8503 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8504 continue;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008505 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008506 if (!printed) {
8507 if (needSep) pw.println(" ");
8508 needSep = true;
8509 pw.println(" PID mappings:");
8510 printed = true;
8511 }
8512 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i));
8513 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008514 }
8515 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008516 }
8517
8518 if (mForegroundProcesses.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008519 synchronized (mPidsSelfLocked) {
8520 boolean printed = false;
8521 for (int i=0; i<mForegroundProcesses.size(); i++) {
8522 ProcessRecord r = mPidsSelfLocked.get(
8523 mForegroundProcesses.valueAt(i).pid);
8524 if (dumpPackage != null && (r == null
8525 || !dumpPackage.equals(r.info.packageName))) {
8526 continue;
8527 }
8528 if (!printed) {
8529 if (needSep) pw.println(" ");
8530 needSep = true;
8531 pw.println(" Foreground Processes:");
8532 printed = true;
8533 }
8534 pw.print(" PID #"); pw.print(mForegroundProcesses.keyAt(i));
8535 pw.print(": "); pw.println(mForegroundProcesses.valueAt(i));
8536 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008537 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008538 }
8539
8540 if (mPersistentStartingProcesses.size() > 0) {
8541 if (needSep) pw.println(" ");
8542 needSep = true;
8543 pw.println(" Persisent processes that are starting:");
8544 dumpProcessList(pw, this, mPersistentStartingProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008545 "Starting Norm", "Restarting PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008546 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008547
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008548 if (mRemovedProcesses.size() > 0) {
8549 if (needSep) pw.println(" ");
8550 needSep = true;
8551 pw.println(" Processes that are being removed:");
8552 dumpProcessList(pw, this, mRemovedProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008553 "Removed Norm", "Removed PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008554 }
8555
8556 if (mProcessesOnHold.size() > 0) {
8557 if (needSep) pw.println(" ");
8558 needSep = true;
8559 pw.println(" Processes that are on old until the system is ready:");
8560 dumpProcessList(pw, this, mProcessesOnHold, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008561 "OnHold Norm", "OnHold PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008562 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008563
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008564 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008565
8566 if (mProcessCrashTimes.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008567 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008568 long now = SystemClock.uptimeMillis();
8569 for (Map.Entry<String, SparseArray<Long>> procs
8570 : mProcessCrashTimes.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008571 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008572 SparseArray<Long> uids = procs.getValue();
8573 final int N = uids.size();
8574 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008575 int puid = uids.keyAt(i);
8576 ProcessRecord r = mProcessNames.get(pname, puid);
8577 if (dumpPackage != null && (r == null
8578 || !dumpPackage.equals(r.info.packageName))) {
8579 continue;
8580 }
8581 if (!printed) {
8582 if (needSep) pw.println(" ");
8583 needSep = true;
8584 pw.println(" Time since processes crashed:");
8585 printed = true;
8586 }
8587 pw.print(" Process "); pw.print(pname);
8588 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008589 pw.print(": last crashed ");
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008590 TimeUtils.formatDuration(now-uids.valueAt(i), pw);
8591 pw.println(" ago");
Dianne Hackbornfd12af42009-08-27 00:44:33 -07008592 }
8593 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008594 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008595
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008596 if (mBadProcesses.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008597 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008598 for (Map.Entry<String, SparseArray<Long>> procs
8599 : mBadProcesses.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008600 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008601 SparseArray<Long> uids = procs.getValue();
8602 final int N = uids.size();
8603 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008604 int puid = uids.keyAt(i);
8605 ProcessRecord r = mProcessNames.get(pname, puid);
8606 if (dumpPackage != null && (r == null
8607 || !dumpPackage.equals(r.info.packageName))) {
8608 continue;
8609 }
8610 if (!printed) {
8611 if (needSep) pw.println(" ");
8612 needSep = true;
8613 pw.println(" Bad processes:");
8614 }
8615 pw.print(" Bad process "); pw.print(pname);
8616 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008617 pw.print(": crashed at time ");
8618 pw.println(uids.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008619 }
8620 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008621 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008622
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008623 pw.println();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008624 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07008625 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn50685602011-12-01 12:23:37 -08008626 if (dumpAll) {
8627 StringBuilder sb = new StringBuilder(128);
8628 sb.append(" mPreviousProcessVisibleTime: ");
8629 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
8630 pw.println(sb);
8631 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07008632 if (mHeavyWeightProcess != null) {
8633 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
8634 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008635 pw.println(" mConfiguration: " + mConfiguration);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008636 if (dumpAll) {
8637 pw.println(" mConfigWillChange: " + mMainStack.mConfigWillChange);
Dianne Hackborn3d0724d2011-05-12 15:39:41 -07008638 if (mCompatModePackages.getPackages().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008639 boolean printed = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07008640 for (Map.Entry<String, Integer> entry
8641 : mCompatModePackages.getPackages().entrySet()) {
8642 String pkg = entry.getKey();
8643 int mode = entry.getValue();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008644 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
8645 continue;
8646 }
8647 if (!printed) {
8648 pw.println(" mScreenCompatPackages:");
8649 printed = true;
8650 }
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07008651 pw.print(" "); pw.print(pkg); pw.print(": ");
8652 pw.print(mode); pw.println();
8653 }
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07008654 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008655 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008656 pw.println(" mSleeping=" + mSleeping + " mShuttingDown=" + mShuttingDown);
8657 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
8658 || mOrigWaitForDebugger) {
8659 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp
8660 + " mDebugTransient=" + mDebugTransient
8661 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger);
8662 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08008663 if (mOpenGlTraceApp != null) {
8664 pw.println(" mOpenGlTraceApp=" + mOpenGlTraceApp);
8665 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07008666 if (mProfileApp != null || mProfileProc != null || mProfileFile != null
8667 || mProfileFd != null) {
8668 pw.println(" mProfileApp=" + mProfileApp + " mProfileProc=" + mProfileProc);
8669 pw.println(" mProfileFile=" + mProfileFile + " mProfileFd=" + mProfileFd);
8670 pw.println(" mProfileType=" + mProfileType + " mAutoStopProfiler="
8671 + mAutoStopProfiler);
8672 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008673 if (mAlwaysFinishActivities || mController != null) {
8674 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities
8675 + " mController=" + mController);
8676 }
8677 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008678 pw.println(" Total persistent processes: " + numPers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008679 pw.println(" mStartRunning=" + mStartRunning
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07008680 + " mProcessesReady=" + mProcessesReady
8681 + " mSystemReady=" + mSystemReady);
8682 pw.println(" mBooting=" + mBooting
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008683 + " mBooted=" + mBooted
8684 + " mFactoryTest=" + mFactoryTest);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008685 pw.print(" mLastPowerCheckRealtime=");
8686 TimeUtils.formatDuration(mLastPowerCheckRealtime, pw);
8687 pw.println("");
8688 pw.print(" mLastPowerCheckUptime=");
8689 TimeUtils.formatDuration(mLastPowerCheckUptime, pw);
8690 pw.println("");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008691 pw.println(" mGoingToSleep=" + mMainStack.mGoingToSleep);
8692 pw.println(" mLaunchingActivity=" + mMainStack.mLaunchingActivity);
Dianne Hackborn906497c2010-05-10 15:57:38 -07008693 pw.println(" mAdjSeq=" + mAdjSeq + " mLruSeq=" + mLruSeq);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008694 pw.println(" mNumServiceProcs=" + mNumServiceProcs
8695 + " mNewNumServiceProcs=" + mNewNumServiceProcs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008696 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008697
8698 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008699 }
8700
Dianne Hackborn287952c2010-09-22 22:34:31 -07008701 boolean dumpProcessesToGc(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008702 int opti, boolean needSep, boolean dumpAll, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07008703 if (mProcessesToGc.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008704 boolean printed = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -07008705 long now = SystemClock.uptimeMillis();
8706 for (int i=0; i<mProcessesToGc.size(); i++) {
8707 ProcessRecord proc = mProcessesToGc.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008708 if (dumpPackage != null && !dumpPackage.equals(proc.info.packageName)) {
8709 continue;
8710 }
8711 if (!printed) {
8712 if (needSep) pw.println(" ");
8713 needSep = true;
8714 pw.println(" Processes that are waiting to GC:");
8715 printed = true;
8716 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008717 pw.print(" Process "); pw.println(proc);
8718 pw.print(" lowMem="); pw.print(proc.reportLowMemory);
8719 pw.print(", last gced=");
8720 pw.print(now-proc.lastRequestedGc);
8721 pw.print(" ms ago, last lowMem=");
8722 pw.print(now-proc.lastLowMemory);
8723 pw.println(" ms ago");
8724
8725 }
8726 }
8727 return needSep;
8728 }
8729
8730 boolean dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args,
8731 int opti, boolean dumpAll) {
8732 boolean needSep = false;
8733
8734 if (mLruProcesses.size() > 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07008735 if (needSep) pw.println(" ");
8736 needSep = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -07008737 pw.println(" OOM levels:");
Dianne Hackborn7d608422011-08-07 16:24:18 -07008738 pw.print(" SYSTEM_ADJ: "); pw.println(ProcessList.SYSTEM_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008739 pw.print(" PERSISTENT_PROC_ADJ: "); pw.println(ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07008740 pw.print(" FOREGROUND_APP_ADJ: "); pw.println(ProcessList.FOREGROUND_APP_ADJ);
8741 pw.print(" VISIBLE_APP_ADJ: "); pw.println(ProcessList.VISIBLE_APP_ADJ);
8742 pw.print(" PERCEPTIBLE_APP_ADJ: "); pw.println(ProcessList.PERCEPTIBLE_APP_ADJ);
8743 pw.print(" HEAVY_WEIGHT_APP_ADJ: "); pw.println(ProcessList.HEAVY_WEIGHT_APP_ADJ);
8744 pw.print(" BACKUP_APP_ADJ: "); pw.println(ProcessList.BACKUP_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008745 pw.print(" SERVICE_ADJ: "); pw.println(ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07008746 pw.print(" HOME_APP_ADJ: "); pw.println(ProcessList.HOME_APP_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07008747 pw.print(" PREVIOUS_APP_ADJ: "); pw.println(ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008748 pw.print(" SERVICE_B_ADJ: "); pw.println(ProcessList.SERVICE_B_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07008749 pw.print(" HIDDEN_APP_MIN_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008750 pw.print(" HIDDEN_APP_MAX_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MAX_ADJ);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07008751
8752 if (needSep) pw.println(" ");
8753 needSep = true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07008754 pw.println(" Process OOM control:");
Dianne Hackborn905577f2011-09-07 18:31:28 -07008755 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008756 "Proc", "PERS", true, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008757 needSep = true;
8758 }
8759
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008760 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008761
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008762 pw.println();
Dianne Hackborn287952c2010-09-22 22:34:31 -07008763 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07008764 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008765 if (mHeavyWeightProcess != null) {
8766 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
8767 }
8768
8769 return true;
8770 }
8771
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008772 /**
8773 * There are three ways to call this:
8774 * - no service specified: dump all the services
8775 * - a flattened component name that matched an existing service was specified as the
8776 * first arg: dump that one service
8777 * - the first arg isn't the flattened component name of an existing service:
8778 * dump all services whose component contains the first arg as a substring
8779 */
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008780 protected boolean dumpService(FileDescriptor fd, PrintWriter pw, String name, String[] args,
8781 int opti, boolean dumpAll) {
8782 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008783
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008784 if ("all".equals(name)) {
Dianne Hackborn14bfa392010-07-24 19:58:06 -07008785 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07008786 try {
8787 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
8788 for (UserInfo user : users) {
8789 for (ServiceRecord r1 : mServiceMap.getAllServices(user.id)) {
8790 services.add(r1);
8791 }
8792 }
8793 } catch (RemoteException re) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008794 }
8795 }
8796 } else {
8797 ComponentName componentName = name != null
8798 ? ComponentName.unflattenFromString(name) : null;
8799 int objectId = 0;
8800 if (componentName == null) {
8801 // Not a '/' separated full component name; maybe an object ID?
8802 try {
8803 objectId = Integer.parseInt(name, 16);
8804 name = null;
8805 componentName = null;
8806 } catch (RuntimeException e) {
8807 }
8808 }
8809
8810 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07008811 try {
8812 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
8813 for (UserInfo user : users) {
8814 for (ServiceRecord r1 : mServiceMap.getAllServices(user.id)) {
8815 if (componentName != null) {
8816 if (r1.name.equals(componentName)) {
8817 services.add(r1);
8818 }
8819 } else if (name != null) {
8820 if (r1.name.flattenToString().contains(name)) {
8821 services.add(r1);
8822 }
8823 } else if (System.identityHashCode(r1) == objectId) {
8824 services.add(r1);
8825 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008826 }
Dianne Hackborn14bfa392010-07-24 19:58:06 -07008827 }
Amith Yamasani742a6712011-05-04 14:49:28 -07008828 } catch (RemoteException re) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008829 }
8830 }
8831 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008832
8833 if (services.size() <= 0) {
8834 return false;
8835 }
8836
8837 boolean needSep = false;
8838 for (int i=0; i<services.size(); i++) {
8839 if (needSep) {
8840 pw.println();
8841 }
8842 needSep = true;
8843 dumpService("", fd, pw, services.get(i), args, dumpAll);
8844 }
8845 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008846 }
8847
8848 /**
8849 * Invokes IApplicationThread.dumpService() on the thread of the specified service if
8850 * there is a thread associated with the service.
8851 */
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008852 private void dumpService(String prefix, FileDescriptor fd, PrintWriter pw,
8853 final ServiceRecord r, String[] args, boolean dumpAll) {
8854 String innerPrefix = prefix + " ";
8855 synchronized (this) {
8856 pw.print(prefix); pw.print("SERVICE ");
8857 pw.print(r.shortName); pw.print(" ");
8858 pw.print(Integer.toHexString(System.identityHashCode(r)));
8859 pw.print(" pid=");
8860 if (r.app != null) pw.println(r.app.pid);
8861 else pw.println("(not running)");
8862 if (dumpAll) {
8863 r.dump(pw, innerPrefix);
8864 }
8865 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008866 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008867 pw.print(prefix); pw.println(" Client:");
8868 pw.flush();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008869 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008870 TransferPipe tp = new TransferPipe();
8871 try {
8872 r.app.thread.dumpService(tp.getWriteFd().getFileDescriptor(), r, args);
8873 tp.setBufferPrefix(prefix + " ");
8874 tp.go(fd);
8875 } finally {
8876 tp.kill();
8877 }
8878 } catch (IOException e) {
8879 pw.println(prefix + " Failure while dumping the service: " + e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008880 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008881 pw.println(prefix + " Got a RemoteException while dumping the service");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008882 }
8883 }
8884 }
8885
Marco Nelissen18cb2872011-11-15 11:19:53 -08008886 /**
8887 * There are three ways to call this:
8888 * - no provider specified: dump all the providers
8889 * - a flattened component name that matched an existing provider was specified as the
8890 * first arg: dump that one provider
8891 * - the first arg isn't the flattened component name of an existing provider:
8892 * dump all providers whose component contains the first arg as a substring
8893 */
8894 protected boolean dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args,
8895 int opti, boolean dumpAll) {
Marco Nelissende7408c2012-02-08 14:57:38 -08008896 return mProviderMap.dumpProvider(fd, pw, name, args, opti, dumpAll);
Marco Nelissen18cb2872011-11-15 11:19:53 -08008897 }
8898
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008899 static class ItemMatcher {
8900 ArrayList<ComponentName> components;
8901 ArrayList<String> strings;
8902 ArrayList<Integer> objects;
8903 boolean all;
8904
8905 ItemMatcher() {
8906 all = true;
8907 }
8908
8909 void build(String name) {
8910 ComponentName componentName = ComponentName.unflattenFromString(name);
8911 if (componentName != null) {
8912 if (components == null) {
8913 components = new ArrayList<ComponentName>();
8914 }
8915 components.add(componentName);
8916 all = false;
8917 } else {
8918 int objectId = 0;
8919 // Not a '/' separated full component name; maybe an object ID?
8920 try {
8921 objectId = Integer.parseInt(name, 16);
8922 if (objects == null) {
8923 objects = new ArrayList<Integer>();
8924 }
8925 objects.add(objectId);
8926 all = false;
8927 } catch (RuntimeException e) {
8928 // Not an integer; just do string match.
8929 if (strings == null) {
8930 strings = new ArrayList<String>();
8931 }
8932 strings.add(name);
8933 all = false;
8934 }
8935 }
8936 }
8937
8938 int build(String[] args, int opti) {
8939 for (; opti<args.length; opti++) {
8940 String name = args[opti];
8941 if ("--".equals(name)) {
8942 return opti+1;
8943 }
8944 build(name);
8945 }
8946 return opti;
8947 }
8948
8949 boolean match(Object object, ComponentName comp) {
8950 if (all) {
8951 return true;
8952 }
8953 if (components != null) {
8954 for (int i=0; i<components.size(); i++) {
8955 if (components.get(i).equals(comp)) {
8956 return true;
8957 }
8958 }
8959 }
8960 if (objects != null) {
8961 for (int i=0; i<objects.size(); i++) {
8962 if (System.identityHashCode(object) == objects.get(i)) {
8963 return true;
8964 }
8965 }
8966 }
8967 if (strings != null) {
8968 String flat = comp.flattenToString();
8969 for (int i=0; i<strings.size(); i++) {
8970 if (flat.contains(strings.get(i))) {
8971 return true;
8972 }
8973 }
8974 }
8975 return false;
8976 }
8977 }
8978
Dianne Hackborn625ac272010-09-17 18:29:22 -07008979 /**
8980 * There are three things that cmd can be:
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008981 * - a flattened component name that matches an existing activity
Dianne Hackborn625ac272010-09-17 18:29:22 -07008982 * - the cmd arg isn't the flattened component name of an existing activity:
8983 * dump all activity whose component contains the cmd as a substring
8984 * - A hex number of the ActivityRecord object instance.
8985 */
8986 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
8987 int opti, boolean dumpAll) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07008988 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008989
8990 if ("all".equals(name)) {
8991 synchronized (this) {
8992 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07008993 activities.add(r1);
8994 }
8995 }
Dianne Hackbornf9302322011-06-14 18:36:14 -07008996 } else if ("top".equals(name)) {
8997 synchronized (this) {
8998 final int N = mMainStack.mHistory.size();
8999 if (N > 0) {
9000 activities.add((ActivityRecord)mMainStack.mHistory.get(N-1));
9001 }
9002 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009003 } else {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009004 ItemMatcher matcher = new ItemMatcher();
9005 matcher.build(name);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009006
9007 synchronized (this) {
9008 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009009 if (matcher.match(r1, r1.intent.getComponent())) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009010 activities.add(r1);
9011 }
9012 }
9013 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009014 }
9015
9016 if (activities.size() <= 0) {
9017 return false;
9018 }
9019
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009020 String[] newArgs = new String[args.length - opti];
9021 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
9022
Dianne Hackborn30d71892010-12-11 10:37:55 -08009023 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009024 boolean needSep = false;
Dianne Hackborn30d71892010-12-11 10:37:55 -08009025 for (int i=activities.size()-1; i>=0; i--) {
9026 ActivityRecord r = (ActivityRecord)activities.get(i);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009027 if (needSep) {
9028 pw.println();
9029 }
9030 needSep = true;
9031 synchronized (this) {
9032 if (lastTask != r.task) {
9033 lastTask = r.task;
9034 pw.print("TASK "); pw.print(lastTask.affinity);
9035 pw.print(" id="); pw.println(lastTask.taskId);
9036 if (dumpAll) {
9037 lastTask.dump(pw, " ");
9038 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08009039 }
9040 }
9041 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009042 }
9043 return true;
9044 }
9045
9046 /**
9047 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
9048 * there is a thread associated with the activity.
9049 */
Dianne Hackborn30d71892010-12-11 10:37:55 -08009050 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009051 final ActivityRecord r, String[] args, boolean dumpAll) {
9052 String innerPrefix = prefix + " ";
Dianne Hackborn30d71892010-12-11 10:37:55 -08009053 synchronized (this) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009054 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
9055 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
9056 pw.print(" pid=");
Dianne Hackborn30d71892010-12-11 10:37:55 -08009057 if (r.app != null) pw.println(r.app.pid);
9058 else pw.println("(not running)");
9059 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009060 r.dump(pw, innerPrefix);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009061 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009062 }
9063 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009064 // flush anything that is already in the PrintWriter since the thread is going
9065 // to write to the file descriptor directly
9066 pw.flush();
Dianne Hackborn625ac272010-09-17 18:29:22 -07009067 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009068 TransferPipe tp = new TransferPipe();
9069 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009070 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9071 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009072 tp.go(fd);
9073 } finally {
9074 tp.kill();
9075 }
9076 } catch (IOException e) {
9077 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009078 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009079 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
Dianne Hackborn625ac272010-09-17 18:29:22 -07009080 }
9081 }
9082 }
9083
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009084 boolean dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009085 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009086 boolean needSep = false;
9087
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009088 pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009089 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009090 if (mRegisteredReceivers.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009091 boolean printed = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009092 Iterator it = mRegisteredReceivers.values().iterator();
9093 while (it.hasNext()) {
9094 ReceiverList r = (ReceiverList)it.next();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009095 if (dumpPackage != null && (r.app == null ||
9096 !dumpPackage.equals(r.app.info.packageName))) {
9097 continue;
9098 }
9099 if (!printed) {
9100 pw.println(" Registered Receivers:");
9101 needSep = true;
9102 printed = true;
9103 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009104 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009105 r.dump(pw, " ");
9106 }
9107 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009108
9109 if (mReceiverResolver.dump(pw, needSep ?
9110 "\n Receiver Resolver Table:" : " Receiver Resolver Table:",
9111 " ", dumpPackage, false)) {
9112 needSep = true;
9113 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009114 }
Christopher Tatef46723b2012-01-26 14:19:24 -08009115
9116 for (BroadcastQueue q : mBroadcastQueues) {
9117 needSep = q.dumpLocked(fd, pw, args, opti, dumpAll, dumpPackage, needSep);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009118 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009119
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009120 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009121
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009122 if (mStickyBroadcasts != null && dumpPackage == null) {
9123 if (needSep) {
9124 pw.println();
9125 }
9126 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009127 pw.println(" Sticky broadcasts:");
9128 StringBuilder sb = new StringBuilder(128);
9129 for (Map.Entry<String, ArrayList<Intent>> ent
9130 : mStickyBroadcasts.entrySet()) {
9131 pw.print(" * Sticky action "); pw.print(ent.getKey());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009132 if (dumpAll) {
9133 pw.println(":");
9134 ArrayList<Intent> intents = ent.getValue();
9135 final int N = intents.size();
9136 for (int i=0; i<N; i++) {
9137 sb.setLength(0);
9138 sb.append(" Intent: ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009139 intents.get(i).toShortString(sb, false, true, false, false);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009140 pw.println(sb.toString());
9141 Bundle bundle = intents.get(i).getExtras();
9142 if (bundle != null) {
9143 pw.print(" ");
9144 pw.println(bundle.toString());
9145 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009146 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009147 } else {
9148 pw.println("");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009149 }
9150 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009151 needSep = true;
9152 }
9153
9154 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009155 pw.println();
Christopher Tatef46723b2012-01-26 14:19:24 -08009156 for (BroadcastQueue queue : mBroadcastQueues) {
9157 pw.println(" mBroadcastsScheduled [" + queue.mQueueName + "]="
9158 + queue.mBroadcastsScheduled);
9159 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009160 pw.println(" mHandler:");
9161 mHandler.dump(new PrintWriterPrinter(pw), " ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009162 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009163 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009164
9165 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009166 }
9167
Marco Nelissen18cb2872011-11-15 11:19:53 -08009168 /**
9169 * Prints a list of ServiceRecords (dumpsys activity services)
9170 */
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009171 boolean dumpServicesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009172 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009173 boolean needSep = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009174
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009175 ItemMatcher matcher = new ItemMatcher();
9176 matcher.build(args, opti);
9177
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009178 pw.println("ACTIVITY MANAGER SERVICES (dumpsys activity services)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009179 try {
9180 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
9181 for (UserInfo user : users) {
9182 if (mServiceMap.getAllServices(user.id).size() > 0) {
9183 boolean printed = false;
9184 long nowReal = SystemClock.elapsedRealtime();
9185 Iterator<ServiceRecord> it = mServiceMap.getAllServices(
9186 user.id).iterator();
9187 needSep = false;
9188 while (it.hasNext()) {
9189 ServiceRecord r = it.next();
9190 if (!matcher.match(r, r.name)) {
9191 continue;
9192 }
9193 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9194 continue;
9195 }
9196 if (!printed) {
9197 pw.println(" Active services:");
9198 printed = true;
9199 }
9200 if (needSep) {
9201 pw.println();
9202 }
9203 pw.print(" * ");
9204 pw.println(r);
9205 if (dumpAll) {
9206 r.dump(pw, " ");
9207 needSep = true;
9208 } else {
9209 pw.print(" app=");
9210 pw.println(r.app);
9211 pw.print(" created=");
9212 TimeUtils.formatDuration(r.createTime, nowReal, pw);
9213 pw.print(" started=");
9214 pw.print(r.startRequested);
9215 pw.print(" connections=");
9216 pw.println(r.connections.size());
9217 if (r.connections.size() > 0) {
9218 pw.println(" Connections:");
9219 for (ArrayList<ConnectionRecord> clist : r.connections.values()) {
9220 for (int i = 0; i < clist.size(); i++) {
9221 ConnectionRecord conn = clist.get(i);
9222 pw.print(" ");
9223 pw.print(conn.binding.intent.intent.getIntent()
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009224 .toShortString(false, false, false, false));
Amith Yamasani742a6712011-05-04 14:49:28 -07009225 pw.print(" -> ");
9226 ProcessRecord proc = conn.binding.client;
9227 pw.println(proc != null ? proc.toShortString() : "null");
9228 }
9229 }
Dianne Hackborn8ec8d412011-11-14 18:27:24 -08009230 }
9231 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009232 if (dumpClient && r.app != null && r.app.thread != null) {
9233 pw.println(" Client:");
9234 pw.flush();
9235 try {
9236 TransferPipe tp = new TransferPipe();
9237 try {
9238 r.app.thread.dumpService(tp.getWriteFd().getFileDescriptor(),
9239 r, args);
9240 tp.setBufferPrefix(" ");
9241 // Short timeout, since blocking here can
9242 // deadlock with the application.
9243 tp.go(fd, 2000);
9244 } finally {
9245 tp.kill();
9246 }
9247 } catch (IOException e) {
9248 pw.println(" Failure while dumping the service: " + e);
9249 } catch (RemoteException e) {
9250 pw.println(" Got a RemoteException while dumping the service");
9251 }
9252 needSep = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009253 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009254 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009255 needSep = printed;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009256 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009257 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009258 } catch (RemoteException re) {
9259
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009260 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009261
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009262 if (mPendingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009263 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009264 for (int i=0; i<mPendingServices.size(); i++) {
9265 ServiceRecord r = mPendingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009266 if (!matcher.match(r, r.name)) {
9267 continue;
9268 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009269 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9270 continue;
9271 }
9272 if (!printed) {
9273 if (needSep) pw.println(" ");
9274 needSep = true;
9275 pw.println(" Pending services:");
9276 printed = true;
9277 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009278 pw.print(" * Pending "); pw.println(r);
9279 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009280 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009281 needSep = true;
9282 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009283
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009284 if (mRestartingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009285 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009286 for (int i=0; i<mRestartingServices.size(); i++) {
9287 ServiceRecord r = mRestartingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009288 if (!matcher.match(r, r.name)) {
9289 continue;
9290 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009291 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9292 continue;
9293 }
9294 if (!printed) {
9295 if (needSep) pw.println(" ");
9296 needSep = true;
9297 pw.println(" Restarting services:");
9298 printed = true;
9299 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009300 pw.print(" * Restarting "); pw.println(r);
9301 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009302 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009303 needSep = true;
9304 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009305
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009306 if (mStoppingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009307 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009308 for (int i=0; i<mStoppingServices.size(); i++) {
9309 ServiceRecord r = mStoppingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009310 if (!matcher.match(r, r.name)) {
9311 continue;
9312 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009313 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9314 continue;
9315 }
9316 if (!printed) {
9317 if (needSep) pw.println(" ");
9318 needSep = true;
9319 pw.println(" Stopping services:");
9320 printed = true;
9321 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009322 pw.print(" * Stopping "); pw.println(r);
9323 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009324 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009325 needSep = true;
9326 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009327
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009328 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009329 if (mServiceConnections.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009330 boolean printed = false;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009331 Iterator<ArrayList<ConnectionRecord>> it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009332 = mServiceConnections.values().iterator();
9333 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009334 ArrayList<ConnectionRecord> r = it.next();
9335 for (int i=0; i<r.size(); i++) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009336 ConnectionRecord cr = r.get(i);
9337 if (!matcher.match(cr.binding.service, cr.binding.service.name)) {
9338 continue;
9339 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009340 if (dumpPackage != null && (cr.binding.client == null
9341 || !dumpPackage.equals(cr.binding.client.info.packageName))) {
9342 continue;
9343 }
9344 if (!printed) {
9345 if (needSep) pw.println(" ");
9346 needSep = true;
9347 pw.println(" Connection bindings to services:");
9348 printed = true;
9349 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009350 pw.print(" * "); pw.println(cr);
9351 cr.dump(pw, " ");
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009352 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009353 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009354 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009355 }
9356 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009357
9358 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009359 }
9360
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009361 boolean dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009362 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009363 boolean needSep = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009364
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009365 ItemMatcher matcher = new ItemMatcher();
9366 matcher.build(args, opti);
9367
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009368 pw.println("ACTIVITY MANAGER CONTENT PROVIDERS (dumpsys activity providers)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009369
9370 mProviderMap.dumpProvidersLocked(pw, dumpAll);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009371
9372 if (mLaunchingProviders.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009373 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009374 for (int i=mLaunchingProviders.size()-1; i>=0; i--) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009375 ContentProviderRecord r = mLaunchingProviders.get(i);
9376 if (dumpPackage != null && !dumpPackage.equals(r.name.getPackageName())) {
9377 continue;
9378 }
9379 if (!printed) {
9380 if (needSep) pw.println(" ");
9381 needSep = true;
9382 pw.println(" Launching content providers:");
9383 printed = true;
9384 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009385 pw.print(" Launching #"); pw.print(i); pw.print(": ");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009386 pw.println(r);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009387 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009388 }
9389
9390 if (mGrantedUriPermissions.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009391 if (needSep) pw.println();
9392 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009393 pw.println("Granted Uri Permissions:");
9394 for (int i=0; i<mGrantedUriPermissions.size(); i++) {
9395 int uid = mGrantedUriPermissions.keyAt(i);
9396 HashMap<Uri, UriPermission> perms
9397 = mGrantedUriPermissions.valueAt(i);
9398 pw.print(" * UID "); pw.print(uid);
9399 pw.println(" holds:");
9400 for (UriPermission perm : perms.values()) {
9401 pw.print(" "); pw.println(perm);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009402 if (dumpAll) {
9403 perm.dump(pw, " ");
9404 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009405 }
9406 }
9407 needSep = true;
9408 }
9409
9410 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009411 }
9412
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009413 boolean dumpPendingIntentsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009414 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009415 boolean needSep = false;
9416
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009417 if (mIntentSenderRecords.size() > 0) {
9418 boolean printed = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009419 Iterator<WeakReference<PendingIntentRecord>> it
9420 = mIntentSenderRecords.values().iterator();
9421 while (it.hasNext()) {
9422 WeakReference<PendingIntentRecord> ref = it.next();
9423 PendingIntentRecord rec = ref != null ? ref.get(): null;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009424 if (dumpPackage != null && (rec == null
9425 || !dumpPackage.equals(rec.key.packageName))) {
9426 continue;
9427 }
9428 if (!printed) {
9429 pw.println("ACTIVITY MANAGER PENDING INTENTS (dumpsys activity intents)");
9430 printed = true;
9431 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009432 needSep = true;
9433 if (rec != null) {
9434 pw.print(" * "); pw.println(rec);
9435 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009436 rec.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009437 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009438 } else {
9439 pw.print(" * "); pw.println(ref);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009440 }
9441 }
9442 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009443
9444 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009445 }
9446
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009447 private static final void dumpHistoryList(FileDescriptor fd, PrintWriter pw, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009448 String prefix, String label, boolean complete, boolean brief, boolean client,
9449 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009450 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009451 boolean needNL = false;
9452 final String innerPrefix = prefix + " ";
9453 final String[] args = new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009454 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009455 final ActivityRecord r = (ActivityRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009456 if (dumpPackage != null && !dumpPackage.equals(r.packageName)) {
9457 continue;
9458 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07009459 final boolean full = !brief && (complete || !r.isInHistory());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009460 if (needNL) {
9461 pw.println(" ");
9462 needNL = false;
9463 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009464 if (lastTask != r.task) {
9465 lastTask = r.task;
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009466 pw.print(prefix);
9467 pw.print(full ? "* " : " ");
9468 pw.println(lastTask);
9469 if (full) {
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009470 lastTask.dump(pw, prefix + " ");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009471 } else if (complete) {
9472 // Complete + brief == give a summary. Isn't that obvious?!?
9473 if (lastTask.intent != null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009474 pw.print(prefix); pw.print(" ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009475 pw.println(lastTask.intent.toInsecureStringWithClip());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009476 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009477 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009478 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009479 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label);
9480 pw.print(" #"); pw.print(i); pw.print(": ");
9481 pw.println(r);
9482 if (full) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009483 r.dump(pw, innerPrefix);
9484 } else if (complete) {
9485 // Complete + brief == give a summary. Isn't that obvious?!?
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009486 pw.print(innerPrefix); pw.println(r.intent.toInsecureString());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009487 if (r.app != null) {
9488 pw.print(innerPrefix); pw.println(r.app);
9489 }
9490 }
9491 if (client && r.app != null && r.app.thread != null) {
9492 // flush anything that is already in the PrintWriter since the thread is going
9493 // to write to the file descriptor directly
9494 pw.flush();
9495 try {
9496 TransferPipe tp = new TransferPipe();
9497 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009498 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9499 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009500 // Short timeout, since blocking here can
9501 // deadlock with the application.
9502 tp.go(fd, 2000);
9503 } finally {
9504 tp.kill();
9505 }
9506 } catch (IOException e) {
9507 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
9508 } catch (RemoteException e) {
9509 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
9510 }
9511 needNL = true;
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009512 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009513 }
9514 }
9515
Dianne Hackborn09c916b2009-12-08 14:50:51 -08009516 private static String buildOomTag(String prefix, String space, int val, int base) {
9517 if (val == base) {
9518 if (space == null) return prefix;
9519 return prefix + " ";
9520 }
9521 return prefix + "+" + Integer.toString(val-base);
9522 }
9523
9524 private static final int dumpProcessList(PrintWriter pw,
9525 ActivityManagerService service, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009526 String prefix, String normalLabel, String persistentLabel,
9527 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009528 int numPers = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07009529 final int N = list.size()-1;
9530 for (int i=N; i>=0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009531 ProcessRecord r = (ProcessRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009532 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9533 continue;
9534 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009535 pw.println(String.format("%s%s #%2d: %s",
9536 prefix, (r.persistent ? persistentLabel : normalLabel),
9537 i, r.toString()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009538 if (r.persistent) {
9539 numPers++;
9540 }
9541 }
9542 return numPers;
9543 }
9544
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009545 private static final boolean dumpProcessOomList(PrintWriter pw,
Dianne Hackborn905577f2011-09-07 18:31:28 -07009546 ActivityManagerService service, List<ProcessRecord> origList,
Dianne Hackborn287952c2010-09-22 22:34:31 -07009547 String prefix, String normalLabel, String persistentLabel,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009548 boolean inclDetails, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009549
Dianne Hackborn905577f2011-09-07 18:31:28 -07009550 ArrayList<Pair<ProcessRecord, Integer>> list
9551 = new ArrayList<Pair<ProcessRecord, Integer>>(origList.size());
9552 for (int i=0; i<origList.size(); i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009553 ProcessRecord r = origList.get(i);
9554 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9555 continue;
9556 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07009557 list.add(new Pair<ProcessRecord, Integer>(origList.get(i), i));
9558 }
9559
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009560 if (list.size() <= 0) {
9561 return false;
9562 }
9563
Dianne Hackborn905577f2011-09-07 18:31:28 -07009564 Comparator<Pair<ProcessRecord, Integer>> comparator
9565 = new Comparator<Pair<ProcessRecord, Integer>>() {
9566 @Override
9567 public int compare(Pair<ProcessRecord, Integer> object1,
9568 Pair<ProcessRecord, Integer> object2) {
9569 if (object1.first.setAdj != object2.first.setAdj) {
9570 return object1.first.setAdj > object2.first.setAdj ? -1 : 1;
9571 }
9572 if (object1.second.intValue() != object2.second.intValue()) {
9573 return object1.second.intValue() > object2.second.intValue() ? -1 : 1;
9574 }
9575 return 0;
9576 }
9577 };
9578
9579 Collections.sort(list, comparator);
9580
Dianne Hackborn287952c2010-09-22 22:34:31 -07009581 final long curRealtime = SystemClock.elapsedRealtime();
9582 final long realtimeSince = curRealtime - service.mLastPowerCheckRealtime;
9583 final long curUptime = SystemClock.uptimeMillis();
9584 final long uptimeSince = curUptime - service.mLastPowerCheckUptime;
9585
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009586 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07009587 ProcessRecord r = list.get(i).first;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009588 String oomAdj;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009589 if (r.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07009590 oomAdj = buildOomTag("bak", " ", r.setAdj, ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009591 } else if (r.setAdj >= ProcessList.SERVICE_B_ADJ) {
9592 oomAdj = buildOomTag("svcb ", null, r.setAdj, ProcessList.SERVICE_B_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009593 } else if (r.setAdj >= ProcessList.PREVIOUS_APP_ADJ) {
9594 oomAdj = buildOomTag("prev ", null, r.setAdj, ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009595 } else if (r.setAdj >= ProcessList.HOME_APP_ADJ) {
9596 oomAdj = buildOomTag("home ", null, r.setAdj, ProcessList.HOME_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009597 } else if (r.setAdj >= ProcessList.SERVICE_ADJ) {
9598 oomAdj = buildOomTag("svc ", null, r.setAdj, ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009599 } else if (r.setAdj >= ProcessList.BACKUP_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08009600 oomAdj = buildOomTag("bkup ", null, r.setAdj, ProcessList.BACKUP_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009601 } else if (r.setAdj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
9602 oomAdj = buildOomTag("hvy ", null, r.setAdj, ProcessList.HEAVY_WEIGHT_APP_ADJ);
9603 } else if (r.setAdj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
9604 oomAdj = buildOomTag("prcp ", null, r.setAdj, ProcessList.PERCEPTIBLE_APP_ADJ);
9605 } else if (r.setAdj >= ProcessList.VISIBLE_APP_ADJ) {
9606 oomAdj = buildOomTag("vis ", null, r.setAdj, ProcessList.VISIBLE_APP_ADJ);
9607 } else if (r.setAdj >= ProcessList.FOREGROUND_APP_ADJ) {
9608 oomAdj = buildOomTag("fore ", null, r.setAdj, ProcessList.FOREGROUND_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009609 } else if (r.setAdj >= ProcessList.PERSISTENT_PROC_ADJ) {
9610 oomAdj = buildOomTag("pers ", null, r.setAdj, ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009611 } else if (r.setAdj >= ProcessList.SYSTEM_ADJ) {
9612 oomAdj = buildOomTag("sys ", null, r.setAdj, ProcessList.SYSTEM_ADJ);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009613 } else {
9614 oomAdj = Integer.toString(r.setAdj);
9615 }
9616 String schedGroup;
9617 switch (r.setSchedGroup) {
9618 case Process.THREAD_GROUP_BG_NONINTERACTIVE:
9619 schedGroup = "B";
9620 break;
9621 case Process.THREAD_GROUP_DEFAULT:
9622 schedGroup = "F";
9623 break;
9624 default:
9625 schedGroup = Integer.toString(r.setSchedGroup);
9626 break;
9627 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07009628 String foreground;
9629 if (r.foregroundActivities) {
9630 foreground = "A";
9631 } else if (r.foregroundServices) {
9632 foreground = "S";
9633 } else {
9634 foreground = " ";
9635 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07009636 pw.println(String.format("%s%s #%2d: adj=%s/%s%s trm=%2d %s (%s)",
Dianne Hackborn287952c2010-09-22 22:34:31 -07009637 prefix, (r.persistent ? persistentLabel : normalLabel),
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009638 (origList.size()-1)-list.get(i).second, oomAdj, schedGroup,
9639 foreground, r.trimMemoryLevel, r.toShortString(), r.adjType));
Dianne Hackborn287952c2010-09-22 22:34:31 -07009640 if (r.adjSource != null || r.adjTarget != null) {
9641 pw.print(prefix);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009642 pw.print(" ");
Dianne Hackborn287952c2010-09-22 22:34:31 -07009643 if (r.adjTarget instanceof ComponentName) {
9644 pw.print(((ComponentName)r.adjTarget).flattenToShortString());
9645 } else if (r.adjTarget != null) {
9646 pw.print(r.adjTarget.toString());
9647 } else {
9648 pw.print("{null}");
9649 }
9650 pw.print("<=");
9651 if (r.adjSource instanceof ProcessRecord) {
9652 pw.print("Proc{");
9653 pw.print(((ProcessRecord)r.adjSource).toShortString());
9654 pw.println("}");
9655 } else if (r.adjSource != null) {
9656 pw.println(r.adjSource.toString());
9657 } else {
9658 pw.println("{null}");
9659 }
9660 }
9661 if (inclDetails) {
9662 pw.print(prefix);
9663 pw.print(" ");
9664 pw.print("oom: max="); pw.print(r.maxAdj);
9665 pw.print(" hidden="); pw.print(r.hiddenAdj);
9666 pw.print(" curRaw="); pw.print(r.curRawAdj);
9667 pw.print(" setRaw="); pw.print(r.setRawAdj);
9668 pw.print(" cur="); pw.print(r.curAdj);
9669 pw.print(" set="); pw.println(r.setAdj);
9670 pw.print(prefix);
9671 pw.print(" ");
9672 pw.print("keeping="); pw.print(r.keeping);
9673 pw.print(" hidden="); pw.print(r.hidden);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009674 pw.print(" empty="); pw.print(r.empty);
9675 pw.print(" hasAboveClient="); pw.println(r.hasAboveClient);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009676
9677 if (!r.keeping) {
9678 if (r.lastWakeTime != 0) {
9679 long wtime;
9680 BatteryStatsImpl stats = service.mBatteryStatsService.getActiveStatistics();
9681 synchronized (stats) {
9682 wtime = stats.getProcessWakeTime(r.info.uid,
9683 r.pid, curRealtime);
9684 }
9685 long timeUsed = wtime - r.lastWakeTime;
9686 pw.print(prefix);
9687 pw.print(" ");
9688 pw.print("keep awake over ");
9689 TimeUtils.formatDuration(realtimeSince, pw);
9690 pw.print(" used ");
9691 TimeUtils.formatDuration(timeUsed, pw);
9692 pw.print(" (");
9693 pw.print((timeUsed*100)/realtimeSince);
9694 pw.println("%)");
9695 }
9696 if (r.lastCpuTime != 0) {
9697 long timeUsed = r.curCpuTime - r.lastCpuTime;
9698 pw.print(prefix);
9699 pw.print(" ");
9700 pw.print("run cpu over ");
9701 TimeUtils.formatDuration(uptimeSince, pw);
9702 pw.print(" used ");
9703 TimeUtils.formatDuration(timeUsed, pw);
9704 pw.print(" (");
9705 pw.print((timeUsed*100)/uptimeSince);
9706 pw.println("%)");
9707 }
9708 }
9709 }
9710 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009711 return true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009712 }
9713
Dianne Hackbornb437e092011-08-05 17:50:29 -07009714 ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, String[] args) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009715 ArrayList<ProcessRecord> procs;
9716 synchronized (this) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009717 if (args != null && args.length > start
9718 && args[start].charAt(0) != '-') {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009719 procs = new ArrayList<ProcessRecord>();
9720 int pid = -1;
9721 try {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009722 pid = Integer.parseInt(args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009723 } catch (NumberFormatException e) {
9724
9725 }
9726 for (int i=mLruProcesses.size()-1; i>=0; i--) {
9727 ProcessRecord proc = mLruProcesses.get(i);
9728 if (proc.pid == pid) {
9729 procs.add(proc);
Dianne Hackbornb437e092011-08-05 17:50:29 -07009730 } else if (proc.processName.equals(args[start])) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009731 procs.add(proc);
9732 }
9733 }
9734 if (procs.size() <= 0) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009735 pw.println("No process found for: " + args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009736 return null;
9737 }
9738 } else {
9739 procs = new ArrayList<ProcessRecord>(mLruProcesses);
9740 }
9741 }
9742 return procs;
9743 }
9744
9745 final void dumpGraphicsHardwareUsage(FileDescriptor fd,
9746 PrintWriter pw, String[] args) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009747 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009748 if (procs == null) {
9749 return;
9750 }
9751
9752 long uptime = SystemClock.uptimeMillis();
9753 long realtime = SystemClock.elapsedRealtime();
9754 pw.println("Applications Graphics Acceleration Info:");
9755 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
9756
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009757 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
9758 ProcessRecord r = procs.get(i);
Chet Haase9c1e23b2011-03-24 10:51:31 -07009759 if (r.thread != null) {
9760 pw.println("\n** Graphics info for pid " + r.pid + " [" + r.processName + "] **");
9761 pw.flush();
9762 try {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009763 TransferPipe tp = new TransferPipe();
9764 try {
9765 r.thread.dumpGfxInfo(tp.getWriteFd().getFileDescriptor(), args);
9766 tp.go(fd);
9767 } finally {
9768 tp.kill();
9769 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009770 } catch (IOException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009771 pw.println("Failure while dumping the app: " + r);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009772 pw.flush();
Chet Haase9c1e23b2011-03-24 10:51:31 -07009773 } catch (RemoteException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009774 pw.println("Got a RemoteException while dumping the app " + r);
Chet Haase9c1e23b2011-03-24 10:51:31 -07009775 pw.flush();
9776 }
9777 }
9778 }
Chet Haase9c1e23b2011-03-24 10:51:31 -07009779 }
9780
Jeff Brown6754ba22011-12-14 20:20:01 -08009781 final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) {
9782 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
9783 if (procs == null) {
9784 return;
9785 }
9786
9787 pw.println("Applications Database Info:");
9788
9789 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
9790 ProcessRecord r = procs.get(i);
9791 if (r.thread != null) {
9792 pw.println("\n** Database info for pid " + r.pid + " [" + r.processName + "] **");
9793 pw.flush();
9794 try {
9795 TransferPipe tp = new TransferPipe();
9796 try {
9797 r.thread.dumpDbInfo(tp.getWriteFd().getFileDescriptor(), args);
9798 tp.go(fd);
9799 } finally {
9800 tp.kill();
9801 }
9802 } catch (IOException e) {
9803 pw.println("Failure while dumping the app: " + r);
9804 pw.flush();
9805 } catch (RemoteException e) {
9806 pw.println("Got a RemoteException while dumping the app " + r);
9807 pw.flush();
9808 }
9809 }
9810 }
9811 }
9812
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009813 final static class MemItem {
9814 final String label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009815 final String shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009816 final long pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009817 final int id;
Dianne Hackborna4bacb82011-08-24 15:12:38 -07009818 ArrayList<MemItem> subitems;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009819
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009820 public MemItem(String _label, String _shortLabel, long _pss, int _id) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009821 label = _label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009822 shortLabel = _shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009823 pss = _pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009824 id = _id;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009825 }
9826 }
9827
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009828 static final void dumpMemItems(PrintWriter pw, String prefix, ArrayList<MemItem> items,
Dianne Hackbornb437e092011-08-05 17:50:29 -07009829 boolean sort) {
9830 if (sort) {
9831 Collections.sort(items, new Comparator<MemItem>() {
9832 @Override
9833 public int compare(MemItem lhs, MemItem rhs) {
9834 if (lhs.pss < rhs.pss) {
9835 return 1;
9836 } else if (lhs.pss > rhs.pss) {
9837 return -1;
9838 }
9839 return 0;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009840 }
Dianne Hackbornb437e092011-08-05 17:50:29 -07009841 });
9842 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009843
9844 for (int i=0; i<items.size(); i++) {
9845 MemItem mi = items.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009846 pw.print(prefix); pw.printf("%7d kB: ", mi.pss); pw.println(mi.label);
Dianne Hackborna4bacb82011-08-24 15:12:38 -07009847 if (mi.subitems != null) {
9848 dumpMemItems(pw, prefix + " ", mi.subitems, true);
9849 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009850 }
9851 }
9852
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009853 // These are in KB.
9854 static final long[] DUMP_MEM_BUCKETS = new long[] {
9855 5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024,
9856 120*1024, 160*1024, 200*1024,
9857 250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024,
9858 1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024
9859 };
9860
Dianne Hackborn672342c2011-11-29 11:29:02 -08009861 static final void appendMemBucket(StringBuilder out, long memKB, String label,
9862 boolean stackLike) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009863 int start = label.lastIndexOf('.');
9864 if (start >= 0) start++;
9865 else start = 0;
9866 int end = label.length();
9867 for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) {
9868 if (DUMP_MEM_BUCKETS[i] >= memKB) {
9869 long bucket = DUMP_MEM_BUCKETS[i]/1024;
9870 out.append(bucket);
Dianne Hackborn672342c2011-11-29 11:29:02 -08009871 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009872 out.append(label, start, end);
9873 return;
9874 }
9875 }
9876 out.append(memKB/1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -08009877 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009878 out.append(label, start, end);
9879 }
9880
9881 static final int[] DUMP_MEM_OOM_ADJ = new int[] {
9882 ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ, ProcessList.FOREGROUND_APP_ADJ,
9883 ProcessList.VISIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ,
9884 ProcessList.BACKUP_APP_ADJ, ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ,
9885 ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.HIDDEN_APP_MAX_ADJ
9886 };
9887 static final String[] DUMP_MEM_OOM_LABEL = new String[] {
9888 "System", "Persistent", "Foreground",
9889 "Visible", "Perceptible", "Heavy Weight",
9890 "Backup", "A Services", "Home", "Previous",
9891 "B Services", "Background"
9892 };
9893
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009894 final void dumpApplicationMemoryUsage(FileDescriptor fd,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08009895 PrintWriter pw, String prefix, String[] args, boolean brief,
Dianne Hackborn672342c2011-11-29 11:29:02 -08009896 PrintWriter categoryPw, StringBuilder outTag, StringBuilder outStack) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009897 boolean dumpAll = false;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08009898 boolean oomOnly = false;
Dianne Hackbornb437e092011-08-05 17:50:29 -07009899
9900 int opti = 0;
9901 while (opti < args.length) {
9902 String opt = args[opti];
9903 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
9904 break;
9905 }
9906 opti++;
9907 if ("-a".equals(opt)) {
9908 dumpAll = true;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08009909 } else if ("--oom".equals(opt)) {
9910 oomOnly = true;
Dianne Hackbornb437e092011-08-05 17:50:29 -07009911 } else if ("-h".equals(opt)) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08009912 pw.println("meminfo dump options: [-a] [--oom] [process]");
Dianne Hackbornb437e092011-08-05 17:50:29 -07009913 pw.println(" -a: include all available information for each process.");
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08009914 pw.println(" --oom: only show processes organized by oom adj.");
Dianne Hackbornb437e092011-08-05 17:50:29 -07009915 pw.println("If [process] is specified it can be the name or ");
9916 pw.println("pid of a specific process to dump.");
9917 return;
9918 } else {
9919 pw.println("Unknown argument: " + opt + "; use -h for help");
9920 }
9921 }
9922
9923 ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009924 if (procs == null) {
9925 return;
9926 }
9927
Dianne Hackborn6447ca32009-04-07 19:50:08 -07009928 final boolean isCheckinRequest = scanArgs(args, "--checkin");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009929 long uptime = SystemClock.uptimeMillis();
9930 long realtime = SystemClock.elapsedRealtime();
Dianne Hackbornb437e092011-08-05 17:50:29 -07009931
9932 if (procs.size() == 1 || isCheckinRequest) {
9933 dumpAll = true;
9934 }
9935
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009936 if (isCheckinRequest) {
9937 // short checkin version
9938 pw.println(uptime + "," + realtime);
9939 pw.flush();
9940 } else {
9941 pw.println("Applications Memory Usage (kB):");
9942 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
9943 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009944
Dianne Hackbornb437e092011-08-05 17:50:29 -07009945 String[] innerArgs = new String[args.length-opti];
9946 System.arraycopy(args, opti, innerArgs, 0, args.length-opti);
9947
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009948 ArrayList<MemItem> procMems = new ArrayList<MemItem>();
9949 long nativePss=0, dalvikPss=0, otherPss=0;
9950 long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
9951
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009952 long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length];
9953 ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[])
9954 new ArrayList[DUMP_MEM_OOM_LABEL.length];
Dianne Hackbornb437e092011-08-05 17:50:29 -07009955
9956 long totalPss = 0;
9957
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009958 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
9959 ProcessRecord r = procs.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009960 if (r.thread != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009961 if (!isCheckinRequest && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009962 pw.println("\n** MEMINFO in pid " + r.pid + " [" + r.processName + "] **");
9963 pw.flush();
9964 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009965 Debug.MemoryInfo mi = null;
Dianne Hackbornb437e092011-08-05 17:50:29 -07009966 if (dumpAll) {
9967 try {
9968 mi = r.thread.dumpMemInfo(fd, isCheckinRequest, dumpAll, innerArgs);
9969 } catch (RemoteException e) {
9970 if (!isCheckinRequest) {
9971 pw.println("Got RemoteException!");
9972 pw.flush();
9973 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009974 }
Dianne Hackbornb437e092011-08-05 17:50:29 -07009975 } else {
9976 mi = new Debug.MemoryInfo();
9977 Debug.getMemoryInfo(r.pid, mi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009978 }
Dianne Hackbornb437e092011-08-05 17:50:29 -07009979
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009980 if (!isCheckinRequest && mi != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009981 long myTotalPss = mi.getTotalPss();
9982 totalPss += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -07009983 MemItem pssItem = new MemItem(r.processName + " (pid " + r.pid + ")",
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009984 r.processName, myTotalPss, 0);
Dianne Hackborna4bacb82011-08-24 15:12:38 -07009985 procMems.add(pssItem);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009986
9987 nativePss += mi.nativePss;
9988 dalvikPss += mi.dalvikPss;
9989 otherPss += mi.otherPss;
9990 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
9991 long mem = mi.getOtherPss(j);
9992 miscPss[j] += mem;
9993 otherPss -= mem;
9994 }
Dianne Hackbornb437e092011-08-05 17:50:29 -07009995
9996 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009997 if (r.setAdj <= DUMP_MEM_OOM_ADJ[oomIndex]
9998 || oomIndex == (oomPss.length-1)) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009999 oomPss[oomIndex] += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010000 if (oomProcs[oomIndex] == null) {
10001 oomProcs[oomIndex] = new ArrayList<MemItem>();
10002 }
10003 oomProcs[oomIndex].add(pssItem);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010004 break;
10005 }
10006 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010007 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010008 }
10009 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010010
10011 if (!isCheckinRequest && procs.size() > 1) {
10012 ArrayList<MemItem> catMems = new ArrayList<MemItem>();
10013
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010014 catMems.add(new MemItem("Native", "Native", nativePss, -1));
10015 catMems.add(new MemItem("Dalvik", "Dalvik", dalvikPss, -2));
10016 catMems.add(new MemItem("Unknown", "Unknown", otherPss, -3));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010017 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010018 String label = Debug.MemoryInfo.getOtherLabel(j);
10019 catMems.add(new MemItem(label, label, miscPss[j], j));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010020 }
10021
Dianne Hackbornb437e092011-08-05 17:50:29 -070010022 ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
10023 for (int j=0; j<oomPss.length; j++) {
10024 if (oomPss[j] != 0) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010025 String label = DUMP_MEM_OOM_LABEL[j];
10026 MemItem item = new MemItem(label, label, oomPss[j],
10027 DUMP_MEM_OOM_ADJ[j]);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010028 item.subitems = oomProcs[j];
10029 oomMems.add(item);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010030 }
10031 }
10032
Dianne Hackborn672342c2011-11-29 11:29:02 -080010033 if (outTag != null || outStack != null) {
10034 if (outTag != null) {
10035 appendMemBucket(outTag, totalPss, "total", false);
10036 }
10037 if (outStack != null) {
10038 appendMemBucket(outStack, totalPss, "total", true);
10039 }
10040 boolean firstLine = true;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010041 for (int i=0; i<oomMems.size(); i++) {
10042 MemItem miCat = oomMems.get(i);
10043 if (miCat.subitems == null || miCat.subitems.size() < 1) {
10044 continue;
10045 }
10046 if (miCat.id < ProcessList.SERVICE_ADJ
10047 || miCat.id == ProcessList.HOME_APP_ADJ
10048 || miCat.id == ProcessList.PREVIOUS_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010049 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10050 outTag.append(" / ");
10051 }
10052 if (outStack != null) {
10053 if (miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10054 if (firstLine) {
10055 outStack.append(":");
10056 firstLine = false;
10057 }
10058 outStack.append("\n\t at ");
10059 } else {
10060 outStack.append("$");
10061 }
10062 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010063 for (int j=0; j<miCat.subitems.size(); j++) {
10064 MemItem mi = miCat.subitems.get(j);
10065 if (j > 0) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010066 if (outTag != null) {
10067 outTag.append(" ");
10068 }
10069 if (outStack != null) {
10070 outStack.append("$");
10071 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010072 }
Dianne Hackborn672342c2011-11-29 11:29:02 -080010073 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10074 appendMemBucket(outTag, mi.pss, mi.shortLabel, false);
10075 }
10076 if (outStack != null) {
10077 appendMemBucket(outStack, mi.pss, mi.shortLabel, true);
10078 }
10079 }
10080 if (outStack != null && miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10081 outStack.append("(");
10082 for (int k=0; k<DUMP_MEM_OOM_ADJ.length; k++) {
10083 if (DUMP_MEM_OOM_ADJ[k] == miCat.id) {
10084 outStack.append(DUMP_MEM_OOM_LABEL[k]);
10085 outStack.append(":");
10086 outStack.append(DUMP_MEM_OOM_ADJ[k]);
10087 }
10088 }
10089 outStack.append(")");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010090 }
10091 }
10092 }
10093 }
10094
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010095 if (!brief && !oomOnly) {
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010096 pw.println();
10097 pw.println("Total PSS by process:");
10098 dumpMemItems(pw, " ", procMems, true);
10099 pw.println();
10100 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010101 pw.println("Total PSS by OOM adjustment:");
10102 dumpMemItems(pw, " ", oomMems, false);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010103 if (!oomOnly) {
10104 PrintWriter out = categoryPw != null ? categoryPw : pw;
10105 out.println();
10106 out.println("Total PSS by category:");
10107 dumpMemItems(out, " ", catMems, true);
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010108 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010109 pw.println();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010110 pw.print("Total PSS: "); pw.print(totalPss); pw.println(" kB");
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010111 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010112 }
10113
10114 /**
10115 * Searches array of arguments for the specified string
10116 * @param args array of argument strings
10117 * @param value value to search for
10118 * @return true if the value is contained in the array
10119 */
10120 private static boolean scanArgs(String[] args, String value) {
10121 if (args != null) {
10122 for (String arg : args) {
10123 if (value.equals(arg)) {
10124 return true;
10125 }
10126 }
10127 }
10128 return false;
10129 }
10130
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010131 private final void killServicesLocked(ProcessRecord app,
10132 boolean allowRestart) {
10133 // Report disconnected services.
10134 if (false) {
10135 // XXX we are letting the client link to the service for
10136 // death notifications.
10137 if (app.services.size() > 0) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010138 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010139 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010140 ServiceRecord r = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010141 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010142 Iterator<ArrayList<ConnectionRecord>> jt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010143 = r.connections.values().iterator();
10144 while (jt.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010145 ArrayList<ConnectionRecord> cl = jt.next();
10146 for (int i=0; i<cl.size(); i++) {
10147 ConnectionRecord c = cl.get(i);
10148 if (c.binding.client != app) {
10149 try {
10150 //c.conn.connected(r.className, null);
10151 } catch (Exception e) {
10152 // todo: this should be asynchronous!
10153 Slog.w(TAG, "Exception thrown disconnected servce "
10154 + r.shortName
10155 + " from app " + app.processName, e);
10156 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010157 }
10158 }
10159 }
10160 }
10161 }
10162 }
10163 }
10164
10165 // Clean up any connections this application has to other services.
10166 if (app.connections.size() > 0) {
10167 Iterator<ConnectionRecord> it = app.connections.iterator();
10168 while (it.hasNext()) {
10169 ConnectionRecord r = it.next();
10170 removeConnectionLocked(r, app, null);
10171 }
10172 }
10173 app.connections.clear();
10174
10175 if (app.services.size() != 0) {
10176 // Any services running in the application need to be placed
10177 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -070010178 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010179 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010180 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010181 synchronized (sr.stats.getBatteryStats()) {
10182 sr.stats.stopLaunchedLocked();
10183 }
10184 sr.app = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010185 sr.isolatedProc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010186 sr.executeNesting = 0;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010187 if (mStoppingServices.remove(sr)) {
10188 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
10189 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010190
10191 boolean hasClients = sr.bindings.size() > 0;
10192 if (hasClients) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010193 Iterator<IntentBindRecord> bindings
10194 = sr.bindings.values().iterator();
10195 while (bindings.hasNext()) {
10196 IntentBindRecord b = bindings.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -080010197 if (DEBUG_SERVICE) Slog.v(TAG, "Killing binding " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010198 + ": shouldUnbind=" + b.hasBound);
10199 b.binder = null;
10200 b.requested = b.received = b.hasBound = false;
10201 }
10202 }
10203
Dianne Hackborn070783f2010-12-29 16:46:28 -080010204 if (sr.crashCount >= 2 && (sr.serviceInfo.applicationInfo.flags
10205 &ApplicationInfo.FLAG_PERSISTENT) == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010206 Slog.w(TAG, "Service crashed " + sr.crashCount
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010207 + " times, stopping: " + sr);
Doug Zongker2bec3d42009-12-04 12:52:44 -080010208 EventLog.writeEvent(EventLogTags.AM_SERVICE_CRASHED_TOO_MUCH,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010209 sr.crashCount, sr.shortName, app.pid);
10210 bringDownServiceLocked(sr, true);
10211 } else if (!allowRestart) {
10212 bringDownServiceLocked(sr, true);
10213 } else {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010214 boolean canceled = scheduleServiceRestartLocked(sr, true);
10215
10216 // Should the service remain running? Note that in the
10217 // extreme case of so many attempts to deliver a command
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010218 // that it failed we also will stop it here.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010219 if (sr.startRequested && (sr.stopIfKilled || canceled)) {
10220 if (sr.pendingStarts.size() == 0) {
10221 sr.startRequested = false;
10222 if (!hasClients) {
10223 // Whoops, no reason to restart!
10224 bringDownServiceLocked(sr, true);
10225 }
10226 }
10227 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010228 }
10229 }
10230
10231 if (!allowRestart) {
10232 app.services.clear();
10233 }
10234 }
10235
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010236 // Make sure we have no more records on the stopping list.
10237 int i = mStoppingServices.size();
10238 while (i > 0) {
10239 i--;
10240 ServiceRecord sr = mStoppingServices.get(i);
10241 if (sr.app == app) {
10242 mStoppingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010243 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010244 }
10245 }
10246
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010247 app.executingServices.clear();
10248 }
10249
10250 private final void removeDyingProviderLocked(ProcessRecord proc,
10251 ContentProviderRecord cpr) {
10252 synchronized (cpr) {
10253 cpr.launchingApp = null;
10254 cpr.notifyAll();
10255 }
10256
Amith Yamasani742a6712011-05-04 14:49:28 -070010257 mProviderMap.removeProviderByClass(cpr.name, UserId.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010258 String names[] = cpr.info.authority.split(";");
10259 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010260 mProviderMap.removeProviderByName(names[j], UserId.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010261 }
10262
10263 Iterator<ProcessRecord> cit = cpr.clients.iterator();
10264 while (cit.hasNext()) {
10265 ProcessRecord capp = cit.next();
10266 if (!capp.persistent && capp.thread != null
10267 && capp.pid != 0
10268 && capp.pid != MY_PID) {
Dianne Hackborn8633e682010-04-22 16:03:41 -070010269 Slog.i(TAG, "Kill " + capp.processName
10270 + " (pid " + capp.pid + "): provider " + cpr.info.name
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010271 + " in dying process " + (proc != null ? proc.processName : "??"));
Dianne Hackborn8633e682010-04-22 16:03:41 -070010272 EventLog.writeEvent(EventLogTags.AM_KILL, capp.pid,
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010273 capp.processName, capp.setAdj, "dying provider "
10274 + cpr.name.toShortString());
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070010275 Process.killProcessQuiet(capp.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010276 }
10277 }
10278
10279 mLaunchingProviders.remove(cpr);
10280 }
10281
10282 /**
10283 * Main code for cleaning up a process when it has gone away. This is
10284 * called both as a result of the process dying, or directly when stopping
10285 * a process when running in single process mode.
10286 */
10287 private final void cleanUpApplicationRecordLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010288 boolean restarting, boolean allowRestart, int index) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010289 if (index >= 0) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010290 mLruProcesses.remove(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010291 }
10292
Dianne Hackborn36124872009-10-08 16:22:03 -070010293 mProcessesToGc.remove(app);
10294
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010295 // Dismiss any open dialogs.
10296 if (app.crashDialog != null) {
10297 app.crashDialog.dismiss();
10298 app.crashDialog = null;
10299 }
10300 if (app.anrDialog != null) {
10301 app.anrDialog.dismiss();
10302 app.anrDialog = null;
10303 }
10304 if (app.waitDialog != null) {
10305 app.waitDialog.dismiss();
10306 app.waitDialog = null;
10307 }
10308
10309 app.crashing = false;
10310 app.notResponding = false;
10311
10312 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -070010313 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010314 app.thread = null;
10315 app.forcingToForeground = null;
10316 app.foregroundServices = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010317 app.foregroundActivities = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070010318 app.hasShownUi = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010319 app.hasAboveClient = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010320
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010321 killServicesLocked(app, allowRestart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010322
10323 boolean restart = false;
10324
10325 int NL = mLaunchingProviders.size();
10326
10327 // Remove published content providers.
10328 if (!app.pubProviders.isEmpty()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010329 Iterator<ContentProviderRecord> it = app.pubProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010330 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010331 ContentProviderRecord cpr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010332 cpr.provider = null;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010333 cpr.proc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010334
10335 // See if someone is waiting for this provider... in which
10336 // case we don't remove it, but just let it restart.
10337 int i = 0;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010338 if (!app.bad && allowRestart) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010339 for (; i<NL; i++) {
10340 if (mLaunchingProviders.get(i) == cpr) {
10341 restart = true;
10342 break;
10343 }
10344 }
10345 } else {
10346 i = NL;
10347 }
10348
10349 if (i >= NL) {
10350 removeDyingProviderLocked(app, cpr);
10351 NL = mLaunchingProviders.size();
10352 }
10353 }
10354 app.pubProviders.clear();
10355 }
10356
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010357 // Take care of any launching providers waiting for this process.
10358 if (checkAppInLaunchingProvidersLocked(app, false)) {
10359 restart = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010360 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010361
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010362 // Unregister from connected content providers.
10363 if (!app.conProviders.isEmpty()) {
Dianne Hackborn0c3154d2009-10-06 17:18:05 -070010364 Iterator it = app.conProviders.keySet().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010365 while (it.hasNext()) {
10366 ContentProviderRecord cpr = (ContentProviderRecord)it.next();
10367 cpr.clients.remove(app);
10368 }
10369 app.conProviders.clear();
10370 }
10371
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010372 // At this point there may be remaining entries in mLaunchingProviders
10373 // where we were the only one waiting, so they are no longer of use.
10374 // Look for these and clean up if found.
10375 // XXX Commented out for now. Trying to figure out a way to reproduce
10376 // the actual situation to identify what is actually going on.
10377 if (false) {
10378 for (int i=0; i<NL; i++) {
10379 ContentProviderRecord cpr = (ContentProviderRecord)
10380 mLaunchingProviders.get(i);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080010381 if (cpr.clients.size() <= 0 && !cpr.hasExternalProcessHandles()) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010382 synchronized (cpr) {
10383 cpr.launchingApp = null;
10384 cpr.notifyAll();
10385 }
10386 }
10387 }
10388 }
10389
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010390 skipCurrentReceiverLocked(app);
10391
10392 // Unregister any receivers.
10393 if (app.receivers.size() > 0) {
10394 Iterator<ReceiverList> it = app.receivers.iterator();
10395 while (it.hasNext()) {
10396 removeReceiverLocked(it.next());
10397 }
10398 app.receivers.clear();
10399 }
10400
Christopher Tate181fafa2009-05-14 11:12:14 -070010401 // If the app is undergoing backup, tell the backup manager about it
10402 if (mBackupTarget != null && app.pid == mBackupTarget.app.pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010403 if (DEBUG_BACKUP) Slog.d(TAG, "App " + mBackupTarget.appInfo + " died during backup");
Christopher Tate181fafa2009-05-14 11:12:14 -070010404 try {
10405 IBackupManager bm = IBackupManager.Stub.asInterface(
10406 ServiceManager.getService(Context.BACKUP_SERVICE));
10407 bm.agentDisconnected(app.info.packageName);
10408 } catch (RemoteException e) {
10409 // can't happen; backup manager is local
10410 }
10411 }
10412
Jeff Sharkey287bd832011-05-28 19:36:26 -070010413 mHandler.obtainMessage(DISPATCH_PROCESS_DIED, app.pid, app.info.uid, null).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010414
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010415 // If the caller is restarting this app, then leave it in its
10416 // current lists and let the caller take care of it.
10417 if (restarting) {
10418 return;
10419 }
10420
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010421 if (!app.persistent || app.isolated) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010422 if (DEBUG_PROCESSES) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010423 "Removing non-persistent process during cleanup: " + app);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010424 mProcessNames.remove(app.processName, app.uid);
10425 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -070010426 if (mHeavyWeightProcess == app) {
10427 mHeavyWeightProcess = null;
10428 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
10429 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010430 } else if (!app.removed) {
10431 // This app is persistent, so we need to keep its record around.
10432 // If it is not already on the pending app list, add it there
10433 // and start a new process for it.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010434 if (mPersistentStartingProcesses.indexOf(app) < 0) {
10435 mPersistentStartingProcesses.add(app);
10436 restart = true;
10437 }
10438 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070010439 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
10440 "Clean-up removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010441 mProcessesOnHold.remove(app);
10442
The Android Open Source Project4df24232009-03-05 14:34:35 -080010443 if (app == mHomeProcess) {
10444 mHomeProcess = null;
10445 }
Dianne Hackbornf35fe232011-11-01 19:25:20 -070010446 if (app == mPreviousProcess) {
10447 mPreviousProcess = null;
10448 }
10449
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010450 if (restart && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010451 // We have components that still need to be running in the
10452 // process, so re-launch it.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010453 mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010454 startProcessLocked(app, "restart", app.processName);
10455 } else if (app.pid > 0 && app.pid != MY_PID) {
10456 // Goodbye!
10457 synchronized (mPidsSelfLocked) {
10458 mPidsSelfLocked.remove(app.pid);
10459 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
10460 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010461 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010462 }
10463 }
10464
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010465 boolean checkAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) {
10466 // Look through the content providers we are waiting to have launched,
10467 // and if any run in this process then either schedule a restart of
10468 // the process or kill the client waiting for it if this process has
10469 // gone bad.
10470 int NL = mLaunchingProviders.size();
10471 boolean restart = false;
10472 for (int i=0; i<NL; i++) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010473 ContentProviderRecord cpr = mLaunchingProviders.get(i);
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010474 if (cpr.launchingApp == app) {
10475 if (!alwaysBad && !app.bad) {
10476 restart = true;
10477 } else {
10478 removeDyingProviderLocked(app, cpr);
10479 NL = mLaunchingProviders.size();
10480 }
10481 }
10482 }
10483 return restart;
10484 }
10485
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010486 // =========================================================
10487 // SERVICES
10488 // =========================================================
10489
10490 ActivityManager.RunningServiceInfo makeRunningServiceInfoLocked(ServiceRecord r) {
10491 ActivityManager.RunningServiceInfo info =
10492 new ActivityManager.RunningServiceInfo();
10493 info.service = r.name;
10494 if (r.app != null) {
10495 info.pid = r.app.pid;
10496 }
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010497 info.uid = r.appInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010498 info.process = r.processName;
10499 info.foreground = r.isForeground;
10500 info.activeSince = r.createTime;
10501 info.started = r.startRequested;
10502 info.clientCount = r.connections.size();
10503 info.crashCount = r.crashCount;
10504 info.lastActivityTime = r.lastActivity;
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010505 if (r.isForeground) {
10506 info.flags |= ActivityManager.RunningServiceInfo.FLAG_FOREGROUND;
10507 }
10508 if (r.startRequested) {
10509 info.flags |= ActivityManager.RunningServiceInfo.FLAG_STARTED;
10510 }
Dan Egnor42471dd2010-01-07 17:25:22 -080010511 if (r.app != null && r.app.pid == MY_PID) {
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010512 info.flags |= ActivityManager.RunningServiceInfo.FLAG_SYSTEM_PROCESS;
10513 }
10514 if (r.app != null && r.app.persistent) {
10515 info.flags |= ActivityManager.RunningServiceInfo.FLAG_PERSISTENT_PROCESS;
10516 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010517
10518 for (ArrayList<ConnectionRecord> connl : r.connections.values()) {
10519 for (int i=0; i<connl.size(); i++) {
10520 ConnectionRecord conn = connl.get(i);
10521 if (conn.clientLabel != 0) {
10522 info.clientPackage = conn.binding.client.info.packageName;
10523 info.clientLabel = conn.clientLabel;
10524 return info;
10525 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010526 }
10527 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010528 return info;
10529 }
10530
10531 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum,
10532 int flags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010533 enforceNotIsolatedCaller("getServices");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010534 synchronized (this) {
10535 ArrayList<ActivityManager.RunningServiceInfo> res
10536 = new ArrayList<ActivityManager.RunningServiceInfo>();
10537
Amith Yamasani742a6712011-05-04 14:49:28 -070010538 int userId = UserId.getUserId(Binder.getCallingUid());
10539 if (mServiceMap.getAllServices(userId).size() > 0) {
10540 Iterator<ServiceRecord> it
10541 = mServiceMap.getAllServices(userId).iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010542 while (it.hasNext() && res.size() < maxNum) {
10543 res.add(makeRunningServiceInfoLocked(it.next()));
10544 }
10545 }
10546
10547 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
10548 ServiceRecord r = mRestartingServices.get(i);
10549 ActivityManager.RunningServiceInfo info =
10550 makeRunningServiceInfoLocked(r);
10551 info.restarting = r.nextRestartTime;
10552 res.add(info);
10553 }
10554
10555 return res;
10556 }
10557 }
10558
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010559 public PendingIntent getRunningServiceControlPanel(ComponentName name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010560 enforceNotIsolatedCaller("getRunningServiceControlPanel");
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010561 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010562 int userId = UserId.getUserId(Binder.getCallingUid());
10563 ServiceRecord r = mServiceMap.getServiceByName(name, userId);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010564 if (r != null) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010565 for (ArrayList<ConnectionRecord> conn : r.connections.values()) {
10566 for (int i=0; i<conn.size(); i++) {
10567 if (conn.get(i).clientIntent != null) {
10568 return conn.get(i).clientIntent;
10569 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010570 }
10571 }
10572 }
10573 }
10574 return null;
10575 }
10576
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010577 private final ServiceRecord findServiceLocked(ComponentName name,
10578 IBinder token) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010579 ServiceRecord r = mServiceMap.getServiceByName(name, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010580 return r == token ? r : null;
10581 }
10582
10583 private final class ServiceLookupResult {
10584 final ServiceRecord record;
10585 final String permission;
10586
10587 ServiceLookupResult(ServiceRecord _record, String _permission) {
10588 record = _record;
10589 permission = _permission;
10590 }
10591 };
10592
10593 private ServiceLookupResult findServiceLocked(Intent service,
10594 String resolvedType) {
10595 ServiceRecord r = null;
10596 if (service.getComponent() != null) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010597 r = mServiceMap.getServiceByName(service.getComponent(), Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010598 }
10599 if (r == null) {
10600 Intent.FilterComparison filter = new Intent.FilterComparison(service);
Amith Yamasani742a6712011-05-04 14:49:28 -070010601 r = mServiceMap.getServiceByIntent(filter, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010602 }
10603
10604 if (r == null) {
10605 try {
10606 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070010607 AppGlobals.getPackageManager().resolveService(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010608 service, resolvedType, 0);
10609 ServiceInfo sInfo =
10610 rInfo != null ? rInfo.serviceInfo : null;
10611 if (sInfo == null) {
10612 return null;
10613 }
10614
10615 ComponentName name = new ComponentName(
10616 sInfo.applicationInfo.packageName, sInfo.name);
Amith Yamasani742a6712011-05-04 14:49:28 -070010617 r = mServiceMap.getServiceByName(name, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010618 } catch (RemoteException ex) {
10619 // pm is in same process, this will never happen.
10620 }
10621 }
10622 if (r != null) {
10623 int callingPid = Binder.getCallingPid();
10624 int callingUid = Binder.getCallingUid();
10625 if (checkComponentPermission(r.permission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010626 callingPid, callingUid, r.appInfo.uid, r.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010627 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010628 if (!r.exported) {
10629 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
10630 + " from pid=" + callingPid
10631 + ", uid=" + callingUid
10632 + " that is not exported from uid " + r.appInfo.uid);
10633 return new ServiceLookupResult(null, "not exported from uid "
10634 + r.appInfo.uid);
10635 }
Joe Onorato8a9b2202010-02-26 18:56:32 -080010636 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010637 + " from pid=" + callingPid
10638 + ", uid=" + callingUid
10639 + " requires " + r.permission);
10640 return new ServiceLookupResult(null, r.permission);
10641 }
10642 return new ServiceLookupResult(r, null);
10643 }
10644 return null;
10645 }
10646
10647 private class ServiceRestarter implements Runnable {
10648 private ServiceRecord mService;
10649
10650 void setService(ServiceRecord service) {
10651 mService = service;
10652 }
10653
10654 public void run() {
10655 synchronized(ActivityManagerService.this) {
10656 performServiceRestartLocked(mService);
10657 }
10658 }
10659 }
10660
10661 private ServiceLookupResult retrieveServiceLocked(Intent service,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010662 String resolvedType, int callingPid, int callingUid, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010663 ServiceRecord r = null;
Amith Yamasani742a6712011-05-04 14:49:28 -070010664 if (DEBUG_SERVICE)
10665 Slog.v(TAG, "retrieveServiceLocked: " + service + " type=" + resolvedType
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010666 + " callingUid=" + callingUid);
Amith Yamasani742a6712011-05-04 14:49:28 -070010667
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010668 if (service.getComponent() != null) {
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010669 r = mServiceMap.getServiceByName(service.getComponent(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010670 }
Amith Yamasani742a6712011-05-04 14:49:28 -070010671 if (r == null) {
10672 Intent.FilterComparison filter = new Intent.FilterComparison(service);
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010673 r = mServiceMap.getServiceByIntent(filter, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -070010674 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010675 if (r == null) {
10676 try {
10677 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070010678 AppGlobals.getPackageManager().resolveService(
Dianne Hackborn1655be42009-05-08 14:29:01 -070010679 service, resolvedType, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010680 ServiceInfo sInfo =
10681 rInfo != null ? rInfo.serviceInfo : null;
10682 if (sInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010683 Slog.w(TAG, "Unable to start service " + service +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010684 ": not found");
10685 return null;
10686 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010687 if (userId > 0) {
10688 sInfo.applicationInfo = getAppInfoForUser(sInfo.applicationInfo, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -070010689 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010690 ComponentName name = new ComponentName(
10691 sInfo.applicationInfo.packageName, sInfo.name);
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010692 r = mServiceMap.getServiceByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010693 if (r == null) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010694 Intent.FilterComparison filter = new Intent.FilterComparison(
10695 service.cloneFilter());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010696 ServiceRestarter res = new ServiceRestarter();
10697 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
10698 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
10699 synchronized (stats) {
10700 ss = stats.getServiceStatsLocked(
10701 sInfo.applicationInfo.uid, sInfo.packageName,
10702 sInfo.name);
10703 }
Dianne Hackbornb1c4a2a2010-01-19 15:36:42 -080010704 r = new ServiceRecord(this, ss, name, filter, sInfo, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010705 res.setService(r);
Amith Yamasani742a6712011-05-04 14:49:28 -070010706 mServiceMap.putServiceByName(name, UserId.getUserId(r.appInfo.uid), r);
10707 mServiceMap.putServiceByIntent(filter, UserId.getUserId(r.appInfo.uid), r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010708
10709 // Make sure this component isn't in the pending list.
10710 int N = mPendingServices.size();
10711 for (int i=0; i<N; i++) {
10712 ServiceRecord pr = mPendingServices.get(i);
10713 if (pr.name.equals(name)) {
10714 mPendingServices.remove(i);
10715 i--;
10716 N--;
10717 }
10718 }
10719 }
10720 } catch (RemoteException ex) {
10721 // pm is in same process, this will never happen.
10722 }
10723 }
10724 if (r != null) {
10725 if (checkComponentPermission(r.permission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010726 callingPid, callingUid, r.appInfo.uid, r.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010727 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010728 if (!r.exported) {
10729 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
10730 + " from pid=" + callingPid
10731 + ", uid=" + callingUid
10732 + " that is not exported from uid " + r.appInfo.uid);
10733 return new ServiceLookupResult(null, "not exported from uid "
10734 + r.appInfo.uid);
10735 }
Joe Onorato8a9b2202010-02-26 18:56:32 -080010736 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010737 + " from pid=" + callingPid
10738 + ", uid=" + callingUid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010739 + " requires " + r.permission);
10740 return new ServiceLookupResult(null, r.permission);
10741 }
10742 return new ServiceLookupResult(r, null);
10743 }
10744 return null;
10745 }
10746
Dianne Hackborn287952c2010-09-22 22:34:31 -070010747 private final void bumpServiceExecutingLocked(ServiceRecord r, String why) {
10748 if (DEBUG_SERVICE) Log.v(TAG, ">>> EXECUTING "
10749 + why + " of " + r + " in app " + r.app);
10750 else if (DEBUG_SERVICE_EXECUTING) Log.v(TAG, ">>> EXECUTING "
10751 + why + " of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010752 long now = SystemClock.uptimeMillis();
10753 if (r.executeNesting == 0 && r.app != null) {
10754 if (r.app.executingServices.size() == 0) {
10755 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
10756 msg.obj = r.app;
10757 mHandler.sendMessageAtTime(msg, now+SERVICE_TIMEOUT);
10758 }
10759 r.app.executingServices.add(r);
10760 }
10761 r.executeNesting++;
10762 r.executingStart = now;
10763 }
10764
10765 private final void sendServiceArgsLocked(ServiceRecord r,
10766 boolean oomAdjusted) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010767 final int N = r.pendingStarts.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010768 if (N == 0) {
10769 return;
10770 }
10771
Dianne Hackborn39792d22010-08-19 18:01:52 -070010772 while (r.pendingStarts.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010773 try {
Dianne Hackborn39792d22010-08-19 18:01:52 -070010774 ServiceRecord.StartItem si = r.pendingStarts.remove(0);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010775 if (DEBUG_SERVICE) Slog.v(TAG, "Sending arguments to: "
10776 + r + " " + r.intent + " args=" + si.intent);
Dianne Hackborn3a28f222011-03-01 12:25:54 -080010777 if (si.intent == null && N > 1) {
10778 // If somehow we got a dummy null intent in the middle,
10779 // then skip it. DO NOT skip a null intent when it is
10780 // the only one in the list -- this is to support the
10781 // onStartCommand(null) case.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010782 continue;
10783 }
Dianne Hackborn39792d22010-08-19 18:01:52 -070010784 si.deliveredTime = SystemClock.uptimeMillis();
10785 r.deliveredStarts.add(si);
10786 si.deliveryCount++;
Dianne Hackborn21c241e2012-03-08 13:57:23 -080010787 if (si.neededGrants != null) {
10788 grantUriPermissionUncheckedFromIntentLocked(si.neededGrants,
10789 si.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -070010790 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070010791 bumpServiceExecutingLocked(r, "start");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010792 if (!oomAdjusted) {
10793 oomAdjusted = true;
10794 updateOomAdjLocked(r.app);
10795 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010796 int flags = 0;
10797 if (si.deliveryCount > 0) {
10798 flags |= Service.START_FLAG_RETRY;
10799 }
10800 if (si.doneExecutingCount > 0) {
10801 flags |= Service.START_FLAG_REDELIVERY;
10802 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070010803 r.app.thread.scheduleServiceArgs(r, si.taskRemoved, si.id, flags, si.intent);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010804 } catch (RemoteException e) {
10805 // Remote process gone... we'll let the normal cleanup take
10806 // care of this.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010807 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while scheduling start: " + r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010808 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010809 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010810 Slog.w(TAG, "Unexpected exception", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010811 break;
10812 }
10813 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010814 }
10815
10816 private final boolean requestServiceBindingLocked(ServiceRecord r,
10817 IntentBindRecord i, boolean rebind) {
10818 if (r.app == null || r.app.thread == null) {
10819 // If service is not currently running, can't yet bind.
10820 return false;
10821 }
10822 if ((!i.requested || rebind) && i.apps.size() > 0) {
10823 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070010824 bumpServiceExecutingLocked(r, "bind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010825 r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind);
10826 if (!rebind) {
10827 i.requested = true;
10828 }
10829 i.hasBound = true;
10830 i.doRebind = false;
10831 } catch (RemoteException e) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010832 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while binding " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010833 return false;
10834 }
10835 }
10836 return true;
10837 }
10838
10839 private final void requestServiceBindingsLocked(ServiceRecord r) {
10840 Iterator<IntentBindRecord> bindings = r.bindings.values().iterator();
10841 while (bindings.hasNext()) {
10842 IntentBindRecord i = bindings.next();
10843 if (!requestServiceBindingLocked(r, i, false)) {
10844 break;
10845 }
10846 }
10847 }
10848
10849 private final void realStartServiceLocked(ServiceRecord r,
10850 ProcessRecord app) throws RemoteException {
10851 if (app.thread == null) {
10852 throw new RemoteException();
10853 }
Amith Yamasani742a6712011-05-04 14:49:28 -070010854 if (DEBUG_MU)
10855 Slog.v(TAG_MU, "realStartServiceLocked, ServiceRecord.uid = " + r.appInfo.uid
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010856 + ", ProcessRecord.uid = " + app.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010857 r.app = app;
The Android Open Source Project10592532009-03-18 17:39:46 -070010858 r.restartTime = r.lastActivity = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010859
10860 app.services.add(r);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010861 bumpServiceExecutingLocked(r, "create");
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010862 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010863
10864 boolean created = false;
10865 try {
Dianne Hackborna33e3f72009-09-29 17:28:24 -070010866 mStringBuilder.setLength(0);
Dianne Hackborn21c241e2012-03-08 13:57:23 -080010867 r.intent.getIntent().toShortString(mStringBuilder, true, false, true, false);
Doug Zongker2bec3d42009-12-04 12:52:44 -080010868 EventLog.writeEvent(EventLogTags.AM_CREATE_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010869 System.identityHashCode(r), r.shortName,
Dianne Hackborna33e3f72009-09-29 17:28:24 -070010870 mStringBuilder.toString(), r.app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010871 synchronized (r.stats.getBatteryStats()) {
10872 r.stats.startLaunchedLocked();
10873 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -070010874 ensurePackageDexOpt(r.serviceInfo.packageName);
Dianne Hackborne2515ee2011-04-27 18:52:56 -040010875 app.thread.scheduleCreateService(r, r.serviceInfo,
10876 compatibilityInfoForPackageLocked(r.serviceInfo.applicationInfo));
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070010877 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010878 created = true;
10879 } finally {
10880 if (!created) {
10881 app.services.remove(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010882 scheduleServiceRestartLocked(r, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010883 }
10884 }
10885
10886 requestServiceBindingsLocked(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010887
10888 // If the service is in the started state, and there are no
10889 // pending arguments, then fake up one so its onStartCommand() will
10890 // be called.
10891 if (r.startRequested && r.callStart && r.pendingStarts.size() == 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070010892 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Dianne Hackborn21c241e2012-03-08 13:57:23 -080010893 null, null));
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010894 }
10895
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010896 sendServiceArgsLocked(r, true);
10897 }
10898
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010899 private final boolean scheduleServiceRestartLocked(ServiceRecord r,
10900 boolean allowCancel) {
10901 boolean canceled = false;
10902
Dianne Hackbornfd12af42009-08-27 00:44:33 -070010903 final long now = SystemClock.uptimeMillis();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010904 long minDuration = SERVICE_RESTART_DURATION;
Dianne Hackborn6ccd2af2009-08-27 12:26:44 -070010905 long resetTime = SERVICE_RESET_RUN_DURATION;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010906
Dianne Hackborn070783f2010-12-29 16:46:28 -080010907 if ((r.serviceInfo.applicationInfo.flags
10908 &ApplicationInfo.FLAG_PERSISTENT) != 0) {
10909 minDuration /= 4;
10910 }
10911
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010912 // Any delivered but not yet finished starts should be put back
10913 // on the pending list.
10914 final int N = r.deliveredStarts.size();
10915 if (N > 0) {
10916 for (int i=N-1; i>=0; i--) {
10917 ServiceRecord.StartItem si = r.deliveredStarts.get(i);
Dianne Hackborn39792d22010-08-19 18:01:52 -070010918 si.removeUriPermissionsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010919 if (si.intent == null) {
10920 // We'll generate this again if needed.
10921 } else if (!allowCancel || (si.deliveryCount < ServiceRecord.MAX_DELIVERY_COUNT
10922 && si.doneExecutingCount < ServiceRecord.MAX_DONE_EXECUTING_COUNT)) {
10923 r.pendingStarts.add(0, si);
10924 long dur = SystemClock.uptimeMillis() - si.deliveredTime;
10925 dur *= 2;
10926 if (minDuration < dur) minDuration = dur;
10927 if (resetTime < dur) resetTime = dur;
10928 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010929 Slog.w(TAG, "Canceling start item " + si.intent + " in service "
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010930 + r.name);
10931 canceled = true;
10932 }
10933 }
10934 r.deliveredStarts.clear();
10935 }
10936
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010937 r.totalRestartCount++;
10938 if (r.restartDelay == 0) {
10939 r.restartCount++;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010940 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010941 } else {
10942 // If it has been a "reasonably long time" since the service
10943 // was started, then reset our restart duration back to
10944 // the beginning, so we don't infinitely increase the duration
10945 // on a service that just occasionally gets killed (which is
10946 // a normal case, due to process being killed to reclaim memory).
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010947 if (now > (r.restartTime+resetTime)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010948 r.restartCount = 1;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010949 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010950 } else {
Dianne Hackborn070783f2010-12-29 16:46:28 -080010951 if ((r.serviceInfo.applicationInfo.flags
10952 &ApplicationInfo.FLAG_PERSISTENT) != 0) {
10953 // Services in peristent processes will restart much more
10954 // quickly, since they are pretty important. (Think SystemUI).
10955 r.restartDelay += minDuration/2;
10956 } else {
10957 r.restartDelay *= SERVICE_RESTART_DURATION_FACTOR;
10958 if (r.restartDelay < minDuration) {
10959 r.restartDelay = minDuration;
10960 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010961 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010962 }
10963 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070010964
10965 r.nextRestartTime = now + r.restartDelay;
10966
10967 // Make sure that we don't end up restarting a bunch of services
10968 // all at the same time.
10969 boolean repeat;
10970 do {
10971 repeat = false;
10972 for (int i=mRestartingServices.size()-1; i>=0; i--) {
10973 ServiceRecord r2 = mRestartingServices.get(i);
10974 if (r2 != r && r.nextRestartTime
10975 >= (r2.nextRestartTime-SERVICE_MIN_RESTART_TIME_BETWEEN)
10976 && r.nextRestartTime
10977 < (r2.nextRestartTime+SERVICE_MIN_RESTART_TIME_BETWEEN)) {
10978 r.nextRestartTime = r2.nextRestartTime + SERVICE_MIN_RESTART_TIME_BETWEEN;
10979 r.restartDelay = r.nextRestartTime - now;
10980 repeat = true;
10981 break;
10982 }
10983 }
10984 } while (repeat);
10985
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010986 if (!mRestartingServices.contains(r)) {
10987 mRestartingServices.add(r);
10988 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070010989
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070010990 r.cancelNotification();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010991
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010992 mHandler.removeCallbacks(r.restarter);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070010993 mHandler.postAtTime(r.restarter, r.nextRestartTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010994 r.nextRestartTime = SystemClock.uptimeMillis() + r.restartDelay;
Joe Onorato8a9b2202010-02-26 18:56:32 -080010995 Slog.w(TAG, "Scheduling restart of crashed service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010996 + r.shortName + " in " + r.restartDelay + "ms");
Doug Zongker2bec3d42009-12-04 12:52:44 -080010997 EventLog.writeEvent(EventLogTags.AM_SCHEDULE_SERVICE_RESTART,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010998 r.shortName, r.restartDelay);
10999
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011000 return canceled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011001 }
11002
11003 final void performServiceRestartLocked(ServiceRecord r) {
11004 if (!mRestartingServices.contains(r)) {
11005 return;
11006 }
11007 bringUpServiceLocked(r, r.intent.getIntent().getFlags(), true);
11008 }
11009
11010 private final boolean unscheduleServiceRestartLocked(ServiceRecord r) {
11011 if (r.restartDelay == 0) {
11012 return false;
11013 }
11014 r.resetRestartCounter();
11015 mRestartingServices.remove(r);
11016 mHandler.removeCallbacks(r.restarter);
11017 return true;
11018 }
11019
11020 private final boolean bringUpServiceLocked(ServiceRecord r,
11021 int intentFlags, boolean whileRestarting) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011022 //Slog.i(TAG, "Bring up service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011023 //r.dump(" ");
11024
Dianne Hackborn36124872009-10-08 16:22:03 -070011025 if (r.app != null && r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011026 sendServiceArgsLocked(r, false);
11027 return true;
11028 }
11029
11030 if (!whileRestarting && r.restartDelay > 0) {
11031 // If waiting for a restart, then do nothing.
11032 return true;
11033 }
11034
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011035 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing up " + r + " " + r.intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011036
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011037 // We are now bringing the service up, so no longer in the
11038 // restarting state.
11039 mRestartingServices.remove(r);
11040
Dianne Hackborne7f97212011-02-24 14:40:20 -080011041 // Service is now being launched, its package can't be stopped.
11042 try {
11043 AppGlobals.getPackageManager().setPackageStoppedState(
11044 r.packageName, false);
11045 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080011046 } catch (IllegalArgumentException e) {
11047 Slog.w(TAG, "Failed trying to unstop package "
11048 + r.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080011049 }
11050
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011051 final boolean isolated = (r.serviceInfo.flags&ServiceInfo.FLAG_ISOLATED_PROCESS) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011052 final String appName = r.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011053 ProcessRecord app;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011054
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011055 if (!isolated) {
11056 app = getProcessRecordLocked(appName, r.appInfo.uid);
11057 if (DEBUG_MU)
11058 Slog.v(TAG_MU, "bringUpServiceLocked: appInfo.uid=" + r.appInfo.uid + " app=" + app);
11059 if (app != null && app.thread != null) {
11060 try {
11061 app.addPackage(r.appInfo.packageName);
11062 realStartServiceLocked(r, app);
11063 return true;
11064 } catch (RemoteException e) {
11065 Slog.w(TAG, "Exception when starting service " + r.shortName, e);
11066 }
11067
11068 // If a dead object exception was thrown -- fall through to
11069 // restart the application.
11070 }
11071 } else {
11072 // If this service runs in an isolated process, then each time
11073 // we call startProcessLocked() we will get a new isolated
11074 // process, starting another process if we are currently waiting
11075 // for a previous process to come up. To deal with this, we store
11076 // in the service any current isolated process it is running in or
11077 // waiting to have come up.
11078 app = r.isolatedProc;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011079 }
11080
Dianne Hackborn36124872009-10-08 16:22:03 -070011081 // Not running -- get it started, and enqueue this service record
11082 // to be executed when the app comes up.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011083 if (app == null) {
11084 if ((app=startProcessLocked(appName, r.appInfo, true, intentFlags,
11085 "service", r.name, false, isolated)) == null) {
11086 Slog.w(TAG, "Unable to launch app "
11087 + r.appInfo.packageName + "/"
11088 + r.appInfo.uid + " for service "
11089 + r.intent.getIntent() + ": process is bad");
11090 bringDownServiceLocked(r, true);
11091 return false;
11092 }
11093 if (isolated) {
11094 r.isolatedProc = app;
11095 }
Dianne Hackborn36124872009-10-08 16:22:03 -070011096 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011097
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011098 if (!mPendingServices.contains(r)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011099 mPendingServices.add(r);
11100 }
Dianne Hackborn36124872009-10-08 16:22:03 -070011101
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011102 return true;
11103 }
11104
11105 private final void bringDownServiceLocked(ServiceRecord r, boolean force) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011106 //Slog.i(TAG, "Bring down service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011107 //r.dump(" ");
11108
11109 // Does it still need to run?
11110 if (!force && r.startRequested) {
11111 return;
11112 }
11113 if (r.connections.size() > 0) {
11114 if (!force) {
11115 // XXX should probably keep a count of the number of auto-create
11116 // connections directly in the service.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011117 Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011118 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011119 ArrayList<ConnectionRecord> cr = it.next();
11120 for (int i=0; i<cr.size(); i++) {
11121 if ((cr.get(i).flags&Context.BIND_AUTO_CREATE) != 0) {
11122 return;
11123 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011124 }
11125 }
11126 }
11127
11128 // Report to all of the connections that the service is no longer
11129 // available.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011130 Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011131 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011132 ArrayList<ConnectionRecord> c = it.next();
11133 for (int i=0; i<c.size(); i++) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011134 ConnectionRecord cr = c.get(i);
11135 // There is still a connection to the service that is
11136 // being brought down. Mark it as dead.
11137 cr.serviceDead = true;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011138 try {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011139 cr.conn.connected(r.name, null);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011140 } catch (Exception e) {
11141 Slog.w(TAG, "Failure disconnecting service " + r.name +
11142 " to connection " + c.get(i).conn.asBinder() +
11143 " (in " + c.get(i).binding.client.processName + ")", e);
11144 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011145 }
11146 }
11147 }
11148
11149 // Tell the service that it has been unbound.
11150 if (r.bindings.size() > 0 && r.app != null && r.app.thread != null) {
11151 Iterator<IntentBindRecord> it = r.bindings.values().iterator();
11152 while (it.hasNext()) {
11153 IntentBindRecord ibr = it.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -080011154 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down binding " + ibr
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011155 + ": hasBound=" + ibr.hasBound);
11156 if (r.app != null && r.app.thread != null && ibr.hasBound) {
11157 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011158 bumpServiceExecutingLocked(r, "bring down unbind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011159 updateOomAdjLocked(r.app);
11160 ibr.hasBound = false;
11161 r.app.thread.scheduleUnbindService(r,
11162 ibr.intent.getIntent());
11163 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011164 Slog.w(TAG, "Exception when unbinding service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011165 + r.shortName, e);
11166 serviceDoneExecutingLocked(r, true);
11167 }
11168 }
11169 }
11170 }
11171
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011172 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down " + r + " " + r.intent);
Doug Zongker2bec3d42009-12-04 12:52:44 -080011173 EventLog.writeEvent(EventLogTags.AM_DESTROY_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011174 System.identityHashCode(r), r.shortName,
11175 (r.app != null) ? r.app.pid : -1);
11176
Amith Yamasani742a6712011-05-04 14:49:28 -070011177 mServiceMap.removeServiceByName(r.name, r.userId);
11178 mServiceMap.removeServiceByIntent(r.intent, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011179 r.totalRestartCount = 0;
11180 unscheduleServiceRestartLocked(r);
11181
11182 // Also make sure it is not on the pending list.
11183 int N = mPendingServices.size();
11184 for (int i=0; i<N; i++) {
11185 if (mPendingServices.get(i) == r) {
11186 mPendingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011187 if (DEBUG_SERVICE) Slog.v(TAG, "Removed pending: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011188 i--;
11189 N--;
11190 }
11191 }
11192
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011193 r.cancelNotification();
11194 r.isForeground = false;
11195 r.foregroundId = 0;
11196 r.foregroundNoti = null;
11197
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011198 // Clear start entries.
Dianne Hackborn39792d22010-08-19 18:01:52 -070011199 r.clearDeliveredStartsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011200 r.pendingStarts.clear();
11201
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011202 if (r.app != null) {
11203 synchronized (r.stats.getBatteryStats()) {
11204 r.stats.stopLaunchedLocked();
11205 }
11206 r.app.services.remove(r);
11207 if (r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011208 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011209 bumpServiceExecutingLocked(r, "stop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011210 mStoppingServices.add(r);
11211 updateOomAdjLocked(r.app);
11212 r.app.thread.scheduleStopService(r);
11213 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011214 Slog.w(TAG, "Exception when stopping service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011215 + r.shortName, e);
11216 serviceDoneExecutingLocked(r, true);
11217 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011218 updateServiceForegroundLocked(r.app, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011219 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011220 if (DEBUG_SERVICE) Slog.v(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011221 TAG, "Removed service that has no process: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011222 }
11223 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011224 if (DEBUG_SERVICE) Slog.v(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011225 TAG, "Removed service that is not running: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011226 }
Vairavan Srinivasana207ce22010-12-23 13:51:48 -080011227
11228 if (r.bindings.size() > 0) {
11229 r.bindings.clear();
11230 }
11231
11232 if (r.restarter instanceof ServiceRestarter) {
11233 ((ServiceRestarter)r.restarter).setService(null);
11234 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011235 }
11236
11237 ComponentName startServiceLocked(IApplicationThread caller,
11238 Intent service, String resolvedType,
11239 int callingPid, int callingUid) {
11240 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011241 if (DEBUG_SERVICE) Slog.v(TAG, "startService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011242 + " type=" + resolvedType + " args=" + service.getExtras());
11243
11244 if (caller != null) {
11245 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11246 if (callerApp == null) {
11247 throw new SecurityException(
11248 "Unable to find app for caller " + caller
11249 + " (pid=" + Binder.getCallingPid()
11250 + ") when starting service " + service);
11251 }
11252 }
11253
11254 ServiceLookupResult res =
11255 retrieveServiceLocked(service, resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011256 callingPid, callingUid, UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011257 if (res == null) {
11258 return null;
11259 }
11260 if (res.record == null) {
11261 return new ComponentName("!", res.permission != null
11262 ? res.permission : "private to package");
11263 }
11264 ServiceRecord r = res.record;
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011265 NeededUriGrants neededGrants = checkGrantUriPermissionFromIntentLocked(
11266 callingUid, r.packageName, service, service.getFlags(), null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011267 if (unscheduleServiceRestartLocked(r)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011268 if (DEBUG_SERVICE) Slog.v(TAG, "START SERVICE WHILE RESTART PENDING: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011269 }
11270 r.startRequested = true;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011271 r.callStart = false;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011272 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011273 service, neededGrants));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011274 r.lastActivity = SystemClock.uptimeMillis();
11275 synchronized (r.stats.getBatteryStats()) {
11276 r.stats.startRunningLocked();
11277 }
11278 if (!bringUpServiceLocked(r, service.getFlags(), false)) {
11279 return new ComponentName("!", "Service process is bad");
11280 }
11281 return r.name;
11282 }
11283 }
11284
11285 public ComponentName startService(IApplicationThread caller, Intent service,
11286 String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011287 enforceNotIsolatedCaller("startService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011288 // Refuse possible leaked file descriptors
11289 if (service != null && service.hasFileDescriptors() == true) {
11290 throw new IllegalArgumentException("File descriptors passed in Intent");
11291 }
11292
Amith Yamasani742a6712011-05-04 14:49:28 -070011293 if (DEBUG_SERVICE)
11294 Slog.v(TAG, "startService: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011295 synchronized(this) {
11296 final int callingPid = Binder.getCallingPid();
11297 final int callingUid = Binder.getCallingUid();
11298 final long origId = Binder.clearCallingIdentity();
11299 ComponentName res = startServiceLocked(caller, service,
11300 resolvedType, callingPid, callingUid);
11301 Binder.restoreCallingIdentity(origId);
11302 return res;
11303 }
11304 }
11305
11306 ComponentName startServiceInPackage(int uid,
11307 Intent service, String resolvedType) {
11308 synchronized(this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070011309 if (DEBUG_SERVICE)
11310 Slog.v(TAG, "startServiceInPackage: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011311 final long origId = Binder.clearCallingIdentity();
11312 ComponentName res = startServiceLocked(null, service,
11313 resolvedType, -1, uid);
11314 Binder.restoreCallingIdentity(origId);
11315 return res;
11316 }
11317 }
11318
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011319 private void stopServiceLocked(ServiceRecord service) {
11320 synchronized (service.stats.getBatteryStats()) {
11321 service.stats.stopRunningLocked();
11322 }
11323 service.startRequested = false;
11324 service.callStart = false;
11325 bringDownServiceLocked(service, false);
11326 }
11327
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011328 public int stopService(IApplicationThread caller, Intent service,
11329 String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011330 enforceNotIsolatedCaller("stopService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011331 // Refuse possible leaked file descriptors
11332 if (service != null && service.hasFileDescriptors() == true) {
11333 throw new IllegalArgumentException("File descriptors passed in Intent");
11334 }
11335
11336 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011337 if (DEBUG_SERVICE) Slog.v(TAG, "stopService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011338 + " type=" + resolvedType);
11339
11340 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11341 if (caller != null && callerApp == null) {
11342 throw new SecurityException(
11343 "Unable to find app for caller " + caller
11344 + " (pid=" + Binder.getCallingPid()
11345 + ") when stopping service " + service);
11346 }
11347
11348 // If this service is active, make sure it is stopped.
11349 ServiceLookupResult r = findServiceLocked(service, resolvedType);
11350 if (r != null) {
11351 if (r.record != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011352 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011353 try {
11354 stopServiceLocked(r.record);
11355 } finally {
11356 Binder.restoreCallingIdentity(origId);
11357 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011358 return 1;
11359 }
11360 return -1;
11361 }
11362 }
11363
11364 return 0;
11365 }
11366
11367 public IBinder peekService(Intent service, String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011368 enforceNotIsolatedCaller("peekService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011369 // Refuse possible leaked file descriptors
11370 if (service != null && service.hasFileDescriptors() == true) {
11371 throw new IllegalArgumentException("File descriptors passed in Intent");
11372 }
11373
11374 IBinder ret = null;
11375
11376 synchronized(this) {
11377 ServiceLookupResult r = findServiceLocked(service, resolvedType);
11378
11379 if (r != null) {
11380 // r.record is null if findServiceLocked() failed the caller permission check
11381 if (r.record == null) {
11382 throw new SecurityException(
11383 "Permission Denial: Accessing service " + r.record.name
11384 + " from pid=" + Binder.getCallingPid()
11385 + ", uid=" + Binder.getCallingUid()
11386 + " requires " + r.permission);
11387 }
11388 IntentBindRecord ib = r.record.bindings.get(r.record.intent);
11389 if (ib != null) {
11390 ret = ib.binder;
11391 }
11392 }
11393 }
11394
11395 return ret;
11396 }
11397
11398 public boolean stopServiceToken(ComponentName className, IBinder token,
11399 int startId) {
11400 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011401 if (DEBUG_SERVICE) Slog.v(TAG, "stopServiceToken: " + className
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011402 + " " + token + " startId=" + startId);
11403 ServiceRecord r = findServiceLocked(className, token);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011404 if (r != null) {
11405 if (startId >= 0) {
11406 // Asked to only stop if done with all work. Note that
11407 // to avoid leaks, we will take this as dropping all
11408 // start items up to and including this one.
11409 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
11410 if (si != null) {
11411 while (r.deliveredStarts.size() > 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -070011412 ServiceRecord.StartItem cur = r.deliveredStarts.remove(0);
11413 cur.removeUriPermissionsLocked();
11414 if (cur == si) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011415 break;
11416 }
11417 }
11418 }
11419
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011420 if (r.getLastStartId() != startId) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011421 return false;
11422 }
11423
11424 if (r.deliveredStarts.size() > 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011425 Slog.w(TAG, "stopServiceToken startId " + startId
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011426 + " is last, but have " + r.deliveredStarts.size()
11427 + " remaining args");
11428 }
11429 }
11430
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011431 synchronized (r.stats.getBatteryStats()) {
11432 r.stats.stopRunningLocked();
11433 r.startRequested = false;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011434 r.callStart = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011435 }
11436 final long origId = Binder.clearCallingIdentity();
11437 bringDownServiceLocked(r, false);
11438 Binder.restoreCallingIdentity(origId);
11439 return true;
11440 }
11441 }
11442 return false;
11443 }
11444
11445 public void setServiceForeground(ComponentName className, IBinder token,
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011446 int id, Notification notification, boolean removeNotification) {
11447 final long origId = Binder.clearCallingIdentity();
11448 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011449 synchronized(this) {
11450 ServiceRecord r = findServiceLocked(className, token);
11451 if (r != null) {
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011452 if (id != 0) {
11453 if (notification == null) {
11454 throw new IllegalArgumentException("null notification");
11455 }
11456 if (r.foregroundId != id) {
11457 r.cancelNotification();
11458 r.foregroundId = id;
11459 }
11460 notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
11461 r.foregroundNoti = notification;
11462 r.isForeground = true;
11463 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011464 if (r.app != null) {
11465 updateServiceForegroundLocked(r.app, true);
11466 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011467 } else {
11468 if (r.isForeground) {
11469 r.isForeground = false;
11470 if (r.app != null) {
Dianne Hackborn8633e682010-04-22 16:03:41 -070011471 updateLruProcessLocked(r.app, false, true);
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011472 updateServiceForegroundLocked(r.app, true);
11473 }
11474 }
11475 if (removeNotification) {
11476 r.cancelNotification();
11477 r.foregroundId = 0;
11478 r.foregroundNoti = null;
11479 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011480 }
11481 }
11482 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011483 } finally {
11484 Binder.restoreCallingIdentity(origId);
11485 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011486 }
11487
11488 public void updateServiceForegroundLocked(ProcessRecord proc, boolean oomAdj) {
11489 boolean anyForeground = false;
Dianne Hackborn860755f2010-06-03 18:47:52 -070011490 for (ServiceRecord sr : proc.services) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011491 if (sr.isForeground) {
11492 anyForeground = true;
11493 break;
11494 }
11495 }
11496 if (anyForeground != proc.foregroundServices) {
11497 proc.foregroundServices = anyForeground;
11498 if (oomAdj) {
11499 updateOomAdjLocked();
11500 }
11501 }
11502 }
11503
11504 public int bindService(IApplicationThread caller, IBinder token,
11505 Intent service, String resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011506 IServiceConnection connection, int flags, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011507 enforceNotIsolatedCaller("bindService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011508 // Refuse possible leaked file descriptors
11509 if (service != null && service.hasFileDescriptors() == true) {
11510 throw new IllegalArgumentException("File descriptors passed in Intent");
11511 }
11512
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011513 checkValidCaller(Binder.getCallingUid(), userId);
11514
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011515 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011516 if (DEBUG_SERVICE) Slog.v(TAG, "bindService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011517 + " type=" + resolvedType + " conn=" + connection.asBinder()
11518 + " flags=0x" + Integer.toHexString(flags));
Amith Yamasani742a6712011-05-04 14:49:28 -070011519 if (DEBUG_MU)
11520 Slog.i(TAG_MU, "bindService uid=" + Binder.getCallingUid() + " origUid="
11521 + Binder.getOrigCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011522 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11523 if (callerApp == null) {
11524 throw new SecurityException(
11525 "Unable to find app for caller " + caller
11526 + " (pid=" + Binder.getCallingPid()
11527 + ") when binding service " + service);
11528 }
11529
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011530 ActivityRecord activity = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011531 if (token != null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070011532 activity = mMainStack.isInStackLocked(token);
11533 if (activity == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011534 Slog.w(TAG, "Binding with unknown activity: " + token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011535 return 0;
11536 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011537 }
11538
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011539 int clientLabel = 0;
11540 PendingIntent clientIntent = null;
11541
11542 if (callerApp.info.uid == Process.SYSTEM_UID) {
11543 // Hacky kind of thing -- allow system stuff to tell us
11544 // what they are, so we can report this elsewhere for
11545 // others to know why certain services are running.
11546 try {
11547 clientIntent = (PendingIntent)service.getParcelableExtra(
11548 Intent.EXTRA_CLIENT_INTENT);
11549 } catch (RuntimeException e) {
11550 }
11551 if (clientIntent != null) {
11552 clientLabel = service.getIntExtra(Intent.EXTRA_CLIENT_LABEL, 0);
11553 if (clientLabel != 0) {
11554 // There are no useful extras in the intent, trash them.
11555 // System code calling with this stuff just needs to know
11556 // this will happen.
11557 service = service.cloneFilter();
11558 }
11559 }
11560 }
11561
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011562 ServiceLookupResult res =
11563 retrieveServiceLocked(service, resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011564 Binder.getCallingPid(), Binder.getCallingUid(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011565 if (res == null) {
11566 return 0;
11567 }
11568 if (res.record == null) {
11569 return -1;
11570 }
11571 ServiceRecord s = res.record;
11572
11573 final long origId = Binder.clearCallingIdentity();
11574
11575 if (unscheduleServiceRestartLocked(s)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011576 if (DEBUG_SERVICE) Slog.v(TAG, "BIND SERVICE WHILE RESTART PENDING: "
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011577 + s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011578 }
11579
11580 AppBindRecord b = s.retrieveAppBindingLocked(service, callerApp);
11581 ConnectionRecord c = new ConnectionRecord(b, activity,
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011582 connection, flags, clientLabel, clientIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011583
11584 IBinder binder = connection.asBinder();
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011585 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
11586 if (clist == null) {
11587 clist = new ArrayList<ConnectionRecord>();
11588 s.connections.put(binder, clist);
11589 }
11590 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011591 b.connections.add(c);
11592 if (activity != null) {
11593 if (activity.connections == null) {
11594 activity.connections = new HashSet<ConnectionRecord>();
11595 }
11596 activity.connections.add(c);
11597 }
11598 b.client.connections.add(c);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070011599 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
11600 b.client.hasAboveClient = true;
11601 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011602 clist = mServiceConnections.get(binder);
11603 if (clist == null) {
11604 clist = new ArrayList<ConnectionRecord>();
11605 mServiceConnections.put(binder, clist);
11606 }
11607 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011608
11609 if ((flags&Context.BIND_AUTO_CREATE) != 0) {
11610 s.lastActivity = SystemClock.uptimeMillis();
11611 if (!bringUpServiceLocked(s, service.getFlags(), false)) {
11612 return 0;
11613 }
11614 }
11615
11616 if (s.app != null) {
11617 // This could have made the service more important.
11618 updateOomAdjLocked(s.app);
11619 }
11620
Joe Onorato8a9b2202010-02-26 18:56:32 -080011621 if (DEBUG_SERVICE) Slog.v(TAG, "Bind " + s + " with " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011622 + ": received=" + b.intent.received
11623 + " apps=" + b.intent.apps.size()
11624 + " doRebind=" + b.intent.doRebind);
11625
11626 if (s.app != null && b.intent.received) {
11627 // Service is already running, so we can immediately
11628 // publish the connection.
11629 try {
11630 c.conn.connected(s.name, b.intent.binder);
11631 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011632 Slog.w(TAG, "Failure sending service " + s.shortName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011633 + " to connection " + c.conn.asBinder()
11634 + " (in " + c.binding.client.processName + ")", e);
11635 }
11636
11637 // If this is the first app connected back to this binding,
11638 // and the service had previously asked to be told when
11639 // rebound, then do so.
11640 if (b.intent.apps.size() == 1 && b.intent.doRebind) {
11641 requestServiceBindingLocked(s, b.intent, true);
11642 }
11643 } else if (!b.intent.requested) {
11644 requestServiceBindingLocked(s, b.intent, false);
11645 }
11646
11647 Binder.restoreCallingIdentity(origId);
11648 }
11649
11650 return 1;
11651 }
11652
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070011653 void removeConnectionLocked(
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011654 ConnectionRecord c, ProcessRecord skipApp, ActivityRecord skipAct) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011655 IBinder binder = c.conn.asBinder();
11656 AppBindRecord b = c.binding;
11657 ServiceRecord s = b.service;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011658 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
11659 if (clist != null) {
11660 clist.remove(c);
11661 if (clist.size() == 0) {
11662 s.connections.remove(binder);
11663 }
11664 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011665 b.connections.remove(c);
11666 if (c.activity != null && c.activity != skipAct) {
11667 if (c.activity.connections != null) {
11668 c.activity.connections.remove(c);
11669 }
11670 }
11671 if (b.client != skipApp) {
11672 b.client.connections.remove(c);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070011673 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
11674 b.client.updateHasAboveClientLocked();
11675 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011676 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011677 clist = mServiceConnections.get(binder);
11678 if (clist != null) {
11679 clist.remove(c);
11680 if (clist.size() == 0) {
11681 mServiceConnections.remove(binder);
11682 }
11683 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011684
11685 if (b.connections.size() == 0) {
11686 b.intent.apps.remove(b.client);
11687 }
11688
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011689 if (!c.serviceDead) {
11690 if (DEBUG_SERVICE) Slog.v(TAG, "Disconnecting binding " + b.intent
11691 + ": shouldUnbind=" + b.intent.hasBound);
11692 if (s.app != null && s.app.thread != null && b.intent.apps.size() == 0
11693 && b.intent.hasBound) {
11694 try {
11695 bumpServiceExecutingLocked(s, "unbind");
11696 updateOomAdjLocked(s.app);
11697 b.intent.hasBound = false;
11698 // Assume the client doesn't want to know about a rebind;
11699 // we will deal with that later if it asks for one.
11700 b.intent.doRebind = false;
11701 s.app.thread.scheduleUnbindService(s, b.intent.intent.getIntent());
11702 } catch (Exception e) {
11703 Slog.w(TAG, "Exception when unbinding service " + s.shortName, e);
11704 serviceDoneExecutingLocked(s, true);
11705 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011706 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011707
11708 if ((c.flags&Context.BIND_AUTO_CREATE) != 0) {
11709 bringDownServiceLocked(s, false);
11710 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011711 }
11712 }
11713
11714 public boolean unbindService(IServiceConnection connection) {
11715 synchronized (this) {
11716 IBinder binder = connection.asBinder();
Joe Onorato8a9b2202010-02-26 18:56:32 -080011717 if (DEBUG_SERVICE) Slog.v(TAG, "unbindService: conn=" + binder);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011718 ArrayList<ConnectionRecord> clist = mServiceConnections.get(binder);
11719 if (clist == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011720 Slog.w(TAG, "Unbind failed: could not find connection for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011721 + connection.asBinder());
11722 return false;
11723 }
11724
11725 final long origId = Binder.clearCallingIdentity();
11726
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011727 while (clist.size() > 0) {
11728 ConnectionRecord r = clist.get(0);
11729 removeConnectionLocked(r, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011730
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011731 if (r.binding.service.app != null) {
11732 // This could have made the service less important.
11733 updateOomAdjLocked(r.binding.service.app);
11734 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011735 }
11736
11737 Binder.restoreCallingIdentity(origId);
11738 }
11739
11740 return true;
11741 }
11742
11743 public void publishService(IBinder token, Intent intent, IBinder service) {
11744 // Refuse possible leaked file descriptors
11745 if (intent != null && intent.hasFileDescriptors() == true) {
11746 throw new IllegalArgumentException("File descriptors passed in Intent");
11747 }
11748
11749 synchronized(this) {
11750 if (!(token instanceof ServiceRecord)) {
11751 throw new IllegalArgumentException("Invalid service token");
11752 }
11753 ServiceRecord r = (ServiceRecord)token;
11754
11755 final long origId = Binder.clearCallingIdentity();
11756
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011757 if (DEBUG_SERVICE) Slog.v(TAG, "PUBLISHING " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011758 + " " + intent + ": " + service);
11759 if (r != null) {
11760 Intent.FilterComparison filter
11761 = new Intent.FilterComparison(intent);
11762 IntentBindRecord b = r.bindings.get(filter);
11763 if (b != null && !b.received) {
11764 b.binder = service;
11765 b.requested = true;
11766 b.received = true;
11767 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011768 Iterator<ArrayList<ConnectionRecord>> it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011769 = r.connections.values().iterator();
11770 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011771 ArrayList<ConnectionRecord> clist = it.next();
11772 for (int i=0; i<clist.size(); i++) {
11773 ConnectionRecord c = clist.get(i);
11774 if (!filter.equals(c.binding.intent.intent)) {
11775 if (DEBUG_SERVICE) Slog.v(
11776 TAG, "Not publishing to: " + c);
11777 if (DEBUG_SERVICE) Slog.v(
11778 TAG, "Bound intent: " + c.binding.intent.intent);
11779 if (DEBUG_SERVICE) Slog.v(
11780 TAG, "Published intent: " + intent);
11781 continue;
11782 }
11783 if (DEBUG_SERVICE) Slog.v(TAG, "Publishing to: " + c);
11784 try {
11785 c.conn.connected(r.name, service);
11786 } catch (Exception e) {
11787 Slog.w(TAG, "Failure sending service " + r.name +
11788 " to connection " + c.conn.asBinder() +
11789 " (in " + c.binding.client.processName + ")", e);
11790 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011791 }
11792 }
11793 }
11794 }
11795
11796 serviceDoneExecutingLocked(r, mStoppingServices.contains(r));
11797
11798 Binder.restoreCallingIdentity(origId);
11799 }
11800 }
11801 }
11802
11803 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
11804 // Refuse possible leaked file descriptors
11805 if (intent != null && intent.hasFileDescriptors() == true) {
11806 throw new IllegalArgumentException("File descriptors passed in Intent");
11807 }
11808
11809 synchronized(this) {
11810 if (!(token instanceof ServiceRecord)) {
11811 throw new IllegalArgumentException("Invalid service token");
11812 }
11813 ServiceRecord r = (ServiceRecord)token;
11814
11815 final long origId = Binder.clearCallingIdentity();
11816
11817 if (r != null) {
11818 Intent.FilterComparison filter
11819 = new Intent.FilterComparison(intent);
11820 IntentBindRecord b = r.bindings.get(filter);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011821 if (DEBUG_SERVICE) Slog.v(TAG, "unbindFinished in " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011822 + " at " + b + ": apps="
11823 + (b != null ? b.apps.size() : 0));
Per Edelberg78f9fff2010-08-30 20:01:35 +020011824
11825 boolean inStopping = mStoppingServices.contains(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011826 if (b != null) {
Per Edelberg78f9fff2010-08-30 20:01:35 +020011827 if (b.apps.size() > 0 && !inStopping) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011828 // Applications have already bound since the last
11829 // unbind, so just rebind right here.
11830 requestServiceBindingLocked(r, b, true);
11831 } else {
11832 // Note to tell the service the next time there is
11833 // a new client.
11834 b.doRebind = true;
11835 }
11836 }
11837
Per Edelberg78f9fff2010-08-30 20:01:35 +020011838 serviceDoneExecutingLocked(r, inStopping);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011839
11840 Binder.restoreCallingIdentity(origId);
11841 }
11842 }
11843 }
11844
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011845 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011846 synchronized(this) {
11847 if (!(token instanceof ServiceRecord)) {
11848 throw new IllegalArgumentException("Invalid service token");
11849 }
11850 ServiceRecord r = (ServiceRecord)token;
11851 boolean inStopping = mStoppingServices.contains(token);
11852 if (r != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011853 if (r != token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011854 Slog.w(TAG, "Done executing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011855 + " with incorrect token: given " + token
11856 + ", expected " + r);
11857 return;
11858 }
11859
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011860 if (type == 1) {
11861 // This is a call from a service start... take care of
11862 // book-keeping.
11863 r.callStart = true;
11864 switch (res) {
11865 case Service.START_STICKY_COMPATIBILITY:
11866 case Service.START_STICKY: {
11867 // We are done with the associated start arguments.
11868 r.findDeliveredStart(startId, true);
11869 // Don't stop if killed.
11870 r.stopIfKilled = false;
11871 break;
11872 }
11873 case Service.START_NOT_STICKY: {
11874 // We are done with the associated start arguments.
11875 r.findDeliveredStart(startId, true);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011876 if (r.getLastStartId() == startId) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011877 // There is no more work, and this service
11878 // doesn't want to hang around if killed.
11879 r.stopIfKilled = true;
11880 }
11881 break;
11882 }
11883 case Service.START_REDELIVER_INTENT: {
11884 // We'll keep this item until they explicitly
11885 // call stop for it, but keep track of the fact
11886 // that it was delivered.
11887 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
11888 if (si != null) {
11889 si.deliveryCount = 0;
11890 si.doneExecutingCount++;
11891 // Don't stop if killed.
11892 r.stopIfKilled = true;
11893 }
11894 break;
11895 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011896 case Service.START_TASK_REMOVED_COMPLETE: {
11897 // Special processing for onTaskRemoved(). Don't
11898 // impact normal onStartCommand() processing.
11899 r.findDeliveredStart(startId, true);
11900 break;
11901 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011902 default:
11903 throw new IllegalArgumentException(
11904 "Unknown service start result: " + res);
11905 }
11906 if (res == Service.START_STICKY_COMPATIBILITY) {
11907 r.callStart = false;
11908 }
11909 }
Amith Yamasani742a6712011-05-04 14:49:28 -070011910 if (DEBUG_MU)
11911 Slog.v(TAG_MU, "before serviceDontExecutingLocked, uid="
11912 + Binder.getOrigCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011913 final long origId = Binder.clearCallingIdentity();
11914 serviceDoneExecutingLocked(r, inStopping);
11915 Binder.restoreCallingIdentity(origId);
11916 } else {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011917 Slog.w(TAG, "Done executing unknown service from pid "
11918 + Binder.getCallingPid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011919 }
11920 }
11921 }
11922
11923 public void serviceDoneExecutingLocked(ServiceRecord r, boolean inStopping) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011924 if (DEBUG_SERVICE) Slog.v(TAG, "<<< DONE EXECUTING " + r
11925 + ": nesting=" + r.executeNesting
11926 + ", inStopping=" + inStopping + ", app=" + r.app);
Dianne Hackborn287952c2010-09-22 22:34:31 -070011927 else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG, "<<< DONE EXECUTING " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011928 r.executeNesting--;
11929 if (r.executeNesting <= 0 && r.app != null) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011930 if (DEBUG_SERVICE) Slog.v(TAG,
11931 "Nesting at 0 of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011932 r.app.executingServices.remove(r);
11933 if (r.app.executingServices.size() == 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011934 if (DEBUG_SERVICE || DEBUG_SERVICE_EXECUTING) Slog.v(TAG,
11935 "No more executingServices of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011936 mHandler.removeMessages(SERVICE_TIMEOUT_MSG, r.app);
11937 }
11938 if (inStopping) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011939 if (DEBUG_SERVICE) Slog.v(TAG,
11940 "doneExecuting remove stopping " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011941 mStoppingServices.remove(r);
Mattias Petersson3996b412010-10-27 09:32:51 +020011942 r.bindings.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011943 }
11944 updateOomAdjLocked(r.app);
11945 }
11946 }
11947
11948 void serviceTimeout(ProcessRecord proc) {
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011949 String anrMessage = null;
11950
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011951 synchronized(this) {
11952 if (proc.executingServices.size() == 0 || proc.thread == null) {
11953 return;
11954 }
11955 long maxTime = SystemClock.uptimeMillis() - SERVICE_TIMEOUT;
11956 Iterator<ServiceRecord> it = proc.executingServices.iterator();
11957 ServiceRecord timeout = null;
11958 long nextTime = 0;
11959 while (it.hasNext()) {
11960 ServiceRecord sr = it.next();
11961 if (sr.executingStart < maxTime) {
11962 timeout = sr;
11963 break;
11964 }
11965 if (sr.executingStart > nextTime) {
11966 nextTime = sr.executingStart;
11967 }
11968 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011969 if (timeout != null && mLruProcesses.contains(proc)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011970 Slog.w(TAG, "Timeout executing service: " + timeout);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011971 anrMessage = "Executing service " + timeout.shortName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011972 } else {
11973 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
11974 msg.obj = proc;
11975 mHandler.sendMessageAtTime(msg, nextTime+SERVICE_TIMEOUT);
11976 }
11977 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011978
11979 if (anrMessage != null) {
11980 appNotResponding(proc, null, null, anrMessage);
11981 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011982 }
11983
11984 // =========================================================
Christopher Tate181fafa2009-05-14 11:12:14 -070011985 // BACKUP AND RESTORE
11986 // =========================================================
11987
11988 // Cause the target app to be launched if necessary and its backup agent
11989 // instantiated. The backup agent will invoke backupAgentCreated() on the
11990 // activity manager to announce its creation.
11991 public boolean bindBackupAgent(ApplicationInfo app, int backupMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011992 if (DEBUG_BACKUP) Slog.v(TAG, "startBackupAgent: app=" + app + " mode=" + backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070011993 enforceCallingPermission("android.permission.BACKUP", "startBackupAgent");
11994
11995 synchronized(this) {
11996 // !!! TODO: currently no check here that we're already bound
11997 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
11998 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
11999 synchronized (stats) {
12000 ss = stats.getServiceStatsLocked(app.uid, app.packageName, app.name);
12001 }
12002
Dianne Hackborne7f97212011-02-24 14:40:20 -080012003 // Backup agent is now in use, its package can't be stopped.
12004 try {
12005 AppGlobals.getPackageManager().setPackageStoppedState(
12006 app.packageName, false);
12007 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080012008 } catch (IllegalArgumentException e) {
12009 Slog.w(TAG, "Failed trying to unstop package "
12010 + app.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080012011 }
12012
Christopher Tate181fafa2009-05-14 11:12:14 -070012013 BackupRecord r = new BackupRecord(ss, app, backupMode);
Christopher Tate4a627c72011-04-01 14:43:32 -070012014 ComponentName hostingName = (backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL)
12015 ? new ComponentName(app.packageName, app.backupAgentName)
12016 : new ComponentName("android", "FullBackupAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -070012017 // startProcessLocked() returns existing proc's record if it's already running
12018 ProcessRecord proc = startProcessLocked(app.processName, app,
Dianne Hackborna0c283e2012-02-09 10:47:01 -080012019 false, 0, "backup", hostingName, false, false);
Christopher Tate181fafa2009-05-14 11:12:14 -070012020 if (proc == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012021 Slog.e(TAG, "Unable to start backup agent process " + r);
Christopher Tate181fafa2009-05-14 11:12:14 -070012022 return false;
12023 }
12024
12025 r.app = proc;
12026 mBackupTarget = r;
12027 mBackupAppName = app.packageName;
12028
Christopher Tate6fa95972009-06-05 18:43:55 -070012029 // Try not to kill the process during backup
12030 updateOomAdjLocked(proc);
12031
Christopher Tate181fafa2009-05-14 11:12:14 -070012032 // If the process is already attached, schedule the creation of the backup agent now.
12033 // If it is not yet live, this will be done when it attaches to the framework.
12034 if (proc.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012035 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc already running: " + proc);
Christopher Tate181fafa2009-05-14 11:12:14 -070012036 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040012037 proc.thread.scheduleCreateBackupAgent(app,
12038 compatibilityInfoForPackageLocked(app), backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070012039 } catch (RemoteException e) {
Christopher Tate436344a2009-09-30 16:17:37 -070012040 // Will time out on the backup manager side
Christopher Tate181fafa2009-05-14 11:12:14 -070012041 }
12042 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012043 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc not running, waiting for attach");
Christopher Tate181fafa2009-05-14 11:12:14 -070012044 }
12045 // Invariants: at this point, the target app process exists and the application
12046 // is either already running or in the process of coming up. mBackupTarget and
12047 // mBackupAppName describe the app, so that when it binds back to the AM we
12048 // know that it's scheduled for a backup-agent operation.
12049 }
12050
12051 return true;
12052 }
12053
12054 // A backup agent has just come up
12055 public void backupAgentCreated(String agentPackageName, IBinder agent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012056 if (DEBUG_BACKUP) Slog.v(TAG, "backupAgentCreated: " + agentPackageName
Christopher Tate181fafa2009-05-14 11:12:14 -070012057 + " = " + agent);
12058
12059 synchronized(this) {
12060 if (!agentPackageName.equals(mBackupAppName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012061 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
Christopher Tate181fafa2009-05-14 11:12:14 -070012062 return;
12063 }
Dianne Hackborn06740692010-09-22 22:46:21 -070012064 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012065
Dianne Hackborn06740692010-09-22 22:46:21 -070012066 long oldIdent = Binder.clearCallingIdentity();
12067 try {
12068 IBackupManager bm = IBackupManager.Stub.asInterface(
12069 ServiceManager.getService(Context.BACKUP_SERVICE));
12070 bm.agentConnected(agentPackageName, agent);
12071 } catch (RemoteException e) {
12072 // can't happen; the backup manager service is local
12073 } catch (Exception e) {
12074 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: ");
12075 e.printStackTrace();
12076 } finally {
12077 Binder.restoreCallingIdentity(oldIdent);
Christopher Tate181fafa2009-05-14 11:12:14 -070012078 }
12079 }
12080
12081 // done with this agent
12082 public void unbindBackupAgent(ApplicationInfo appInfo) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012083 if (DEBUG_BACKUP) Slog.v(TAG, "unbindBackupAgent: " + appInfo);
Christopher Tate8a27f922009-06-26 11:49:18 -070012084 if (appInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012085 Slog.w(TAG, "unbind backup agent for null app");
Christopher Tate8a27f922009-06-26 11:49:18 -070012086 return;
12087 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012088
12089 synchronized(this) {
Christopher Tate8a27f922009-06-26 11:49:18 -070012090 if (mBackupAppName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012091 Slog.w(TAG, "Unbinding backup agent with no active backup");
Christopher Tate8a27f922009-06-26 11:49:18 -070012092 return;
12093 }
12094
Christopher Tate181fafa2009-05-14 11:12:14 -070012095 if (!mBackupAppName.equals(appInfo.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012096 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
Christopher Tate181fafa2009-05-14 11:12:14 -070012097 return;
12098 }
12099
Christopher Tate6fa95972009-06-05 18:43:55 -070012100 ProcessRecord proc = mBackupTarget.app;
12101 mBackupTarget = null;
12102 mBackupAppName = null;
12103
12104 // Not backing this app up any more; reset its OOM adjustment
12105 updateOomAdjLocked(proc);
12106
Christopher Tatec7b31e32009-06-10 15:49:30 -070012107 // If the app crashed during backup, 'thread' will be null here
12108 if (proc.thread != null) {
12109 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040012110 proc.thread.scheduleDestroyBackupAgent(appInfo,
12111 compatibilityInfoForPackageLocked(appInfo));
Christopher Tatec7b31e32009-06-10 15:49:30 -070012112 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012113 Slog.e(TAG, "Exception when unbinding backup agent:");
Christopher Tatec7b31e32009-06-10 15:49:30 -070012114 e.printStackTrace();
12115 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012116 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012117 }
12118 }
12119 // =========================================================
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012120 // BROADCASTS
12121 // =========================================================
12122
Josh Bartel7f208742010-02-25 11:01:44 -060012123 private final List getStickiesLocked(String action, IntentFilter filter,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012124 List cur) {
12125 final ContentResolver resolver = mContext.getContentResolver();
12126 final ArrayList<Intent> list = mStickyBroadcasts.get(action);
12127 if (list == null) {
12128 return cur;
12129 }
12130 int N = list.size();
12131 for (int i=0; i<N; i++) {
12132 Intent intent = list.get(i);
12133 if (filter.match(resolver, intent, true, TAG) >= 0) {
12134 if (cur == null) {
12135 cur = new ArrayList<Intent>();
12136 }
12137 cur.add(intent);
12138 }
12139 }
12140 return cur;
12141 }
12142
Christopher Tatef46723b2012-01-26 14:19:24 -080012143 boolean isPendingBroadcastProcessLocked(int pid) {
12144 return mFgBroadcastQueue.isPendingBroadcastProcessLocked(pid)
12145 || mBgBroadcastQueue.isPendingBroadcastProcessLocked(pid);
12146 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012147
Christopher Tatef46723b2012-01-26 14:19:24 -080012148 void skipPendingBroadcastLocked(int pid) {
12149 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
12150 for (BroadcastQueue queue : mBroadcastQueues) {
12151 queue.skipPendingBroadcastLocked(pid);
12152 }
12153 }
12154
12155 // The app just attached; send any pending broadcasts that it should receive
12156 boolean sendPendingBroadcastsLocked(ProcessRecord app) {
12157 boolean didSomething = false;
12158 for (BroadcastQueue queue : mBroadcastQueues) {
12159 didSomething |= queue.sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012160 }
Christopher Tatef46723b2012-01-26 14:19:24 -080012161 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012162 }
12163
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012164 public Intent registerReceiver(IApplicationThread caller, String callerPackage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012165 IIntentReceiver receiver, IntentFilter filter, String permission) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012166 enforceNotIsolatedCaller("registerReceiver");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012167 synchronized(this) {
12168 ProcessRecord callerApp = null;
12169 if (caller != null) {
12170 callerApp = getRecordForAppLocked(caller);
12171 if (callerApp == null) {
12172 throw new SecurityException(
12173 "Unable to find app for caller " + caller
12174 + " (pid=" + Binder.getCallingPid()
12175 + ") when registering receiver " + receiver);
12176 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012177 if (callerApp.info.uid != Process.SYSTEM_UID &&
12178 !callerApp.pkgList.contains(callerPackage)) {
12179 throw new SecurityException("Given caller package " + callerPackage
12180 + " is not running in process " + callerApp);
12181 }
12182 } else {
12183 callerPackage = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012184 }
12185
12186 List allSticky = null;
12187
12188 // Look for any matching sticky broadcasts...
12189 Iterator actions = filter.actionsIterator();
12190 if (actions != null) {
12191 while (actions.hasNext()) {
12192 String action = (String)actions.next();
Josh Bartel7f208742010-02-25 11:01:44 -060012193 allSticky = getStickiesLocked(action, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012194 }
12195 } else {
Josh Bartel7f208742010-02-25 11:01:44 -060012196 allSticky = getStickiesLocked(null, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012197 }
12198
12199 // The first sticky in the list is returned directly back to
12200 // the client.
12201 Intent sticky = allSticky != null ? (Intent)allSticky.get(0) : null;
12202
Joe Onorato8a9b2202010-02-26 18:56:32 -080012203 if (DEBUG_BROADCAST) Slog.v(TAG, "Register receiver " + filter
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012204 + ": " + sticky);
12205
12206 if (receiver == null) {
12207 return sticky;
12208 }
12209
12210 ReceiverList rl
12211 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
12212 if (rl == null) {
12213 rl = new ReceiverList(this, callerApp,
12214 Binder.getCallingPid(),
12215 Binder.getCallingUid(), receiver);
12216 if (rl.app != null) {
12217 rl.app.receivers.add(rl);
12218 } else {
12219 try {
12220 receiver.asBinder().linkToDeath(rl, 0);
12221 } catch (RemoteException e) {
12222 return sticky;
12223 }
12224 rl.linkedToDeath = true;
12225 }
12226 mRegisteredReceivers.put(receiver.asBinder(), rl);
12227 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012228 BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage, permission);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012229 rl.add(bf);
12230 if (!bf.debugCheck()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012231 Slog.w(TAG, "==> For Dynamic broadast");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012232 }
12233 mReceiverResolver.addFilter(bf);
12234
12235 // Enqueue broadcasts for all existing stickies that match
12236 // this filter.
12237 if (allSticky != null) {
12238 ArrayList receivers = new ArrayList();
12239 receivers.add(bf);
12240
12241 int N = allSticky.size();
12242 for (int i=0; i<N; i++) {
12243 Intent intent = (Intent)allSticky.get(i);
Christopher Tatef46723b2012-01-26 14:19:24 -080012244 BroadcastQueue queue = broadcastQueueForIntent(intent);
12245 BroadcastRecord r = new BroadcastRecord(queue, intent, null,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012246 null, -1, -1, null, receivers, null, 0, null, null,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012247 false, true, true);
Christopher Tatef46723b2012-01-26 14:19:24 -080012248 queue.enqueueParallelBroadcastLocked(r);
12249 queue.scheduleBroadcastsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012250 }
12251 }
12252
12253 return sticky;
12254 }
12255 }
12256
12257 public void unregisterReceiver(IIntentReceiver receiver) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012258 if (DEBUG_BROADCAST) Slog.v(TAG, "Unregister receiver: " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012259
Christopher Tatef46723b2012-01-26 14:19:24 -080012260 final long origId = Binder.clearCallingIdentity();
12261 try {
12262 boolean doTrim = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012263
Christopher Tatef46723b2012-01-26 14:19:24 -080012264 synchronized(this) {
12265 ReceiverList rl
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012266 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
Christopher Tatef46723b2012-01-26 14:19:24 -080012267 if (rl != null) {
12268 if (rl.curBroadcast != null) {
12269 BroadcastRecord r = rl.curBroadcast;
12270 final boolean doNext = finishReceiverLocked(
12271 receiver.asBinder(), r.resultCode, r.resultData,
12272 r.resultExtras, r.resultAbort, true);
12273 if (doNext) {
12274 doTrim = true;
12275 r.queue.processNextBroadcast(false);
12276 }
12277 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012278
Christopher Tatef46723b2012-01-26 14:19:24 -080012279 if (rl.app != null) {
12280 rl.app.receivers.remove(rl);
12281 }
12282 removeReceiverLocked(rl);
12283 if (rl.linkedToDeath) {
12284 rl.linkedToDeath = false;
12285 rl.receiver.asBinder().unlinkToDeath(rl, 0);
12286 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012287 }
12288 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012289
Christopher Tatef46723b2012-01-26 14:19:24 -080012290 // If we actually concluded any broadcasts, we might now be able
12291 // to trim the recipients' apps from our working set
12292 if (doTrim) {
12293 trimApplications();
12294 return;
12295 }
12296
12297 } finally {
12298 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012299 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012300 }
12301
12302 void removeReceiverLocked(ReceiverList rl) {
12303 mRegisteredReceivers.remove(rl.receiver.asBinder());
12304 int N = rl.size();
12305 for (int i=0; i<N; i++) {
12306 mReceiverResolver.removeFilter(rl.get(i));
12307 }
12308 }
12309
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012310 private final void sendPackageBroadcastLocked(int cmd, String[] packages) {
12311 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
12312 ProcessRecord r = mLruProcesses.get(i);
12313 if (r.thread != null) {
12314 try {
12315 r.thread.dispatchPackageBroadcast(cmd, packages);
12316 } catch (RemoteException ex) {
12317 }
12318 }
12319 }
12320 }
12321
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012322 private final int broadcastIntentLocked(ProcessRecord callerApp,
12323 String callerPackage, Intent intent, String resolvedType,
12324 IIntentReceiver resultTo, int resultCode, String resultData,
12325 Bundle map, String requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070012326 boolean ordered, boolean sticky, int callingPid, int callingUid,
12327 int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012328 intent = new Intent(intent);
12329
Dianne Hackborne7f97212011-02-24 14:40:20 -080012330 // By default broadcasts do not go to stopped apps.
12331 intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
12332
Joe Onorato8a9b2202010-02-26 18:56:32 -080012333 if (DEBUG_BROADCAST_LIGHT) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012334 TAG, (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
12335 + " ordered=" + ordered);
12336 if ((resultTo != null) && !ordered) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012337 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012338 }
12339
12340 // Handle special intents: if this broadcast is from the package
12341 // manager about a package being removed, we need to remove all of
12342 // its activities from the history stack.
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012343 final boolean uidRemoved = Intent.ACTION_UID_REMOVED.equals(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012344 intent.getAction());
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012345 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())
12346 || Intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction())
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080012347 || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012348 || uidRemoved) {
12349 if (checkComponentPermission(
12350 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080012351 callingPid, callingUid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012352 == PackageManager.PERMISSION_GRANTED) {
12353 if (uidRemoved) {
12354 final Bundle intentExtras = intent.getExtras();
12355 final int uid = intentExtras != null
12356 ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
12357 if (uid >= 0) {
12358 BatteryStatsImpl bs = mBatteryStatsService.getActiveStatistics();
12359 synchronized (bs) {
12360 bs.removeUidStatsLocked(uid);
12361 }
12362 }
12363 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012364 // If resources are unvailble just force stop all
12365 // those packages and flush the attribute cache as well.
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080012366 if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012367 String list[] = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
12368 if (list != null && (list.length > 0)) {
12369 for (String pkg : list) {
Christopher Tate3dacd842011-08-19 14:56:15 -070012370 forceStopPackageLocked(pkg, -1, false, true, true, false);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012371 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012372 sendPackageBroadcastLocked(
12373 IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE, list);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012374 }
12375 } else {
12376 Uri data = intent.getData();
12377 String ssp;
12378 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
12379 if (!intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false)) {
12380 forceStopPackageLocked(ssp,
Christopher Tate3dacd842011-08-19 14:56:15 -070012381 intent.getIntExtra(Intent.EXTRA_UID, -1), false, true, true, false);
Dianne Hackbornde7faf62009-06-30 13:27:30 -070012382 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012383 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012384 sendPackageBroadcastLocked(IApplicationThread.PACKAGE_REMOVED,
12385 new String[] {ssp});
12386 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012387 }
12388 }
12389 }
12390 } else {
12391 String msg = "Permission Denial: " + intent.getAction()
12392 + " broadcast from " + callerPackage + " (pid=" + callingPid
12393 + ", uid=" + callingUid + ")"
12394 + " requires "
12395 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012396 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012397 throw new SecurityException(msg);
12398 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012399
12400 // Special case for adding a package: by default turn on compatibility
12401 // mode.
12402 } else if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -070012403 Uri data = intent.getData();
12404 String ssp;
12405 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
12406 mCompatModePackages.handlePackageAddedLocked(ssp,
12407 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false));
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012408 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012409 }
12410
12411 /*
12412 * If this is the time zone changed action, queue up a message that will reset the timezone
12413 * of all currently running processes. This message will get queued up before the broadcast
12414 * happens.
12415 */
12416 if (intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) {
12417 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
12418 }
12419
Robert Greenwalt03595d02010-11-02 14:08:23 -070012420 if (intent.ACTION_CLEAR_DNS_CACHE.equals(intent.getAction())) {
12421 mHandler.sendEmptyMessage(CLEAR_DNS_CACHE);
12422 }
12423
Robert Greenwalt434203a2010-10-11 16:00:27 -070012424 if (Proxy.PROXY_CHANGE_ACTION.equals(intent.getAction())) {
12425 ProxyProperties proxy = intent.getParcelableExtra("proxy");
12426 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY, proxy));
12427 }
12428
Dianne Hackborn854060af2009-07-09 18:14:31 -070012429 /*
12430 * Prevent non-system code (defined here to be non-persistent
12431 * processes) from sending protected broadcasts.
12432 */
12433 if (callingUid == Process.SYSTEM_UID || callingUid == Process.PHONE_UID
12434 || callingUid == Process.SHELL_UID || callingUid == 0) {
12435 // Always okay.
12436 } else if (callerApp == null || !callerApp.persistent) {
12437 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012438 if (AppGlobals.getPackageManager().isProtectedBroadcast(
Dianne Hackborn854060af2009-07-09 18:14:31 -070012439 intent.getAction())) {
12440 String msg = "Permission Denial: not allowed to send broadcast "
12441 + intent.getAction() + " from pid="
12442 + callingPid + ", uid=" + callingUid;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012443 Slog.w(TAG, msg);
Dianne Hackborn854060af2009-07-09 18:14:31 -070012444 throw new SecurityException(msg);
12445 }
12446 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012447 Slog.w(TAG, "Remote exception", e);
Dianne Hackborna4972e92012-03-14 10:38:05 -070012448 return ActivityManager.BROADCAST_SUCCESS;
Dianne Hackborn854060af2009-07-09 18:14:31 -070012449 }
12450 }
12451
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012452 // Add to the sticky list if requested.
12453 if (sticky) {
12454 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
12455 callingPid, callingUid)
12456 != PackageManager.PERMISSION_GRANTED) {
12457 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
12458 + callingPid + ", uid=" + callingUid
12459 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012460 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012461 throw new SecurityException(msg);
12462 }
12463 if (requiredPermission != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012464 Slog.w(TAG, "Can't broadcast sticky intent " + intent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012465 + " and enforce permission " + requiredPermission);
Dianne Hackborna4972e92012-03-14 10:38:05 -070012466 return ActivityManager.BROADCAST_STICKY_CANT_HAVE_PERMISSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012467 }
12468 if (intent.getComponent() != null) {
12469 throw new SecurityException(
12470 "Sticky broadcasts can't target a specific component");
12471 }
12472 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
12473 if (list == null) {
12474 list = new ArrayList<Intent>();
12475 mStickyBroadcasts.put(intent.getAction(), list);
12476 }
12477 int N = list.size();
12478 int i;
12479 for (i=0; i<N; i++) {
12480 if (intent.filterEquals(list.get(i))) {
12481 // This sticky already exists, replace it.
12482 list.set(i, new Intent(intent));
12483 break;
12484 }
12485 }
12486 if (i >= N) {
12487 list.add(new Intent(intent));
12488 }
12489 }
12490
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012491 // Figure out who all will receive this broadcast.
12492 List receivers = null;
12493 List<BroadcastFilter> registeredReceivers = null;
12494 try {
12495 if (intent.getComponent() != null) {
12496 // Broadcast is going to one specific receiver class...
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012497 ActivityInfo ai = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -070012498 getReceiverInfo(intent.getComponent(), STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012499 if (ai != null) {
12500 receivers = new ArrayList();
12501 ResolveInfo ri = new ResolveInfo();
Amith Yamasani742a6712011-05-04 14:49:28 -070012502 ri.activityInfo = getActivityInfoForUser(ai, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012503 receivers.add(ri);
12504 }
12505 } else {
Amith Yamasani742a6712011-05-04 14:49:28 -070012506 // TODO: Apply userId
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012507 // Need to resolve the intent to interested receivers...
12508 if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
12509 == 0) {
12510 receivers =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012511 AppGlobals.getPackageManager().queryIntentReceivers(
Dianne Hackborn1655be42009-05-08 14:29:01 -070012512 intent, resolvedType, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012513 }
Mihai Preda074edef2009-05-18 17:13:31 +020012514 registeredReceivers = mReceiverResolver.queryIntent(intent, resolvedType, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012515 }
12516 } catch (RemoteException ex) {
12517 // pm is in same process, this will never happen.
12518 }
12519
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012520 final boolean replacePending =
12521 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
12522
Joe Onorato8a9b2202010-02-26 18:56:32 -080012523 if (DEBUG_BROADCAST) Slog.v(TAG, "Enqueing broadcast: " + intent.getAction()
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012524 + " replacePending=" + replacePending);
12525
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012526 int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
12527 if (!ordered && NR > 0) {
12528 // If we are not serializing this broadcast, then send the
12529 // registered receivers separately so they don't wait for the
12530 // components to be launched.
Christopher Tatef46723b2012-01-26 14:19:24 -080012531 final BroadcastQueue queue = broadcastQueueForIntent(intent);
12532 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012533 callerPackage, callingPid, callingUid, requiredPermission,
12534 registeredReceivers, resultTo, resultCode, resultData, map,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012535 ordered, sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012536 if (DEBUG_BROADCAST) Slog.v(
Christopher Tatef46723b2012-01-26 14:19:24 -080012537 TAG, "Enqueueing parallel broadcast " + r);
12538 final boolean replaced = replacePending && queue.replaceParallelBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012539 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012540 queue.enqueueParallelBroadcastLocked(r);
12541 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012542 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012543 registeredReceivers = null;
12544 NR = 0;
12545 }
12546
12547 // Merge into one list.
12548 int ir = 0;
12549 if (receivers != null) {
12550 // A special case for PACKAGE_ADDED: do not allow the package
12551 // being added to see this broadcast. This prevents them from
12552 // using this as a back door to get run as soon as they are
12553 // installed. Maybe in the future we want to have a special install
12554 // broadcast or such for apps, but we'd like to deliberately make
12555 // this decision.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012556 String skipPackages[] = null;
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012557 if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
12558 || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
12559 || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012560 Uri data = intent.getData();
12561 if (data != null) {
12562 String pkgName = data.getSchemeSpecificPart();
12563 if (pkgName != null) {
12564 skipPackages = new String[] { pkgName };
12565 }
12566 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012567 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012568 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
The Android Open Source Project10592532009-03-18 17:39:46 -070012569 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012570 if (skipPackages != null && (skipPackages.length > 0)) {
12571 for (String skipPackage : skipPackages) {
12572 if (skipPackage != null) {
12573 int NT = receivers.size();
12574 for (int it=0; it<NT; it++) {
12575 ResolveInfo curt = (ResolveInfo)receivers.get(it);
12576 if (curt.activityInfo.packageName.equals(skipPackage)) {
12577 receivers.remove(it);
12578 it--;
12579 NT--;
12580 }
12581 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012582 }
12583 }
12584 }
12585
12586 int NT = receivers != null ? receivers.size() : 0;
12587 int it = 0;
12588 ResolveInfo curt = null;
12589 BroadcastFilter curr = null;
12590 while (it < NT && ir < NR) {
12591 if (curt == null) {
12592 curt = (ResolveInfo)receivers.get(it);
12593 }
12594 if (curr == null) {
12595 curr = registeredReceivers.get(ir);
12596 }
12597 if (curr.getPriority() >= curt.priority) {
12598 // Insert this broadcast record into the final list.
12599 receivers.add(it, curr);
12600 ir++;
12601 curr = null;
12602 it++;
12603 NT++;
12604 } else {
12605 // Skip to the next ResolveInfo in the final list.
12606 it++;
12607 curt = null;
12608 }
12609 }
12610 }
12611 while (ir < NR) {
12612 if (receivers == null) {
12613 receivers = new ArrayList();
12614 }
12615 receivers.add(registeredReceivers.get(ir));
12616 ir++;
12617 }
12618
12619 if ((receivers != null && receivers.size() > 0)
12620 || resultTo != null) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012621 BroadcastQueue queue = broadcastQueueForIntent(intent);
12622 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012623 callerPackage, callingPid, callingUid, requiredPermission,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012624 receivers, resultTo, resultCode, resultData, map, ordered,
12625 sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012626 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012627 TAG, "Enqueueing ordered broadcast " + r
Christopher Tatef46723b2012-01-26 14:19:24 -080012628 + ": prev had " + queue.mOrderedBroadcasts.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012629 if (DEBUG_BROADCAST) {
12630 int seq = r.intent.getIntExtra("seq", -1);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012631 Slog.i(TAG, "Enqueueing broadcast " + r.intent.getAction() + " seq=" + seq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012632 }
Christopher Tatef46723b2012-01-26 14:19:24 -080012633 boolean replaced = replacePending && queue.replaceOrderedBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012634 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012635 queue.enqueueOrderedBroadcastLocked(r);
12636 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012637 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012638 }
12639
Dianne Hackborna4972e92012-03-14 10:38:05 -070012640 return ActivityManager.BROADCAST_SUCCESS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012641 }
12642
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012643 final Intent verifyBroadcastLocked(Intent intent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012644 // Refuse possible leaked file descriptors
12645 if (intent != null && intent.hasFileDescriptors() == true) {
12646 throw new IllegalArgumentException("File descriptors passed in Intent");
12647 }
12648
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012649 int flags = intent.getFlags();
12650
12651 if (!mProcessesReady) {
12652 // if the caller really truly claims to know what they're doing, go
12653 // ahead and allow the broadcast without launching any receivers
12654 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
12655 intent = new Intent(intent);
12656 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
12657 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
12658 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
12659 + " before boot completion");
12660 throw new IllegalStateException("Cannot broadcast before boot completed");
12661 }
12662 }
12663
12664 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
12665 throw new IllegalArgumentException(
12666 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
12667 }
12668
12669 return intent;
12670 }
12671
12672 public final int broadcastIntent(IApplicationThread caller,
12673 Intent intent, String resolvedType, IIntentReceiver resultTo,
12674 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070012675 String requiredPermission, boolean serialized, boolean sticky, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012676 enforceNotIsolatedCaller("broadcastIntent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012677 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012678 intent = verifyBroadcastLocked(intent);
Dianne Hackborn9acc0302009-08-25 00:27:12 -070012679
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012680 final ProcessRecord callerApp = getRecordForAppLocked(caller);
12681 final int callingPid = Binder.getCallingPid();
12682 final int callingUid = Binder.getCallingUid();
12683 final long origId = Binder.clearCallingIdentity();
12684 int res = broadcastIntentLocked(callerApp,
12685 callerApp != null ? callerApp.info.packageName : null,
12686 intent, resolvedType, resultTo,
Amith Yamasani742a6712011-05-04 14:49:28 -070012687 resultCode, resultData, map, requiredPermission, serialized, sticky,
12688 callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012689 Binder.restoreCallingIdentity(origId);
12690 return res;
12691 }
12692 }
12693
12694 int broadcastIntentInPackage(String packageName, int uid,
12695 Intent intent, String resolvedType, IIntentReceiver resultTo,
12696 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070012697 String requiredPermission, boolean serialized, boolean sticky, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012698 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012699 intent = verifyBroadcastLocked(intent);
12700
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012701 final long origId = Binder.clearCallingIdentity();
12702 int res = broadcastIntentLocked(null, packageName, intent, resolvedType,
12703 resultTo, resultCode, resultData, map, requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070012704 serialized, sticky, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012705 Binder.restoreCallingIdentity(origId);
12706 return res;
12707 }
12708 }
12709
Amith Yamasani742a6712011-05-04 14:49:28 -070012710 // TODO: Use the userId; maybe mStickyBroadcasts need to be tied to the user.
12711 public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012712 // Refuse possible leaked file descriptors
12713 if (intent != null && intent.hasFileDescriptors() == true) {
12714 throw new IllegalArgumentException("File descriptors passed in Intent");
12715 }
12716
12717 synchronized(this) {
12718 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
12719 != PackageManager.PERMISSION_GRANTED) {
12720 String msg = "Permission Denial: unbroadcastIntent() from pid="
12721 + Binder.getCallingPid()
12722 + ", uid=" + Binder.getCallingUid()
12723 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012724 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012725 throw new SecurityException(msg);
12726 }
12727 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
12728 if (list != null) {
12729 int N = list.size();
12730 int i;
12731 for (i=0; i<N; i++) {
12732 if (intent.filterEquals(list.get(i))) {
12733 list.remove(i);
12734 break;
12735 }
12736 }
12737 }
12738 }
12739 }
12740
12741 private final boolean finishReceiverLocked(IBinder receiver, int resultCode,
12742 String resultData, Bundle resultExtras, boolean resultAbort,
12743 boolean explicit) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012744 final BroadcastRecord r = broadcastRecordForReceiverLocked(receiver);
12745 if (r == null) {
12746 Slog.w(TAG, "finishReceiver called but not found on queue");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012747 return false;
12748 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012749
Christopher Tatef46723b2012-01-26 14:19:24 -080012750 return r.queue.finishReceiverLocked(r, resultCode, resultData, resultExtras, resultAbort,
12751 explicit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012752 }
12753
12754 public void finishReceiver(IBinder who, int resultCode, String resultData,
12755 Bundle resultExtras, boolean resultAbort) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012756 if (DEBUG_BROADCAST) Slog.v(TAG, "Finish receiver: " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012757
12758 // Refuse possible leaked file descriptors
12759 if (resultExtras != null && resultExtras.hasFileDescriptors()) {
12760 throw new IllegalArgumentException("File descriptors passed in Bundle");
12761 }
12762
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012763 final long origId = Binder.clearCallingIdentity();
Christopher Tatef46723b2012-01-26 14:19:24 -080012764 try {
12765 boolean doNext = false;
12766 BroadcastRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012767
Christopher Tatef46723b2012-01-26 14:19:24 -080012768 synchronized(this) {
12769 r = broadcastRecordForReceiverLocked(who);
12770 if (r != null) {
12771 doNext = r.queue.finishReceiverLocked(r, resultCode,
12772 resultData, resultExtras, resultAbort, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012773 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012774 }
Jeff Brown4d94a762010-09-23 11:33:28 -070012775
Christopher Tatef46723b2012-01-26 14:19:24 -080012776 if (doNext) {
12777 r.queue.processNextBroadcast(false);
12778 }
12779 trimApplications();
12780 } finally {
12781 Binder.restoreCallingIdentity(origId);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012782 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012783 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012784
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012785 // =========================================================
12786 // INSTRUMENTATION
12787 // =========================================================
12788
12789 public boolean startInstrumentation(ComponentName className,
12790 String profileFile, int flags, Bundle arguments,
12791 IInstrumentationWatcher watcher) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012792 enforceNotIsolatedCaller("startInstrumentation");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012793 // Refuse possible leaked file descriptors
12794 if (arguments != null && arguments.hasFileDescriptors()) {
12795 throw new IllegalArgumentException("File descriptors passed in Bundle");
12796 }
12797
12798 synchronized(this) {
12799 InstrumentationInfo ii = null;
12800 ApplicationInfo ai = null;
12801 try {
12802 ii = mContext.getPackageManager().getInstrumentationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070012803 className, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012804 ai = mContext.getPackageManager().getApplicationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070012805 ii.targetPackage, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012806 } catch (PackageManager.NameNotFoundException e) {
12807 }
12808 if (ii == null) {
12809 reportStartInstrumentationFailure(watcher, className,
12810 "Unable to find instrumentation info for: " + className);
12811 return false;
12812 }
12813 if (ai == null) {
12814 reportStartInstrumentationFailure(watcher, className,
12815 "Unable to find instrumentation target package: " + ii.targetPackage);
12816 return false;
12817 }
12818
12819 int match = mContext.getPackageManager().checkSignatures(
12820 ii.targetPackage, ii.packageName);
12821 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
12822 String msg = "Permission Denial: starting instrumentation "
12823 + className + " from pid="
12824 + Binder.getCallingPid()
12825 + ", uid=" + Binder.getCallingPid()
12826 + " not allowed because package " + ii.packageName
12827 + " does not have a signature matching the target "
12828 + ii.targetPackage;
12829 reportStartInstrumentationFailure(watcher, className, msg);
12830 throw new SecurityException(msg);
12831 }
12832
12833 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -070012834 // Instrumentation can kill and relaunch even persistent processes
12835 forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080012836 ProcessRecord app = addAppLocked(ai, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012837 app.instrumentationClass = className;
Dianne Hackborn1655be42009-05-08 14:29:01 -070012838 app.instrumentationInfo = ai;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012839 app.instrumentationProfileFile = profileFile;
12840 app.instrumentationArguments = arguments;
12841 app.instrumentationWatcher = watcher;
12842 app.instrumentationResultClass = className;
12843 Binder.restoreCallingIdentity(origId);
12844 }
12845
12846 return true;
12847 }
12848
12849 /**
12850 * Report errors that occur while attempting to start Instrumentation. Always writes the
12851 * error to the logs, but if somebody is watching, send the report there too. This enables
12852 * the "am" command to report errors with more information.
12853 *
12854 * @param watcher The IInstrumentationWatcher. Null if there isn't one.
12855 * @param cn The component name of the instrumentation.
12856 * @param report The error report.
12857 */
12858 private void reportStartInstrumentationFailure(IInstrumentationWatcher watcher,
12859 ComponentName cn, String report) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012860 Slog.w(TAG, report);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012861 try {
12862 if (watcher != null) {
12863 Bundle results = new Bundle();
12864 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
12865 results.putString("Error", report);
12866 watcher.instrumentationStatus(cn, -1, results);
12867 }
12868 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012869 Slog.w(TAG, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012870 }
12871 }
12872
12873 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
12874 if (app.instrumentationWatcher != null) {
12875 try {
12876 // NOTE: IInstrumentationWatcher *must* be oneway here
12877 app.instrumentationWatcher.instrumentationFinished(
12878 app.instrumentationClass,
12879 resultCode,
12880 results);
12881 } catch (RemoteException e) {
12882 }
12883 }
12884 app.instrumentationWatcher = null;
12885 app.instrumentationClass = null;
Dianne Hackborn1655be42009-05-08 14:29:01 -070012886 app.instrumentationInfo = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012887 app.instrumentationProfileFile = null;
12888 app.instrumentationArguments = null;
12889
Christopher Tate3dacd842011-08-19 14:56:15 -070012890 forceStopPackageLocked(app.processName, -1, false, false, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012891 }
12892
12893 public void finishInstrumentation(IApplicationThread target,
12894 int resultCode, Bundle results) {
12895 // Refuse possible leaked file descriptors
12896 if (results != null && results.hasFileDescriptors()) {
12897 throw new IllegalArgumentException("File descriptors passed in Intent");
12898 }
12899
12900 synchronized(this) {
12901 ProcessRecord app = getRecordForAppLocked(target);
12902 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012903 Slog.w(TAG, "finishInstrumentation: no app for " + target);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012904 return;
12905 }
12906 final long origId = Binder.clearCallingIdentity();
12907 finishInstrumentationLocked(app, resultCode, results);
12908 Binder.restoreCallingIdentity(origId);
12909 }
12910 }
12911
12912 // =========================================================
12913 // CONFIGURATION
12914 // =========================================================
12915
12916 public ConfigurationInfo getDeviceConfigurationInfo() {
12917 ConfigurationInfo config = new ConfigurationInfo();
12918 synchronized (this) {
12919 config.reqTouchScreen = mConfiguration.touchscreen;
12920 config.reqKeyboardType = mConfiguration.keyboard;
12921 config.reqNavigation = mConfiguration.navigation;
Dianne Hackbornfae76f52009-07-16 13:41:23 -070012922 if (mConfiguration.navigation == Configuration.NAVIGATION_DPAD
12923 || mConfiguration.navigation == Configuration.NAVIGATION_TRACKBALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012924 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
12925 }
Dianne Hackbornfae76f52009-07-16 13:41:23 -070012926 if (mConfiguration.keyboard != Configuration.KEYBOARD_UNDEFINED
12927 && mConfiguration.keyboard != Configuration.KEYBOARD_NOKEYS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012928 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
12929 }
Jack Palevichb90d28c2009-07-22 15:35:24 -070012930 config.reqGlEsVersion = GL_ES_VERSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012931 }
12932 return config;
12933 }
12934
12935 public Configuration getConfiguration() {
12936 Configuration ci;
12937 synchronized(this) {
12938 ci = new Configuration(mConfiguration);
12939 }
12940 return ci;
12941 }
12942
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012943 public void updatePersistentConfiguration(Configuration values) {
12944 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
12945 "updateConfiguration()");
12946 enforceCallingPermission(android.Manifest.permission.WRITE_SETTINGS,
12947 "updateConfiguration()");
12948 if (values == null) {
12949 throw new NullPointerException("Configuration must not be null");
12950 }
12951
12952 synchronized(this) {
12953 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn813075a62011-11-14 17:45:19 -080012954 updateConfigurationLocked(values, null, true, false);
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012955 Binder.restoreCallingIdentity(origId);
12956 }
12957 }
12958
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012959 public void updateConfiguration(Configuration values) {
12960 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
12961 "updateConfiguration()");
12962
12963 synchronized(this) {
12964 if (values == null && mWindowManager != null) {
12965 // sentinel: fetch the current configuration from the window manager
12966 values = mWindowManager.computeNewConfiguration();
12967 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012968
12969 if (mWindowManager != null) {
12970 mProcessList.applyDisplaySize(mWindowManager);
12971 }
12972
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012973 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012974 if (values != null) {
12975 Settings.System.clearConfiguration(values);
12976 }
Dianne Hackborn813075a62011-11-14 17:45:19 -080012977 updateConfigurationLocked(values, null, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012978 Binder.restoreCallingIdentity(origId);
12979 }
12980 }
12981
12982 /**
12983 * Do either or both things: (1) change the current configuration, and (2)
12984 * make sure the given activity is running with the (now) current
12985 * configuration. Returns true if the activity has been left running, or
12986 * false if <var>starting</var> is being destroyed to match the new
12987 * configuration.
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012988 * @param persistent TODO
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012989 */
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012990 boolean updateConfigurationLocked(Configuration values,
Dianne Hackborn813075a62011-11-14 17:45:19 -080012991 ActivityRecord starting, boolean persistent, boolean initLocale) {
Mike Lockwood3a74bd32011-08-12 13:55:22 -070012992 // do nothing if we are headless
12993 if (mHeadless) return true;
12994
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012995 int changes = 0;
12996
12997 boolean kept = true;
12998
12999 if (values != null) {
13000 Configuration newConfig = new Configuration(mConfiguration);
13001 changes = newConfig.updateFrom(values);
13002 if (changes != 0) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013003 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013004 Slog.i(TAG, "Updating configuration to: " + values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013005 }
13006
Doug Zongker2bec3d42009-12-04 12:52:44 -080013007 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013008
Dianne Hackborn813075a62011-11-14 17:45:19 -080013009 if (values.locale != null && !initLocale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013010 saveLocaleLocked(values.locale,
13011 !values.locale.equals(mConfiguration.locale),
13012 values.userSetLocale);
13013 }
13014
Dianne Hackborne36d6e22010-02-17 19:46:25 -080013015 mConfigurationSeq++;
13016 if (mConfigurationSeq <= 0) {
13017 mConfigurationSeq = 1;
13018 }
13019 newConfig.seq = mConfigurationSeq;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013020 mConfiguration = newConfig;
Joe Onorato8a9b2202010-02-26 18:56:32 -080013021 Slog.i(TAG, "Config changed: " + newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013022
13023 final Configuration configCopy = new Configuration(mConfiguration);
Joe Onorato54a4a412011-11-02 20:50:08 -070013024
13025 // TODO: If our config changes, should we auto dismiss any currently
13026 // showing dialogs?
13027 mShowDialogs = shouldShowDialogs(newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013028
Dianne Hackborn826d17c2009-11-12 12:55:51 -080013029 AttributeCache ac = AttributeCache.instance();
13030 if (ac != null) {
Dianne Hackborn813075a62011-11-14 17:45:19 -080013031 ac.updateConfiguration(configCopy);
Dianne Hackborn826d17c2009-11-12 12:55:51 -080013032 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013033
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070013034 // Make sure all resources in our process are updated
13035 // right now, so that anyone who is going to retrieve
13036 // resource values after we return will be sure to get
13037 // the new ones. This is especially important during
13038 // boot, where the first config change needs to guarantee
13039 // all resources have that config before following boot
13040 // code is executed.
Dianne Hackborn813075a62011-11-14 17:45:19 -080013041 mSystemThread.applyConfigurationToResources(configCopy);
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070013042
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013043 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080013044 Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013045 msg.obj = new Configuration(configCopy);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080013046 mHandler.sendMessage(msg);
13047 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013048
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013049 for (int i=mLruProcesses.size()-1; i>=0; i--) {
13050 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013051 try {
13052 if (app.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013053 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending to proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013054 + app.processName + " new config " + mConfiguration);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013055 app.thread.scheduleConfigurationChanged(configCopy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013056 }
13057 } catch (Exception e) {
13058 }
13059 }
13060 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080013061 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
13062 | Intent.FLAG_RECEIVER_REPLACE_PENDING);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013063 broadcastIntentLocked(null, null, intent, null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070013064 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080013065 if ((changes&ActivityInfo.CONFIG_LOCALE) != 0) {
13066 broadcastIntentLocked(null, null,
13067 new Intent(Intent.ACTION_LOCALE_CHANGED),
13068 null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070013069 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080013070 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013071 }
13072 }
13073
13074 if (changes != 0 && starting == null) {
13075 // If the configuration changed, and the caller is not already
13076 // in the process of starting an activity, then find the top
13077 // activity to check if its configuration needs to change.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013078 starting = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013079 }
13080
13081 if (starting != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013082 kept = mMainStack.ensureActivityConfigurationLocked(starting, changes);
Dianne Hackborn5f4d6432010-12-21 20:40:11 -080013083 // And we need to make sure at this point that all other activities
13084 // are made visible with the correct configuration.
13085 mMainStack.ensureActivitiesVisibleLocked(starting, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013086 }
13087
Dianne Hackborne36d6e22010-02-17 19:46:25 -080013088 if (values != null && mWindowManager != null) {
13089 mWindowManager.setNewConfiguration(mConfiguration);
13090 }
13091
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013092 return kept;
13093 }
Joe Onorato54a4a412011-11-02 20:50:08 -070013094
13095 /**
13096 * Decide based on the configuration whether we should shouw the ANR,
13097 * crash, etc dialogs. The idea is that if there is no affordnace to
13098 * press the on-screen buttons, we shouldn't show the dialog.
13099 *
13100 * A thought: SystemUI might also want to get told about this, the Power
13101 * dialog / global actions also might want different behaviors.
13102 */
13103 private static final boolean shouldShowDialogs(Configuration config) {
13104 return !(config.keyboard == Configuration.KEYBOARD_NOKEYS
13105 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH);
13106 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013107
13108 /**
13109 * Save the locale. You must be inside a synchronized (this) block.
13110 */
13111 private void saveLocaleLocked(Locale l, boolean isDiff, boolean isPersist) {
13112 if(isDiff) {
13113 SystemProperties.set("user.language", l.getLanguage());
13114 SystemProperties.set("user.region", l.getCountry());
13115 }
13116
13117 if(isPersist) {
13118 SystemProperties.set("persist.sys.language", l.getLanguage());
13119 SystemProperties.set("persist.sys.country", l.getCountry());
13120 SystemProperties.set("persist.sys.localevar", l.getVariant());
13121 }
13122 }
13123
13124 // =========================================================
13125 // LIFETIME MANAGEMENT
13126 // =========================================================
13127
Christopher Tatef46723b2012-01-26 14:19:24 -080013128 // Returns which broadcast queue the app is the current [or imminent] receiver
13129 // on, or 'null' if the app is not an active broadcast recipient.
13130 private BroadcastQueue isReceivingBroadcast(ProcessRecord app) {
13131 BroadcastRecord r = app.curReceiver;
13132 if (r != null) {
13133 return r.queue;
13134 }
13135
13136 // It's not the current receiver, but it might be starting up to become one
13137 synchronized (this) {
13138 for (BroadcastQueue queue : mBroadcastQueues) {
13139 r = queue.mPendingBroadcast;
13140 if (r != null && r.curApp == app) {
13141 // found it; report which queue it's in
13142 return queue;
13143 }
13144 }
13145 }
13146
13147 return null;
13148 }
13149
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013150 private final int computeOomAdjLocked(ProcessRecord app, int hiddenAdj,
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013151 ProcessRecord TOP_APP, boolean recursed, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013152 if (mAdjSeq == app.adjSeq) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013153 // This adjustment has already been computed. If we are calling
13154 // from the top, we may have already computed our adjustment with
13155 // an earlier hidden adjustment that isn't really for us... if
13156 // so, use the new hidden adjustment.
13157 if (!recursed && app.hidden) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013158 app.curAdj = app.curRawAdj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013159 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013160 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013161 }
13162
13163 if (app.thread == null) {
13164 app.adjSeq = mAdjSeq;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013165 app.curSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013166 return (app.curAdj=ProcessList.HIDDEN_APP_MAX_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013167 }
13168
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013169 app.adjTypeCode = ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN;
13170 app.adjSource = null;
13171 app.adjTarget = null;
13172 app.empty = false;
13173 app.hidden = false;
13174
13175 final int activitiesSize = app.activities.size();
13176
Dianne Hackborn7d608422011-08-07 16:24:18 -070013177 if (app.maxAdj <= ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013178 // The max adjustment doesn't allow this app to be anything
13179 // below foreground, so it is not worth doing work for it.
13180 app.adjType = "fixed";
13181 app.adjSeq = mAdjSeq;
13182 app.curRawAdj = app.maxAdj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013183 app.foregroundActivities = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013184 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013185 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013186 // System process can do UI, and when they do we want to have
13187 // them trim their memory after the user leaves the UI. To
13188 // facilitate this, here we need to determine whether or not it
13189 // is currently showing UI.
13190 app.systemNoUi = true;
13191 if (app == TOP_APP) {
13192 app.systemNoUi = false;
13193 } else if (activitiesSize > 0) {
13194 for (int j = 0; j < activitiesSize; j++) {
13195 final ActivityRecord r = app.activities.get(j);
13196 if (r.visible) {
13197 app.systemNoUi = false;
13198 break;
13199 }
13200 }
13201 }
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013202 return (app.curAdj=app.maxAdj);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013203 }
13204
13205 final boolean hadForegroundActivities = app.foregroundActivities;
13206
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013207 app.foregroundActivities = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013208 app.keeping = false;
13209 app.systemNoUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013210
The Android Open Source Project4df24232009-03-05 14:34:35 -080013211 // Determine the importance of the process, starting with most
13212 // important to least, and assign an appropriate OOM adjustment.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013213 int adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013214 int schedGroup;
Christopher Tatef46723b2012-01-26 14:19:24 -080013215 BroadcastQueue queue;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013216 if (app == TOP_APP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013217 // The last app on the list is the foreground app.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013218 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013219 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013220 app.adjType = "top-activity";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013221 app.foregroundActivities = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013222 } else if (app.instrumentationClass != null) {
13223 // Don't want to kill running instrumentation.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013224 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013225 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013226 app.adjType = "instrumentation";
Christopher Tatef46723b2012-01-26 14:19:24 -080013227 } else if ((queue = isReceivingBroadcast(app)) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013228 // An app that is currently receiving a broadcast also
Christopher Tatef46723b2012-01-26 14:19:24 -080013229 // counts as being in the foreground for OOM killer purposes.
13230 // It's placed in a sched group based on the nature of the
13231 // broadcast as reflected by which queue it's active in.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013232 adj = ProcessList.FOREGROUND_APP_ADJ;
Christopher Tatef46723b2012-01-26 14:19:24 -080013233 schedGroup = (queue == mFgBroadcastQueue)
13234 ? Process.THREAD_GROUP_DEFAULT : Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013235 app.adjType = "broadcast";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013236 } else if (app.executingServices.size() > 0) {
13237 // An app that is currently executing a service callback also
13238 // counts as being in the foreground.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013239 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013240 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013241 app.adjType = "exec-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013242 } else if (activitiesSize > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013243 // This app is in the background with paused activities.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013244 // We inspect activities to potentially upgrade adjustment further below.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013245 adj = hiddenAdj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013246 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013247 app.hidden = true;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013248 app.adjType = "bg-activities";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013249 } else {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013250 // A very not-needed process. If this is lower in the lru list,
13251 // we will push it in to the empty bucket.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013252 adj = hiddenAdj;
13253 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013254 app.hidden = true;
13255 app.empty = true;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013256 app.adjType = "bg-empty";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013257 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013258
13259 // Examine all activities if not already foreground.
13260 if (!app.foregroundActivities && activitiesSize > 0) {
13261 for (int j = 0; j < activitiesSize; j++) {
13262 final ActivityRecord r = app.activities.get(j);
13263 if (r.visible) {
13264 // App has a visible activity; only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013265 if (adj > ProcessList.VISIBLE_APP_ADJ) {
13266 adj = ProcessList.VISIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013267 app.adjType = "visible";
13268 }
13269 schedGroup = Process.THREAD_GROUP_DEFAULT;
13270 app.hidden = false;
13271 app.foregroundActivities = true;
13272 break;
13273 } else if (r.state == ActivityState.PAUSING || r.state == ActivityState.PAUSED
13274 || r.state == ActivityState.STOPPING) {
13275 // Only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013276 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13277 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013278 app.adjType = "stopping";
13279 }
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -080013280 app.hidden = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013281 app.foregroundActivities = true;
13282 }
13283 }
13284 }
13285
Dianne Hackborn7d608422011-08-07 16:24:18 -070013286 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013287 if (app.foregroundServices) {
13288 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013289 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013290 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013291 app.adjType = "foreground-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013292 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013293 } else if (app.forcingToForeground != null) {
13294 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013295 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013296 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013297 app.adjType = "force-foreground";
13298 app.adjSource = app.forcingToForeground;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013299 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013300 }
13301 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013302
Dianne Hackborn7d608422011-08-07 16:24:18 -070013303 if (adj > ProcessList.HEAVY_WEIGHT_APP_ADJ && app == mHeavyWeightProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013304 // We don't want to kill the current heavy-weight process.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013305 adj = ProcessList.HEAVY_WEIGHT_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013306 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013307 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013308 app.adjType = "heavy";
13309 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013310
Dianne Hackborn7d608422011-08-07 16:24:18 -070013311 if (adj > ProcessList.HOME_APP_ADJ && app == mHomeProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013312 // This process is hosting what we currently consider to be the
13313 // home app, so we don't want to let it go into the background.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013314 adj = ProcessList.HOME_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013315 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013316 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013317 app.adjType = "home";
13318 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013319
Dianne Hackbornf35fe232011-11-01 19:25:20 -070013320 if (adj > ProcessList.PREVIOUS_APP_ADJ && app == mPreviousProcess
13321 && app.activities.size() > 0) {
13322 // This was the previous process that showed UI to the user.
13323 // We want to try to keep it around more aggressively, to give
13324 // a good experience around switching between two apps.
13325 adj = ProcessList.PREVIOUS_APP_ADJ;
13326 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
13327 app.hidden = false;
13328 app.adjType = "previous";
13329 }
13330
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013331 if (false) Slog.i(TAG, "OOM " + app + ": initial adj=" + adj
13332 + " reason=" + app.adjType);
13333
The Android Open Source Project4df24232009-03-05 14:34:35 -080013334 // By default, we use the computed adjustment. It may be changed if
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013335 // there are applications dependent on our services or providers, but
13336 // this gives us a baseline and makes sure we don't get into an
13337 // infinite recursion.
13338 app.adjSeq = mAdjSeq;
13339 app.curRawAdj = adj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013340
Christopher Tate6fa95972009-06-05 18:43:55 -070013341 if (mBackupTarget != null && app == mBackupTarget.app) {
13342 // If possible we want to avoid killing apps while they're being backed up
Dianne Hackborn7d608422011-08-07 16:24:18 -070013343 if (adj > ProcessList.BACKUP_APP_ADJ) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013344 if (DEBUG_BACKUP) Slog.v(TAG, "oom BACKUP_APP_ADJ for " + app);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013345 adj = ProcessList.BACKUP_APP_ADJ;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013346 app.adjType = "backup";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013347 app.hidden = false;
Christopher Tate6fa95972009-06-05 18:43:55 -070013348 }
13349 }
13350
Dianne Hackborn7d608422011-08-07 16:24:18 -070013351 if (app.services.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013352 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013353 final long now = SystemClock.uptimeMillis();
13354 // This process is more important if the top activity is
13355 // bound to the service.
Dianne Hackborn860755f2010-06-03 18:47:52 -070013356 Iterator<ServiceRecord> jt = app.services.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013357 while (jt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013358 ServiceRecord s = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013359 if (s.startRequested) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013360 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013361 // If this process has shown some UI, let it immediately
13362 // go to the LRU list because it may be pretty heavy with
13363 // UI stuff. We'll tag it with a label just to help
13364 // debug and understand what is going on.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013365 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013366 app.adjType = "started-bg-ui-services";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013367 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013368 } else {
13369 if (now < (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
13370 // This service has seen some activity within
13371 // recent memory, so we will keep its process ahead
13372 // of the background processes.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013373 if (adj > ProcessList.SERVICE_ADJ) {
13374 adj = ProcessList.SERVICE_ADJ;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013375 app.adjType = "started-services";
13376 app.hidden = false;
13377 }
13378 }
13379 // If we have let the service slide into the background
13380 // state, still have some text describing what it is doing
13381 // even though the service no longer has an impact.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013382 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013383 app.adjType = "started-bg-services";
13384 }
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080013385 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013386 // Don't kill this process because it is doing work; it
13387 // has said it is doing work.
13388 app.keeping = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013389 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013390 if (s.connections.size() > 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013391 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013392 Iterator<ArrayList<ConnectionRecord>> kt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013393 = s.connections.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013394 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013395 ArrayList<ConnectionRecord> clist = kt.next();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013396 for (int i=0; i<clist.size() && adj > ProcessList.FOREGROUND_APP_ADJ; i++) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013397 // XXX should compute this based on the max of
13398 // all connected clients.
13399 ConnectionRecord cr = clist.get(i);
13400 if (cr.binding.client == app) {
13401 // Binding to ourself is not interesting.
13402 continue;
13403 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013404 if ((cr.flags&Context.BIND_WAIVE_PRIORITY) == 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013405 ProcessRecord client = cr.binding.client;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013406 int clientAdj = adj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013407 int myHiddenAdj = hiddenAdj;
13408 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013409 if (client.hiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013410 myHiddenAdj = client.hiddenAdj;
13411 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013412 myHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013413 }
13414 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013415 clientAdj = computeOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013416 client, myHiddenAdj, TOP_APP, true, doingAll);
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013417 String adjType = null;
13418 if ((cr.flags&Context.BIND_ALLOW_OOM_MANAGEMENT) != 0) {
13419 // Not doing bind OOM management, so treat
13420 // this guy more like a started service.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013421 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013422 // If this process has shown some UI, let it immediately
13423 // go to the LRU list because it may be pretty heavy with
13424 // UI stuff. We'll tag it with a label just to help
13425 // debug and understand what is going on.
13426 if (adj > clientAdj) {
13427 adjType = "bound-bg-ui-services";
13428 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013429 app.hidden = false;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013430 clientAdj = adj;
13431 } else {
13432 if (now >= (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
13433 // This service has not seen activity within
13434 // recent memory, so allow it to drop to the
13435 // LRU list if there is no other reason to keep
13436 // it around. We'll also tag it with a label just
13437 // to help debug and undertand what is going on.
13438 if (adj > clientAdj) {
13439 adjType = "bound-bg-services";
13440 }
13441 clientAdj = adj;
13442 }
13443 }
13444 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013445 if (adj > clientAdj) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013446 // If this process has recently shown UI, and
13447 // the process that is binding to it is less
13448 // important than being visible, then we don't
13449 // care about the binding as much as we care
13450 // about letting this process get into the LRU
13451 // list to be killed and restarted if needed for
13452 // memory.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013453 if (app.hasShownUi && app != mHomeProcess
13454 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013455 adjType = "bound-bg-ui-services";
13456 } else {
13457 if ((cr.flags&(Context.BIND_ABOVE_CLIENT
13458 |Context.BIND_IMPORTANT)) != 0) {
13459 adj = clientAdj;
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070013460 } else if ((cr.flags&Context.BIND_NOT_VISIBLE) != 0
13461 && clientAdj < ProcessList.PERCEPTIBLE_APP_ADJ
13462 && adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13463 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13464 } else if (clientAdj > ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013465 adj = clientAdj;
13466 } else {
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070013467 app.pendingUiClean = true;
13468 if (adj > ProcessList.VISIBLE_APP_ADJ) {
13469 adj = ProcessList.VISIBLE_APP_ADJ;
13470 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013471 }
13472 if (!client.hidden) {
13473 app.hidden = false;
13474 }
13475 if (client.keeping) {
13476 app.keeping = true;
13477 }
13478 adjType = "service";
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013479 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013480 }
13481 if (adjType != null) {
13482 app.adjType = adjType;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013483 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13484 .REASON_SERVICE_IN_USE;
13485 app.adjSource = cr.binding.client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013486 app.adjSourceOom = clientAdj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013487 app.adjTarget = s.name;
13488 }
13489 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
13490 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
13491 schedGroup = Process.THREAD_GROUP_DEFAULT;
13492 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013493 }
13494 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013495 if ((cr.flags&Context.BIND_ADJUST_WITH_ACTIVITY) != 0) {
13496 ActivityRecord a = cr.activity;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013497 if (a != null && adj > ProcessList.FOREGROUND_APP_ADJ &&
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013498 (a.visible || a.state == ActivityState.RESUMED
13499 || a.state == ActivityState.PAUSING)) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013500 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013501 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
13502 schedGroup = Process.THREAD_GROUP_DEFAULT;
13503 }
13504 app.hidden = false;
13505 app.adjType = "service";
13506 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13507 .REASON_SERVICE_IN_USE;
13508 app.adjSource = a;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013509 app.adjSourceOom = adj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013510 app.adjTarget = s.name;
13511 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013512 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013513 }
13514 }
13515 }
13516 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013517
Dianne Hackborn287952c2010-09-22 22:34:31 -070013518 // Finally, if this process has active services running in it, we
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013519 // would like to avoid killing it unless it would prevent the current
13520 // application from running. By default we put the process in
13521 // with the rest of the background processes; as we scan through
13522 // its services we may bump it up from there.
13523 if (adj > hiddenAdj) {
13524 adj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013525 app.hidden = false;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013526 app.adjType = "bg-services";
13527 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013528 }
13529
Dianne Hackborn7d608422011-08-07 16:24:18 -070013530 if (app.pubProviders.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013531 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013532 Iterator<ContentProviderRecord> jt = app.pubProviders.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013533 while (jt.hasNext() && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013534 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013535 ContentProviderRecord cpr = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013536 if (cpr.clients.size() != 0) {
13537 Iterator<ProcessRecord> kt = cpr.clients.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013538 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013539 ProcessRecord client = kt.next();
The Android Open Source Project10592532009-03-18 17:39:46 -070013540 if (client == app) {
13541 // Being our own client is not interesting.
13542 continue;
13543 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013544 int myHiddenAdj = hiddenAdj;
13545 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013546 if (client.hiddenAdj > ProcessList.FOREGROUND_APP_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013547 myHiddenAdj = client.hiddenAdj;
13548 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013549 myHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013550 }
13551 }
13552 int clientAdj = computeOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013553 client, myHiddenAdj, TOP_APP, true, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013554 if (adj > clientAdj) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013555 if (app.hasShownUi && app != mHomeProcess
13556 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013557 app.adjType = "bg-ui-provider";
13558 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013559 adj = clientAdj > ProcessList.FOREGROUND_APP_ADJ
13560 ? clientAdj : ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013561 app.adjType = "provider";
13562 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013563 if (!client.hidden) {
13564 app.hidden = false;
13565 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013566 if (client.keeping) {
13567 app.keeping = true;
13568 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070013569 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13570 .REASON_PROVIDER_IN_USE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013571 app.adjSource = client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013572 app.adjSourceOom = clientAdj;
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070013573 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013574 }
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013575 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
13576 schedGroup = Process.THREAD_GROUP_DEFAULT;
13577 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013578 }
13579 }
13580 // If the provider has external (non-framework) process
13581 // dependencies, ensure that its adjustment is at least
13582 // FOREGROUND_APP_ADJ.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080013583 if (cpr.hasExternalProcessHandles()) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013584 if (adj > ProcessList.FOREGROUND_APP_ADJ) {
13585 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013586 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013587 app.hidden = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013588 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013589 app.adjType = "provider";
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070013590 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013591 }
13592 }
13593 }
13594 }
13595
13596 app.curRawAdj = adj;
13597
Joe Onorato8a9b2202010-02-26 18:56:32 -080013598 //Slog.i(TAG, "OOM ADJ " + app + ": pid=" + app.pid +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013599 // " adj=" + adj + " curAdj=" + app.curAdj + " maxAdj=" + app.maxAdj);
13600 if (adj > app.maxAdj) {
13601 adj = app.maxAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013602 if (app.maxAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013603 schedGroup = Process.THREAD_GROUP_DEFAULT;
13604 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013605 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013606 if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070013607 app.keeping = true;
13608 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013609
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013610 if (app.hasAboveClient) {
13611 // If this process has bound to any services with BIND_ABOVE_CLIENT,
13612 // then we need to drop its adjustment to be lower than the service's
13613 // in order to honor the request. We want to drop it by one adjustment
13614 // level... but there is special meaning applied to various levels so
13615 // we will skip some of them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013616 if (adj < ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013617 // System process will not get dropped, ever
Dianne Hackborn7d608422011-08-07 16:24:18 -070013618 } else if (adj < ProcessList.VISIBLE_APP_ADJ) {
13619 adj = ProcessList.VISIBLE_APP_ADJ;
13620 } else if (adj < ProcessList.PERCEPTIBLE_APP_ADJ) {
13621 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13622 } else if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
13623 adj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013624 } else if (adj < ProcessList.HIDDEN_APP_MAX_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013625 adj++;
13626 }
13627 }
13628
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013629 if (adj == ProcessList.SERVICE_ADJ) {
13630 if (doingAll) {
13631 app.serviceb = mNewNumServiceProcs > (mNumServiceProcs/3);
13632 mNewNumServiceProcs++;
13633 }
13634 if (app.serviceb) {
13635 adj = ProcessList.SERVICE_B_ADJ;
13636 }
13637 } else {
13638 app.serviceb = false;
13639 }
13640
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013641 app.curAdj = adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013642 app.curSchedGroup = schedGroup;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013643
13644 if (hadForegroundActivities != app.foregroundActivities) {
Jeff Sharkey287bd832011-05-28 19:36:26 -070013645 mHandler.obtainMessage(DISPATCH_FOREGROUND_ACTIVITIES_CHANGED, app.pid, app.info.uid,
13646 app.foregroundActivities).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013647 }
13648
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013649 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013650 }
13651
13652 /**
13653 * Ask a given process to GC right now.
13654 */
13655 final void performAppGcLocked(ProcessRecord app) {
13656 try {
13657 app.lastRequestedGc = SystemClock.uptimeMillis();
13658 if (app.thread != null) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013659 if (app.reportLowMemory) {
13660 app.reportLowMemory = false;
13661 app.thread.scheduleLowMemory();
13662 } else {
13663 app.thread.processInBackground();
13664 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013665 }
13666 } catch (Exception e) {
13667 // whatever.
13668 }
13669 }
13670
13671 /**
13672 * Returns true if things are idle enough to perform GCs.
13673 */
Josh Bartel7f208742010-02-25 11:01:44 -060013674 private final boolean canGcNowLocked() {
Christopher Tatef46723b2012-01-26 14:19:24 -080013675 boolean processingBroadcasts = false;
13676 for (BroadcastQueue q : mBroadcastQueues) {
13677 if (q.mParallelBroadcasts.size() != 0 || q.mOrderedBroadcasts.size() != 0) {
13678 processingBroadcasts = true;
13679 }
13680 }
13681 return !processingBroadcasts
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013682 && (mSleeping || (mMainStack.mResumedActivity != null &&
13683 mMainStack.mResumedActivity.idle));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013684 }
13685
13686 /**
13687 * Perform GCs on all processes that are waiting for it, but only
13688 * if things are idle.
13689 */
13690 final void performAppGcsLocked() {
13691 final int N = mProcessesToGc.size();
13692 if (N <= 0) {
13693 return;
13694 }
Josh Bartel7f208742010-02-25 11:01:44 -060013695 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013696 while (mProcessesToGc.size() > 0) {
13697 ProcessRecord proc = mProcessesToGc.remove(0);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013698 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013699 if ((proc.lastRequestedGc+GC_MIN_INTERVAL)
13700 <= SystemClock.uptimeMillis()) {
13701 // To avoid spamming the system, we will GC processes one
13702 // at a time, waiting a few seconds between each.
13703 performAppGcLocked(proc);
13704 scheduleAppGcsLocked();
13705 return;
13706 } else {
13707 // It hasn't been long enough since we last GCed this
13708 // process... put it in the list to wait for its time.
13709 addProcessToGcListLocked(proc);
13710 break;
13711 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013712 }
13713 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013714
13715 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013716 }
13717 }
13718
13719 /**
13720 * If all looks good, perform GCs on all processes waiting for them.
13721 */
13722 final void performAppGcsIfAppropriateLocked() {
Josh Bartel7f208742010-02-25 11:01:44 -060013723 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013724 performAppGcsLocked();
13725 return;
13726 }
13727 // Still not idle, wait some more.
13728 scheduleAppGcsLocked();
13729 }
13730
13731 /**
13732 * Schedule the execution of all pending app GCs.
13733 */
13734 final void scheduleAppGcsLocked() {
13735 mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013736
13737 if (mProcessesToGc.size() > 0) {
13738 // Schedule a GC for the time to the next process.
13739 ProcessRecord proc = mProcessesToGc.get(0);
13740 Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG);
13741
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013742 long when = proc.lastRequestedGc + GC_MIN_INTERVAL;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013743 long now = SystemClock.uptimeMillis();
13744 if (when < (now+GC_TIMEOUT)) {
13745 when = now + GC_TIMEOUT;
13746 }
13747 mHandler.sendMessageAtTime(msg, when);
13748 }
13749 }
13750
13751 /**
13752 * Add a process to the array of processes waiting to be GCed. Keeps the
13753 * list in sorted order by the last GC time. The process can't already be
13754 * on the list.
13755 */
13756 final void addProcessToGcListLocked(ProcessRecord proc) {
13757 boolean added = false;
13758 for (int i=mProcessesToGc.size()-1; i>=0; i--) {
13759 if (mProcessesToGc.get(i).lastRequestedGc <
13760 proc.lastRequestedGc) {
13761 added = true;
13762 mProcessesToGc.add(i+1, proc);
13763 break;
13764 }
13765 }
13766 if (!added) {
13767 mProcessesToGc.add(0, proc);
13768 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013769 }
13770
13771 /**
13772 * Set up to ask a process to GC itself. This will either do it
13773 * immediately, or put it on the list of processes to gc the next
13774 * time things are idle.
13775 */
13776 final void scheduleAppGcLocked(ProcessRecord app) {
13777 long now = SystemClock.uptimeMillis();
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013778 if ((app.lastRequestedGc+GC_MIN_INTERVAL) > now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013779 return;
13780 }
13781 if (!mProcessesToGc.contains(app)) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013782 addProcessToGcListLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013783 scheduleAppGcsLocked();
13784 }
13785 }
13786
Dianne Hackborn287952c2010-09-22 22:34:31 -070013787 final void checkExcessivePowerUsageLocked(boolean doKills) {
13788 updateCpuStatsNow();
13789
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013790 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013791 boolean doWakeKills = doKills;
13792 boolean doCpuKills = doKills;
13793 if (mLastPowerCheckRealtime == 0) {
13794 doWakeKills = false;
13795 }
13796 if (mLastPowerCheckUptime == 0) {
13797 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013798 }
13799 if (stats.isScreenOn()) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070013800 doWakeKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013801 }
13802 final long curRealtime = SystemClock.elapsedRealtime();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013803 final long realtimeSince = curRealtime - mLastPowerCheckRealtime;
13804 final long curUptime = SystemClock.uptimeMillis();
13805 final long uptimeSince = curUptime - mLastPowerCheckUptime;
13806 mLastPowerCheckRealtime = curRealtime;
13807 mLastPowerCheckUptime = curUptime;
13808 if (realtimeSince < WAKE_LOCK_MIN_CHECK_DURATION) {
13809 doWakeKills = false;
13810 }
13811 if (uptimeSince < CPU_MIN_CHECK_DURATION) {
13812 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013813 }
13814 int i = mLruProcesses.size();
13815 while (i > 0) {
13816 i--;
13817 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013818 if (!app.keeping) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013819 long wtime;
13820 synchronized (stats) {
13821 wtime = stats.getProcessWakeTime(app.info.uid,
13822 app.pid, curRealtime);
13823 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013824 long wtimeUsed = wtime - app.lastWakeTime;
13825 long cputimeUsed = app.curCpuTime - app.lastCpuTime;
13826 if (DEBUG_POWER) {
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013827 StringBuilder sb = new StringBuilder(128);
13828 sb.append("Wake for ");
13829 app.toShortString(sb);
13830 sb.append(": over ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013831 TimeUtils.formatDuration(realtimeSince, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013832 sb.append(" used ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013833 TimeUtils.formatDuration(wtimeUsed, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013834 sb.append(" (");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013835 sb.append((wtimeUsed*100)/realtimeSince);
13836 sb.append("%)");
13837 Slog.i(TAG, sb.toString());
13838 sb.setLength(0);
13839 sb.append("CPU for ");
13840 app.toShortString(sb);
13841 sb.append(": over ");
13842 TimeUtils.formatDuration(uptimeSince, sb);
13843 sb.append(" used ");
13844 TimeUtils.formatDuration(cputimeUsed, sb);
13845 sb.append(" (");
13846 sb.append((cputimeUsed*100)/uptimeSince);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013847 sb.append("%)");
13848 Slog.i(TAG, sb.toString());
13849 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013850 // If a process has held a wake lock for more
13851 // than 50% of the time during this period,
13852 // that sounds pad. Kill!
Dianne Hackborn287952c2010-09-22 22:34:31 -070013853 if (doWakeKills && realtimeSince > 0
13854 && ((wtimeUsed*100)/realtimeSince) >= 50) {
13855 synchronized (stats) {
13856 stats.reportExcessiveWakeLocked(app.info.uid, app.processName,
13857 realtimeSince, wtimeUsed);
13858 }
13859 Slog.w(TAG, "Excessive wake lock in " + app.processName
13860 + " (pid " + app.pid + "): held " + wtimeUsed
13861 + " during " + realtimeSince);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013862 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13863 app.processName, app.setAdj, "excessive wake lock");
13864 Process.killProcessQuiet(app.pid);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013865 } else if (doCpuKills && uptimeSince > 0
13866 && ((cputimeUsed*100)/uptimeSince) >= 50) {
13867 synchronized (stats) {
13868 stats.reportExcessiveCpuLocked(app.info.uid, app.processName,
13869 uptimeSince, cputimeUsed);
13870 }
13871 Slog.w(TAG, "Excessive CPU in " + app.processName
13872 + " (pid " + app.pid + "): used " + cputimeUsed
13873 + " during " + uptimeSince);
13874 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13875 app.processName, app.setAdj, "excessive cpu");
13876 Process.killProcessQuiet(app.pid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013877 } else {
13878 app.lastWakeTime = wtime;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013879 app.lastCpuTime = app.curCpuTime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013880 }
13881 }
13882 }
13883 }
13884
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013885 private final boolean updateOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013886 ProcessRecord app, int hiddenAdj, ProcessRecord TOP_APP, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013887 app.hiddenAdj = hiddenAdj;
13888
13889 if (app.thread == null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013890 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013891 }
13892
Dianne Hackborn287952c2010-09-22 22:34:31 -070013893 final boolean wasKeeping = app.keeping;
13894
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013895 boolean success = true;
13896
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013897 computeOomAdjLocked(app, hiddenAdj, TOP_APP, false, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013898
Jeff Brown10e89712011-07-08 18:52:57 -070013899 if (app.curRawAdj != app.setRawAdj) {
Dianne Hackborn905577f2011-09-07 18:31:28 -070013900 if (false) {
13901 // Removing for now. Forcing GCs is not so useful anymore
13902 // with Dalvik, and the new memory level hint facility is
13903 // better for what we need to do these days.
13904 if (app.curRawAdj > ProcessList.FOREGROUND_APP_ADJ
13905 && app.setRawAdj <= ProcessList.FOREGROUND_APP_ADJ) {
13906 // If this app is transitioning from foreground to
13907 // non-foreground, have it do a gc.
13908 scheduleAppGcLocked(app);
13909 } else if (app.curRawAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13910 && app.setRawAdj < ProcessList.HIDDEN_APP_MIN_ADJ) {
13911 // Likewise do a gc when an app is moving in to the
13912 // background (such as a service stopping).
13913 scheduleAppGcLocked(app);
13914 }
Jeff Brown10e89712011-07-08 18:52:57 -070013915 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013916
Jeff Brown10e89712011-07-08 18:52:57 -070013917 if (wasKeeping && !app.keeping) {
13918 // This app is no longer something we want to keep. Note
13919 // its current wake lock time to later know to kill it if
13920 // it is not behaving well.
13921 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
13922 synchronized (stats) {
13923 app.lastWakeTime = stats.getProcessWakeTime(app.info.uid,
13924 app.pid, SystemClock.elapsedRealtime());
13925 }
13926 app.lastCpuTime = app.curCpuTime;
13927 }
13928
13929 app.setRawAdj = app.curRawAdj;
13930 }
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013931
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013932 if (app.curAdj != app.setAdj) {
13933 if (Process.setOomAdj(app.pid, app.curAdj)) {
Dianne Hackbornbbb09ac2011-11-30 11:31:29 -080013934 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013935 TAG, "Set " + app.pid + " " + app.processName +
13936 " adj " + app.curAdj + ": " + app.adjType);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013937 app.setAdj = app.curAdj;
Jeff Brown10e89712011-07-08 18:52:57 -070013938 } else {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013939 success = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013940 Slog.w(TAG, "Failed setting oom adj of " + app + " to " + app.curAdj);
Jeff Brown10e89712011-07-08 18:52:57 -070013941 }
13942 }
13943 if (app.setSchedGroup != app.curSchedGroup) {
13944 app.setSchedGroup = app.curSchedGroup;
13945 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
13946 "Setting process group of " + app.processName
13947 + " to " + app.curSchedGroup);
13948 if (app.waitingToKill != null &&
13949 app.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
13950 Slog.i(TAG, "Killing " + app.toShortString() + ": " + app.waitingToKill);
13951 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13952 app.processName, app.setAdj, app.waitingToKill);
13953 Process.killProcessQuiet(app.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013954 success = false;
Jeff Brown10e89712011-07-08 18:52:57 -070013955 } else {
13956 if (true) {
13957 long oldId = Binder.clearCallingIdentity();
13958 try {
13959 Process.setProcessGroup(app.pid, app.curSchedGroup);
13960 } catch (Exception e) {
13961 Slog.w(TAG, "Failed setting process group of " + app.pid
13962 + " to " + app.curSchedGroup);
13963 e.printStackTrace();
13964 } finally {
13965 Binder.restoreCallingIdentity(oldId);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013966 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013967 } else {
Jeff Brown10e89712011-07-08 18:52:57 -070013968 if (app.thread != null) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070013969 try {
Jeff Brown10e89712011-07-08 18:52:57 -070013970 app.thread.setSchedulingGroup(app.curSchedGroup);
13971 } catch (RemoteException e) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070013972 }
13973 }
13974 }
13975 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013976 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013977 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013978 }
13979
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013980 private final ActivityRecord resumedAppLocked() {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013981 ActivityRecord resumedActivity = mMainStack.mResumedActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013982 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -080013983 resumedActivity = mMainStack.mPausingActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013984 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013985 resumedActivity = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013986 }
13987 }
13988 return resumedActivity;
13989 }
13990
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013991 private final boolean updateOomAdjLocked(ProcessRecord app) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013992 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013993 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
13994 int curAdj = app.curAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013995 final boolean wasHidden = curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13996 && curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013997
13998 mAdjSeq++;
13999
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014000 boolean success = updateOomAdjLocked(app, app.hiddenAdj, TOP_APP, false);
Dianne Hackborn7d608422011-08-07 16:24:18 -070014001 final boolean nowHidden = app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
14002 && app.curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014003 if (nowHidden != wasHidden) {
14004 // Changed to/from hidden state, so apps after it in the LRU
14005 // list may also be changed.
14006 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014007 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014008 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014009 }
14010
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014011 final void updateOomAdjLocked() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014012 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014013 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
14014
14015 if (false) {
14016 RuntimeException e = new RuntimeException();
14017 e.fillInStackTrace();
Joe Onorato8a9b2202010-02-26 18:56:32 -080014018 Slog.i(TAG, "updateOomAdj: top=" + TOP_ACT, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014019 }
14020
14021 mAdjSeq++;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014022 mNewNumServiceProcs = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014023
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014024 // Let's determine how many processes we have running vs.
14025 // how many slots we have for background processes; we may want
14026 // to put multiple processes in a slot of there are enough of
14027 // them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014028 int numSlots = ProcessList.HIDDEN_APP_MAX_ADJ - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014029 int factor = (mLruProcesses.size()-4)/numSlots;
14030 if (factor < 1) factor = 1;
14031 int step = 0;
Dianne Hackborn8633e682010-04-22 16:03:41 -070014032 int numHidden = 0;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014033
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014034 // First update the OOM adjustment for each of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014035 // application processes based on their current state.
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014036 int i = mLruProcesses.size();
Dianne Hackborn7d608422011-08-07 16:24:18 -070014037 int curHiddenAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014038 while (i > 0) {
14039 i--;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014040 ProcessRecord app = mLruProcesses.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080014041 //Slog.i(TAG, "OOM " + app + ": cur hidden=" + curHiddenAdj);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014042 updateOomAdjLocked(app, curHiddenAdj, TOP_APP, true);
14043 if (curHiddenAdj < ProcessList.HIDDEN_APP_MAX_ADJ
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014044 && app.curAdj == curHiddenAdj) {
14045 step++;
14046 if (step >= factor) {
14047 step = 0;
14048 curHiddenAdj++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014049 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014050 }
14051 if (!app.killedBackground) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070014052 if (app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014053 numHidden++;
14054 if (numHidden > mProcessLimit) {
14055 Slog.i(TAG, "No longer want " + app.processName
14056 + " (pid " + app.pid + "): hidden #" + numHidden);
14057 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14058 app.processName, app.setAdj, "too many background");
14059 app.killedBackground = true;
14060 Process.killProcessQuiet(app.pid);
Dianne Hackborn8633e682010-04-22 16:03:41 -070014061 }
14062 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -080014063 if (!app.killedBackground && app.isolated && app.services.size() <= 0) {
14064 // If this is an isolated process, and there are no
14065 // services running in it, then the process is no longer
14066 // needed. We agressively kill these because we can by
14067 // definition not re-use the same process again, and it is
14068 // good to avoid having whatever code was running in them
14069 // left sitting around after no longer needed.
14070 Slog.i(TAG, "Isolated process " + app.processName
14071 + " (pid " + app.pid + ") no longer needed");
14072 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14073 app.processName, app.setAdj, "isolated not needed");
14074 app.killedBackground = true;
14075 Process.killProcessQuiet(app.pid);
14076 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014077 }
14078 }
14079
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014080 mNumServiceProcs = mNewNumServiceProcs;
14081
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014082 // Now determine the memory trimming level of background processes.
14083 // Unfortunately we need to start at the back of the list to do this
14084 // properly. We only do this if the number of background apps we
14085 // are managing to keep around is less than half the maximum we desire;
14086 // if we are keeping a good number around, we'll let them use whatever
14087 // memory they want.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014088 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/2)) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014089 final int N = mLruProcesses.size();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080014090 factor = numHidden/3;
14091 int minFactor = 2;
14092 if (mHomeProcess != null) minFactor++;
14093 if (mPreviousProcess != null) minFactor++;
14094 if (factor < minFactor) factor = minFactor;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014095 step = 0;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014096 int fgTrimLevel;
14097 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/5)) {
14098 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL;
14099 } else if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/3)) {
14100 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW;
14101 } else {
14102 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE;
14103 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014104 int curLevel = ComponentCallbacks2.TRIM_MEMORY_COMPLETE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014105 for (i=0; i<N; i++) {
14106 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080014107 if (app.curAdj >= ProcessList.HOME_APP_ADJ
14108 && app.curAdj != ProcessList.SERVICE_B_ADJ
14109 && !app.killedBackground) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014110 if (app.trimMemoryLevel < curLevel && app.thread != null) {
14111 try {
14112 app.thread.scheduleTrimMemory(curLevel);
14113 } catch (RemoteException e) {
14114 }
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080014115 if (false) {
14116 // For now we won't do this; our memory trimming seems
14117 // to be good enough at this point that destroying
14118 // activities causes more harm than good.
14119 if (curLevel >= ComponentCallbacks2.TRIM_MEMORY_COMPLETE
14120 && app != mHomeProcess && app != mPreviousProcess) {
14121 // For these apps we will also finish their activities
14122 // to help them free memory.
14123 mMainStack.destroyActivitiesLocked(app, false, "trim");
14124 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014125 }
14126 }
14127 app.trimMemoryLevel = curLevel;
14128 step++;
14129 if (step >= factor) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014130 step = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014131 switch (curLevel) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014132 case ComponentCallbacks2.TRIM_MEMORY_COMPLETE:
14133 curLevel = ComponentCallbacks2.TRIM_MEMORY_MODERATE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014134 break;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014135 case ComponentCallbacks2.TRIM_MEMORY_MODERATE:
14136 curLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014137 break;
14138 }
14139 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070014140 } else if (app.curAdj == ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014141 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014142 && app.thread != null) {
14143 try {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014144 app.thread.scheduleTrimMemory(
14145 ComponentCallbacks2.TRIM_MEMORY_BACKGROUND);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014146 } catch (RemoteException e) {
14147 }
14148 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014149 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014150 } else {
14151 if ((app.curAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
14152 && app.pendingUiClean) {
14153 // If this application is now in the background and it
14154 // had done UI, then give it the special trim level to
14155 // have it free UI resources.
14156 final int level = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
14157 if (app.trimMemoryLevel < level && app.thread != null) {
14158 try {
14159 app.thread.scheduleTrimMemory(level);
14160 } catch (RemoteException e) {
14161 }
14162 }
14163 app.pendingUiClean = false;
14164 }
14165 if (app.trimMemoryLevel < fgTrimLevel && app.thread != null) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014166 try {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014167 app.thread.scheduleTrimMemory(fgTrimLevel);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014168 } catch (RemoteException e) {
14169 }
14170 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014171 app.trimMemoryLevel = fgTrimLevel;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014172 }
14173 }
14174 } else {
14175 final int N = mLruProcesses.size();
14176 for (i=0; i<N; i++) {
14177 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -070014178 if ((app.curAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014179 && app.pendingUiClean) {
14180 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
14181 && app.thread != null) {
14182 try {
14183 app.thread.scheduleTrimMemory(
14184 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
14185 } catch (RemoteException e) {
14186 }
14187 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014188 app.pendingUiClean = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014189 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014190 app.trimMemoryLevel = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014191 }
14192 }
14193
14194 if (mAlwaysFinishActivities) {
Dianne Hackborn28695e02011-11-02 21:59:51 -070014195 mMainStack.destroyActivitiesLocked(null, false, "always-finish");
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014196 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014197 }
14198
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014199 final void trimApplications() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014200 synchronized (this) {
14201 int i;
14202
14203 // First remove any unused application processes whose package
14204 // has been removed.
14205 for (i=mRemovedProcesses.size()-1; i>=0; i--) {
14206 final ProcessRecord app = mRemovedProcesses.get(i);
14207 if (app.activities.size() == 0
14208 && app.curReceiver == null && app.services.size() == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080014209 Slog.i(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014210 TAG, "Exiting empty application process "
14211 + app.processName + " ("
14212 + (app.thread != null ? app.thread.asBinder() : null)
14213 + ")\n");
14214 if (app.pid > 0 && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070014215 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14216 app.processName, app.setAdj, "empty");
14217 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014218 } else {
14219 try {
14220 app.thread.scheduleExit();
14221 } catch (Exception e) {
14222 // Ignore exceptions.
14223 }
14224 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070014225 cleanUpApplicationRecordLocked(app, false, true, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014226 mRemovedProcesses.remove(i);
14227
14228 if (app.persistent) {
14229 if (app.persistent) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080014230 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014231 }
14232 }
14233 }
14234 }
14235
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014236 // Now update the oom adj for all processes.
14237 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014238 }
14239 }
14240
14241 /** This method sends the specified signal to each of the persistent apps */
14242 public void signalPersistentProcesses(int sig) throws RemoteException {
14243 if (sig != Process.SIGNAL_USR1) {
14244 throw new SecurityException("Only SIGNAL_USR1 is allowed");
14245 }
14246
14247 synchronized (this) {
14248 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
14249 != PackageManager.PERMISSION_GRANTED) {
14250 throw new SecurityException("Requires permission "
14251 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
14252 }
14253
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014254 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
14255 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014256 if (r.thread != null && r.persistent) {
14257 Process.sendSignal(r.pid, sig);
14258 }
14259 }
14260 }
14261 }
14262
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014263 private void stopProfilerLocked(ProcessRecord proc, String path, int profileType) {
14264 if (proc == null || proc == mProfileProc) {
14265 proc = mProfileProc;
14266 path = mProfileFile;
14267 profileType = mProfileType;
14268 clearProfilerLocked();
14269 }
14270 if (proc == null) {
14271 return;
14272 }
14273 try {
14274 proc.thread.profilerControl(false, path, null, profileType);
14275 } catch (RemoteException e) {
14276 throw new IllegalStateException("Process disappeared");
14277 }
14278 }
14279
14280 private void clearProfilerLocked() {
14281 if (mProfileFd != null) {
14282 try {
14283 mProfileFd.close();
14284 } catch (IOException e) {
14285 }
14286 }
14287 mProfileApp = null;
14288 mProfileProc = null;
14289 mProfileFile = null;
14290 mProfileType = 0;
14291 mAutoStopProfiler = false;
14292 }
14293
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014294 public boolean profileControl(String process, boolean start,
Romain Guy7eabe552011-07-21 14:56:34 -070014295 String path, ParcelFileDescriptor fd, int profileType) throws RemoteException {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014296
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014297 try {
14298 synchronized (this) {
14299 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14300 // its own permission.
14301 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14302 != PackageManager.PERMISSION_GRANTED) {
14303 throw new SecurityException("Requires permission "
14304 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014305 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014306
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014307 if (start && fd == null) {
14308 throw new IllegalArgumentException("null fd");
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014309 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014310
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014311 ProcessRecord proc = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014312 if (process != null) {
14313 try {
14314 int pid = Integer.parseInt(process);
14315 synchronized (mPidsSelfLocked) {
14316 proc = mPidsSelfLocked.get(pid);
14317 }
14318 } catch (NumberFormatException e) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014319 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014320
14321 if (proc == null) {
14322 HashMap<String, SparseArray<ProcessRecord>> all
14323 = mProcessNames.getMap();
14324 SparseArray<ProcessRecord> procs = all.get(process);
14325 if (procs != null && procs.size() > 0) {
14326 proc = procs.valueAt(0);
14327 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014328 }
14329 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014330
14331 if (start && (proc == null || proc.thread == null)) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014332 throw new IllegalArgumentException("Unknown process: " + process);
14333 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014334
14335 if (start) {
14336 stopProfilerLocked(null, null, 0);
14337 setProfileApp(proc.info, proc.processName, path, fd, false);
14338 mProfileProc = proc;
14339 mProfileType = profileType;
14340 try {
14341 fd = fd.dup();
14342 } catch (IOException e) {
14343 fd = null;
14344 }
14345 proc.thread.profilerControl(start, path, fd, profileType);
14346 fd = null;
14347 mProfileFd = null;
14348 } else {
14349 stopProfilerLocked(proc, path, profileType);
14350 if (fd != null) {
14351 try {
14352 fd.close();
14353 } catch (IOException e) {
14354 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014355 }
14356 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014357
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014358 return true;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014359 }
14360 } catch (RemoteException e) {
14361 throw new IllegalStateException("Process disappeared");
14362 } finally {
14363 if (fd != null) {
14364 try {
14365 fd.close();
14366 } catch (IOException e) {
14367 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014368 }
14369 }
14370 }
Andy McFadden824c5102010-07-09 16:26:57 -070014371
14372 public boolean dumpHeap(String process, boolean managed,
14373 String path, ParcelFileDescriptor fd) throws RemoteException {
14374
14375 try {
14376 synchronized (this) {
14377 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14378 // its own permission (same as profileControl).
14379 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14380 != PackageManager.PERMISSION_GRANTED) {
14381 throw new SecurityException("Requires permission "
14382 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
14383 }
14384
14385 if (fd == null) {
14386 throw new IllegalArgumentException("null fd");
14387 }
14388
14389 ProcessRecord proc = null;
14390 try {
14391 int pid = Integer.parseInt(process);
14392 synchronized (mPidsSelfLocked) {
14393 proc = mPidsSelfLocked.get(pid);
14394 }
14395 } catch (NumberFormatException e) {
14396 }
14397
14398 if (proc == null) {
14399 HashMap<String, SparseArray<ProcessRecord>> all
14400 = mProcessNames.getMap();
14401 SparseArray<ProcessRecord> procs = all.get(process);
14402 if (procs != null && procs.size() > 0) {
14403 proc = procs.valueAt(0);
14404 }
14405 }
14406
14407 if (proc == null || proc.thread == null) {
14408 throw new IllegalArgumentException("Unknown process: " + process);
14409 }
14410
Dianne Hackbornf02e57b2011-03-01 22:21:04 -080014411 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
14412 if (!isDebuggable) {
Andy McFadden824c5102010-07-09 16:26:57 -070014413 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
14414 throw new SecurityException("Process not debuggable: " + proc);
14415 }
14416 }
14417
14418 proc.thread.dumpHeap(managed, path, fd);
14419 fd = null;
14420 return true;
14421 }
14422 } catch (RemoteException e) {
14423 throw new IllegalStateException("Process disappeared");
14424 } finally {
14425 if (fd != null) {
14426 try {
14427 fd.close();
14428 } catch (IOException e) {
14429 }
14430 }
14431 }
14432 }
14433
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014434 /** In this method we try to acquire our lock to make sure that we have not deadlocked */
14435 public void monitor() {
14436 synchronized (this) { }
14437 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014438
Dianne Hackborna573f6a2012-02-09 16:12:18 -080014439 void onCoreSettingsChange(Bundle settings) {
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014440 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
14441 ProcessRecord processRecord = mLruProcesses.get(i);
14442 try {
14443 if (processRecord.thread != null) {
14444 processRecord.thread.setCoreSettings(settings);
14445 }
14446 } catch (RemoteException re) {
14447 /* ignore */
14448 }
14449 }
14450 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014451
14452 // Multi-user methods
14453
Amith Yamasani742a6712011-05-04 14:49:28 -070014454 private int mCurrentUserId;
14455 private SparseIntArray mLoggedInUsers = new SparseIntArray(5);
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014456 private ArrayList<UserListener> mUserListeners = new ArrayList<UserListener>(3);
14457
14458 public interface UserListener {
14459 public void onUserChanged(int userId);
14460
14461 public void onUserAdded(int userId);
14462
14463 public void onUserRemoved(int userId);
14464
14465 public void onUserLoggedOut(int userId);
14466 }
14467
14468 public void addUserListener(UserListener listener) {
14469 synchronized (this) {
14470 if (!mUserListeners.contains(listener)) {
14471 mUserListeners.add(listener);
14472 }
14473 }
14474 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014475
14476 public boolean switchUser(int userId) {
14477 final int callingUid = Binder.getCallingUid();
14478 if (callingUid != 0 && callingUid != Process.myUid()) {
14479 Slog.e(TAG, "Trying to switch user from unauthorized app");
14480 return false;
14481 }
14482 if (mCurrentUserId == userId)
14483 return true;
14484
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014485 ArrayList<UserListener> listeners;
14486
Amith Yamasani742a6712011-05-04 14:49:28 -070014487 synchronized (this) {
14488 // Check if user is already logged in, otherwise check if user exists first before
14489 // adding to the list of logged in users.
14490 if (mLoggedInUsers.indexOfKey(userId) < 0) {
14491 if (!userExists(userId)) {
14492 return false;
14493 }
14494 mLoggedInUsers.append(userId, userId);
14495 }
14496
14497 mCurrentUserId = userId;
14498 boolean haveActivities = mMainStack.switchUser(userId);
14499 if (!haveActivities) {
14500 startHomeActivityLocked(userId);
14501 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014502
14503 listeners = (ArrayList<UserListener>) mUserListeners.clone();
14504 }
14505 // Inform the listeners
14506 for (UserListener listener : listeners) {
14507 listener.onUserChanged(userId);
Amith Yamasani742a6712011-05-04 14:49:28 -070014508 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014509 return true;
14510 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014511
14512 private boolean userExists(int userId) {
14513 try {
14514 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
14515 for (UserInfo user : users) {
14516 if (user.id == userId) {
14517 return true;
14518 }
14519 }
14520 } catch (RemoteException re) {
14521 // Won't happen, in same process
14522 }
14523
14524 return false;
14525 }
14526
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014527 private void checkValidCaller(int uid, int userId) {
14528 if (UserId.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) return;
14529
14530 throw new SecurityException("Caller uid=" + uid
14531 + " is not privileged to communicate with user=" + userId);
14532 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014533
14534 private int applyUserId(int uid, int userId) {
14535 return UserId.getUid(userId, uid);
14536 }
14537
14538 private ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080014539 if (info == null) return null;
Amith Yamasani742a6712011-05-04 14:49:28 -070014540 ApplicationInfo newInfo = new ApplicationInfo(info);
14541 newInfo.uid = applyUserId(info.uid, userId);
14542 if (newInfo.uid >= Process.FIRST_APPLICATION_UID) {
14543 newInfo.dataDir = USER_DATA_DIR + userId + "/"
14544 + info.packageName;
14545 }
14546 return newInfo;
14547 }
14548
14549 ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080014550 if (aInfo == null || aInfo.applicationInfo.uid < Process.FIRST_APPLICATION_UID
Amith Yamasani742a6712011-05-04 14:49:28 -070014551 || userId < 1) {
14552 return aInfo;
14553 }
14554
14555 ActivityInfo info = new ActivityInfo(aInfo);
14556 info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId);
14557 return info;
14558 }
14559
14560 static class ServiceMap {
14561
14562 private final SparseArray<HashMap<ComponentName, ServiceRecord>> mServicesByNamePerUser
14563 = new SparseArray<HashMap<ComponentName, ServiceRecord>>();
14564 private final SparseArray<HashMap<Intent.FilterComparison, ServiceRecord>>
14565 mServicesByIntentPerUser = new SparseArray<
14566 HashMap<Intent.FilterComparison, ServiceRecord>>();
14567
14568 ServiceRecord getServiceByName(ComponentName name, int callingUser) {
14569 // TODO: Deal with global services
14570 if (DEBUG_MU)
14571 Slog.v(TAG_MU, "getServiceByName(" + name + "), callingUser = " + callingUser);
14572 return getServices(callingUser).get(name);
14573 }
14574
14575 ServiceRecord getServiceByName(ComponentName name) {
14576 return getServiceByName(name, -1);
14577 }
14578
14579 ServiceRecord getServiceByIntent(Intent.FilterComparison filter, int callingUser) {
14580 // TODO: Deal with global services
14581 if (DEBUG_MU)
14582 Slog.v(TAG_MU, "getServiceByIntent(" + filter + "), callingUser = " + callingUser);
14583 return getServicesByIntent(callingUser).get(filter);
14584 }
14585
14586 ServiceRecord getServiceByIntent(Intent.FilterComparison filter) {
14587 return getServiceByIntent(filter, -1);
14588 }
14589
14590 void putServiceByName(ComponentName name, int callingUser, ServiceRecord value) {
14591 // TODO: Deal with global services
14592 getServices(callingUser).put(name, value);
14593 }
14594
14595 void putServiceByIntent(Intent.FilterComparison filter, int callingUser,
14596 ServiceRecord value) {
14597 // TODO: Deal with global services
14598 getServicesByIntent(callingUser).put(filter, value);
14599 }
14600
14601 void removeServiceByName(ComponentName name, int callingUser) {
14602 // TODO: Deal with global services
14603 ServiceRecord removed = getServices(callingUser).remove(name);
14604 if (DEBUG_MU)
14605 Slog.v(TAG, "removeServiceByName user=" + callingUser + " name=" + name
14606 + " removed=" + removed);
14607 }
14608
14609 void removeServiceByIntent(Intent.FilterComparison filter, int callingUser) {
14610 // TODO: Deal with global services
14611 ServiceRecord removed = getServicesByIntent(callingUser).remove(filter);
14612 if (DEBUG_MU)
14613 Slog.v(TAG_MU, "removeServiceByIntent user=" + callingUser + " intent=" + filter
14614 + " removed=" + removed);
14615 }
14616
14617 Collection<ServiceRecord> getAllServices(int callingUser) {
14618 // TODO: Deal with global services
14619 return getServices(callingUser).values();
14620 }
14621
14622 private HashMap<ComponentName, ServiceRecord> getServices(int callingUser) {
14623 HashMap map = mServicesByNamePerUser.get(callingUser);
14624 if (map == null) {
14625 map = new HashMap<ComponentName, ServiceRecord>();
14626 mServicesByNamePerUser.put(callingUser, map);
14627 }
14628 return map;
14629 }
14630
14631 private HashMap<Intent.FilterComparison, ServiceRecord> getServicesByIntent(
14632 int callingUser) {
14633 HashMap map = mServicesByIntentPerUser.get(callingUser);
14634 if (map == null) {
14635 map = new HashMap<Intent.FilterComparison, ServiceRecord>();
14636 mServicesByIntentPerUser.put(callingUser, map);
14637 }
14638 return map;
14639 }
14640 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014641}