blob: ce597adf5c5b5227d8d3f2b9fa7ddd2fe6cbc5ad [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
Dianne Hackborn860755f2010-06-03 18:47:52 -070019import com.android.internal.R;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080020import com.android.internal.os.BatteryStatsImpl;
Dianne Hackborn45ce8642011-07-14 16:10:16 -070021import com.android.internal.os.ProcessStats;
Dianne Hackbornde7faf62009-06-30 13:27:30 -070022import com.android.server.AttributeCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080023import com.android.server.IntentResolver;
24import com.android.server.ProcessMap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025import com.android.server.SystemServer;
26import com.android.server.Watchdog;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070027import com.android.server.am.ActivityStack.ActivityState;
Dianne Hackborna924dc0d2011-02-17 14:22:17 -080028import com.android.server.wm.WindowManagerService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080029
Dianne Hackborndd71fc82009-12-16 19:24:32 -080030import dalvik.system.Zygote;
31
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080032import android.app.Activity;
33import android.app.ActivityManager;
34import android.app.ActivityManagerNative;
35import android.app.ActivityThread;
36import android.app.AlertDialog;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070037import android.app.AppGlobals;
Jacek Surazskif5b9c722009-05-18 12:09:59 +020038import android.app.ApplicationErrorReport;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039import android.app.Dialog;
Dianne Hackbornb06ea702009-07-13 13:07:51 -070040import android.app.IActivityController;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.app.IApplicationThread;
42import android.app.IInstrumentationWatcher;
Dianne Hackborn860755f2010-06-03 18:47:52 -070043import android.app.INotificationManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -070044import android.app.IProcessObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import android.app.IServiceConnection;
46import android.app.IThumbnailReceiver;
47import android.app.Instrumentation;
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070048import android.app.Notification;
Dianne Hackborn860755f2010-06-03 18:47:52 -070049import android.app.NotificationManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050import android.app.PendingIntent;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070051import android.app.Service;
Christopher Tate45281862010-03-05 15:46:30 -080052import android.app.backup.IBackupManager;
Jacek Surazskif5b9c722009-05-18 12:09:59 +020053import android.content.ActivityNotFoundException;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -080054import android.content.BroadcastReceiver;
Dianne Hackborn21c241e2012-03-08 13:57:23 -080055import android.content.ClipData;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070056import android.content.ComponentCallbacks2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080057import android.content.ComponentName;
58import android.content.ContentResolver;
59import android.content.Context;
Christian Mehlmauer7664e202010-07-20 08:46:17 +020060import android.content.DialogInterface;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061import android.content.Intent;
62import android.content.IntentFilter;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070063import android.content.IIntentReceiver;
64import android.content.IIntentSender;
Dianne Hackbornfa82f222009-09-17 15:14:12 -070065import android.content.IntentSender;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066import android.content.pm.ActivityInfo;
67import android.content.pm.ApplicationInfo;
68import android.content.pm.ConfigurationInfo;
69import android.content.pm.IPackageDataObserver;
70import android.content.pm.IPackageManager;
71import android.content.pm.InstrumentationInfo;
Dan Egnor66c40e72010-01-26 16:23:11 -080072import android.content.pm.PackageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073import android.content.pm.PackageManager;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070074import android.content.pm.PathPermission;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075import android.content.pm.ProviderInfo;
76import android.content.pm.ResolveInfo;
77import android.content.pm.ServiceInfo;
Amith Yamasani742a6712011-05-04 14:49:28 -070078import android.content.pm.UserInfo;
Dianne Hackborn860755f2010-06-03 18:47:52 -070079import android.content.pm.PackageManager.NameNotFoundException;
Dianne Hackborne2515ee2011-04-27 18:52:56 -040080import android.content.res.CompatibilityInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080081import android.content.res.Configuration;
82import android.graphics.Bitmap;
Robert Greenwalt434203a2010-10-11 16:00:27 -070083import android.net.Proxy;
84import android.net.ProxyProperties;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085import android.net.Uri;
86import android.os.Binder;
Dan Egnor60d87622009-12-16 16:32:58 -080087import android.os.Build;
Dan Egnor42471dd2010-01-07 17:25:22 -080088import android.os.Bundle;
Dianne Hackborn3025ef32009-08-31 21:31:47 -070089import android.os.Debug;
Dan Egnor60d87622009-12-16 16:32:58 -080090import android.os.DropBoxManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080091import android.os.Environment;
Dan Egnor42471dd2010-01-07 17:25:22 -080092import android.os.FileObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080093import android.os.FileUtils;
94import android.os.Handler;
95import android.os.IBinder;
96import android.os.IPermissionController;
97import android.os.Looper;
98import android.os.Message;
99import android.os.Parcel;
100import android.os.ParcelFileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800101import android.os.Process;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700102import android.os.RemoteCallbackList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800103import android.os.RemoteException;
104import android.os.ServiceManager;
Brad Fitzpatrick46d42382010-06-11 13:57:58 -0700105import android.os.StrictMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106import android.os.SystemClock;
107import android.os.SystemProperties;
Amith Yamasani742a6712011-05-04 14:49:28 -0700108import android.os.UserId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800109import android.provider.Settings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110import android.util.EventLog;
Dianne Hackborn905577f2011-09-07 18:31:28 -0700111import android.util.Pair;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800112import android.util.Slog;
Joe Onorato5d3bea62010-03-01 13:44:29 -0800113import android.util.Log;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800114import android.util.PrintWriterPrinter;
115import android.util.SparseArray;
Amith Yamasani742a6712011-05-04 14:49:28 -0700116import android.util.SparseIntArray;
Dianne Hackborn1ebccf52010-08-15 13:04:34 -0700117import android.util.TimeUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118import android.view.Gravity;
119import android.view.LayoutInflater;
120import android.view.View;
121import android.view.WindowManager;
122import android.view.WindowManagerPolicy;
123
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700124import java.io.BufferedInputStream;
125import java.io.BufferedOutputStream;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700126import java.io.BufferedReader;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700127import java.io.DataInputStream;
128import java.io.DataOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800129import java.io.File;
130import java.io.FileDescriptor;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700131import java.io.FileInputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800132import java.io.FileNotFoundException;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700133import java.io.FileOutputStream;
Jacek Surazskif5b9c722009-05-18 12:09:59 +0200134import java.io.IOException;
Dan Egnora455d192010-03-12 08:52:28 -0800135import java.io.InputStreamReader;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800136import java.io.PrintWriter;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700137import java.io.StringWriter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800138import java.lang.IllegalStateException;
139import java.lang.ref.WeakReference;
140import java.util.ArrayList;
Amith Yamasani742a6712011-05-04 14:49:28 -0700141import java.util.Collection;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700142import java.util.Collections;
143import java.util.Comparator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800144import java.util.HashMap;
145import java.util.HashSet;
146import java.util.Iterator;
147import java.util.List;
148import java.util.Locale;
149import java.util.Map;
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -0700150import java.util.Set;
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700151import java.util.concurrent.atomic.AtomicBoolean;
152import java.util.concurrent.atomic.AtomicLong;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800153
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700154public final class ActivityManagerService extends ActivityManagerNative
155 implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
Amith Yamasani742a6712011-05-04 14:49:28 -0700156 private static final String USER_DATA_DIR = "/data/user/";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800157 static final String TAG = "ActivityManager";
Amith Yamasani742a6712011-05-04 14:49:28 -0700158 static final String TAG_MU = "ActivityManagerServiceMU";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800159 static final boolean DEBUG = false;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400160 static final boolean localLOGV = DEBUG;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800161 static final boolean DEBUG_SWITCH = localLOGV || false;
162 static final boolean DEBUG_TASKS = localLOGV || false;
163 static final boolean DEBUG_PAUSE = localLOGV || false;
164 static final boolean DEBUG_OOM_ADJ = localLOGV || false;
165 static final boolean DEBUG_TRANSITION = localLOGV || false;
166 static final boolean DEBUG_BROADCAST = localLOGV || false;
Christopher Tatef46723b2012-01-26 14:19:24 -0800167 static final boolean DEBUG_BACKGROUND_BROADCAST = DEBUG_BROADCAST || false;
Dianne Hackborn82f3f002009-06-16 18:49:05 -0700168 static final boolean DEBUG_BROADCAST_LIGHT = DEBUG_BROADCAST || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800169 static final boolean DEBUG_SERVICE = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700170 static final boolean DEBUG_SERVICE_EXECUTING = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800171 static final boolean DEBUG_VISBILITY = localLOGV || false;
172 static final boolean DEBUG_PROCESSES = localLOGV || false;
Dianne Hackborna1e989b2009-09-01 19:54:29 -0700173 static final boolean DEBUG_PROVIDER = localLOGV || false;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800174 static final boolean DEBUG_URI_PERMISSION = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800175 static final boolean DEBUG_USER_LEAVING = localLOGV || false;
The Android Open Source Project10592532009-03-18 17:39:46 -0700176 static final boolean DEBUG_RESULTS = localLOGV || false;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -0700177 static final boolean DEBUG_BACKUP = localLOGV || false;
Dianne Hackborndc6b6352009-09-30 14:20:09 -0700178 static final boolean DEBUG_CONFIGURATION = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700179 static final boolean DEBUG_POWER = localLOGV || false;
180 static final boolean DEBUG_POWER_QUICK = DEBUG_POWER || false;
Amith Yamasani742a6712011-05-04 14:49:28 -0700181 static final boolean DEBUG_MU = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800182 static final boolean VALIDATE_TOKENS = false;
183 static final boolean SHOW_ACTIVITY_START_TIME = true;
184
185 // Control over CPU and battery monitoring.
186 static final long BATTERY_STATS_TIME = 30*60*1000; // write battery stats every 30 minutes.
187 static final boolean MONITOR_CPU_USAGE = true;
188 static final long MONITOR_CPU_MIN_TIME = 5*1000; // don't sample cpu less than every 5 seconds.
189 static final long MONITOR_CPU_MAX_TIME = 0x0fffffff; // wait possibly forever for next cpu sample.
190 static final boolean MONITOR_THREAD_CPU_USAGE = false;
191
Dianne Hackborn1655be42009-05-08 14:29:01 -0700192 // The flags that are set for all calls we make to the package manager.
Dianne Hackborn11b822d2009-07-21 20:03:02 -0700193 static final int STOCK_PM_FLAGS = PackageManager.GET_SHARED_LIBRARY_FILES;
Dianne Hackborn1655be42009-05-08 14:29:01 -0700194
Dianne Hackbornf02e57b2011-03-01 22:21:04 -0800195 private static final String SYSTEM_DEBUGGABLE = "ro.debuggable";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800196
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800197 // Maximum number of recent tasks that we can remember.
198 static final int MAX_RECENT_TASKS = 20;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700199
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700200 // Amount of time after a call to stopAppSwitches() during which we will
201 // prevent further untrusted switches from happening.
202 static final long APP_SWITCH_DELAY_TIME = 5*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800203
204 // How long we wait for a launched process to attach to the activity manager
205 // before we decide it's never going to come up for real.
206 static final int PROC_START_TIMEOUT = 10*1000;
207
Jeff Brown3f9dd282011-07-08 20:02:19 -0700208 // How long we wait for a launched process to attach to the activity manager
209 // before we decide it's never going to come up for real, when the process was
210 // started with a wrapper for instrumentation (such as Valgrind) because it
211 // could take much longer than usual.
212 static final int PROC_START_TIMEOUT_WITH_WRAPPER = 300*1000;
213
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800214 // How long to wait after going idle before forcing apps to GC.
215 static final int GC_TIMEOUT = 5*1000;
216
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700217 // The minimum amount of time between successive GC requests for a process.
218 static final int GC_MIN_INTERVAL = 60*1000;
219
Dianne Hackborn287952c2010-09-22 22:34:31 -0700220 // The rate at which we check for apps using excessive power -- 15 mins.
221 static final int POWER_CHECK_DELAY = (DEBUG_POWER_QUICK ? 2 : 15) * 60*1000;
222
223 // The minimum sample duration we will allow before deciding we have
224 // enough data on wake locks to start killing things.
225 static final int WAKE_LOCK_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
226
227 // The minimum sample duration we will allow before deciding we have
228 // enough data on CPU usage to start killing things.
229 static final int CPU_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700230
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800231 // How long we allow a receiver to run before giving up on it.
Christopher Tatef46723b2012-01-26 14:19:24 -0800232 static final int BROADCAST_FG_TIMEOUT = 10*1000;
233 static final int BROADCAST_BG_TIMEOUT = 60*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800234
235 // How long we wait for a service to finish executing.
236 static final int SERVICE_TIMEOUT = 20*1000;
237
238 // How long a service needs to be running until restarting its process
239 // is no longer considered to be a relaunch of the service.
240 static final int SERVICE_RESTART_DURATION = 5*1000;
241
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700242 // How long a service needs to be running until it will start back at
243 // SERVICE_RESTART_DURATION after being killed.
244 static final int SERVICE_RESET_RUN_DURATION = 60*1000;
245
246 // Multiplying factor to increase restart duration time by, for each time
247 // a service is killed before it has run for SERVICE_RESET_RUN_DURATION.
248 static final int SERVICE_RESTART_DURATION_FACTOR = 4;
249
250 // The minimum amount of time between restarting services that we allow.
251 // That is, when multiple services are restarting, we won't allow each
252 // to restart less than this amount of time from the last one.
253 static final int SERVICE_MIN_RESTART_TIME_BETWEEN = 10*1000;
254
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800255 // Maximum amount of time for there to be no activity on a service before
256 // we consider it non-essential and allow its process to go on the
257 // LRU background list.
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700258 static final int MAX_SERVICE_INACTIVITY = 30*60*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800259
260 // How long we wait until we timeout on key dispatching.
261 static final int KEY_DISPATCHING_TIMEOUT = 5*1000;
262
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800263 // How long we wait until we timeout on key dispatching during instrumentation.
264 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT = 60*1000;
265
Dan Egnor42471dd2010-01-07 17:25:22 -0800266 static final int MY_PID = Process.myPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800267
268 static final String[] EMPTY_STRING_ARRAY = new String[0];
269
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700270 public ActivityStack mMainStack;
Mike Lockwood3a74bd32011-08-12 13:55:22 -0700271
272 private final boolean mHeadless;
273
Joe Onorato54a4a412011-11-02 20:50:08 -0700274 // Whether we should show our dialogs (ANR, crash, etc) or just perform their
275 // default actuion automatically. Important for devices without direct input
276 // devices.
277 private boolean mShowDialogs = true;
278
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800279 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700280 * Description of a request to start a new activity, which has been held
281 * due to app switches being disabled.
282 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700283 static class PendingActivityLaunch {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700284 ActivityRecord r;
285 ActivityRecord sourceRecord;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700286 Uri[] grantedUriPermissions;
287 int grantedMode;
288 boolean onlyIfNeeded;
289 }
290
291 final ArrayList<PendingActivityLaunch> mPendingActivityLaunches
292 = new ArrayList<PendingActivityLaunch>();
293
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800294
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800295 BroadcastQueue mFgBroadcastQueue;
296 BroadcastQueue mBgBroadcastQueue;
Christopher Tatef46723b2012-01-26 14:19:24 -0800297 // Convenient for easy iteration over the queues. Foreground is first
298 // so that dispatch of foreground broadcasts gets precedence.
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800299 final BroadcastQueue[] mBroadcastQueues = new BroadcastQueue[2];
Christopher Tatef46723b2012-01-26 14:19:24 -0800300
301 BroadcastQueue broadcastQueueForIntent(Intent intent) {
302 final boolean isFg = (intent.getFlags() & Intent.FLAG_RECEIVER_FOREGROUND) != 0;
303 if (DEBUG_BACKGROUND_BROADCAST) {
304 Slog.i(TAG, "Broadcast intent " + intent + " on "
305 + (isFg ? "foreground" : "background")
306 + " queue");
307 }
308 return (isFg) ? mFgBroadcastQueue : mBgBroadcastQueue;
309 }
310
311 BroadcastRecord broadcastRecordForReceiverLocked(IBinder receiver) {
312 for (BroadcastQueue queue : mBroadcastQueues) {
313 BroadcastRecord r = queue.getMatchingOrderedReceiver(receiver);
314 if (r != null) {
315 return r;
316 }
317 }
318 return null;
319 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800320
321 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800322 * Activity we have told the window manager to have key focus.
323 */
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700324 ActivityRecord mFocusedActivity = null;
Dianne Hackbornbfe319e2009-09-21 00:34:05 -0700325 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800326 * List of intents that were used to start the most recent tasks.
327 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700328 final ArrayList<TaskRecord> mRecentTasks = new ArrayList<TaskRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800329
330 /**
Dianne Hackborn7d608422011-08-07 16:24:18 -0700331 * Process management.
332 */
333 final ProcessList mProcessList = new ProcessList();
334
335 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800336 * All of the applications we currently have running organized by name.
337 * The keys are strings of the application package name (as
338 * returned by the package manager), and the keys are ApplicationRecord
339 * objects.
340 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700341 final ProcessMap<ProcessRecord> mProcessNames = new ProcessMap<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800342
343 /**
Dianne Hackborna0c283e2012-02-09 10:47:01 -0800344 * The currently running isolated processes.
345 */
346 final SparseArray<ProcessRecord> mIsolatedProcesses = new SparseArray<ProcessRecord>();
347
348 /**
349 * Counter for assigning isolated process uids, to avoid frequently reusing the
350 * same ones.
351 */
352 int mNextIsolatedProcessUid = 0;
353
354 /**
Dianne Hackborn860755f2010-06-03 18:47:52 -0700355 * The currently running heavy-weight process, if any.
356 */
357 ProcessRecord mHeavyWeightProcess = null;
358
359 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800360 * The last time that various processes have crashed.
361 */
362 final ProcessMap<Long> mProcessCrashTimes = new ProcessMap<Long>();
363
364 /**
365 * Set of applications that we consider to be bad, and will reject
366 * incoming broadcasts from (which the user has no control over).
367 * Processes are added to this set when they have crashed twice within
368 * a minimum amount of time; they are removed from it when they are
369 * later restarted (hopefully due to some user action). The value is the
370 * time it was added to the list.
371 */
372 final ProcessMap<Long> mBadProcesses = new ProcessMap<Long>();
373
374 /**
375 * All of the processes we currently have running organized by pid.
376 * The keys are the pid running the application.
377 *
378 * <p>NOTE: This object is protected by its own lock, NOT the global
379 * activity manager lock!
380 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700381 final SparseArray<ProcessRecord> mPidsSelfLocked = new SparseArray<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800382
383 /**
384 * All of the processes that have been forced to be foreground. The key
385 * is the pid of the caller who requested it (we hold a death
386 * link on it).
387 */
388 abstract class ForegroundToken implements IBinder.DeathRecipient {
389 int pid;
390 IBinder token;
391 }
392 final SparseArray<ForegroundToken> mForegroundProcesses
393 = new SparseArray<ForegroundToken>();
394
395 /**
396 * List of records for processes that someone had tried to start before the
397 * system was ready. We don't start them at that point, but ensure they
398 * are started by the time booting is complete.
399 */
400 final ArrayList<ProcessRecord> mProcessesOnHold
401 = new ArrayList<ProcessRecord>();
402
403 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800404 * List of persistent applications that are in the process
405 * of being started.
406 */
407 final ArrayList<ProcessRecord> mPersistentStartingProcesses
408 = new ArrayList<ProcessRecord>();
409
410 /**
411 * Processes that are being forcibly torn down.
412 */
413 final ArrayList<ProcessRecord> mRemovedProcesses
414 = new ArrayList<ProcessRecord>();
415
416 /**
417 * List of running applications, sorted by recent usage.
418 * The first entry in the list is the least recently used.
419 * It contains ApplicationRecord objects. This list does NOT include
420 * any persistent application records (since we never want to exit them).
421 */
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800422 final ArrayList<ProcessRecord> mLruProcesses
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800423 = new ArrayList<ProcessRecord>();
424
425 /**
426 * List of processes that should gc as soon as things are idle.
427 */
428 final ArrayList<ProcessRecord> mProcessesToGc
429 = new ArrayList<ProcessRecord>();
430
431 /**
The Android Open Source Project4df24232009-03-05 14:34:35 -0800432 * This is the process holding what we currently consider to be
433 * the "home" activity.
434 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700435 ProcessRecord mHomeProcess;
The Android Open Source Project4df24232009-03-05 14:34:35 -0800436
437 /**
Dianne Hackbornf35fe232011-11-01 19:25:20 -0700438 * This is the process holding the activity the user last visited that
439 * is in a different process from the one they are currently in.
440 */
441 ProcessRecord mPreviousProcess;
Dianne Hackborn50685602011-12-01 12:23:37 -0800442
443 /**
444 * The time at which the previous process was last visible.
445 */
446 long mPreviousProcessVisibleTime;
447
Dianne Hackbornf35fe232011-11-01 19:25:20 -0700448 /**
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400449 * Packages that the user has asked to have run in screen size
450 * compatibility mode instead of filling the screen.
451 */
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -0700452 final CompatModePackages mCompatModePackages;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400453
454 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800455 * Set of PendingResultRecord objects that are currently active.
456 */
457 final HashSet mPendingResultRecords = new HashSet();
458
459 /**
460 * Set of IntentSenderRecord objects that are currently active.
461 */
462 final HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>> mIntentSenderRecords
463 = new HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>>();
464
465 /**
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -0800466 * Fingerprints (hashCode()) of stack traces that we've
Brad Fitzpatrick143666f2010-06-14 12:40:21 -0700467 * already logged DropBox entries for. Guarded by itself. If
468 * something (rogue user app) forces this over
469 * MAX_DUP_SUPPRESSED_STACKS entries, the contents are cleared.
470 */
471 private final HashSet<Integer> mAlreadyLoggedViolatedStacks = new HashSet<Integer>();
472 private static final int MAX_DUP_SUPPRESSED_STACKS = 5000;
473
474 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -0700475 * Strict Mode background batched logging state.
476 *
477 * The string buffer is guarded by itself, and its lock is also
478 * used to determine if another batched write is already
479 * in-flight.
480 */
481 private final StringBuilder mStrictModeBuffer = new StringBuilder();
482
483 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800484 * Keeps track of all IIntentReceivers that have been registered for
485 * broadcasts. Hash keys are the receiver IBinder, hash value is
486 * a ReceiverList.
487 */
488 final HashMap mRegisteredReceivers = new HashMap();
489
490 /**
491 * Resolver for broadcast intents to registered receivers.
492 * Holds BroadcastFilter (subclass of IntentFilter).
493 */
494 final IntentResolver<BroadcastFilter, BroadcastFilter> mReceiverResolver
495 = new IntentResolver<BroadcastFilter, BroadcastFilter>() {
496 @Override
497 protected boolean allowFilterResult(
498 BroadcastFilter filter, List<BroadcastFilter> dest) {
499 IBinder target = filter.receiverList.receiver.asBinder();
500 for (int i=dest.size()-1; i>=0; i--) {
501 if (dest.get(i).receiverList.receiver.asBinder() == target) {
502 return false;
503 }
504 }
505 return true;
506 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700507
508 @Override
509 protected String packageForFilter(BroadcastFilter filter) {
510 return filter.packageName;
511 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800512 };
513
514 /**
515 * State of all active sticky broadcasts. Keys are the action of the
516 * sticky Intent, values are an ArrayList of all broadcasted intents with
517 * that action (which should usually be one).
518 */
519 final HashMap<String, ArrayList<Intent>> mStickyBroadcasts =
520 new HashMap<String, ArrayList<Intent>>();
521
Amith Yamasani742a6712011-05-04 14:49:28 -0700522 final ServiceMap mServiceMap = new ServiceMap();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800523
524 /**
525 * All currently bound service connections. Keys are the IBinder of
526 * the client's IServiceConnection.
527 */
Dianne Hackborn43d9ac82010-08-25 15:06:25 -0700528 final HashMap<IBinder, ArrayList<ConnectionRecord>> mServiceConnections
529 = new HashMap<IBinder, ArrayList<ConnectionRecord>>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800530
531 /**
532 * List of services that we have been asked to start,
533 * but haven't yet been able to. It is used to hold start requests
534 * while waiting for their corresponding application thread to get
535 * going.
536 */
537 final ArrayList<ServiceRecord> mPendingServices
538 = new ArrayList<ServiceRecord>();
539
540 /**
541 * List of services that are scheduled to restart following a crash.
542 */
543 final ArrayList<ServiceRecord> mRestartingServices
544 = new ArrayList<ServiceRecord>();
545
546 /**
547 * List of services that are in the process of being stopped.
548 */
549 final ArrayList<ServiceRecord> mStoppingServices
550 = new ArrayList<ServiceRecord>();
551
552 /**
Christopher Tate181fafa2009-05-14 11:12:14 -0700553 * Backup/restore process management
554 */
555 String mBackupAppName = null;
556 BackupRecord mBackupTarget = null;
557
558 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800559 * List of PendingThumbnailsRecord objects of clients who are still
560 * waiting to receive all of the thumbnails for a task.
561 */
562 final ArrayList mPendingThumbnails = new ArrayList();
563
564 /**
565 * List of HistoryRecord objects that have been finished and must
566 * still report back to a pending thumbnail receiver.
567 */
568 final ArrayList mCancelledThumbnails = new ArrayList();
569
Amith Yamasani742a6712011-05-04 14:49:28 -0700570 final ProviderMap mProviderMap = new ProviderMap();
571
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800572 /**
573 * List of content providers who have clients waiting for them. The
574 * application is currently being launched and the provider will be
575 * removed from this list once it is published.
576 */
Dianne Hackborn860755f2010-06-03 18:47:52 -0700577 final ArrayList<ContentProviderRecord> mLaunchingProviders
578 = new ArrayList<ContentProviderRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800579
580 /**
581 * Global set of specific Uri permissions that have been granted.
582 */
583 final private SparseArray<HashMap<Uri, UriPermission>> mGrantedUriPermissions
584 = new SparseArray<HashMap<Uri, UriPermission>>();
585
Svetoslav Ganov54d068e2011-03-02 12:58:40 -0800586 CoreSettingsObserver mCoreSettingsObserver;
587
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800588 /**
589 * Thread-local storage used to carry caller permissions over through
590 * indirect content-provider access.
591 * @see #ActivityManagerService.openContentUri()
592 */
593 private class Identity {
594 public int pid;
595 public int uid;
596
597 Identity(int _pid, int _uid) {
598 pid = _pid;
599 uid = _uid;
600 }
601 }
Amith Yamasani742a6712011-05-04 14:49:28 -0700602
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800603 private static ThreadLocal<Identity> sCallerIdentity = new ThreadLocal<Identity>();
604
605 /**
606 * All information we have collected about the runtime performance of
607 * any user id that can impact battery performance.
608 */
609 final BatteryStatsService mBatteryStatsService;
610
611 /**
612 * information about component usage
613 */
614 final UsageStatsService mUsageStatsService;
615
616 /**
617 * Current configuration information. HistoryRecord objects are given
618 * a reference to this object to indicate which configuration they are
619 * currently running in, so this object must be kept immutable.
620 */
621 Configuration mConfiguration = new Configuration();
622
623 /**
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800624 * Current sequencing integer of the configuration, for skipping old
625 * configurations.
626 */
627 int mConfigurationSeq = 0;
628
629 /**
Jack Palevichb90d28c2009-07-22 15:35:24 -0700630 * Hardware-reported OpenGLES version.
631 */
632 final int GL_ES_VERSION;
633
634 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800635 * List of initialization arguments to pass to all processes when binding applications to them.
636 * For example, references to the commonly used services.
637 */
638 HashMap<String, IBinder> mAppBindArgs;
639
640 /**
Dianne Hackbornf210d6b2009-04-13 18:42:49 -0700641 * Temporary to avoid allocations. Protected by main lock.
642 */
643 final StringBuilder mStringBuilder = new StringBuilder(256);
644
645 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800646 * Used to control how we initialize the service.
647 */
648 boolean mStartRunning = false;
649 ComponentName mTopComponent;
650 String mTopAction;
651 String mTopData;
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700652 boolean mProcessesReady = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800653 boolean mSystemReady = false;
654 boolean mBooting = false;
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700655 boolean mWaitingUpdate = false;
656 boolean mDidUpdate = false;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700657 boolean mOnBattery = false;
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700658 boolean mLaunchWarningShown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800659
660 Context mContext;
661
662 int mFactoryTest;
663
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -0700664 boolean mCheckedForSetup;
665
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800666 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700667 * The time at which we will allow normal application switches again,
668 * after a call to {@link #stopAppSwitches()}.
669 */
670 long mAppSwitchesAllowedTime;
671
672 /**
673 * This is set to true after the first switch after mAppSwitchesAllowedTime
674 * is set; any switches after that will clear the time.
675 */
676 boolean mDidAppSwitch;
677
678 /**
Dianne Hackborn287952c2010-09-22 22:34:31 -0700679 * Last time (in realtime) at which we checked for power usage.
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700680 */
Dianne Hackborn287952c2010-09-22 22:34:31 -0700681 long mLastPowerCheckRealtime;
682
683 /**
684 * Last time (in uptime) at which we checked for power usage.
685 */
686 long mLastPowerCheckUptime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700687
688 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800689 * Set while we are wanting to sleep, to prevent any
690 * activities from being started/resumed.
691 */
692 boolean mSleeping = false;
693
694 /**
Dianne Hackborn55280a92009-05-07 15:53:46 -0700695 * Set if we are shutting down the system, similar to sleeping.
696 */
697 boolean mShuttingDown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800698
699 /**
700 * Task identifier that activities are currently being started
701 * in. Incremented each time a new task is created.
702 * todo: Replace this with a TokenSpace class that generates non-repeating
703 * integers that won't wrap.
704 */
705 int mCurTask = 1;
706
707 /**
708 * Current sequence id for oom_adj computation traversal.
709 */
710 int mAdjSeq = 0;
711
712 /**
Dianne Hackborn906497c2010-05-10 15:57:38 -0700713 * Current sequence id for process LRU updating.
714 */
715 int mLruSeq = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800716
717 /**
Dianne Hackborne02c88a2011-10-28 13:58:15 -0700718 * Keep track of the number of service processes we last found, to
719 * determine on the next iteration which should be B services.
720 */
721 int mNumServiceProcs = 0;
722 int mNewNumServiceProcs = 0;
723
724 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800725 * System monitoring: number of processes that died since the last
726 * N procs were started.
727 */
728 int[] mProcDeaths = new int[20];
729
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700730 /**
731 * This is set if we had to do a delayed dexopt of an app before launching
732 * it, to increasing the ANR timeouts in that case.
733 */
734 boolean mDidDexOpt;
735
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800736 String mDebugApp = null;
737 boolean mWaitForDebugger = false;
738 boolean mDebugTransient = false;
739 String mOrigDebugApp = null;
740 boolean mOrigWaitForDebugger = false;
741 boolean mAlwaysFinishActivities = false;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700742 IActivityController mController = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700743 String mProfileApp = null;
744 ProcessRecord mProfileProc = null;
745 String mProfileFile;
746 ParcelFileDescriptor mProfileFd;
747 int mProfileType = 0;
748 boolean mAutoStopProfiler = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800749
Jeff Sharkeya4620792011-05-20 15:29:23 -0700750 final RemoteCallbackList<IProcessObserver> mProcessObservers
751 = new RemoteCallbackList<IProcessObserver>();
752
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800753 /**
754 * Callback of last caller to {@link #requestPss}.
755 */
756 Runnable mRequestPssCallback;
757
758 /**
759 * Remaining processes for which we are waiting results from the last
760 * call to {@link #requestPss}.
761 */
762 final ArrayList<ProcessRecord> mRequestPssList
763 = new ArrayList<ProcessRecord>();
764
765 /**
766 * Runtime statistics collection thread. This object's lock is used to
767 * protect all related state.
768 */
769 final Thread mProcessStatsThread;
770
771 /**
772 * Used to collect process stats when showing not responding dialog.
773 * Protected by mProcessStatsThread.
774 */
775 final ProcessStats mProcessStats = new ProcessStats(
776 MONITOR_THREAD_CPU_USAGE);
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700777 final AtomicLong mLastCpuTime = new AtomicLong(0);
778 final AtomicBoolean mProcessStatsMutexFree = new AtomicBoolean(true);
779
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800780 long mLastWriteTime = 0;
781
782 /**
783 * Set to true after the system has finished booting.
784 */
785 boolean mBooted = false;
786
Dianne Hackborn7d608422011-08-07 16:24:18 -0700787 int mProcessLimit = ProcessList.MAX_HIDDEN_APPS;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700788 int mProcessLimitOverride = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800789
790 WindowManagerService mWindowManager;
791
792 static ActivityManagerService mSelf;
793 static ActivityThread mSystemThread;
794
795 private final class AppDeathRecipient implements IBinder.DeathRecipient {
796 final ProcessRecord mApp;
797 final int mPid;
798 final IApplicationThread mAppThread;
799
800 AppDeathRecipient(ProcessRecord app, int pid,
801 IApplicationThread thread) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800802 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800803 TAG, "New death recipient " + this
804 + " for thread " + thread.asBinder());
805 mApp = app;
806 mPid = pid;
807 mAppThread = thread;
808 }
809
810 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800811 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800812 TAG, "Death received in " + this
813 + " for thread " + mAppThread.asBinder());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800814 synchronized(ActivityManagerService.this) {
815 appDiedLocked(mApp, mPid, mAppThread);
816 }
817 }
818 }
819
820 static final int SHOW_ERROR_MSG = 1;
821 static final int SHOW_NOT_RESPONDING_MSG = 2;
822 static final int SHOW_FACTORY_ERROR_MSG = 3;
823 static final int UPDATE_CONFIGURATION_MSG = 4;
824 static final int GC_BACKGROUND_PROCESSES_MSG = 5;
825 static final int WAIT_FOR_DEBUGGER_MSG = 6;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800826 static final int SERVICE_TIMEOUT_MSG = 12;
827 static final int UPDATE_TIME_ZONE = 13;
828 static final int SHOW_UID_ERROR_MSG = 14;
829 static final int IM_FEELING_LUCKY_MSG = 15;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800830 static final int PROC_START_TIMEOUT_MSG = 20;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700831 static final int DO_PENDING_ACTIVITY_LAUNCHES_MSG = 21;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -0700832 static final int KILL_APPLICATION_MSG = 22;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800833 static final int FINALIZE_PENDING_INTENT_MSG = 23;
Dianne Hackborn860755f2010-06-03 18:47:52 -0700834 static final int POST_HEAVY_NOTIFICATION_MSG = 24;
835 static final int CANCEL_HEAVY_NOTIFICATION_MSG = 25;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700836 static final int SHOW_STRICT_MODE_VIOLATION_MSG = 26;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700837 static final int CHECK_EXCESSIVE_WAKE_LOCKS_MSG = 27;
Robert Greenwalt03595d02010-11-02 14:08:23 -0700838 static final int CLEAR_DNS_CACHE = 28;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700839 static final int UPDATE_HTTP_PROXY = 29;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700840 static final int SHOW_COMPAT_MODE_DIALOG_MSG = 30;
Dianne Hackborn36f80f32011-05-31 18:26:45 -0700841 static final int DISPATCH_FOREGROUND_ACTIVITIES_CHANGED = 31;
842 static final int DISPATCH_PROCESS_DIED = 32;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700843 static final int REPORT_MEM_USAGE = 33;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800844
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800845 static final int FIRST_ACTIVITY_STACK_MSG = 100;
846 static final int FIRST_BROADCAST_QUEUE_MSG = 200;
847 static final int FIRST_COMPAT_MODE_MSG = 300;
848
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800849 AlertDialog mUidAlert;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700850 CompatModeDialog mCompatModeDialog;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700851 long mLastMemUsageReportTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800852
853 final Handler mHandler = new Handler() {
854 //public Handler() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800855 // if (localLOGV) Slog.v(TAG, "Handler started!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800856 //}
857
858 public void handleMessage(Message msg) {
859 switch (msg.what) {
860 case SHOW_ERROR_MSG: {
861 HashMap data = (HashMap) msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800862 synchronized (ActivityManagerService.this) {
863 ProcessRecord proc = (ProcessRecord)data.get("app");
864 if (proc != null && proc.crashDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800865 Slog.e(TAG, "App already has crash dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800866 return;
867 }
868 AppErrorResult res = (AppErrorResult) data.get("result");
Joe Onorato54a4a412011-11-02 20:50:08 -0700869 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Dan Egnorb7f03672009-12-09 16:22:32 -0800870 Dialog d = new AppErrorDialog(mContext, res, proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800871 d.show();
872 proc.crashDialog = d;
873 } else {
874 // The device is asleep, so just pretend that the user
875 // saw a crash dialog and hit "force quit".
876 res.set(0);
877 }
878 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700879
880 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800881 } break;
882 case SHOW_NOT_RESPONDING_MSG: {
883 synchronized (ActivityManagerService.this) {
884 HashMap data = (HashMap) msg.obj;
885 ProcessRecord proc = (ProcessRecord)data.get("app");
886 if (proc != null && proc.anrDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800887 Slog.e(TAG, "App already has anr dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800888 return;
889 }
The Android Open Source Project4df24232009-03-05 14:34:35 -0800890
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700891 Intent intent = new Intent("android.intent.action.ANR");
892 if (!mProcessesReady) {
Christopher Tatef46723b2012-01-26 14:19:24 -0800893 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
894 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700895 }
896 broadcastIntentLocked(null, null, intent,
The Android Open Source Project4df24232009-03-05 14:34:35 -0800897 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -0700898 false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
The Android Open Source Project4df24232009-03-05 14:34:35 -0800899
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800900 Dialog d = new AppNotRespondingDialog(ActivityManagerService.this,
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700901 mContext, proc, (ActivityRecord)data.get("activity"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800902 d.show();
903 proc.anrDialog = d;
904 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700905
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700906 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800907 } break;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700908 case SHOW_STRICT_MODE_VIOLATION_MSG: {
909 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj;
910 synchronized (ActivityManagerService.this) {
911 ProcessRecord proc = (ProcessRecord) data.get("app");
912 if (proc == null) {
913 Slog.e(TAG, "App not found when showing strict mode dialog.");
914 break;
915 }
916 if (proc.crashDialog != null) {
917 Slog.e(TAG, "App already has strict mode dialog: " + proc);
918 return;
919 }
920 AppErrorResult res = (AppErrorResult) data.get("result");
Joe Onorato54a4a412011-11-02 20:50:08 -0700921 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700922 Dialog d = new StrictModeViolationDialog(mContext, res, proc);
923 d.show();
924 proc.crashDialog = d;
925 } else {
926 // The device is asleep, so just pretend that the user
927 // saw a crash dialog and hit "force quit".
928 res.set(0);
929 }
930 }
931 ensureBootCompleted();
932 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800933 case SHOW_FACTORY_ERROR_MSG: {
934 Dialog d = new FactoryErrorDialog(
935 mContext, msg.getData().getCharSequence("msg"));
936 d.show();
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700937 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800938 } break;
939 case UPDATE_CONFIGURATION_MSG: {
940 final ContentResolver resolver = mContext.getContentResolver();
941 Settings.System.putConfiguration(resolver, (Configuration)msg.obj);
942 } break;
943 case GC_BACKGROUND_PROCESSES_MSG: {
944 synchronized (ActivityManagerService.this) {
945 performAppGcsIfAppropriateLocked();
946 }
947 } break;
948 case WAIT_FOR_DEBUGGER_MSG: {
949 synchronized (ActivityManagerService.this) {
950 ProcessRecord app = (ProcessRecord)msg.obj;
951 if (msg.arg1 != 0) {
952 if (!app.waitedForDebugger) {
953 Dialog d = new AppWaitingForDebuggerDialog(
954 ActivityManagerService.this,
955 mContext, app);
956 app.waitDialog = d;
957 app.waitedForDebugger = true;
958 d.show();
959 }
960 } else {
961 if (app.waitDialog != null) {
962 app.waitDialog.dismiss();
963 app.waitDialog = null;
964 }
965 }
966 }
967 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800968 case SERVICE_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700969 if (mDidDexOpt) {
970 mDidDexOpt = false;
971 Message nmsg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
972 nmsg.obj = msg.obj;
973 mHandler.sendMessageDelayed(nmsg, SERVICE_TIMEOUT);
974 return;
975 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800976 serviceTimeout((ProcessRecord)msg.obj);
977 } break;
978 case UPDATE_TIME_ZONE: {
979 synchronized (ActivityManagerService.this) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800980 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
981 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800982 if (r.thread != null) {
983 try {
984 r.thread.updateTimeZone();
985 } catch (RemoteException ex) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800986 Slog.w(TAG, "Failed to update time zone for: " + r.info.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800987 }
988 }
989 }
990 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700991 } break;
Robert Greenwalt03595d02010-11-02 14:08:23 -0700992 case CLEAR_DNS_CACHE: {
993 synchronized (ActivityManagerService.this) {
994 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
995 ProcessRecord r = mLruProcesses.get(i);
996 if (r.thread != null) {
997 try {
998 r.thread.clearDnsCache();
999 } catch (RemoteException ex) {
1000 Slog.w(TAG, "Failed to clear dns cache for: " + r.info.processName);
1001 }
1002 }
1003 }
1004 }
1005 } break;
Robert Greenwalt434203a2010-10-11 16:00:27 -07001006 case UPDATE_HTTP_PROXY: {
1007 ProxyProperties proxy = (ProxyProperties)msg.obj;
1008 String host = "";
1009 String port = "";
1010 String exclList = "";
1011 if (proxy != null) {
1012 host = proxy.getHost();
1013 port = Integer.toString(proxy.getPort());
1014 exclList = proxy.getExclusionList();
1015 }
1016 synchronized (ActivityManagerService.this) {
1017 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1018 ProcessRecord r = mLruProcesses.get(i);
1019 if (r.thread != null) {
1020 try {
1021 r.thread.setHttpProxy(host, port, exclList);
1022 } catch (RemoteException ex) {
1023 Slog.w(TAG, "Failed to update http proxy for: " +
1024 r.info.processName);
1025 }
1026 }
1027 }
1028 }
1029 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001030 case SHOW_UID_ERROR_MSG: {
Joe Onorato54a4a412011-11-02 20:50:08 -07001031 String title = "System UIDs Inconsistent";
1032 String text = "UIDs on the system are inconsistent, you need to wipe your"
1033 + " data partition or your device will be unstable.";
1034 Log.e(TAG, title + ": " + text);
1035 if (mShowDialogs) {
1036 // XXX This is a temporary dialog, no need to localize.
1037 AlertDialog d = new BaseErrorDialog(mContext);
1038 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
1039 d.setCancelable(false);
1040 d.setTitle(title);
1041 d.setMessage(text);
1042 d.setButton(DialogInterface.BUTTON_POSITIVE, "I'm Feeling Lucky",
1043 mHandler.obtainMessage(IM_FEELING_LUCKY_MSG));
1044 mUidAlert = d;
1045 d.show();
1046 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001047 } break;
1048 case IM_FEELING_LUCKY_MSG: {
1049 if (mUidAlert != null) {
1050 mUidAlert.dismiss();
1051 mUidAlert = null;
1052 }
1053 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001054 case PROC_START_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001055 if (mDidDexOpt) {
1056 mDidDexOpt = false;
1057 Message nmsg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
1058 nmsg.obj = msg.obj;
1059 mHandler.sendMessageDelayed(nmsg, PROC_START_TIMEOUT);
1060 return;
1061 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001062 ProcessRecord app = (ProcessRecord)msg.obj;
1063 synchronized (ActivityManagerService.this) {
1064 processStartTimedOutLocked(app);
1065 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001066 } break;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07001067 case DO_PENDING_ACTIVITY_LAUNCHES_MSG: {
1068 synchronized (ActivityManagerService.this) {
1069 doPendingActivityLaunchesLocked(true);
1070 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001071 } break;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001072 case KILL_APPLICATION_MSG: {
1073 synchronized (ActivityManagerService.this) {
1074 int uid = msg.arg1;
1075 boolean restart = (msg.arg2 == 1);
1076 String pkg = (String) msg.obj;
Christopher Tate3dacd842011-08-19 14:56:15 -07001077 forceStopPackageLocked(pkg, uid, restart, false, true, false);
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001078 }
1079 } break;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001080 case FINALIZE_PENDING_INTENT_MSG: {
1081 ((PendingIntentRecord)msg.obj).completeFinalize();
1082 } break;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001083 case POST_HEAVY_NOTIFICATION_MSG: {
1084 INotificationManager inm = NotificationManager.getService();
1085 if (inm == null) {
1086 return;
1087 }
1088
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001089 ActivityRecord root = (ActivityRecord)msg.obj;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001090 ProcessRecord process = root.app;
1091 if (process == null) {
1092 return;
1093 }
1094
1095 try {
1096 Context context = mContext.createPackageContext(process.info.packageName, 0);
1097 String text = mContext.getString(R.string.heavy_weight_notification,
1098 context.getApplicationInfo().loadLabel(context.getPackageManager()));
1099 Notification notification = new Notification();
1100 notification.icon = com.android.internal.R.drawable.stat_sys_adb; //context.getApplicationInfo().icon;
1101 notification.when = 0;
1102 notification.flags = Notification.FLAG_ONGOING_EVENT;
1103 notification.tickerText = text;
1104 notification.defaults = 0; // please be quiet
1105 notification.sound = null;
1106 notification.vibrate = null;
1107 notification.setLatestEventInfo(context, text,
1108 mContext.getText(R.string.heavy_weight_notification_detail),
1109 PendingIntent.getActivity(mContext, 0, root.intent,
1110 PendingIntent.FLAG_CANCEL_CURRENT));
1111
1112 try {
1113 int[] outId = new int[1];
1114 inm.enqueueNotification("android", R.string.heavy_weight_notification,
1115 notification, outId);
1116 } catch (RuntimeException e) {
1117 Slog.w(ActivityManagerService.TAG,
1118 "Error showing notification for heavy-weight app", e);
1119 } catch (RemoteException e) {
1120 }
1121 } catch (NameNotFoundException e) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07001122 Slog.w(TAG, "Unable to create context for heavy notification", e);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001123 }
1124 } break;
1125 case CANCEL_HEAVY_NOTIFICATION_MSG: {
1126 INotificationManager inm = NotificationManager.getService();
1127 if (inm == null) {
1128 return;
1129 }
1130 try {
1131 inm.cancelNotification("android",
1132 R.string.heavy_weight_notification);
1133 } catch (RuntimeException e) {
1134 Slog.w(ActivityManagerService.TAG,
1135 "Error canceling notification for service", e);
1136 } catch (RemoteException e) {
1137 }
1138 } break;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001139 case CHECK_EXCESSIVE_WAKE_LOCKS_MSG: {
1140 synchronized (ActivityManagerService.this) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001141 checkExcessivePowerUsageLocked(true);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07001142 removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001143 Message nmsg = obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
1144 sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001145 }
1146 } break;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001147 case SHOW_COMPAT_MODE_DIALOG_MSG: {
1148 synchronized (ActivityManagerService.this) {
1149 ActivityRecord ar = (ActivityRecord)msg.obj;
1150 if (mCompatModeDialog != null) {
1151 if (mCompatModeDialog.mAppInfo.packageName.equals(
1152 ar.info.applicationInfo.packageName)) {
1153 return;
1154 }
1155 mCompatModeDialog.dismiss();
1156 mCompatModeDialog = null;
1157 }
Dianne Hackborn29478262011-06-07 15:44:22 -07001158 if (ar != null && false) {
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001159 if (mCompatModePackages.getPackageAskCompatModeLocked(
1160 ar.packageName)) {
1161 int mode = mCompatModePackages.computeCompatModeLocked(
1162 ar.info.applicationInfo);
1163 if (mode == ActivityManager.COMPAT_MODE_DISABLED
1164 || mode == ActivityManager.COMPAT_MODE_ENABLED) {
1165 mCompatModeDialog = new CompatModeDialog(
1166 ActivityManagerService.this, mContext,
1167 ar.info.applicationInfo);
1168 mCompatModeDialog.show();
1169 }
1170 }
1171 }
1172 }
Dianne Hackborn36f80f32011-05-31 18:26:45 -07001173 break;
1174 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001175 case DISPATCH_FOREGROUND_ACTIVITIES_CHANGED: {
Jeff Sharkey287bd832011-05-28 19:36:26 -07001176 final int pid = msg.arg1;
1177 final int uid = msg.arg2;
1178 final boolean foregroundActivities = (Boolean) msg.obj;
1179 dispatchForegroundActivitiesChanged(pid, uid, foregroundActivities);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001180 break;
1181 }
1182 case DISPATCH_PROCESS_DIED: {
Jeff Sharkey287bd832011-05-28 19:36:26 -07001183 final int pid = msg.arg1;
1184 final int uid = msg.arg2;
1185 dispatchProcessDied(pid, uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001186 break;
1187 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001188 case REPORT_MEM_USAGE: {
1189 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
1190 if (!isDebuggable) {
1191 return;
1192 }
1193 synchronized (ActivityManagerService.this) {
1194 long now = SystemClock.uptimeMillis();
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001195 if (now < (mLastMemUsageReportTime+5*60*1000)) {
1196 // Don't report more than every 5 minutes to somewhat
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001197 // avoid spamming.
1198 return;
1199 }
1200 mLastMemUsageReportTime = now;
1201 }
1202 Thread thread = new Thread() {
1203 @Override public void run() {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001204 StringBuilder dropBuilder = new StringBuilder(1024);
1205 StringBuilder logBuilder = new StringBuilder(1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -08001206 StringWriter oomSw = new StringWriter();
1207 PrintWriter oomPw = new PrintWriter(oomSw);
1208 StringWriter catSw = new StringWriter();
1209 PrintWriter catPw = new PrintWriter(catSw);
1210 String[] emptyArgs = new String[] { };
1211 StringBuilder tag = new StringBuilder(128);
1212 StringBuilder stack = new StringBuilder(128);
1213 tag.append("Low on memory -- ");
1214 dumpApplicationMemoryUsage(null, oomPw, " ", emptyArgs, true, catPw,
1215 tag, stack);
1216 dropBuilder.append(stack);
1217 dropBuilder.append('\n');
1218 dropBuilder.append('\n');
1219 String oomString = oomSw.toString();
1220 dropBuilder.append(oomString);
1221 dropBuilder.append('\n');
1222 logBuilder.append(oomString);
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001223 try {
1224 java.lang.Process proc = Runtime.getRuntime().exec(new String[] {
1225 "procrank", });
1226 final InputStreamReader converter = new InputStreamReader(
1227 proc.getInputStream());
1228 BufferedReader in = new BufferedReader(converter);
1229 String line;
1230 while (true) {
1231 line = in.readLine();
1232 if (line == null) {
1233 break;
1234 }
1235 if (line.length() > 0) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001236 logBuilder.append(line);
1237 logBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001238 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001239 dropBuilder.append(line);
1240 dropBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001241 }
1242 converter.close();
1243 } catch (IOException e) {
1244 }
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001245 synchronized (ActivityManagerService.this) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08001246 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001247 dumpProcessesLocked(null, catPw, emptyArgs, 0, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001248 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001249 dumpServicesLocked(null, catPw, emptyArgs, 0, false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001250 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001251 dumpActivitiesLocked(null, catPw, emptyArgs, 0, false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001252 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001253 dropBuilder.append(catSw.toString());
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001254 addErrorToDropBox("lowmem", null, "system_server", null,
1255 null, tag.toString(), dropBuilder.toString(), null, null);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001256 Slog.i(TAG, logBuilder.toString());
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001257 synchronized (ActivityManagerService.this) {
1258 long now = SystemClock.uptimeMillis();
1259 if (mLastMemUsageReportTime < now) {
1260 mLastMemUsageReportTime = now;
1261 }
1262 }
1263 }
1264 };
1265 thread.start();
1266 break;
1267 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001268 }
1269 }
1270 };
1271
1272 public static void setSystemProcess() {
1273 try {
1274 ActivityManagerService m = mSelf;
1275
Dianne Hackborna573f6a2012-02-09 16:12:18 -08001276 ServiceManager.addService("activity", m, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001277 ServiceManager.addService("meminfo", new MemBinder(m));
Chet Haase9c1e23b2011-03-24 10:51:31 -07001278 ServiceManager.addService("gfxinfo", new GraphicsBinder(m));
Jeff Brown6754ba22011-12-14 20:20:01 -08001279 ServiceManager.addService("dbinfo", new DbBinder(m));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001280 if (MONITOR_CPU_USAGE) {
1281 ServiceManager.addService("cpuinfo", new CpuBinder(m));
1282 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001283 ServiceManager.addService("permission", new PermissionController(m));
1284
1285 ApplicationInfo info =
1286 mSelf.mContext.getPackageManager().getApplicationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -07001287 "android", STOCK_PM_FLAGS);
Mike Cleron432b7132009-09-24 15:28:29 -07001288 mSystemThread.installSystemApplicationInfo(info);
1289
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001290 synchronized (mSelf) {
1291 ProcessRecord app = mSelf.newProcessRecordLocked(
1292 mSystemThread.getApplicationThread(), info,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001293 info.processName, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001294 app.persistent = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08001295 app.pid = MY_PID;
Dianne Hackborn7d608422011-08-07 16:24:18 -07001296 app.maxAdj = ProcessList.SYSTEM_ADJ;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001297 mSelf.mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001298 synchronized (mSelf.mPidsSelfLocked) {
1299 mSelf.mPidsSelfLocked.put(app.pid, app);
1300 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001301 mSelf.updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001302 }
1303 } catch (PackageManager.NameNotFoundException e) {
1304 throw new RuntimeException(
1305 "Unable to find android system package", e);
1306 }
1307 }
1308
1309 public void setWindowManager(WindowManagerService wm) {
1310 mWindowManager = wm;
1311 }
1312
1313 public static final Context main(int factoryTest) {
1314 AThread thr = new AThread();
1315 thr.start();
1316
1317 synchronized (thr) {
1318 while (thr.mService == null) {
1319 try {
1320 thr.wait();
1321 } catch (InterruptedException e) {
1322 }
1323 }
1324 }
1325
1326 ActivityManagerService m = thr.mService;
1327 mSelf = m;
1328 ActivityThread at = ActivityThread.systemMain();
1329 mSystemThread = at;
1330 Context context = at.getSystemContext();
Dianne Hackborn247fe742011-01-08 17:25:57 -08001331 context.setTheme(android.R.style.Theme_Holo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001332 m.mContext = context;
1333 m.mFactoryTest = factoryTest;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001334 m.mMainStack = new ActivityStack(m, context, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001335
1336 m.mBatteryStatsService.publish(context);
1337 m.mUsageStatsService.publish(context);
1338
1339 synchronized (thr) {
1340 thr.mReady = true;
1341 thr.notifyAll();
1342 }
1343
1344 m.startRunning(null, null, null, null);
1345
1346 return context;
1347 }
1348
1349 public static ActivityManagerService self() {
1350 return mSelf;
1351 }
1352
1353 static class AThread extends Thread {
1354 ActivityManagerService mService;
1355 boolean mReady = false;
1356
1357 public AThread() {
1358 super("ActivityManager");
1359 }
1360
1361 public void run() {
1362 Looper.prepare();
1363
1364 android.os.Process.setThreadPriority(
1365 android.os.Process.THREAD_PRIORITY_FOREGROUND);
Christopher Tate160edb32010-06-30 17:46:30 -07001366 android.os.Process.setCanSelfBackground(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001367
1368 ActivityManagerService m = new ActivityManagerService();
1369
1370 synchronized (this) {
1371 mService = m;
1372 notifyAll();
1373 }
1374
1375 synchronized (this) {
1376 while (!mReady) {
1377 try {
1378 wait();
1379 } catch (InterruptedException e) {
1380 }
1381 }
1382 }
1383
Brad Fitzpatrickec062f62010-11-03 09:56:54 -07001384 // For debug builds, log event loop stalls to dropbox for analysis.
1385 if (StrictMode.conditionallyEnableDebugLogging()) {
1386 Slog.i(TAG, "Enabled StrictMode logging for AThread's Looper");
1387 }
1388
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001389 Looper.loop();
1390 }
1391 }
1392
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001393 static class MemBinder extends Binder {
1394 ActivityManagerService mActivityManagerService;
1395 MemBinder(ActivityManagerService activityManagerService) {
1396 mActivityManagerService = activityManagerService;
1397 }
1398
1399 @Override
1400 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001401 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1402 != PackageManager.PERMISSION_GRANTED) {
1403 pw.println("Permission Denial: can't dump meminfo from from pid="
1404 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1405 + " without permission " + android.Manifest.permission.DUMP);
1406 return;
1407 }
1408
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001409 mActivityManagerService.dumpApplicationMemoryUsage(fd, pw, " ", args,
Dianne Hackborn672342c2011-11-29 11:29:02 -08001410 false, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001411 }
1412 }
1413
Chet Haase9c1e23b2011-03-24 10:51:31 -07001414 static class GraphicsBinder extends Binder {
1415 ActivityManagerService mActivityManagerService;
1416 GraphicsBinder(ActivityManagerService activityManagerService) {
1417 mActivityManagerService = activityManagerService;
1418 }
1419
1420 @Override
1421 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001422 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1423 != PackageManager.PERMISSION_GRANTED) {
1424 pw.println("Permission Denial: can't dump gfxinfo from from pid="
1425 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1426 + " without permission " + android.Manifest.permission.DUMP);
1427 return;
1428 }
1429
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001430 mActivityManagerService.dumpGraphicsHardwareUsage(fd, pw, args);
Chet Haase9c1e23b2011-03-24 10:51:31 -07001431 }
1432 }
1433
Jeff Brown6754ba22011-12-14 20:20:01 -08001434 static class DbBinder extends Binder {
1435 ActivityManagerService mActivityManagerService;
1436 DbBinder(ActivityManagerService activityManagerService) {
1437 mActivityManagerService = activityManagerService;
1438 }
1439
1440 @Override
1441 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1442 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1443 != PackageManager.PERMISSION_GRANTED) {
1444 pw.println("Permission Denial: can't dump dbinfo from from pid="
1445 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1446 + " without permission " + android.Manifest.permission.DUMP);
1447 return;
1448 }
1449
1450 mActivityManagerService.dumpDbInfo(fd, pw, args);
1451 }
1452 }
1453
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001454 static class CpuBinder extends Binder {
1455 ActivityManagerService mActivityManagerService;
1456 CpuBinder(ActivityManagerService activityManagerService) {
1457 mActivityManagerService = activityManagerService;
1458 }
1459
1460 @Override
1461 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001462 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1463 != PackageManager.PERMISSION_GRANTED) {
1464 pw.println("Permission Denial: can't dump cpuinfo from from pid="
1465 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1466 + " without permission " + android.Manifest.permission.DUMP);
1467 return;
1468 }
1469
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001470 synchronized (mActivityManagerService.mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07001471 pw.print(mActivityManagerService.mProcessStats.printCurrentLoad());
1472 pw.print(mActivityManagerService.mProcessStats.printCurrentState(
1473 SystemClock.uptimeMillis()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001474 }
1475 }
1476 }
1477
1478 private ActivityManagerService() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001479 Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
Dianne Hackborn2c6c5e62009-10-08 17:55:49 -07001480
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001481 mFgBroadcastQueue = new BroadcastQueue(this, "foreground", BROADCAST_FG_TIMEOUT);
1482 mBgBroadcastQueue = new BroadcastQueue(this, "background", BROADCAST_BG_TIMEOUT);
1483 mBroadcastQueues[0] = mFgBroadcastQueue;
1484 mBroadcastQueues[1] = mBgBroadcastQueue;
1485
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001486 File dataDir = Environment.getDataDirectory();
1487 File systemDir = new File(dataDir, "system");
1488 systemDir.mkdirs();
1489 mBatteryStatsService = new BatteryStatsService(new File(
1490 systemDir, "batterystats.bin").toString());
1491 mBatteryStatsService.getActiveStatistics().readLocked();
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001492 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
Dianne Hackborn287952c2010-09-22 22:34:31 -07001493 mOnBattery = DEBUG_POWER ? true
1494 : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001495 mBatteryStatsService.getActiveStatistics().setCallback(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001496
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001497 mUsageStatsService = new UsageStatsService(new File(
Dianne Hackborn6447ca32009-04-07 19:50:08 -07001498 systemDir, "usagestats").toString());
Mike Lockwood3a74bd32011-08-12 13:55:22 -07001499 mHeadless = "1".equals(SystemProperties.get("ro.config.headless", "0"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001500
Jack Palevichb90d28c2009-07-22 15:35:24 -07001501 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",
1502 ConfigurationInfo.GL_ES_VERSION_UNDEFINED);
1503
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001504 mConfiguration.setToDefaults();
1505 mConfiguration.locale = Locale.getDefault();
Dianne Hackborn813075a62011-11-14 17:45:19 -08001506 mConfigurationSeq = mConfiguration.seq = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001507 mProcessStats.init();
1508
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07001509 mCompatModePackages = new CompatModePackages(this, systemDir);
1510
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001511 // Add ourself to the Watchdog monitors.
1512 Watchdog.getInstance().addMonitor(this);
1513
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001514 mProcessStatsThread = new Thread("ProcessStats") {
1515 public void run() {
1516 while (true) {
1517 try {
1518 try {
1519 synchronized(this) {
1520 final long now = SystemClock.uptimeMillis();
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001521 long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001522 long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001523 //Slog.i(TAG, "Cpu delay=" + nextCpuDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001524 // + ", write delay=" + nextWriteDelay);
1525 if (nextWriteDelay < nextCpuDelay) {
1526 nextCpuDelay = nextWriteDelay;
1527 }
1528 if (nextCpuDelay > 0) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001529 mProcessStatsMutexFree.set(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001530 this.wait(nextCpuDelay);
1531 }
1532 }
1533 } catch (InterruptedException e) {
1534 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001535 updateCpuStatsNow();
1536 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001537 Slog.e(TAG, "Unexpected exception collecting process stats", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001538 }
1539 }
1540 }
1541 };
1542 mProcessStatsThread.start();
1543 }
1544
1545 @Override
1546 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1547 throws RemoteException {
1548 try {
1549 return super.onTransact(code, data, reply, flags);
1550 } catch (RuntimeException e) {
1551 // The activity manager only throws security exceptions, so let's
1552 // log all others.
1553 if (!(e instanceof SecurityException)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001554 Slog.e(TAG, "Activity Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001555 }
1556 throw e;
1557 }
1558 }
1559
1560 void updateCpuStats() {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001561 final long now = SystemClock.uptimeMillis();
1562 if (mLastCpuTime.get() >= now - MONITOR_CPU_MIN_TIME) {
1563 return;
1564 }
1565 if (mProcessStatsMutexFree.compareAndSet(true, false)) {
1566 synchronized (mProcessStatsThread) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001567 mProcessStatsThread.notify();
1568 }
1569 }
1570 }
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001571
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001572 void updateCpuStatsNow() {
1573 synchronized (mProcessStatsThread) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001574 mProcessStatsMutexFree.set(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001575 final long now = SystemClock.uptimeMillis();
1576 boolean haveNewCpuStats = false;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07001577
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001578 if (MONITOR_CPU_USAGE &&
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001579 mLastCpuTime.get() < (now-MONITOR_CPU_MIN_TIME)) {
1580 mLastCpuTime.set(now);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001581 haveNewCpuStats = true;
1582 mProcessStats.update();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001583 //Slog.i(TAG, mProcessStats.printCurrentState());
1584 //Slog.i(TAG, "Total CPU usage: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001585 // + mProcessStats.getTotalCpuPercent() + "%");
1586
Joe Onorato8a9b2202010-02-26 18:56:32 -08001587 // Slog the cpu usage if the property is set.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001588 if ("true".equals(SystemProperties.get("events.cpu"))) {
1589 int user = mProcessStats.getLastUserTime();
1590 int system = mProcessStats.getLastSystemTime();
1591 int iowait = mProcessStats.getLastIoWaitTime();
1592 int irq = mProcessStats.getLastIrqTime();
1593 int softIrq = mProcessStats.getLastSoftIrqTime();
1594 int idle = mProcessStats.getLastIdleTime();
1595
1596 int total = user + system + iowait + irq + softIrq + idle;
1597 if (total == 0) total = 1;
1598
Doug Zongker2bec3d42009-12-04 12:52:44 -08001599 EventLog.writeEvent(EventLogTags.CPU,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001600 ((user+system+iowait+irq+softIrq) * 100) / total,
1601 (user * 100) / total,
1602 (system * 100) / total,
1603 (iowait * 100) / total,
1604 (irq * 100) / total,
1605 (softIrq * 100) / total);
1606 }
1607 }
1608
Amith Yamasanie43530a2009-08-21 13:11:37 -07001609 long[] cpuSpeedTimes = mProcessStats.getLastCpuSpeedTimes();
Amith Yamasani819f9282009-06-24 23:18:15 -07001610 final BatteryStatsImpl bstats = mBatteryStatsService.getActiveStatistics();
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001611 synchronized(bstats) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001612 synchronized(mPidsSelfLocked) {
1613 if (haveNewCpuStats) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001614 if (mOnBattery) {
1615 int perc = bstats.startAddingCpuLocked();
1616 int totalUTime = 0;
1617 int totalSTime = 0;
Dianne Hackborn287952c2010-09-22 22:34:31 -07001618 final int N = mProcessStats.countStats();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001619 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001620 ProcessStats.Stats st = mProcessStats.getStats(i);
1621 if (!st.working) {
1622 continue;
1623 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001624 ProcessRecord pr = mPidsSelfLocked.get(st.pid);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001625 int otherUTime = (st.rel_utime*perc)/100;
1626 int otherSTime = (st.rel_stime*perc)/100;
1627 totalUTime += otherUTime;
1628 totalSTime += otherSTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001629 if (pr != null) {
1630 BatteryStatsImpl.Uid.Proc ps = pr.batteryStats;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001631 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1632 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001633 ps.addSpeedStepTimes(cpuSpeedTimes);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001634 pr.curCpuTime += (st.rel_utime+st.rel_stime) * 10;
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001635 } else {
1636 BatteryStatsImpl.Uid.Proc ps =
Amith Yamasani819f9282009-06-24 23:18:15 -07001637 bstats.getProcessStatsLocked(st.name, st.pid);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001638 if (ps != null) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001639 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1640 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001641 ps.addSpeedStepTimes(cpuSpeedTimes);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001642 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001643 }
1644 }
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001645 bstats.finishAddingCpuLocked(perc, totalUTime,
1646 totalSTime, cpuSpeedTimes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001647 }
1648 }
1649 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001650
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001651 if (mLastWriteTime < (now-BATTERY_STATS_TIME)) {
1652 mLastWriteTime = now;
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001653 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001654 }
1655 }
1656 }
1657 }
1658
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001659 @Override
1660 public void batteryNeedsCpuUpdate() {
1661 updateCpuStatsNow();
1662 }
1663
1664 @Override
1665 public void batteryPowerChanged(boolean onBattery) {
1666 // When plugging in, update the CPU stats first before changing
1667 // the plug state.
1668 updateCpuStatsNow();
1669 synchronized (this) {
1670 synchronized(mPidsSelfLocked) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001671 mOnBattery = DEBUG_POWER ? true : onBattery;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001672 }
1673 }
1674 }
1675
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001676 /**
1677 * Initialize the application bind args. These are passed to each
1678 * process when the bindApplication() IPC is sent to the process. They're
1679 * lazily setup to make sure the services are running when they're asked for.
1680 */
1681 private HashMap<String, IBinder> getCommonServicesLocked() {
1682 if (mAppBindArgs == null) {
1683 mAppBindArgs = new HashMap<String, IBinder>();
1684
1685 // Setup the application init args
1686 mAppBindArgs.put("package", ServiceManager.getService("package"));
1687 mAppBindArgs.put("window", ServiceManager.getService("window"));
1688 mAppBindArgs.put(Context.ALARM_SERVICE,
1689 ServiceManager.getService(Context.ALARM_SERVICE));
1690 }
1691 return mAppBindArgs;
1692 }
1693
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001694 final void setFocusedActivityLocked(ActivityRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001695 if (mFocusedActivity != r) {
1696 mFocusedActivity = r;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001697 if (r != null) {
1698 mWindowManager.setFocusedApp(r.appToken, true);
1699 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001700 }
1701 }
1702
Dianne Hackborn906497c2010-05-10 15:57:38 -07001703 private final void updateLruProcessInternalLocked(ProcessRecord app,
1704 boolean oomAdj, boolean updateActivityTime, int bestPos) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001705 // put it on the LRU to keep track of when it should be exited.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001706 int lrui = mLruProcesses.indexOf(app);
1707 if (lrui >= 0) mLruProcesses.remove(lrui);
1708
1709 int i = mLruProcesses.size()-1;
1710 int skipTop = 0;
1711
Dianne Hackborn906497c2010-05-10 15:57:38 -07001712 app.lruSeq = mLruSeq;
1713
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001714 // compute the new weight for this process.
1715 if (updateActivityTime) {
1716 app.lastActivityTime = SystemClock.uptimeMillis();
1717 }
1718 if (app.activities.size() > 0) {
1719 // If this process has activities, we more strongly want to keep
1720 // it around.
1721 app.lruWeight = app.lastActivityTime;
1722 } else if (app.pubProviders.size() > 0) {
1723 // If this process contains content providers, we want to keep
1724 // it a little more strongly.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001725 app.lruWeight = app.lastActivityTime - ProcessList.CONTENT_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001726 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001727 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001728 } else {
1729 // If this process doesn't have activities, we less strongly
1730 // want to keep it around, and generally want to avoid getting
1731 // in front of any very recently used activities.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001732 app.lruWeight = app.lastActivityTime - ProcessList.EMPTY_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001733 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001734 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001735 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001736
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001737 while (i >= 0) {
1738 ProcessRecord p = mLruProcesses.get(i);
1739 // If this app shouldn't be in front of the first N background
1740 // apps, then skip over that many that are currently hidden.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001741 if (skipTop > 0 && p.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001742 skipTop--;
1743 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001744 if (p.lruWeight <= app.lruWeight || i < bestPos) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001745 mLruProcesses.add(i+1, app);
1746 break;
1747 }
1748 i--;
1749 }
1750 if (i < 0) {
1751 mLruProcesses.add(0, app);
1752 }
1753
Dianne Hackborn906497c2010-05-10 15:57:38 -07001754 // If the app is currently using a content provider or service,
1755 // bump those processes as well.
1756 if (app.connections.size() > 0) {
1757 for (ConnectionRecord cr : app.connections) {
1758 if (cr.binding != null && cr.binding.service != null
1759 && cr.binding.service.app != null
1760 && cr.binding.service.app.lruSeq != mLruSeq) {
1761 updateLruProcessInternalLocked(cr.binding.service.app, oomAdj,
1762 updateActivityTime, i+1);
1763 }
1764 }
1765 }
1766 if (app.conProviders.size() > 0) {
1767 for (ContentProviderRecord cpr : app.conProviders.keySet()) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07001768 if (cpr.proc != null && cpr.proc.lruSeq != mLruSeq) {
1769 updateLruProcessInternalLocked(cpr.proc, oomAdj,
Dianne Hackborn906497c2010-05-10 15:57:38 -07001770 updateActivityTime, i+1);
1771 }
1772 }
1773 }
1774
Joe Onorato8a9b2202010-02-26 18:56:32 -08001775 //Slog.i(TAG, "Putting proc to front: " + app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001776 if (oomAdj) {
1777 updateOomAdjLocked();
1778 }
1779 }
1780
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001781 final void updateLruProcessLocked(ProcessRecord app,
Dianne Hackborn906497c2010-05-10 15:57:38 -07001782 boolean oomAdj, boolean updateActivityTime) {
1783 mLruSeq++;
1784 updateLruProcessInternalLocked(app, oomAdj, updateActivityTime, 0);
1785 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001786
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001787 final ProcessRecord getProcessRecordLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001788 String processName, int uid) {
1789 if (uid == Process.SYSTEM_UID) {
1790 // The system gets to run in any process. If there are multiple
1791 // processes with the same uid, just pick the first (this
1792 // should never happen).
1793 SparseArray<ProcessRecord> procs = mProcessNames.getMap().get(
1794 processName);
1795 return procs != null ? procs.valueAt(0) : null;
1796 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001797 // uid = applyUserId(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001798 ProcessRecord proc = mProcessNames.get(processName, uid);
1799 return proc;
1800 }
1801
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001802 void ensurePackageDexOpt(String packageName) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001803 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001804 try {
1805 if (pm.performDexOpt(packageName)) {
1806 mDidDexOpt = true;
1807 }
1808 } catch (RemoteException e) {
1809 }
1810 }
1811
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001812 boolean isNextTransitionForward() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001813 int transit = mWindowManager.getPendingAppTransition();
1814 return transit == WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
1815 || transit == WindowManagerPolicy.TRANSIT_TASK_OPEN
1816 || transit == WindowManagerPolicy.TRANSIT_TASK_TO_FRONT;
1817 }
1818
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001819 final ProcessRecord startProcessLocked(String processName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001820 ApplicationInfo info, boolean knownToBeDead, int intentFlags,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001821 String hostingType, ComponentName hostingName, boolean allowWhileBooting,
1822 boolean isolated) {
1823 ProcessRecord app;
1824 if (!isolated) {
1825 app = getProcessRecordLocked(processName, info.uid);
1826 } else {
1827 // If this is an isolated process, it can't re-use an existing process.
1828 app = null;
1829 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001830 // We don't have to do anything more if:
1831 // (1) There is an existing application record; and
1832 // (2) The caller doesn't think it is dead, OR there is no thread
1833 // object attached to it so we know it couldn't have crashed; and
1834 // (3) There is a pid assigned to it, so it is either starting or
1835 // already running.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001836 if (DEBUG_PROCESSES) Slog.v(TAG, "startProcess: name=" + processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001837 + " app=" + app + " knownToBeDead=" + knownToBeDead
1838 + " thread=" + (app != null ? app.thread : null)
1839 + " pid=" + (app != null ? app.pid : -1));
Magnus Edlund7bb25812010-02-24 15:45:06 +01001840 if (app != null && app.pid > 0) {
1841 if (!knownToBeDead || app.thread == null) {
Dianne Hackborn20cb56e2010-03-04 00:58:29 -08001842 // We already have the app running, or are waiting for it to
1843 // come up (we have a pid but not yet its thread), so keep it.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001844 if (DEBUG_PROCESSES) Slog.v(TAG, "App already running: " + app);
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001845 // If this is a new package in the process, add the package to the list
1846 app.addPackage(info.packageName);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001847 return app;
1848 } else {
1849 // An application record is attached to a previous process,
1850 // clean it up now.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001851 if (DEBUG_PROCESSES) Slog.v(TAG, "App died: " + app);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07001852 handleAppDiedLocked(app, true, true);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001853 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001854 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01001855
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001856 String hostingNameStr = hostingName != null
1857 ? hostingName.flattenToShortString() : null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001858
1859 if (!isolated) {
1860 if ((intentFlags&Intent.FLAG_FROM_BACKGROUND) != 0) {
1861 // If we are in the background, then check to see if this process
1862 // is bad. If so, we will just silently fail.
1863 if (mBadProcesses.get(info.processName, info.uid) != null) {
1864 if (DEBUG_PROCESSES) Slog.v(TAG, "Bad process: " + info.uid
1865 + "/" + info.processName);
1866 return null;
1867 }
1868 } else {
1869 // When the user is explicitly starting a process, then clear its
1870 // crash count so that we won't make it bad until they see at
1871 // least one crash dialog again, and make the process good again
1872 // if it had been bad.
1873 if (DEBUG_PROCESSES) Slog.v(TAG, "Clearing bad process: " + info.uid
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001874 + "/" + info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001875 mProcessCrashTimes.remove(info.processName, info.uid);
1876 if (mBadProcesses.get(info.processName, info.uid) != null) {
1877 EventLog.writeEvent(EventLogTags.AM_PROC_GOOD, info.uid,
1878 info.processName);
1879 mBadProcesses.remove(info.processName, info.uid);
1880 if (app != null) {
1881 app.bad = false;
1882 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001883 }
1884 }
1885 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001886
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001887 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001888 app = newProcessRecordLocked(null, info, processName, isolated);
1889 if (app == null) {
1890 Slog.w(TAG, "Failed making new process record for "
1891 + processName + "/" + info.uid + " isolated=" + isolated);
1892 return null;
1893 }
1894 mProcessNames.put(processName, app.uid, app);
1895 if (isolated) {
1896 mIsolatedProcesses.put(app.uid, app);
1897 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001898 } else {
1899 // If this is a new package in the process, add the package to the list
1900 app.addPackage(info.packageName);
1901 }
1902
1903 // If the system is not ready yet, then hold off on starting this
1904 // process until it is.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001905 if (!mProcessesReady
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001906 && !isAllowedWhileBooting(info)
1907 && !allowWhileBooting) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001908 if (!mProcessesOnHold.contains(app)) {
1909 mProcessesOnHold.add(app);
1910 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001911 if (DEBUG_PROCESSES) Slog.v(TAG, "System not ready, putting on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001912 return app;
1913 }
1914
1915 startProcessLocked(app, hostingType, hostingNameStr);
1916 return (app.pid != 0) ? app : null;
1917 }
1918
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001919 boolean isAllowedWhileBooting(ApplicationInfo ai) {
1920 return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0;
1921 }
1922
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001923 private final void startProcessLocked(ProcessRecord app,
1924 String hostingType, String hostingNameStr) {
1925 if (app.pid > 0 && app.pid != MY_PID) {
1926 synchronized (mPidsSelfLocked) {
1927 mPidsSelfLocked.remove(app.pid);
1928 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
1929 }
1930 app.pid = 0;
1931 }
1932
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001933 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
1934 "startProcessLocked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001935 mProcessesOnHold.remove(app);
1936
1937 updateCpuStats();
1938
1939 System.arraycopy(mProcDeaths, 0, mProcDeaths, 1, mProcDeaths.length-1);
1940 mProcDeaths[0] = 0;
1941
1942 try {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001943 int uid = app.uid;
Amith Yamasani742a6712011-05-04 14:49:28 -07001944
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001945 int[] gids = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001946 if (!app.isolated) {
1947 try {
1948 gids = mContext.getPackageManager().getPackageGids(
1949 app.info.packageName);
1950 } catch (PackageManager.NameNotFoundException e) {
1951 Slog.w(TAG, "Unable to retrieve gids", e);
1952 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001953 }
1954 if (mFactoryTest != SystemServer.FACTORY_TEST_OFF) {
1955 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
1956 && mTopComponent != null
1957 && app.processName.equals(mTopComponent.getPackageName())) {
1958 uid = 0;
1959 }
1960 if (mFactoryTest == SystemServer.FACTORY_TEST_HIGH_LEVEL
1961 && (app.info.flags&ApplicationInfo.FLAG_FACTORY_TEST) != 0) {
1962 uid = 0;
1963 }
1964 }
1965 int debugFlags = 0;
1966 if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
1967 debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;
Elliott Hughesfa36aee2011-06-17 14:39:41 -07001968 // Also turn on CheckJNI for debuggable apps. It's quite
1969 // awkward to turn on otherwise.
1970 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001971 }
Ben Cheng6c0afff2010-02-14 16:18:56 -08001972 // Run the app in safe mode if its manifest requests so or the
1973 // system is booted in safe mode.
1974 if ((app.info.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0 ||
1975 Zygote.systemInSafeMode == true) {
Ben Cheng23085b72010-02-08 16:06:32 -08001976 debugFlags |= Zygote.DEBUG_ENABLE_SAFEMODE;
1977 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001978 if ("1".equals(SystemProperties.get("debug.checkjni"))) {
1979 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
1980 }
Elliott Hughesae07ecf2011-07-06 17:33:27 -07001981 if ("1".equals(SystemProperties.get("debug.jni.logging"))) {
1982 debugFlags |= Zygote.DEBUG_ENABLE_JNI_LOGGING;
1983 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001984 if ("1".equals(SystemProperties.get("debug.assert"))) {
1985 debugFlags |= Zygote.DEBUG_ENABLE_ASSERT;
1986 }
Jeff Brown3f9dd282011-07-08 20:02:19 -07001987
1988 // Start the process. It will either succeed and return a result containing
1989 // the PID of the new process, or else throw a RuntimeException.
1990 Process.ProcessStartResult startResult = Process.start("android.app.ActivityThread",
Elliott Hughese1dfcb72011-07-08 11:08:07 -07001991 app.processName, uid, uid, gids, debugFlags,
1992 app.info.targetSdkVersion, null);
Jeff Brown3f9dd282011-07-08 20:02:19 -07001993
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001994 BatteryStatsImpl bs = app.batteryStats.getBatteryStats();
1995 synchronized (bs) {
1996 if (bs.isOnBattery()) {
1997 app.batteryStats.incStartsLocked();
1998 }
1999 }
2000
Jeff Brown3f9dd282011-07-08 20:02:19 -07002001 EventLog.writeEvent(EventLogTags.AM_PROC_START, startResult.pid, uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002002 app.processName, hostingType,
2003 hostingNameStr != null ? hostingNameStr : "");
2004
2005 if (app.persistent) {
Jeff Brown3f9dd282011-07-08 20:02:19 -07002006 Watchdog.getInstance().processStarted(app.processName, startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002007 }
2008
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07002009 StringBuilder buf = mStringBuilder;
2010 buf.setLength(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002011 buf.append("Start proc ");
2012 buf.append(app.processName);
2013 buf.append(" for ");
2014 buf.append(hostingType);
2015 if (hostingNameStr != null) {
2016 buf.append(" ");
2017 buf.append(hostingNameStr);
2018 }
2019 buf.append(": pid=");
Jeff Brown3f9dd282011-07-08 20:02:19 -07002020 buf.append(startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002021 buf.append(" uid=");
2022 buf.append(uid);
2023 buf.append(" gids={");
2024 if (gids != null) {
2025 for (int gi=0; gi<gids.length; gi++) {
2026 if (gi != 0) buf.append(", ");
2027 buf.append(gids[gi]);
2028
2029 }
2030 }
2031 buf.append("}");
Joe Onorato8a9b2202010-02-26 18:56:32 -08002032 Slog.i(TAG, buf.toString());
Jeff Brown3f9dd282011-07-08 20:02:19 -07002033 app.pid = startResult.pid;
2034 app.usingWrapper = startResult.usingWrapper;
2035 app.removed = false;
2036 synchronized (mPidsSelfLocked) {
2037 this.mPidsSelfLocked.put(startResult.pid, app);
2038 Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
2039 msg.obj = app;
2040 mHandler.sendMessageDelayed(msg, startResult.usingWrapper
2041 ? PROC_START_TIMEOUT_WITH_WRAPPER : PROC_START_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002042 }
2043 } catch (RuntimeException e) {
2044 // XXX do better error recovery.
2045 app.pid = 0;
Joe Onorato8a9b2202010-02-26 18:56:32 -08002046 Slog.e(TAG, "Failure starting process " + app.processName, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002047 }
2048 }
2049
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002050 void updateUsageStats(ActivityRecord resumedComponent, boolean resumed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002051 if (resumed) {
2052 mUsageStatsService.noteResumeComponent(resumedComponent.realActivity);
2053 } else {
2054 mUsageStatsService.notePauseComponent(resumedComponent.realActivity);
2055 }
2056 }
2057
Amith Yamasani742a6712011-05-04 14:49:28 -07002058 boolean startHomeActivityLocked(int userId) {
Mike Lockwooda8f767a2011-08-31 14:32:37 -04002059 if (mHeadless) {
2060 // Added because none of the other calls to ensureBootCompleted seem to fire
2061 // when running headless.
2062 ensureBootCompleted();
2063 return false;
2064 }
2065
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002066 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2067 && mTopAction == null) {
2068 // We are running in factory test mode, but unable to find
2069 // the factory test app, so just sit around displaying the
2070 // error message and don't try to start anything.
2071 return false;
2072 }
2073 Intent intent = new Intent(
2074 mTopAction,
2075 mTopData != null ? Uri.parse(mTopData) : null);
2076 intent.setComponent(mTopComponent);
2077 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
2078 intent.addCategory(Intent.CATEGORY_HOME);
2079 }
2080 ActivityInfo aInfo =
2081 intent.resolveActivityInfo(mContext.getPackageManager(),
2082 STOCK_PM_FLAGS);
2083 if (aInfo != null) {
2084 intent.setComponent(new ComponentName(
2085 aInfo.applicationInfo.packageName, aInfo.name));
2086 // Don't do this if the home app is currently being
2087 // instrumented.
Amith Yamasani742a6712011-05-04 14:49:28 -07002088 aInfo = new ActivityInfo(aInfo);
2089 aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002090 ProcessRecord app = getProcessRecordLocked(aInfo.processName,
2091 aInfo.applicationInfo.uid);
2092 if (app == null || app.instrumentationClass == null) {
2093 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002094 mMainStack.startActivityLocked(null, intent, null, null, 0, aInfo,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002095 null, null, 0, 0, 0, false, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002096 }
2097 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002098
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002099 return true;
2100 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002101
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002102 /**
2103 * Starts the "new version setup screen" if appropriate.
2104 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002105 void startSetupActivityLocked() {
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002106 // Only do this once per boot.
2107 if (mCheckedForSetup) {
2108 return;
2109 }
2110
2111 // We will show this screen if the current one is a different
2112 // version than the last one shown, and we are not running in
2113 // low-level factory test mode.
2114 final ContentResolver resolver = mContext.getContentResolver();
2115 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL &&
2116 Settings.Secure.getInt(resolver,
2117 Settings.Secure.DEVICE_PROVISIONED, 0) != 0) {
2118 mCheckedForSetup = true;
2119
2120 // See if we should be showing the platform update setup UI.
2121 Intent intent = new Intent(Intent.ACTION_UPGRADE_SETUP);
2122 List<ResolveInfo> ris = mSelf.mContext.getPackageManager()
2123 .queryIntentActivities(intent, PackageManager.GET_META_DATA);
2124
2125 // We don't allow third party apps to replace this.
2126 ResolveInfo ri = null;
2127 for (int i=0; ris != null && i<ris.size(); i++) {
2128 if ((ris.get(i).activityInfo.applicationInfo.flags
2129 & ApplicationInfo.FLAG_SYSTEM) != 0) {
2130 ri = ris.get(i);
2131 break;
2132 }
2133 }
2134
2135 if (ri != null) {
2136 String vers = ri.activityInfo.metaData != null
2137 ? ri.activityInfo.metaData.getString(Intent.METADATA_SETUP_VERSION)
2138 : null;
2139 if (vers == null && ri.activityInfo.applicationInfo.metaData != null) {
2140 vers = ri.activityInfo.applicationInfo.metaData.getString(
2141 Intent.METADATA_SETUP_VERSION);
2142 }
2143 String lastVers = Settings.Secure.getString(
2144 resolver, Settings.Secure.LAST_SETUP_SHOWN);
2145 if (vers != null && !vers.equals(lastVers)) {
2146 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2147 intent.setComponent(new ComponentName(
2148 ri.activityInfo.packageName, ri.activityInfo.name));
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002149 mMainStack.startActivityLocked(null, intent, null, null, 0, ri.activityInfo,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002150 null, null, 0, 0, 0, false, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002151 }
2152 }
2153 }
2154 }
2155
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002156 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002157 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002158 }
2159
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002160 void enforceNotIsolatedCaller(String caller) {
2161 if (UserId.isIsolated(Binder.getCallingUid())) {
2162 throw new SecurityException("Isolated process not allowed to call " + caller);
2163 }
2164 }
2165
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002166 public int getFrontActivityScreenCompatMode() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002167 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002168 synchronized (this) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002169 return mCompatModePackages.getFrontActivityScreenCompatModeLocked();
2170 }
2171 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002172
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002173 public void setFrontActivityScreenCompatMode(int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002174 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2175 "setFrontActivityScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002176 synchronized (this) {
2177 mCompatModePackages.setFrontActivityScreenCompatModeLocked(mode);
2178 }
2179 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002180
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002181 public int getPackageScreenCompatMode(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002182 enforceNotIsolatedCaller("getPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002183 synchronized (this) {
2184 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
2185 }
2186 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002187
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002188 public void setPackageScreenCompatMode(String packageName, int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002189 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2190 "setPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002191 synchronized (this) {
2192 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002193 }
2194 }
2195
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002196 public boolean getPackageAskScreenCompat(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002197 enforceNotIsolatedCaller("getPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002198 synchronized (this) {
2199 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
2200 }
2201 }
2202
2203 public void setPackageAskScreenCompat(String packageName, boolean ask) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002204 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2205 "setPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002206 synchronized (this) {
2207 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
2208 }
2209 }
2210
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002211 void reportResumedActivityLocked(ActivityRecord r) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002212 //Slog.i(TAG, "**** REPORT RESUME: " + r);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002213
2214 final int identHash = System.identityHashCode(r);
2215 updateUsageStats(r, true);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002216 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002217
Jeff Sharkeya4620792011-05-20 15:29:23 -07002218 private void dispatchForegroundActivitiesChanged(int pid, int uid, boolean foregroundActivities) {
2219 int i = mProcessObservers.beginBroadcast();
2220 while (i > 0) {
2221 i--;
2222 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2223 if (observer != null) {
2224 try {
2225 observer.onForegroundActivitiesChanged(pid, uid, foregroundActivities);
2226 } catch (RemoteException e) {
2227 }
2228 }
2229 }
2230 mProcessObservers.finishBroadcast();
2231 }
2232
2233 private void dispatchProcessDied(int pid, int uid) {
2234 int i = mProcessObservers.beginBroadcast();
2235 while (i > 0) {
2236 i--;
2237 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2238 if (observer != null) {
2239 try {
2240 observer.onProcessDied(pid, uid);
2241 } catch (RemoteException e) {
2242 }
2243 }
2244 }
2245 mProcessObservers.finishBroadcast();
2246 }
2247
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002248 final void doPendingActivityLaunchesLocked(boolean doResume) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002249 final int N = mPendingActivityLaunches.size();
2250 if (N <= 0) {
2251 return;
2252 }
2253 for (int i=0; i<N; i++) {
2254 PendingActivityLaunch pal = mPendingActivityLaunches.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002255 mMainStack.startActivityUncheckedLocked(pal.r, pal.sourceRecord,
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002256 pal.grantedUriPermissions, pal.grantedMode, pal.onlyIfNeeded,
2257 doResume && i == (N-1));
2258 }
2259 mPendingActivityLaunches.clear();
2260 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002261
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002262 public final int startActivity(IApplicationThread caller,
2263 Intent intent, String resolvedType, Uri[] grantedUriPermissions,
2264 int grantedMode, IBinder resultTo,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002265 String resultWho, int requestCode, boolean onlyIfNeeded, boolean debug,
2266 String profileFile, ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
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,
Amith Yamasani742a6712011-05-04 14:49:28 -07002283 grantedUriPermissions, grantedMode, resultTo, resultWho, requestCode, onlyIfNeeded,
2284 debug, profileFile, profileFd, autoStopProfiler, null, null, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002285 }
2286
2287 public final WaitResult startActivityAndWait(IApplicationThread caller,
2288 Intent intent, String resolvedType, Uri[] grantedUriPermissions,
2289 int grantedMode, IBinder resultTo,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002290 String resultWho, int requestCode, boolean onlyIfNeeded, boolean debug,
2291 String profileFile, ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002292 enforceNotIsolatedCaller("startActivityAndWait");
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002293 WaitResult res = new WaitResult();
Amith Yamasani742a6712011-05-04 14:49:28 -07002294 int userId = Binder.getOrigCallingUser();
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002295 mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002296 grantedUriPermissions, grantedMode, resultTo, resultWho,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002297 requestCode, onlyIfNeeded, debug, profileFile, profileFd, autoStopProfiler,
Amith Yamasani742a6712011-05-04 14:49:28 -07002298 res, null, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002299 return res;
2300 }
2301
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002302 public final int startActivityWithConfig(IApplicationThread caller,
2303 Intent intent, String resolvedType, Uri[] grantedUriPermissions,
2304 int grantedMode, IBinder resultTo,
2305 String resultWho, int requestCode, boolean onlyIfNeeded,
2306 boolean debug, Configuration config) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002307 enforceNotIsolatedCaller("startActivityWithConfig");
Amith Yamasani742a6712011-05-04 14:49:28 -07002308 int ret = mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002309 grantedUriPermissions, grantedMode, resultTo, resultWho,
Amith Yamasani742a6712011-05-04 14:49:28 -07002310 requestCode, onlyIfNeeded,
2311 debug, null, null, false, null, config, Binder.getOrigCallingUser());
2312 return ret;
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002313 }
2314
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002315 public int startActivityIntentSender(IApplicationThread caller,
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002316 IntentSender intent, Intent fillInIntent, String resolvedType,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002317 IBinder resultTo, String resultWho, int requestCode,
2318 int flagsMask, int flagsValues) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002319 enforceNotIsolatedCaller("startActivityIntentSender");
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002320 // Refuse possible leaked file descriptors
2321 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
2322 throw new IllegalArgumentException("File descriptors passed in Intent");
2323 }
2324
2325 IIntentSender sender = intent.getTarget();
2326 if (!(sender instanceof PendingIntentRecord)) {
2327 throw new IllegalArgumentException("Bad PendingIntent object");
2328 }
2329
2330 PendingIntentRecord pir = (PendingIntentRecord)sender;
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002331
2332 synchronized (this) {
2333 // If this is coming from the currently resumed activity, it is
2334 // effectively saying that app switches are allowed at this point.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002335 if (mMainStack.mResumedActivity != null
2336 && mMainStack.mResumedActivity.info.applicationInfo.uid ==
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002337 Binder.getCallingUid()) {
2338 mAppSwitchesAllowedTime = 0;
2339 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002340 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002341 int ret = pir.sendInner(0, fillInIntent, resolvedType, null,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002342 null, resultTo, resultWho, requestCode, flagsMask, flagsValues);
Amith Yamasani742a6712011-05-04 14:49:28 -07002343 return ret;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002344 }
2345
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002346 public boolean startNextMatchingActivity(IBinder callingActivity,
2347 Intent intent) {
2348 // Refuse possible leaked file descriptors
2349 if (intent != null && intent.hasFileDescriptors() == true) {
2350 throw new IllegalArgumentException("File descriptors passed in Intent");
2351 }
2352
2353 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002354 ActivityRecord r = mMainStack.isInStackLocked(callingActivity);
2355 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002356 return false;
2357 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002358 if (r.app == null || r.app.thread == null) {
2359 // The caller is not running... d'oh!
2360 return false;
2361 }
2362 intent = new Intent(intent);
2363 // The caller is not allowed to change the data.
2364 intent.setDataAndType(r.intent.getData(), r.intent.getType());
2365 // And we are resetting to find the next component...
2366 intent.setComponent(null);
2367
2368 ActivityInfo aInfo = null;
2369 try {
2370 List<ResolveInfo> resolves =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002371 AppGlobals.getPackageManager().queryIntentActivities(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002372 intent, r.resolvedType,
Dianne Hackborn1655be42009-05-08 14:29:01 -07002373 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002374
2375 // Look for the original activity in the list...
2376 final int N = resolves != null ? resolves.size() : 0;
2377 for (int i=0; i<N; i++) {
2378 ResolveInfo rInfo = resolves.get(i);
2379 if (rInfo.activityInfo.packageName.equals(r.packageName)
2380 && rInfo.activityInfo.name.equals(r.info.name)) {
2381 // We found the current one... the next matching is
2382 // after it.
2383 i++;
2384 if (i<N) {
2385 aInfo = resolves.get(i).activityInfo;
2386 }
2387 break;
2388 }
2389 }
2390 } catch (RemoteException e) {
2391 }
2392
2393 if (aInfo == null) {
2394 // Nobody who is next!
2395 return false;
2396 }
2397
2398 intent.setComponent(new ComponentName(
2399 aInfo.applicationInfo.packageName, aInfo.name));
2400 intent.setFlags(intent.getFlags()&~(
2401 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
2402 Intent.FLAG_ACTIVITY_CLEAR_TOP|
2403 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
2404 Intent.FLAG_ACTIVITY_NEW_TASK));
2405
2406 // Okay now we need to start the new activity, replacing the
2407 // currently running activity. This is a little tricky because
2408 // we want to start the new one as if the current one is finished,
2409 // but not finish the current one first so that there is no flicker.
2410 // And thus...
2411 final boolean wasFinishing = r.finishing;
2412 r.finishing = true;
2413
2414 // Propagate reply information over to the new activity.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002415 final ActivityRecord resultTo = r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002416 final String resultWho = r.resultWho;
2417 final int requestCode = r.requestCode;
2418 r.resultTo = null;
2419 if (resultTo != null) {
2420 resultTo.removeResultsLocked(r, resultWho, requestCode);
2421 }
2422
2423 final long origId = Binder.clearCallingIdentity();
2424 // XXX we are not dealing with propagating grantedUriPermissions...
2425 // those are not yet exposed to user code, so there is no need.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002426 int res = mMainStack.startActivityLocked(r.app.thread, intent,
Dianne Hackbornbe707852011-11-11 14:32:10 -08002427 r.resolvedType, null, 0, aInfo,
2428 resultTo != null ? resultTo.appToken : null, resultWho,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002429 requestCode, -1, r.launchedFromUid, false, false, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002430 Binder.restoreCallingIdentity(origId);
2431
2432 r.finishing = wasFinishing;
2433 if (res != START_SUCCESS) {
2434 return false;
2435 }
2436 return true;
2437 }
2438 }
2439
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002440 public final int startActivityInPackage(int uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002441 Intent intent, String resolvedType, IBinder resultTo,
2442 String resultWho, int requestCode, boolean onlyIfNeeded) {
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002443
2444 // This is so super not safe, that only the system (or okay root)
2445 // can do it.
Amith Yamasani742a6712011-05-04 14:49:28 -07002446 int userId = Binder.getOrigCallingUser();
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002447 final int callingUid = Binder.getCallingUid();
2448 if (callingUid != 0 && callingUid != Process.myUid()) {
2449 throw new SecurityException(
2450 "startActivityInPackage only available to the system");
2451 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002452
Amith Yamasani742a6712011-05-04 14:49:28 -07002453 int ret = mMainStack.startActivityMayWait(null, uid, intent, resolvedType,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002454 null, 0, resultTo, resultWho, requestCode, onlyIfNeeded, false,
Amith Yamasani742a6712011-05-04 14:49:28 -07002455 null, null, false, null, null, userId);
2456 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002457 }
2458
2459 public final int startActivities(IApplicationThread caller,
2460 Intent[] intents, String[] resolvedTypes, IBinder resultTo) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002461 enforceNotIsolatedCaller("startActivities");
Amith Yamasani742a6712011-05-04 14:49:28 -07002462 int ret = mMainStack.startActivities(caller, -1, intents, resolvedTypes, resultTo,
2463 Binder.getOrigCallingUser());
2464 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002465 }
2466
2467 public final int startActivitiesInPackage(int uid,
2468 Intent[] intents, String[] resolvedTypes, IBinder resultTo) {
2469
2470 // This is so super not safe, that only the system (or okay root)
2471 // can do it.
2472 final int callingUid = Binder.getCallingUid();
2473 if (callingUid != 0 && callingUid != Process.myUid()) {
2474 throw new SecurityException(
2475 "startActivityInPackage only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002476 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002477 int ret = mMainStack.startActivities(null, uid, intents, resolvedTypes, resultTo,
2478 UserId.getUserId(uid));
2479 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002480 }
2481
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002482 final void addRecentTaskLocked(TaskRecord task) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002483 int N = mRecentTasks.size();
Dianne Hackborn7c0e75e2010-12-21 19:15:40 -08002484 // Quick case: check if the top-most recent task is the same.
2485 if (N > 0 && mRecentTasks.get(0) == task) {
2486 return;
2487 }
2488 // Remove any existing entries that are the same kind of task.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002489 for (int i=0; i<N; i++) {
2490 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07002491 if (task.userId == tr.userId
2492 && ((task.affinity != null && task.affinity.equals(tr.affinity))
2493 || (task.intent != null && task.intent.filterEquals(tr.intent)))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002494 mRecentTasks.remove(i);
2495 i--;
2496 N--;
2497 if (task.intent == null) {
2498 // If the new recent task we are adding is not fully
2499 // specified, then replace it with the existing recent task.
2500 task = tr;
2501 }
2502 }
2503 }
2504 if (N >= MAX_RECENT_TASKS) {
2505 mRecentTasks.remove(N-1);
2506 }
2507 mRecentTasks.add(0, task);
2508 }
2509
2510 public void setRequestedOrientation(IBinder token,
2511 int requestedOrientation) {
2512 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002513 ActivityRecord r = mMainStack.isInStackLocked(token);
2514 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002515 return;
2516 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002517 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornbe707852011-11-11 14:32:10 -08002518 mWindowManager.setAppOrientation(r.appToken, requestedOrientation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002519 Configuration config = mWindowManager.updateOrientationFromAppTokens(
The Android Open Source Project10592532009-03-18 17:39:46 -07002520 mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -08002521 r.mayFreezeScreenLocked(r.app) ? r.appToken : null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002522 if (config != null) {
2523 r.frozenBeforeDestroy = true;
Dianne Hackborn813075a62011-11-14 17:45:19 -08002524 if (!updateConfigurationLocked(config, r, false, false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002525 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002526 }
2527 }
2528 Binder.restoreCallingIdentity(origId);
2529 }
2530 }
2531
2532 public int getRequestedOrientation(IBinder token) {
2533 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002534 ActivityRecord r = mMainStack.isInStackLocked(token);
2535 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002536 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
2537 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08002538 return mWindowManager.getAppOrientation(r.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002539 }
2540 }
2541
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002542 /**
2543 * This is the internal entry point for handling Activity.finish().
2544 *
2545 * @param token The Binder token referencing the Activity we want to finish.
2546 * @param resultCode Result code, if any, from this Activity.
2547 * @param resultData Result data (Intent), if any, from this Activity.
2548 *
Alexey Tarasov83bad3d2009-08-12 15:05:43 +11002549 * @return Returns true if the activity successfully finished, or false if it is still running.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002550 */
2551 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData) {
2552 // Refuse possible leaked file descriptors
2553 if (resultData != null && resultData.hasFileDescriptors() == true) {
2554 throw new IllegalArgumentException("File descriptors passed in Intent");
2555 }
2556
2557 synchronized(this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002558 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002559 // Find the first activity that is not finishing.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002560 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002561 if (next != null) {
2562 // ask watcher if this is allowed
2563 boolean resumeOK = true;
2564 try {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002565 resumeOK = mController.activityResuming(next.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002566 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002567 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002568 }
2569
2570 if (!resumeOK) {
2571 return false;
2572 }
2573 }
2574 }
2575 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002576 boolean res = mMainStack.requestFinishActivityLocked(token, resultCode,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002577 resultData, "app-request");
2578 Binder.restoreCallingIdentity(origId);
2579 return res;
2580 }
2581 }
2582
Dianne Hackborn860755f2010-06-03 18:47:52 -07002583 public final void finishHeavyWeightApp() {
2584 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2585 != PackageManager.PERMISSION_GRANTED) {
2586 String msg = "Permission Denial: finishHeavyWeightApp() from pid="
2587 + Binder.getCallingPid()
2588 + ", uid=" + Binder.getCallingUid()
2589 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2590 Slog.w(TAG, msg);
2591 throw new SecurityException(msg);
2592 }
2593
2594 synchronized(this) {
2595 if (mHeavyWeightProcess == null) {
2596 return;
2597 }
2598
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002599 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>(
Dianne Hackborn860755f2010-06-03 18:47:52 -07002600 mHeavyWeightProcess.activities);
2601 for (int i=0; i<activities.size(); i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002602 ActivityRecord r = activities.get(i);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002603 if (!r.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002604 int index = mMainStack.indexOfTokenLocked(r.appToken);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002605 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002606 mMainStack.finishActivityLocked(r, index, Activity.RESULT_CANCELED,
Dianne Hackborn860755f2010-06-03 18:47:52 -07002607 null, "finish-heavy");
2608 }
2609 }
2610 }
2611
2612 mHeavyWeightProcess = null;
2613 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
2614 }
2615 }
2616
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002617 public void crashApplication(int uid, int initialPid, String packageName,
2618 String message) {
2619 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2620 != PackageManager.PERMISSION_GRANTED) {
2621 String msg = "Permission Denial: crashApplication() from pid="
2622 + Binder.getCallingPid()
2623 + ", uid=" + Binder.getCallingUid()
2624 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2625 Slog.w(TAG, msg);
2626 throw new SecurityException(msg);
2627 }
2628
2629 synchronized(this) {
2630 ProcessRecord proc = null;
2631
2632 // Figure out which process to kill. We don't trust that initialPid
2633 // still has any relation to current pids, so must scan through the
2634 // list.
2635 synchronized (mPidsSelfLocked) {
2636 for (int i=0; i<mPidsSelfLocked.size(); i++) {
2637 ProcessRecord p = mPidsSelfLocked.valueAt(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002638 if (p.uid != uid) {
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002639 continue;
2640 }
2641 if (p.pid == initialPid) {
2642 proc = p;
2643 break;
2644 }
2645 for (String str : p.pkgList) {
2646 if (str.equals(packageName)) {
2647 proc = p;
2648 }
2649 }
2650 }
2651 }
2652
2653 if (proc == null) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07002654 Slog.w(TAG, "crashApplication: nothing for uid=" + uid
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002655 + " initialPid=" + initialPid
2656 + " packageName=" + packageName);
2657 return;
2658 }
2659
2660 if (proc.thread != null) {
Dianne Hackborn9f531192010-08-04 17:48:03 -07002661 if (proc.pid == Process.myPid()) {
2662 Log.w(TAG, "crashApplication: trying to crash self!");
2663 return;
2664 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002665 long ident = Binder.clearCallingIdentity();
2666 try {
2667 proc.thread.scheduleCrash(message);
2668 } catch (RemoteException e) {
2669 }
2670 Binder.restoreCallingIdentity(ident);
2671 }
2672 }
2673 }
2674
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002675 public final void finishSubActivity(IBinder token, String resultWho,
2676 int requestCode) {
2677 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002678 ActivityRecord self = mMainStack.isInStackLocked(token);
2679 if (self == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002680 return;
2681 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002682
2683 final long origId = Binder.clearCallingIdentity();
2684
2685 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002686 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2687 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002688 if (r.resultTo == self && r.requestCode == requestCode) {
2689 if ((r.resultWho == null && resultWho == null) ||
2690 (r.resultWho != null && r.resultWho.equals(resultWho))) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002691 mMainStack.finishActivityLocked(r, i,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002692 Activity.RESULT_CANCELED, null, "request-sub");
2693 }
2694 }
2695 }
2696
2697 Binder.restoreCallingIdentity(origId);
2698 }
2699 }
2700
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002701 public boolean willActivityBeVisible(IBinder token) {
2702 synchronized(this) {
2703 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002704 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2705 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08002706 if (r.appToken == token) {
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002707 return true;
2708 }
2709 if (r.fullscreen && !r.finishing) {
2710 return false;
2711 }
2712 }
2713 return true;
2714 }
2715 }
2716
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002717 public void overridePendingTransition(IBinder token, String packageName,
2718 int enterAnim, int exitAnim) {
2719 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002720 ActivityRecord self = mMainStack.isInStackLocked(token);
2721 if (self == null) {
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002722 return;
2723 }
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002724
2725 final long origId = Binder.clearCallingIdentity();
2726
2727 if (self.state == ActivityState.RESUMED
2728 || self.state == ActivityState.PAUSING) {
2729 mWindowManager.overridePendingAppTransition(packageName,
2730 enterAnim, exitAnim);
2731 }
2732
2733 Binder.restoreCallingIdentity(origId);
2734 }
2735 }
2736
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002737 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002738 * Main function for removing an existing process from the activity manager
2739 * as a result of that process going away. Clears out all connections
2740 * to the process.
2741 */
2742 private final void handleAppDiedLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002743 boolean restarting, boolean allowRestart) {
2744 cleanUpApplicationRecordLocked(app, restarting, allowRestart, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002745 if (!restarting) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002746 mLruProcesses.remove(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002747 }
2748
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002749 if (mProfileProc == app) {
2750 clearProfilerLocked();
2751 }
2752
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002753 // Just in case...
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002754 if (mMainStack.mPausingActivity != null && mMainStack.mPausingActivity.app == app) {
2755 if (DEBUG_PAUSE) Slog.v(TAG, "App died while pausing: " +mMainStack.mPausingActivity);
2756 mMainStack.mPausingActivity = null;
2757 }
2758 if (mMainStack.mLastPausedActivity != null && mMainStack.mLastPausedActivity.app == app) {
2759 mMainStack.mLastPausedActivity = null;
2760 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002761
2762 // Remove this application's activities from active lists.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002763 mMainStack.removeHistoryRecordsForAppLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002764
2765 boolean atTop = true;
2766 boolean hasVisibleActivities = false;
2767
2768 // Clean out the history list.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002769 int i = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08002770 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002771 TAG, "Removing app " + app + " from history with " + i + " entries");
2772 while (i > 0) {
2773 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002774 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002775 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002776 TAG, "Record #" + i + " " + r + ": app=" + r.app);
2777 if (r.app == app) {
2778 if ((!r.haveState && !r.stateNotNeeded) || r.finishing) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002779 if (ActivityStack.DEBUG_ADD_REMOVE) {
2780 RuntimeException here = new RuntimeException("here");
2781 here.fillInStackTrace();
2782 Slog.i(TAG, "Removing activity " + r + " from stack at " + i
2783 + ": haveState=" + r.haveState
2784 + " stateNotNeeded=" + r.stateNotNeeded
2785 + " finishing=" + r.finishing
2786 + " state=" + r.state, here);
2787 }
2788 if (!r.finishing) {
2789 Slog.w(TAG, "Force removing " + r + ": app died, no saved state");
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -08002790 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
2791 System.identityHashCode(r),
2792 r.task.taskId, r.shortComponentName,
2793 "proc died without state saved");
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002794 }
Dianne Hackborn5c607432012-02-28 14:44:19 -08002795 mMainStack.removeActivityFromHistoryLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002796
2797 } else {
2798 // We have the current state for this activity, so
2799 // it can be restarted later when needed.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002800 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002801 TAG, "Keeping entry, setting app to null");
2802 if (r.visible) {
2803 hasVisibleActivities = true;
2804 }
2805 r.app = null;
2806 r.nowVisible = false;
2807 if (!r.haveState) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002808 if (ActivityStack.DEBUG_SAVED_STATE) Slog.i(TAG,
2809 "App died, clearing saved state of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002810 r.icicle = null;
2811 }
2812 }
2813
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002814 r.stack.cleanUpActivityLocked(r, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002815 }
2816 atTop = false;
2817 }
2818
2819 app.activities.clear();
2820
2821 if (app.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002822 Slog.w(TAG, "Crash of app " + app.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002823 + " running instrumentation " + app.instrumentationClass);
2824 Bundle info = new Bundle();
2825 info.putString("shortMsg", "Process crashed.");
2826 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
2827 }
2828
2829 if (!restarting) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002830 if (!mMainStack.resumeTopActivityLocked(null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002831 // If there was nothing to resume, and we are not already
2832 // restarting this process, but there is a visible activity that
2833 // is hosted by the process... then make sure all visible
2834 // activities are running, taking care of restarting this
2835 // process.
2836 if (hasVisibleActivities) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002837 mMainStack.ensureActivitiesVisibleLocked(null, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002838 }
2839 }
2840 }
2841 }
2842
2843 private final int getLRURecordIndexForAppLocked(IApplicationThread thread) {
2844 IBinder threadBinder = thread.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002845 // Find the application record.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002846 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2847 ProcessRecord rec = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002848 if (rec.thread != null && rec.thread.asBinder() == threadBinder) {
2849 return i;
2850 }
2851 }
2852 return -1;
2853 }
2854
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002855 final ProcessRecord getRecordForAppLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002856 IApplicationThread thread) {
2857 if (thread == null) {
2858 return null;
2859 }
2860
2861 int appIndex = getLRURecordIndexForAppLocked(thread);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002862 return appIndex >= 0 ? mLruProcesses.get(appIndex) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002863 }
2864
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002865 final void appDiedLocked(ProcessRecord app, int pid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002866 IApplicationThread thread) {
2867
2868 mProcDeaths[0]++;
2869
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002870 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
2871 synchronized (stats) {
2872 stats.noteProcessDiedLocked(app.info.uid, pid);
2873 }
2874
Magnus Edlund7bb25812010-02-24 15:45:06 +01002875 // Clean up already done if the process has been re-started.
2876 if (app.pid == pid && app.thread != null &&
2877 app.thread.asBinder() == thread.asBinder()) {
Dianne Hackborn906497c2010-05-10 15:57:38 -07002878 if (!app.killedBackground) {
2879 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
2880 + ") has died.");
2881 }
Doug Zongker2bec3d42009-12-04 12:52:44 -08002882 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002883 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002884 TAG, "Dying app: " + app + ", pid: " + pid
2885 + ", thread: " + thread.asBinder());
2886 boolean doLowMem = app.instrumentationClass == null;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002887 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002888
2889 if (doLowMem) {
2890 // If there are no longer any background processes running,
2891 // and the app that died was not running instrumentation,
2892 // then tell everyone we are now low on memory.
2893 boolean haveBg = false;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002894 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2895 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -07002896 if (rec.thread != null && rec.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002897 haveBg = true;
2898 break;
2899 }
2900 }
2901
2902 if (!haveBg) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002903 EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mLruProcesses.size());
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002904 long now = SystemClock.uptimeMillis();
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002905 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2906 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn36124872009-10-08 16:22:03 -07002907 if (rec != app && rec.thread != null &&
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002908 (rec.lastLowMemory+GC_MIN_INTERVAL) <= now) {
2909 // The low memory report is overriding any current
2910 // state for a GC request. Make sure to do
Dianne Hackborn32907cf2010-06-10 17:50:20 -07002911 // heavy/important/visible/foreground processes first.
Dianne Hackborn7d608422011-08-07 16:24:18 -07002912 if (rec.setAdj <= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002913 rec.lastRequestedGc = 0;
2914 } else {
2915 rec.lastRequestedGc = rec.lastLowMemory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002916 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002917 rec.reportLowMemory = true;
2918 rec.lastLowMemory = now;
2919 mProcessesToGc.remove(rec);
2920 addProcessToGcListLocked(rec);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002921 }
2922 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07002923 mHandler.sendEmptyMessage(REPORT_MEM_USAGE);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002924 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002925 }
2926 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01002927 } else if (app.pid != pid) {
2928 // A new process has already been started.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002929 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
Magnus Edlund7bb25812010-02-24 15:45:06 +01002930 + ") has died and restarted (pid " + app.pid + ").");
Dianne Hackborn28a8c2b2010-03-01 11:30:02 -08002931 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08002932 } else if (DEBUG_PROCESSES) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002933 Slog.d(TAG, "Received spurious death notification for thread "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002934 + thread.asBinder());
2935 }
2936 }
2937
Dan Egnor42471dd2010-01-07 17:25:22 -08002938 /**
2939 * If a stack trace dump file is configured, dump process stack traces.
Christopher Tate6ee412d2010-05-28 12:01:56 -07002940 * @param clearTraces causes the dump file to be erased prior to the new
2941 * traces being written, if true; when false, the new traces will be
2942 * appended to any existing file content.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002943 * @param firstPids of dalvik VM processes to dump stack traces for first
2944 * @param lastPids of dalvik VM processes to dump stack traces for last
Dan Egnor42471dd2010-01-07 17:25:22 -08002945 * @return file containing stack traces, or null if no dump file is configured
2946 */
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002947 public static File dumpStackTraces(boolean clearTraces, ArrayList<Integer> firstPids,
2948 ProcessStats processStats, SparseArray<Boolean> lastPids) {
Dan Egnor42471dd2010-01-07 17:25:22 -08002949 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
2950 if (tracesPath == null || tracesPath.length() == 0) {
2951 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002952 }
Dan Egnor42471dd2010-01-07 17:25:22 -08002953
2954 File tracesFile = new File(tracesPath);
2955 try {
2956 File tracesDir = tracesFile.getParentFile();
2957 if (!tracesDir.exists()) tracesFile.mkdirs();
2958 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
2959
Christopher Tate6ee412d2010-05-28 12:01:56 -07002960 if (clearTraces && tracesFile.exists()) tracesFile.delete();
Dan Egnor42471dd2010-01-07 17:25:22 -08002961 tracesFile.createNewFile();
2962 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
2963 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002964 Slog.w(TAG, "Unable to prepare ANR traces file: " + tracesPath, e);
Dan Egnor42471dd2010-01-07 17:25:22 -08002965 return null;
2966 }
2967
2968 // Use a FileObserver to detect when traces finish writing.
2969 // The order of traces is considered important to maintain for legibility.
2970 FileObserver observer = new FileObserver(tracesPath, FileObserver.CLOSE_WRITE) {
2971 public synchronized void onEvent(int event, String path) { notify(); }
2972 };
2973
2974 try {
2975 observer.startWatching();
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002976
2977 // First collect all of the stacks of the most important pids.
2978 try {
2979 int num = firstPids.size();
2980 for (int i = 0; i < num; i++) {
2981 synchronized (observer) {
2982 Process.sendSignal(firstPids.get(i), Process.SIGNAL_QUIT);
2983 observer.wait(200); // Wait for write-close, give up after 200msec
2984 }
2985 }
2986 } catch (InterruptedException e) {
2987 Log.wtf(TAG, e);
2988 }
2989
2990 // Next measure CPU usage.
2991 if (processStats != null) {
2992 processStats.init();
2993 System.gc();
2994 processStats.update();
2995 try {
2996 synchronized (processStats) {
2997 processStats.wait(500); // measure over 1/2 second.
2998 }
2999 } catch (InterruptedException e) {
3000 }
3001 processStats.update();
3002
3003 // We'll take the stack crawls of just the top apps using CPU.
3004 final int N = processStats.countWorkingStats();
3005 int numProcs = 0;
3006 for (int i=0; i<N && numProcs<5; i++) {
3007 ProcessStats.Stats stats = processStats.getWorkingStats(i);
3008 if (lastPids.indexOfKey(stats.pid) >= 0) {
3009 numProcs++;
3010 try {
3011 synchronized (observer) {
3012 Process.sendSignal(stats.pid, Process.SIGNAL_QUIT);
3013 observer.wait(200); // Wait for write-close, give up after 200msec
3014 }
3015 } catch (InterruptedException e) {
3016 Log.wtf(TAG, e);
3017 }
3018
3019 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003020 }
3021 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003022
3023 return tracesFile;
3024
Dan Egnor42471dd2010-01-07 17:25:22 -08003025 } finally {
3026 observer.stopWatching();
3027 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003028 }
3029
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003030 final void appNotResponding(ProcessRecord app, ActivityRecord activity,
3031 ActivityRecord parent, final String annotation) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003032 ArrayList<Integer> firstPids = new ArrayList<Integer>(5);
3033 SparseArray<Boolean> lastPids = new SparseArray<Boolean>(20);
3034
Dianne Hackborn287952c2010-09-22 22:34:31 -07003035 if (mController != null) {
3036 try {
3037 // 0 == continue, -1 = kill process immediately
3038 int res = mController.appEarlyNotResponding(app.processName, app.pid, annotation);
3039 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3040 } catch (RemoteException e) {
3041 mController = null;
3042 }
3043 }
3044
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003045 long anrTime = SystemClock.uptimeMillis();
3046 if (MONITOR_CPU_USAGE) {
3047 updateCpuStatsNow();
3048 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003049
3050 synchronized (this) {
3051 // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down.
3052 if (mShuttingDown) {
3053 Slog.i(TAG, "During shutdown skipping ANR: " + app + " " + annotation);
3054 return;
3055 } else if (app.notResponding) {
3056 Slog.i(TAG, "Skipping duplicate ANR: " + app + " " + annotation);
3057 return;
3058 } else if (app.crashing) {
3059 Slog.i(TAG, "Crashing app skipping ANR: " + app + " " + annotation);
3060 return;
3061 }
3062
3063 // In case we come through here for the same app before completing
3064 // this one, mark as anring now so we will bail out.
3065 app.notResponding = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08003066
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003067 // Log the ANR to the event log.
3068 EventLog.writeEvent(EventLogTags.AM_ANR, app.pid, app.processName, app.info.flags,
3069 annotation);
Dan Egnor42471dd2010-01-07 17:25:22 -08003070
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003071 // Dump thread traces as quickly as we can, starting with "interesting" processes.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003072 firstPids.add(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003073
3074 int parentPid = app.pid;
3075 if (parent != null && parent.app != null && parent.app.pid > 0) parentPid = parent.app.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003076 if (parentPid != app.pid) firstPids.add(parentPid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003077
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003078 if (MY_PID != app.pid && MY_PID != parentPid) firstPids.add(MY_PID);
Dan Egnor42471dd2010-01-07 17:25:22 -08003079
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003080 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
3081 ProcessRecord r = mLruProcesses.get(i);
3082 if (r != null && r.thread != null) {
3083 int pid = r.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003084 if (pid > 0 && pid != app.pid && pid != parentPid && pid != MY_PID) {
3085 if (r.persistent) {
3086 firstPids.add(pid);
3087 } else {
3088 lastPids.put(pid, Boolean.TRUE);
3089 }
3090 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003091 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003092 }
3093 }
3094
Dan Egnor42471dd2010-01-07 17:25:22 -08003095 // Log the ANR to the main log.
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07003096 StringBuilder info = mStringBuilder;
3097 info.setLength(0);
Dan Egnor42471dd2010-01-07 17:25:22 -08003098 info.append("ANR in ").append(app.processName);
3099 if (activity != null && activity.shortComponentName != null) {
3100 info.append(" (").append(activity.shortComponentName).append(")");
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07003101 }
Eric Rowe6f4f6192010-02-17 18:29:04 -08003102 info.append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003103 if (annotation != null) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003104 info.append("Reason: ").append(annotation).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003105 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003106 if (parent != null && parent != activity) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003107 info.append("Parent: ").append(parent.shortComponentName).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003108 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003109
Dianne Hackborn287952c2010-09-22 22:34:31 -07003110 final ProcessStats processStats = new ProcessStats(true);
3111
3112 File tracesFile = dumpStackTraces(true, firstPids, processStats, lastPids);
3113
Dan Egnor42471dd2010-01-07 17:25:22 -08003114 String cpuInfo = null;
3115 if (MONITOR_CPU_USAGE) {
3116 updateCpuStatsNow();
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003117 synchronized (mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003118 cpuInfo = mProcessStats.printCurrentState(anrTime);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003119 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003120 info.append(processStats.printCurrentLoad());
Dan Egnor42471dd2010-01-07 17:25:22 -08003121 info.append(cpuInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003122 }
3123
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003124 info.append(processStats.printCurrentState(anrTime));
3125
Joe Onorato8a9b2202010-02-26 18:56:32 -08003126 Slog.e(TAG, info.toString());
Dan Egnor42471dd2010-01-07 17:25:22 -08003127 if (tracesFile == null) {
3128 // There is no trace file, so dump (only) the alleged culprit's threads to the log
3129 Process.sendSignal(app.pid, Process.SIGNAL_QUIT);
3130 }
3131
Jeff Sharkeya353d262011-10-28 11:12:06 -07003132 addErrorToDropBox("anr", app, app.processName, activity, parent, annotation,
3133 cpuInfo, tracesFile, null);
Dan Egnor42471dd2010-01-07 17:25:22 -08003134
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003135 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003136 try {
Dan Egnor42471dd2010-01-07 17:25:22 -08003137 // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately
3138 int res = mController.appNotResponding(app.processName, app.pid, info.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003139 if (res != 0) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003140 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3141 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003142 }
3143 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003144 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003145 }
3146 }
3147
Dan Egnor42471dd2010-01-07 17:25:22 -08003148 // Unless configured otherwise, swallow ANRs in background processes & kill the process.
3149 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
3150 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003151
3152 synchronized (this) {
3153 if (!showBackground && !app.isInterestingToUserLocked() && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003154 Slog.w(TAG, "Killing " + app + ": background ANR");
3155 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
3156 app.processName, app.setAdj, "background ANR");
3157 Process.killProcessQuiet(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003158 return;
3159 }
3160
3161 // Set the app's notResponding state, and look up the errorReportReceiver
3162 makeAppNotRespondingLocked(app,
3163 activity != null ? activity.shortComponentName : null,
3164 annotation != null ? "ANR " + annotation : "ANR",
3165 info.toString());
3166
3167 // Bring up the infamous App Not Responding dialog
3168 Message msg = Message.obtain();
3169 HashMap map = new HashMap();
3170 msg.what = SHOW_NOT_RESPONDING_MSG;
3171 msg.obj = map;
3172 map.put("app", app);
3173 if (activity != null) {
3174 map.put("activity", activity);
3175 }
3176
3177 mHandler.sendMessage(msg);
Dan Egnor42471dd2010-01-07 17:25:22 -08003178 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003179 }
3180
Dianne Hackborn0dad3642010-09-09 21:25:35 -07003181 final void showLaunchWarningLocked(final ActivityRecord cur, final ActivityRecord next) {
3182 if (!mLaunchWarningShown) {
3183 mLaunchWarningShown = true;
3184 mHandler.post(new Runnable() {
3185 @Override
3186 public void run() {
3187 synchronized (ActivityManagerService.this) {
3188 final Dialog d = new LaunchWarningWindow(mContext, cur, next);
3189 d.show();
3190 mHandler.postDelayed(new Runnable() {
3191 @Override
3192 public void run() {
3193 synchronized (ActivityManagerService.this) {
3194 d.dismiss();
3195 mLaunchWarningShown = false;
3196 }
3197 }
3198 }, 4000);
3199 }
3200 }
3201 });
3202 }
3203 }
3204
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003205 public boolean clearApplicationUserData(final String packageName,
Amith Yamasani742a6712011-05-04 14:49:28 -07003206 final IPackageDataObserver observer, final int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003207 enforceNotIsolatedCaller("clearApplicationUserData");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003208 int uid = Binder.getCallingUid();
3209 int pid = Binder.getCallingPid();
3210 long callingId = Binder.clearCallingIdentity();
3211 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003212 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003213 int pkgUid = -1;
3214 synchronized(this) {
3215 try {
3216 pkgUid = pm.getPackageUid(packageName);
3217 } catch (RemoteException e) {
3218 }
3219 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003220 Slog.w(TAG, "Invalid packageName:" + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003221 return false;
3222 }
3223 if (uid == pkgUid || checkComponentPermission(
3224 android.Manifest.permission.CLEAR_APP_USER_DATA,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08003225 pid, uid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003226 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003227 forceStopPackageLocked(packageName, pkgUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003228 } else {
3229 throw new SecurityException(pid+" does not have permission:"+
3230 android.Manifest.permission.CLEAR_APP_USER_DATA+" to clear data" +
3231 "for process:"+packageName);
3232 }
3233 }
3234
3235 try {
3236 //clear application user data
3237 pm.clearApplicationUserData(packageName, observer);
3238 Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED,
3239 Uri.fromParts("package", packageName, null));
3240 intent.putExtra(Intent.EXTRA_UID, pkgUid);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003241 broadcastIntentInPackage("android", Process.SYSTEM_UID, intent,
Amith Yamasani742a6712011-05-04 14:49:28 -07003242 null, null, 0, null, null, null, false, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003243 } catch (RemoteException e) {
3244 }
3245 } finally {
3246 Binder.restoreCallingIdentity(callingId);
3247 }
3248 return true;
3249 }
3250
Dianne Hackborn03abb812010-01-04 18:43:19 -08003251 public void killBackgroundProcesses(final String packageName) {
3252 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3253 != PackageManager.PERMISSION_GRANTED &&
3254 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES)
3255 != PackageManager.PERMISSION_GRANTED) {
3256 String msg = "Permission Denial: killBackgroundProcesses() from pid="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003257 + Binder.getCallingPid()
3258 + ", uid=" + Binder.getCallingUid()
Dianne Hackborn03abb812010-01-04 18:43:19 -08003259 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003260 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003261 throw new SecurityException(msg);
3262 }
3263
3264 long callingId = Binder.clearCallingIdentity();
3265 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003266 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003267 int pkgUid = -1;
3268 synchronized(this) {
3269 try {
3270 pkgUid = pm.getPackageUid(packageName);
3271 } catch (RemoteException e) {
3272 }
3273 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003274 Slog.w(TAG, "Invalid packageName: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003275 return;
3276 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003277 killPackageProcessesLocked(packageName, pkgUid,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003278 ProcessList.SERVICE_ADJ, false, true, true, false, "kill background");
3279 }
3280 } finally {
3281 Binder.restoreCallingIdentity(callingId);
3282 }
3283 }
3284
3285 public void killAllBackgroundProcesses() {
3286 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3287 != PackageManager.PERMISSION_GRANTED) {
3288 String msg = "Permission Denial: killAllBackgroundProcesses() from pid="
3289 + Binder.getCallingPid()
3290 + ", uid=" + Binder.getCallingUid()
3291 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
3292 Slog.w(TAG, msg);
3293 throw new SecurityException(msg);
3294 }
3295
3296 long callingId = Binder.clearCallingIdentity();
3297 try {
3298 synchronized(this) {
3299 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
3300 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3301 final int NA = apps.size();
3302 for (int ia=0; ia<NA; ia++) {
3303 ProcessRecord app = apps.valueAt(ia);
3304 if (app.persistent) {
3305 // we don't kill persistent processes
3306 continue;
3307 }
3308 if (app.removed) {
3309 procs.add(app);
3310 } else if (app.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
3311 app.removed = true;
3312 procs.add(app);
3313 }
3314 }
3315 }
3316
3317 int N = procs.size();
3318 for (int i=0; i<N; i++) {
3319 removeProcessLocked(procs.get(i), false, true, "kill all background");
3320 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003321 }
3322 } finally {
3323 Binder.restoreCallingIdentity(callingId);
3324 }
3325 }
3326
3327 public void forceStopPackage(final String packageName) {
3328 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3329 != PackageManager.PERMISSION_GRANTED) {
3330 String msg = "Permission Denial: forceStopPackage() from pid="
3331 + Binder.getCallingPid()
3332 + ", uid=" + Binder.getCallingUid()
3333 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003334 Slog.w(TAG, msg);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003335 throw new SecurityException(msg);
3336 }
Amith Yamasani742a6712011-05-04 14:49:28 -07003337 final int userId = Binder.getOrigCallingUser();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003338 long callingId = Binder.clearCallingIdentity();
3339 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003340 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003341 int pkgUid = -1;
3342 synchronized(this) {
3343 try {
3344 pkgUid = pm.getPackageUid(packageName);
Amith Yamasani742a6712011-05-04 14:49:28 -07003345 // Convert the uid to the one for the calling user
3346 pkgUid = UserId.getUid(userId, pkgUid);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003347 } catch (RemoteException e) {
3348 }
3349 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003350 Slog.w(TAG, "Invalid packageName: " + packageName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003351 return;
3352 }
3353 forceStopPackageLocked(packageName, pkgUid);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003354 try {
3355 pm.setPackageStoppedState(packageName, true);
3356 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08003357 } catch (IllegalArgumentException e) {
3358 Slog.w(TAG, "Failed trying to unstop package "
3359 + packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003360 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003361 }
3362 } finally {
3363 Binder.restoreCallingIdentity(callingId);
3364 }
3365 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003366
3367 /*
3368 * The pkg name and uid have to be specified.
3369 * @see android.app.IActivityManager#killApplicationWithUid(java.lang.String, int)
3370 */
3371 public void killApplicationWithUid(String pkg, int uid) {
3372 if (pkg == null) {
3373 return;
3374 }
3375 // Make sure the uid is valid.
3376 if (uid < 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003377 Slog.w(TAG, "Invalid uid specified for pkg : " + pkg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003378 return;
3379 }
3380 int callerUid = Binder.getCallingUid();
3381 // Only the system server can kill an application
3382 if (callerUid == Process.SYSTEM_UID) {
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07003383 // Post an aysnc message to kill the application
3384 Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG);
3385 msg.arg1 = uid;
3386 msg.arg2 = 0;
3387 msg.obj = pkg;
Suchi Amalapurapud50066f2009-08-18 16:57:41 -07003388 mHandler.sendMessage(msg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003389 } else {
3390 throw new SecurityException(callerUid + " cannot kill pkg: " +
3391 pkg);
3392 }
3393 }
3394
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003395 public void closeSystemDialogs(String reason) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003396 enforceNotIsolatedCaller("closeSystemDialogs");
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003397 Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003398 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003399 if (reason != null) {
3400 intent.putExtra("reason", reason);
3401 }
3402
3403 final int uid = Binder.getCallingUid();
3404 final long origId = Binder.clearCallingIdentity();
3405 synchronized (this) {
Dianne Hackbornffa42482009-09-23 22:20:11 -07003406 mWindowManager.closeSystemDialogs(reason);
3407
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08003408 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003409 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornffa42482009-09-23 22:20:11 -07003410 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003411 r.stack.finishActivityLocked(r, i,
Dianne Hackbornffa42482009-09-23 22:20:11 -07003412 Activity.RESULT_CANCELED, null, "close-sys");
3413 }
3414 }
3415
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003416 broadcastIntentLocked(null, null, intent, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07003417 null, 0, null, null, null, false, false, -1, uid, 0 /* TODO: Verify */);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003418 }
3419 Binder.restoreCallingIdentity(origId);
3420 }
3421
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003422 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids)
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003423 throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003424 enforceNotIsolatedCaller("getProcessMemoryInfo");
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003425 Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length];
3426 for (int i=pids.length-1; i>=0; i--) {
3427 infos[i] = new Debug.MemoryInfo();
3428 Debug.getMemoryInfo(pids[i], infos[i]);
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003429 }
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003430 return infos;
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003431 }
Christopher Tate5e1ab332009-09-01 20:32:49 -07003432
Dianne Hackbornb437e092011-08-05 17:50:29 -07003433 public long[] getProcessPss(int[] pids) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003434 enforceNotIsolatedCaller("getProcessPss");
Dianne Hackbornb437e092011-08-05 17:50:29 -07003435 long[] pss = new long[pids.length];
3436 for (int i=pids.length-1; i>=0; i--) {
3437 pss[i] = Debug.getPss(pids[i]);
3438 }
3439 return pss;
3440 }
3441
Christopher Tate5e1ab332009-09-01 20:32:49 -07003442 public void killApplicationProcess(String processName, int uid) {
3443 if (processName == null) {
3444 return;
3445 }
3446
3447 int callerUid = Binder.getCallingUid();
3448 // Only the system server can kill an application
3449 if (callerUid == Process.SYSTEM_UID) {
3450 synchronized (this) {
3451 ProcessRecord app = getProcessRecordLocked(processName, uid);
Christopher Tate4a627c72011-04-01 14:43:32 -07003452 if (app != null && app.thread != null) {
Christopher Tate5e1ab332009-09-01 20:32:49 -07003453 try {
3454 app.thread.scheduleSuicide();
3455 } catch (RemoteException e) {
3456 // If the other end already died, then our work here is done.
3457 }
3458 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003459 Slog.w(TAG, "Process/uid not found attempting kill of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07003460 + processName + " / " + uid);
3461 }
3462 }
3463 } else {
3464 throw new SecurityException(callerUid + " cannot kill app process: " +
3465 processName);
3466 }
3467 }
3468
Dianne Hackborn03abb812010-01-04 18:43:19 -08003469 private void forceStopPackageLocked(final String packageName, int uid) {
Christopher Tate3dacd842011-08-19 14:56:15 -07003470 forceStopPackageLocked(packageName, uid, false, false, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003471 Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED,
3472 Uri.fromParts("package", packageName, null));
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003473 if (!mProcessesReady) {
3474 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3475 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003476 intent.putExtra(Intent.EXTRA_UID, uid);
3477 broadcastIntentLocked(null, null, intent,
3478 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07003479 false, false,
3480 MY_PID, Process.SYSTEM_UID, UserId.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003481 }
3482
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003483 private final boolean killPackageProcessesLocked(String packageName, int uid,
Christopher Tate3dacd842011-08-19 14:56:15 -07003484 int minOomAdj, boolean callerWillRestart, boolean allowRestart, boolean doit,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003485 boolean evenPersistent, String reason) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003486 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003487
Dianne Hackborn03abb812010-01-04 18:43:19 -08003488 // Remove all processes this package may have touched: all with the
3489 // same UID (except for the system or root user), and all whose name
3490 // matches the package name.
3491 final String procNamePrefix = packageName + ":";
3492 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3493 final int NA = apps.size();
3494 for (int ia=0; ia<NA; ia++) {
3495 ProcessRecord app = apps.valueAt(ia);
Christopher Tate3dacd842011-08-19 14:56:15 -07003496 if (app.persistent && !evenPersistent) {
Christopher Tate064d8422011-07-26 15:38:07 -07003497 // we don't kill persistent processes
3498 continue;
3499 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003500 if (app.removed) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003501 if (doit) {
3502 procs.add(app);
3503 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003504 } else if ((uid > 0 && uid != Process.SYSTEM_UID && app.info.uid == uid)
3505 || app.processName.equals(packageName)
3506 || app.processName.startsWith(procNamePrefix)) {
3507 if (app.setAdj >= minOomAdj) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003508 if (!doit) {
3509 return true;
3510 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003511 app.removed = true;
3512 procs.add(app);
3513 }
3514 }
3515 }
3516 }
3517
3518 int N = procs.size();
3519 for (int i=0; i<N; i++) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003520 removeProcessLocked(procs.get(i), callerWillRestart, allowRestart, reason);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003521 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003522 return N > 0;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003523 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003524
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003525 private final boolean forceStopPackageLocked(String name, int uid,
Christopher Tate3dacd842011-08-19 14:56:15 -07003526 boolean callerWillRestart, boolean purgeCache, boolean doit,
3527 boolean evenPersistent) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003528 int i;
3529 int N;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003530
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003531 if (uid < 0) {
3532 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003533 uid = AppGlobals.getPackageManager().getPackageUid(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003534 } catch (RemoteException e) {
3535 }
3536 }
3537
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003538 if (doit) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003539 Slog.i(TAG, "Force stopping package " + name + " uid=" + uid);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003540
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003541 Iterator<SparseArray<Long>> badApps = mProcessCrashTimes.getMap().values().iterator();
3542 while (badApps.hasNext()) {
3543 SparseArray<Long> ba = badApps.next();
3544 if (ba.get(uid) != null) {
3545 badApps.remove();
3546 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003547 }
3548 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003549
3550 boolean didSomething = killPackageProcessesLocked(name, uid, -100,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003551 callerWillRestart, false, doit, evenPersistent, "force stop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003552
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003553 TaskRecord lastTask = null;
3554 for (i=0; i<mMainStack.mHistory.size(); i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003555 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003556 final boolean samePackage = r.packageName.equals(name);
3557 if ((samePackage || r.task == lastTask)
Christopher Tate3dacd842011-08-19 14:56:15 -07003558 && (r.app == null || evenPersistent || !r.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003559 if (!doit) {
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003560 if (r.finishing) {
3561 // If this activity is just finishing, then it is not
3562 // interesting as far as something to stop.
3563 continue;
3564 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003565 return true;
3566 }
3567 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003568 Slog.i(TAG, " Force finishing activity " + r);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003569 if (samePackage) {
3570 if (r.app != null) {
3571 r.app.removed = true;
3572 }
3573 r.app = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003574 }
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003575 lastTask = r.task;
3576 if (r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
3577 null, "force-stop")) {
3578 i--;
3579 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003580 }
3581 }
3582
3583 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
Amith Yamasani742a6712011-05-04 14:49:28 -07003584 int userId = UserId.getUserId(uid);
3585 for (ServiceRecord service : mServiceMap.getAllServices(userId)) {
Christopher Tate064d8422011-07-26 15:38:07 -07003586 if (service.packageName.equals(name)
Christopher Tate3dacd842011-08-19 14:56:15 -07003587 && (service.app == null || evenPersistent || !service.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003588 if (!doit) {
3589 return true;
3590 }
3591 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003592 Slog.i(TAG, " Force stopping service " + service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003593 if (service.app != null) {
3594 service.app.removed = true;
3595 }
3596 service.app = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003597 service.isolatedProc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003598 services.add(service);
3599 }
3600 }
3601
3602 N = services.size();
3603 for (i=0; i<N; i++) {
3604 bringDownServiceLocked(services.get(i), true);
3605 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003606
3607 ArrayList<ContentProviderRecord> providers = new ArrayList<ContentProviderRecord>();
Amith Yamasani37ce3a82012-02-06 12:04:42 -08003608 for (ContentProviderRecord provider : mProviderMap.getProvidersByClass(-1).values()) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003609 if (provider.info.packageName.equals(name)
3610 && (provider.proc == null || evenPersistent || !provider.proc.persistent)) {
3611 if (!doit) {
3612 return true;
3613 }
3614 didSomething = true;
3615 providers.add(provider);
3616 }
3617 }
3618
3619 N = providers.size();
3620 for (i=0; i<N; i++) {
3621 removeDyingProviderLocked(null, providers.get(i));
3622 }
3623
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003624 if (doit) {
3625 if (purgeCache) {
3626 AttributeCache ac = AttributeCache.instance();
3627 if (ac != null) {
3628 ac.removePackage(name);
3629 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003630 }
Dianne Hackborn38cc8962011-10-13 11:33:55 -07003631 if (mBooted) {
3632 mMainStack.resumeTopActivityLocked(null);
3633 mMainStack.scheduleIdleLocked();
3634 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003635 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003636
3637 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003638 }
3639
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003640 private final boolean removeProcessLocked(ProcessRecord app,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003641 boolean callerWillRestart, boolean allowRestart, String reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003642 final String name = app.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003643 final int uid = app.uid;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003644 if (DEBUG_PROCESSES) Slog.d(
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003645 TAG, "Force removing proc " + app.toShortString() + " (" + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003646 + "/" + uid + ")");
3647
3648 mProcessNames.remove(name, uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003649 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003650 if (mHeavyWeightProcess == app) {
3651 mHeavyWeightProcess = null;
3652 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3653 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003654 boolean needRestart = false;
3655 if (app.pid > 0 && app.pid != MY_PID) {
3656 int pid = app.pid;
3657 synchronized (mPidsSelfLocked) {
3658 mPidsSelfLocked.remove(pid);
3659 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3660 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003661 Slog.i(TAG, "Killing proc " + app.toShortString() + ": " + reason);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003662 handleAppDiedLocked(app, true, allowRestart);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003663 mLruProcesses.remove(app);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003664 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003665
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003666 if (app.persistent && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003667 if (!callerWillRestart) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003668 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003669 } else {
3670 needRestart = true;
3671 }
3672 }
3673 } else {
3674 mRemovedProcesses.add(app);
3675 }
3676
3677 return needRestart;
3678 }
3679
3680 private final void processStartTimedOutLocked(ProcessRecord app) {
3681 final int pid = app.pid;
3682 boolean gone = false;
3683 synchronized (mPidsSelfLocked) {
3684 ProcessRecord knownApp = mPidsSelfLocked.get(pid);
3685 if (knownApp != null && knownApp.thread == null) {
3686 mPidsSelfLocked.remove(pid);
3687 gone = true;
3688 }
3689 }
3690
3691 if (gone) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003692 Slog.w(TAG, "Process " + app + " failed to attach");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003693 EventLog.writeEvent(EventLogTags.AM_PROCESS_START_TIMEOUT, pid, app.uid,
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003694 app.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003695 mProcessNames.remove(app.processName, app.uid);
3696 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003697 if (mHeavyWeightProcess == app) {
3698 mHeavyWeightProcess = null;
3699 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3700 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003701 // Take care of any launching providers waiting for this process.
3702 checkAppInLaunchingProvidersLocked(app, true);
3703 // Take care of any services that are waiting for the process.
3704 for (int i=0; i<mPendingServices.size(); i++) {
3705 ServiceRecord sr = mPendingServices.get(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003706 if ((app.uid == sr.appInfo.uid
3707 && app.processName.equals(sr.processName))
3708 || sr.isolatedProc == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003709 Slog.w(TAG, "Forcing bringing down service: " + sr);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003710 sr.isolatedProc = null;
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003711 mPendingServices.remove(i);
3712 i--;
3713 bringDownServiceLocked(sr, true);
3714 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003715 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003716 EventLog.writeEvent(EventLogTags.AM_KILL, pid,
3717 app.processName, app.setAdj, "start timeout");
3718 Process.killProcessQuiet(pid);
Christopher Tate181fafa2009-05-14 11:12:14 -07003719 if (mBackupTarget != null && mBackupTarget.app.pid == pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003720 Slog.w(TAG, "Unattached app died before backup, skipping");
Christopher Tate181fafa2009-05-14 11:12:14 -07003721 try {
3722 IBackupManager bm = IBackupManager.Stub.asInterface(
3723 ServiceManager.getService(Context.BACKUP_SERVICE));
3724 bm.agentDisconnected(app.info.packageName);
3725 } catch (RemoteException e) {
3726 // Can't happen; the backup manager is local
3727 }
3728 }
Christopher Tatef46723b2012-01-26 14:19:24 -08003729 if (isPendingBroadcastProcessLocked(pid)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003730 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
Christopher Tatef46723b2012-01-26 14:19:24 -08003731 skipPendingBroadcastLocked(pid);
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003732 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003733 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003734 Slog.w(TAG, "Spurious process start timeout - pid not known for " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003735 }
3736 }
3737
3738 private final boolean attachApplicationLocked(IApplicationThread thread,
3739 int pid) {
3740
3741 // Find the application record that is being attached... either via
3742 // the pid if we are running in multiple processes, or just pull the
3743 // next app record if we are emulating process with anonymous threads.
3744 ProcessRecord app;
3745 if (pid != MY_PID && pid >= 0) {
3746 synchronized (mPidsSelfLocked) {
3747 app = mPidsSelfLocked.get(pid);
3748 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003749 } else {
3750 app = null;
3751 }
3752
3753 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003754 Slog.w(TAG, "No pending application record for pid " + pid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003755 + " (IApplicationThread " + thread + "); dropping process");
Doug Zongker2bec3d42009-12-04 12:52:44 -08003756 EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003757 if (pid > 0 && pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003758 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003759 } else {
3760 try {
3761 thread.scheduleExit();
3762 } catch (Exception e) {
3763 // Ignore exceptions.
3764 }
3765 }
3766 return false;
3767 }
3768
3769 // If this application record is still attached to a previous
3770 // process, clean it up now.
3771 if (app.thread != null) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003772 handleAppDiedLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003773 }
3774
3775 // Tell the process all about itself.
3776
Joe Onorato8a9b2202010-02-26 18:56:32 -08003777 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003778 TAG, "Binding process pid " + pid + " to record " + app);
3779
3780 String processName = app.processName;
3781 try {
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07003782 AppDeathRecipient adr = new AppDeathRecipient(
3783 app, pid, thread);
3784 thread.asBinder().linkToDeath(adr, 0);
3785 app.deathRecipient = adr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003786 } catch (RemoteException e) {
3787 app.resetPackageList();
3788 startProcessLocked(app, "link fail", processName);
3789 return false;
3790 }
3791
Doug Zongker2bec3d42009-12-04 12:52:44 -08003792 EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.pid, app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003793
3794 app.thread = thread;
3795 app.curAdj = app.setAdj = -100;
Dianne Hackborn09c916b2009-12-08 14:50:51 -08003796 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
3797 app.setSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003798 app.forcingToForeground = null;
3799 app.foregroundServices = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07003800 app.hasShownUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003801 app.debugging = false;
3802
3803 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3804
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003805 boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003806 List providers = normalMode ? generateApplicationProvidersLocked(app) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003807
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003808 if (!normalMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003809 Slog.i(TAG, "Launching preboot mode app: " + app);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003810 }
3811
Joe Onorato8a9b2202010-02-26 18:56:32 -08003812 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003813 TAG, "New app record " + app
3814 + " thread=" + thread.asBinder() + " pid=" + pid);
3815 try {
3816 int testMode = IApplicationThread.DEBUG_OFF;
3817 if (mDebugApp != null && mDebugApp.equals(processName)) {
3818 testMode = mWaitForDebugger
3819 ? IApplicationThread.DEBUG_WAIT
3820 : IApplicationThread.DEBUG_ON;
3821 app.debugging = true;
3822 if (mDebugTransient) {
3823 mDebugApp = mOrigDebugApp;
3824 mWaitForDebugger = mOrigWaitForDebugger;
3825 }
3826 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003827 String profileFile = app.instrumentationProfileFile;
3828 ParcelFileDescriptor profileFd = null;
3829 boolean profileAutoStop = false;
3830 if (mProfileApp != null && mProfileApp.equals(processName)) {
3831 mProfileProc = app;
3832 profileFile = mProfileFile;
3833 profileFd = mProfileFd;
3834 profileAutoStop = mAutoStopProfiler;
3835 }
3836
Christopher Tate181fafa2009-05-14 11:12:14 -07003837 // If the app is being launched for restore or full backup, set it up specially
3838 boolean isRestrictedBackupMode = false;
3839 if (mBackupTarget != null && mBackupAppName.equals(processName)) {
3840 isRestrictedBackupMode = (mBackupTarget.backupMode == BackupRecord.RESTORE)
Christopher Tate75a99702011-05-18 16:28:19 -07003841 || (mBackupTarget.backupMode == BackupRecord.RESTORE_FULL)
Christopher Tate181fafa2009-05-14 11:12:14 -07003842 || (mBackupTarget.backupMode == BackupRecord.BACKUP_FULL);
3843 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003844
Dianne Hackbornd7f6daa2009-06-22 17:06:35 -07003845 ensurePackageDexOpt(app.instrumentationInfo != null
3846 ? app.instrumentationInfo.packageName
3847 : app.info.packageName);
3848 if (app.instrumentationClass != null) {
3849 ensurePackageDexOpt(app.instrumentationClass.getPackageName());
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003850 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08003851 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Binding proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003852 + processName + " with config " + mConfiguration);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003853 ApplicationInfo appInfo = app.instrumentationInfo != null
3854 ? app.instrumentationInfo : app.info;
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -07003855 app.compat = compatibilityInfoForPackageLocked(appInfo);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003856 if (profileFd != null) {
3857 profileFd = profileFd.dup();
3858 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003859 thread.bindApplication(processName, appInfo, providers,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003860 app.instrumentationClass, profileFile, profileFd, profileAutoStop,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003861 app.instrumentationArguments, app.instrumentationWatcher, testMode,
Dianne Hackborn5d927c22011-09-02 12:22:18 -07003862 isRestrictedBackupMode || !normalMode, app.persistent,
Dianne Hackborn813075a62011-11-14 17:45:19 -08003863 new Configuration(mConfiguration), app.compat, getCommonServicesLocked(),
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08003864 mCoreSettingsObserver.getCoreSettingsLocked());
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003865 updateLruProcessLocked(app, false, true);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003866 app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003867 } catch (Exception e) {
3868 // todo: Yikes! What should we do? For now we will try to
3869 // start another process, but that could easily get us in
3870 // an infinite loop of restarting processes...
Joe Onorato8a9b2202010-02-26 18:56:32 -08003871 Slog.w(TAG, "Exception thrown during bind!", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003872
3873 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07003874 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003875 startProcessLocked(app, "bind fail", processName);
3876 return false;
3877 }
3878
3879 // Remove this record from the list of starting applications.
3880 mPersistentStartingProcesses.remove(app);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003881 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
3882 "Attach application locked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003883 mProcessesOnHold.remove(app);
3884
3885 boolean badApp = false;
3886 boolean didSomething = false;
3887
3888 // See if the top visible activity is waiting to run in this process...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003889 ActivityRecord hr = mMainStack.topRunningActivityLocked(null);
Christopher Tate04c0af82010-06-07 18:35:20 -07003890 if (hr != null && normalMode) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003891 if (hr.app == null && app.uid == hr.info.applicationInfo.uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003892 && processName.equals(hr.processName)) {
3893 try {
Mike Lockwood3a74bd32011-08-12 13:55:22 -07003894 if (mHeadless) {
3895 Slog.e(TAG, "Starting activities not supported on headless device: " + hr);
3896 } else if (mMainStack.realStartActivityLocked(hr, app, true, true)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003897 didSomething = true;
3898 }
3899 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003900 Slog.w(TAG, "Exception in new application when starting activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003901 + hr.intent.getComponent().flattenToShortString(), e);
3902 badApp = true;
3903 }
3904 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003905 mMainStack.ensureActivitiesVisibleLocked(hr, null, processName, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003906 }
3907 }
3908
3909 // Find any services that should be running in this process...
3910 if (!badApp && mPendingServices.size() > 0) {
3911 ServiceRecord sr = null;
3912 try {
3913 for (int i=0; i<mPendingServices.size(); i++) {
3914 sr = mPendingServices.get(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003915 if (app != sr.isolatedProc && (app.uid != sr.appInfo.uid
3916 || !processName.equals(sr.processName))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003917 continue;
3918 }
3919
3920 mPendingServices.remove(i);
3921 i--;
3922 realStartServiceLocked(sr, app);
3923 didSomething = true;
3924 }
3925 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003926 Slog.w(TAG, "Exception in new application when starting service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003927 + sr.shortName, e);
3928 badApp = true;
3929 }
3930 }
3931
Christopher Tatef46723b2012-01-26 14:19:24 -08003932 // Check if a next-broadcast receiver is in this process...
3933 if (!badApp && isPendingBroadcastProcessLocked(pid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003934 try {
Christopher Tatef46723b2012-01-26 14:19:24 -08003935 didSomething = sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003936 } catch (Exception e) {
Christopher Tatef46723b2012-01-26 14:19:24 -08003937 // If the app died trying to launch the receiver we declare it 'bad'
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003938 badApp = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003939 }
3940 }
3941
Christopher Tate181fafa2009-05-14 11:12:14 -07003942 // Check whether the next backup agent is in this process...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003943 if (!badApp && mBackupTarget != null && mBackupTarget.appInfo.uid == app.uid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003944 if (DEBUG_BACKUP) Slog.v(TAG, "New app is backup target, launching agent for " + app);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003945 ensurePackageDexOpt(mBackupTarget.appInfo.packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07003946 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003947 thread.scheduleCreateBackupAgent(mBackupTarget.appInfo,
3948 compatibilityInfoForPackageLocked(mBackupTarget.appInfo),
3949 mBackupTarget.backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -07003950 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003951 Slog.w(TAG, "Exception scheduling backup agent creation: ");
Christopher Tate181fafa2009-05-14 11:12:14 -07003952 e.printStackTrace();
3953 }
3954 }
3955
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003956 if (badApp) {
3957 // todo: Also need to kill application to deal with all
3958 // kinds of exceptions.
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003959 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003960 return false;
3961 }
3962
3963 if (!didSomething) {
3964 updateOomAdjLocked();
3965 }
3966
3967 return true;
3968 }
3969
3970 public final void attachApplication(IApplicationThread thread) {
3971 synchronized (this) {
3972 int callingPid = Binder.getCallingPid();
3973 final long origId = Binder.clearCallingIdentity();
3974 attachApplicationLocked(thread, callingPid);
3975 Binder.restoreCallingIdentity(origId);
3976 }
3977 }
3978
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003979 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003980 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003981 ActivityRecord r = mMainStack.activityIdleInternal(token, false, config);
3982 if (stopProfiling) {
3983 synchronized (this) {
3984 if (mProfileProc == r.app) {
3985 if (mProfileFd != null) {
3986 try {
3987 mProfileFd.close();
3988 } catch (IOException e) {
3989 }
3990 clearProfilerLocked();
3991 }
3992 }
3993 }
3994 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003995 Binder.restoreCallingIdentity(origId);
3996 }
3997
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003998 void enableScreenAfterBoot() {
Doug Zongker2bec3d42009-12-04 12:52:44 -08003999 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004000 SystemClock.uptimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004001 mWindowManager.enableScreenAfterBoot();
4002 }
4003
Dianne Hackborn661cd522011-08-22 00:26:20 -07004004 public void showBootMessage(final CharSequence msg, final boolean always) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004005 enforceNotIsolatedCaller("showBootMessage");
Dianne Hackborn661cd522011-08-22 00:26:20 -07004006 mWindowManager.showBootMessage(msg, always);
4007 }
4008
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004009 public void dismissKeyguardOnNextActivity() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004010 enforceNotIsolatedCaller("dismissKeyguardOnNextActivity");
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004011 synchronized (this) {
4012 mMainStack.dismissKeyguardOnNextActivityLocked();
4013 }
4014 }
4015
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004016 final void finishBooting() {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004017 IntentFilter pkgFilter = new IntentFilter();
4018 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
4019 pkgFilter.addDataScheme("package");
4020 mContext.registerReceiver(new BroadcastReceiver() {
4021 @Override
4022 public void onReceive(Context context, Intent intent) {
4023 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
4024 if (pkgs != null) {
4025 for (String pkg : pkgs) {
Vairavan Srinivasan61f07652010-07-22 13:36:40 -07004026 synchronized (ActivityManagerService.this) {
Christopher Tate3dacd842011-08-19 14:56:15 -07004027 if (forceStopPackageLocked(pkg, -1, false, false, false, false)) {
Vairavan Srinivasan61f07652010-07-22 13:36:40 -07004028 setResultCode(Activity.RESULT_OK);
4029 return;
4030 }
4031 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004032 }
4033 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004034 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004035 }, pkgFilter);
4036
4037 synchronized (this) {
4038 // Ensure that any processes we had put on hold are now started
4039 // up.
4040 final int NP = mProcessesOnHold.size();
4041 if (NP > 0) {
4042 ArrayList<ProcessRecord> procs =
4043 new ArrayList<ProcessRecord>(mProcessesOnHold);
4044 for (int ip=0; ip<NP; ip++) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004045 if (DEBUG_PROCESSES) Slog.v(TAG, "Starting process on hold: "
4046 + procs.get(ip));
4047 startProcessLocked(procs.get(ip), "on-hold", null);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004048 }
4049 }
4050
4051 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004052 // Start looking for apps that are abusing wake locks.
4053 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07004054 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004055 // Tell anyone interested that we are done booting!
Dianne Hackbornf4c454b2010-08-11 12:47:41 -07004056 SystemProperties.set("sys.boot_completed", "1");
Guang Zhu191713a2012-01-12 12:02:22 -08004057 SystemProperties.set("dev.bootcomplete", "1");
Amith Yamasani742a6712011-05-04 14:49:28 -07004058 /* TODO: Send this to all users that are to be logged in on startup */
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004059 broadcastIntentLocked(null, null,
4060 new Intent(Intent.ACTION_BOOT_COMPLETED, null),
4061 null, null, 0, null, null,
4062 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
Amith Yamasani742a6712011-05-04 14:49:28 -07004063 false, false, MY_PID, Process.SYSTEM_UID, Binder.getOrigCallingUser());
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004064 }
4065 }
4066 }
4067
4068 final void ensureBootCompleted() {
4069 boolean booting;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004070 boolean enableScreen;
4071 synchronized (this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004072 booting = mBooting;
4073 mBooting = false;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004074 enableScreen = !mBooted;
4075 mBooted = true;
4076 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004077
4078 if (booting) {
4079 finishBooting();
4080 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004081
4082 if (enableScreen) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004083 enableScreenAfterBoot();
4084 }
4085 }
4086
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004087 public final void activityPaused(IBinder token) {
4088 final long origId = Binder.clearCallingIdentity();
4089 mMainStack.activityPaused(token, false);
4090 Binder.restoreCallingIdentity(origId);
4091 }
4092
4093 public final void activityStopped(IBinder token, Bundle icicle, Bitmap thumbnail,
4094 CharSequence description) {
4095 if (localLOGV) Slog.v(
4096 TAG, "Activity stopped: token=" + token);
4097
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004098 // Refuse possible leaked file descriptors
4099 if (icicle != null && icicle.hasFileDescriptors()) {
4100 throw new IllegalArgumentException("File descriptors passed in Bundle");
4101 }
4102
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004103 ActivityRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004104
4105 final long origId = Binder.clearCallingIdentity();
4106
4107 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004108 r = mMainStack.isInStackLocked(token);
4109 if (r != null) {
4110 r.stack.activityStoppedLocked(r, icicle, thumbnail, description);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004111 }
4112 }
4113
4114 if (r != null) {
4115 sendPendingThumbnail(r, null, null, null, false);
4116 }
4117
4118 trimApplications();
4119
4120 Binder.restoreCallingIdentity(origId);
4121 }
4122
4123 public final void activityDestroyed(IBinder token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004124 if (DEBUG_SWITCH) Slog.v(TAG, "ACTIVITY DESTROYED: " + token);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004125 mMainStack.activityDestroyed(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004126 }
4127
4128 public String getCallingPackage(IBinder token) {
4129 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004130 ActivityRecord r = getCallingRecordLocked(token);
Dianne Hackborn9bbcb912009-10-20 15:42:38 -07004131 return r != null && r.app != null ? r.info.packageName : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004132 }
4133 }
4134
4135 public ComponentName getCallingActivity(IBinder token) {
4136 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004137 ActivityRecord r = getCallingRecordLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004138 return r != null ? r.intent.getComponent() : null;
4139 }
4140 }
4141
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004142 private ActivityRecord getCallingRecordLocked(IBinder token) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004143 ActivityRecord r = mMainStack.isInStackLocked(token);
4144 if (r == null) {
4145 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004146 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004147 return r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004148 }
4149
4150 public ComponentName getActivityClassForToken(IBinder token) {
4151 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004152 ActivityRecord r = mMainStack.isInStackLocked(token);
4153 if (r == null) {
4154 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004155 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004156 return r.intent.getComponent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004157 }
4158 }
4159
4160 public String getPackageForToken(IBinder token) {
4161 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004162 ActivityRecord r = mMainStack.isInStackLocked(token);
4163 if (r == null) {
4164 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004165 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004166 return r.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004167 }
4168 }
4169
4170 public IIntentSender getIntentSender(int type,
4171 String packageName, IBinder token, String resultWho,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004172 int requestCode, Intent[] intents, String[] resolvedTypes, int flags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004173 enforceNotIsolatedCaller("getIntentSender");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004174 // Refuse possible leaked file descriptors
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004175 if (intents != null) {
4176 if (intents.length < 1) {
4177 throw new IllegalArgumentException("Intents array length must be >= 1");
4178 }
4179 for (int i=0; i<intents.length; i++) {
4180 Intent intent = intents[i];
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004181 if (intent != null) {
4182 if (intent.hasFileDescriptors()) {
4183 throw new IllegalArgumentException("File descriptors passed in Intent");
4184 }
4185 if (type == INTENT_SENDER_BROADCAST &&
4186 (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
4187 throw new IllegalArgumentException(
4188 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
4189 }
4190 intents[i] = new Intent(intent);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004191 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004192 }
4193 if (resolvedTypes != null && resolvedTypes.length != intents.length) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004194 throw new IllegalArgumentException(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004195 "Intent array length does not match resolvedTypes length");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004196 }
4197 }
4198
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004199 synchronized(this) {
4200 int callingUid = Binder.getCallingUid();
4201 try {
Jeff Brown10e89712011-07-08 18:52:57 -07004202 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004203 int uid = AppGlobals.getPackageManager()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004204 .getPackageUid(packageName);
Amith Yamasani742a6712011-05-04 14:49:28 -07004205 if (UserId.getAppId(callingUid) != uid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004206 String msg = "Permission Denial: getIntentSender() from pid="
4207 + Binder.getCallingPid()
4208 + ", uid=" + Binder.getCallingUid()
4209 + ", (need uid=" + uid + ")"
4210 + " is not allowed to send as package " + packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004211 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004212 throw new SecurityException(msg);
4213 }
4214 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004215
Amith Yamasani742a6712011-05-04 14:49:28 -07004216 if (DEBUG_MU)
4217 Slog.i(TAG_MU, "Getting intent sender for origCallingUid="
4218 + Binder.getOrigCallingUid());
4219 return getIntentSenderLocked(type, packageName, Binder.getOrigCallingUid(),
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004220 token, resultWho, requestCode, intents, resolvedTypes, flags);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004221
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004222 } catch (RemoteException e) {
4223 throw new SecurityException(e);
4224 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004225 }
4226 }
4227
4228 IIntentSender getIntentSenderLocked(int type,
4229 String packageName, int callingUid, IBinder token, String resultWho,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004230 int requestCode, Intent[] intents, String[] resolvedTypes, int flags) {
Amith Yamasani742a6712011-05-04 14:49:28 -07004231 if (DEBUG_MU)
4232 Slog.v(TAG_MU, "getIntentSenderLocked(): uid=" + callingUid);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004233 ActivityRecord activity = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07004234 if (type == INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004235 activity = mMainStack.isInStackLocked(token);
4236 if (activity == null) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004237 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004238 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004239 if (activity.finishing) {
4240 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004241 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004242 }
4243
4244 final boolean noCreate = (flags&PendingIntent.FLAG_NO_CREATE) != 0;
4245 final boolean cancelCurrent = (flags&PendingIntent.FLAG_CANCEL_CURRENT) != 0;
4246 final boolean updateCurrent = (flags&PendingIntent.FLAG_UPDATE_CURRENT) != 0;
4247 flags &= ~(PendingIntent.FLAG_NO_CREATE|PendingIntent.FLAG_CANCEL_CURRENT
4248 |PendingIntent.FLAG_UPDATE_CURRENT);
4249
4250 PendingIntentRecord.Key key = new PendingIntentRecord.Key(
4251 type, packageName, activity, resultWho,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004252 requestCode, intents, resolvedTypes, flags);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004253 WeakReference<PendingIntentRecord> ref;
4254 ref = mIntentSenderRecords.get(key);
4255 PendingIntentRecord rec = ref != null ? ref.get() : null;
4256 if (rec != null) {
4257 if (!cancelCurrent) {
4258 if (updateCurrent) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004259 if (rec.key.requestIntent != null) {
4260 rec.key.requestIntent.replaceExtras(intents != null ? intents[0] : null);
4261 }
4262 if (intents != null) {
4263 intents[intents.length-1] = rec.key.requestIntent;
4264 rec.key.allIntents = intents;
4265 rec.key.allResolvedTypes = resolvedTypes;
4266 } else {
4267 rec.key.allIntents = null;
4268 rec.key.allResolvedTypes = null;
4269 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004270 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004271 return rec;
4272 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004273 rec.canceled = true;
4274 mIntentSenderRecords.remove(key);
4275 }
4276 if (noCreate) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004277 return rec;
4278 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004279 rec = new PendingIntentRecord(this, key, callingUid);
4280 mIntentSenderRecords.put(key, rec.ref);
4281 if (type == INTENT_SENDER_ACTIVITY_RESULT) {
4282 if (activity.pendingResults == null) {
4283 activity.pendingResults
4284 = new HashSet<WeakReference<PendingIntentRecord>>();
4285 }
4286 activity.pendingResults.add(rec.ref);
4287 }
4288 return rec;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004289 }
4290
4291 public void cancelIntentSender(IIntentSender sender) {
4292 if (!(sender instanceof PendingIntentRecord)) {
4293 return;
4294 }
4295 synchronized(this) {
4296 PendingIntentRecord rec = (PendingIntentRecord)sender;
4297 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004298 int uid = AppGlobals.getPackageManager()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004299 .getPackageUid(rec.key.packageName);
4300 if (uid != Binder.getCallingUid()) {
4301 String msg = "Permission Denial: cancelIntentSender() from pid="
4302 + Binder.getCallingPid()
4303 + ", uid=" + Binder.getCallingUid()
4304 + " is not allowed to cancel packges "
4305 + rec.key.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004306 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004307 throw new SecurityException(msg);
4308 }
4309 } catch (RemoteException e) {
4310 throw new SecurityException(e);
4311 }
4312 cancelIntentSenderLocked(rec, true);
4313 }
4314 }
4315
4316 void cancelIntentSenderLocked(PendingIntentRecord rec, boolean cleanActivity) {
4317 rec.canceled = true;
4318 mIntentSenderRecords.remove(rec.key);
4319 if (cleanActivity && rec.key.activity != null) {
4320 rec.key.activity.pendingResults.remove(rec.ref);
4321 }
4322 }
4323
4324 public String getPackageForIntentSender(IIntentSender pendingResult) {
4325 if (!(pendingResult instanceof PendingIntentRecord)) {
4326 return null;
4327 }
Brad Fitzpatrickb213d102010-04-19 11:58:52 -07004328 try {
4329 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4330 return res.key.packageName;
4331 } catch (ClassCastException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004332 }
4333 return null;
4334 }
4335
Dianne Hackborn6c418d52011-06-29 14:05:33 -07004336 public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) {
4337 if (!(pendingResult instanceof PendingIntentRecord)) {
4338 return false;
4339 }
4340 try {
4341 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4342 if (res.key.allIntents == null) {
4343 return false;
4344 }
4345 for (int i=0; i<res.key.allIntents.length; i++) {
4346 Intent intent = res.key.allIntents[i];
4347 if (intent.getPackage() != null && intent.getComponent() != null) {
4348 return false;
4349 }
4350 }
4351 return true;
4352 } catch (ClassCastException e) {
4353 }
4354 return false;
4355 }
4356
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004357 public void setProcessLimit(int max) {
4358 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4359 "setProcessLimit()");
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004360 synchronized (this) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07004361 mProcessLimit = max < 0 ? ProcessList.MAX_HIDDEN_APPS : max;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004362 mProcessLimitOverride = max;
4363 }
4364 trimApplications();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004365 }
4366
4367 public int getProcessLimit() {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004368 synchronized (this) {
4369 return mProcessLimitOverride;
4370 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004371 }
4372
4373 void foregroundTokenDied(ForegroundToken token) {
4374 synchronized (ActivityManagerService.this) {
4375 synchronized (mPidsSelfLocked) {
4376 ForegroundToken cur
4377 = mForegroundProcesses.get(token.pid);
4378 if (cur != token) {
4379 return;
4380 }
4381 mForegroundProcesses.remove(token.pid);
4382 ProcessRecord pr = mPidsSelfLocked.get(token.pid);
4383 if (pr == null) {
4384 return;
4385 }
4386 pr.forcingToForeground = null;
4387 pr.foregroundServices = false;
4388 }
4389 updateOomAdjLocked();
4390 }
4391 }
4392
4393 public void setProcessForeground(IBinder token, int pid, boolean isForeground) {
4394 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4395 "setProcessForeground()");
4396 synchronized(this) {
4397 boolean changed = false;
4398
4399 synchronized (mPidsSelfLocked) {
4400 ProcessRecord pr = mPidsSelfLocked.get(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004401 if (pr == null && isForeground) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004402 Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004403 return;
4404 }
4405 ForegroundToken oldToken = mForegroundProcesses.get(pid);
4406 if (oldToken != null) {
4407 oldToken.token.unlinkToDeath(oldToken, 0);
4408 mForegroundProcesses.remove(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004409 if (pr != null) {
4410 pr.forcingToForeground = null;
4411 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004412 changed = true;
4413 }
4414 if (isForeground && token != null) {
4415 ForegroundToken newToken = new ForegroundToken() {
4416 public void binderDied() {
4417 foregroundTokenDied(this);
4418 }
4419 };
4420 newToken.pid = pid;
4421 newToken.token = token;
4422 try {
4423 token.linkToDeath(newToken, 0);
4424 mForegroundProcesses.put(pid, newToken);
4425 pr.forcingToForeground = token;
4426 changed = true;
4427 } catch (RemoteException e) {
4428 // If the process died while doing this, we will later
4429 // do the cleanup with the process death link.
4430 }
4431 }
4432 }
4433
4434 if (changed) {
4435 updateOomAdjLocked();
4436 }
4437 }
4438 }
4439
4440 // =========================================================
4441 // PERMISSIONS
4442 // =========================================================
4443
4444 static class PermissionController extends IPermissionController.Stub {
4445 ActivityManagerService mActivityManagerService;
4446 PermissionController(ActivityManagerService activityManagerService) {
4447 mActivityManagerService = activityManagerService;
4448 }
4449
4450 public boolean checkPermission(String permission, int pid, int uid) {
4451 return mActivityManagerService.checkPermission(permission, pid,
4452 uid) == PackageManager.PERMISSION_GRANTED;
4453 }
4454 }
4455
4456 /**
4457 * This can be called with or without the global lock held.
4458 */
4459 int checkComponentPermission(String permission, int pid, int uid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004460 int owningUid, boolean exported) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004461 // We might be performing an operation on behalf of an indirect binder
4462 // invocation, e.g. via {@link #openContentUri}. Check and adjust the
4463 // client identity accordingly before proceeding.
4464 Identity tlsIdentity = sCallerIdentity.get();
4465 if (tlsIdentity != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004466 Slog.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004467 + tlsIdentity.pid + "," + tlsIdentity.uid + "}");
4468 uid = tlsIdentity.uid;
4469 pid = tlsIdentity.pid;
4470 }
4471
4472 // Root, system server and our own process get to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07004473 if (uid == 0 || uid == Process.SYSTEM_UID || pid == MY_PID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004474 return PackageManager.PERMISSION_GRANTED;
4475 }
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004476 // Isolated processes don't get any permissions.
4477 if (UserId.isIsolated(uid)) {
4478 return PackageManager.PERMISSION_DENIED;
4479 }
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004480 // If there is a uid that owns whatever is being accessed, it has
4481 // blanket access to it regardless of the permissions it requires.
Amith Yamasani742a6712011-05-04 14:49:28 -07004482 if (owningUid >= 0 && UserId.isSameApp(uid, owningUid)) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004483 return PackageManager.PERMISSION_GRANTED;
4484 }
4485 // If the target is not exported, then nobody else can get to it.
4486 if (!exported) {
4487 Slog.w(TAG, "Permission denied: checkComponentPermission() owningUid=" + owningUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004488 return PackageManager.PERMISSION_DENIED;
4489 }
4490 if (permission == null) {
4491 return PackageManager.PERMISSION_GRANTED;
4492 }
4493 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004494 return AppGlobals.getPackageManager()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004495 .checkUidPermission(permission, uid);
4496 } catch (RemoteException e) {
4497 // Should never happen, but if it does... deny!
Joe Onorato8a9b2202010-02-26 18:56:32 -08004498 Slog.e(TAG, "PackageManager is dead?!?", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004499 }
4500 return PackageManager.PERMISSION_DENIED;
4501 }
4502
4503 /**
4504 * As the only public entry point for permissions checking, this method
4505 * can enforce the semantic that requesting a check on a null global
4506 * permission is automatically denied. (Internally a null permission
4507 * string is used when calling {@link #checkComponentPermission} in cases
4508 * when only uid-based security is needed.)
4509 *
4510 * This can be called with or without the global lock held.
4511 */
4512 public int checkPermission(String permission, int pid, int uid) {
4513 if (permission == null) {
4514 return PackageManager.PERMISSION_DENIED;
4515 }
Amith Yamasani742a6712011-05-04 14:49:28 -07004516 return checkComponentPermission(permission, pid, UserId.getAppId(uid), -1, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004517 }
4518
4519 /**
4520 * Binder IPC calls go through the public entry point.
4521 * This can be called with or without the global lock held.
4522 */
4523 int checkCallingPermission(String permission) {
4524 return checkPermission(permission,
4525 Binder.getCallingPid(),
Amith Yamasani742a6712011-05-04 14:49:28 -07004526 UserId.getAppId(Binder.getCallingUid()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004527 }
4528
4529 /**
4530 * This can be called with or without the global lock held.
4531 */
4532 void enforceCallingPermission(String permission, String func) {
4533 if (checkCallingPermission(permission)
4534 == PackageManager.PERMISSION_GRANTED) {
4535 return;
4536 }
4537
4538 String msg = "Permission Denial: " + func + " from pid="
4539 + Binder.getCallingPid()
4540 + ", uid=" + Binder.getCallingUid()
4541 + " requires " + permission;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004542 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004543 throw new SecurityException(msg);
4544 }
4545
4546 private final boolean checkHoldingPermissionsLocked(IPackageManager pm,
Dianne Hackborn48058e82010-09-27 16:53:23 -07004547 ProviderInfo pi, Uri uri, int uid, int modeFlags) {
4548 boolean readPerm = (modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) == 0;
4549 boolean writePerm = (modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) == 0;
4550 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4551 "checkHoldingPermissionsLocked: uri=" + uri + " uid=" + uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004552 try {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004553 // Is the component private from the target uid?
4554 final boolean prv = !pi.exported && pi.applicationInfo.uid != uid;
4555
4556 // Acceptable if the there is no read permission needed from the
4557 // target or the target is holding the read permission.
4558 if (!readPerm) {
4559 if ((!prv && pi.readPermission == null) ||
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004560 (pm.checkUidPermission(pi.readPermission, uid)
Dianne Hackborn48058e82010-09-27 16:53:23 -07004561 == PackageManager.PERMISSION_GRANTED)) {
4562 readPerm = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004563 }
4564 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004565
4566 // Acceptable if the there is no write permission needed from the
4567 // target or the target is holding the read permission.
4568 if (!writePerm) {
4569 if (!prv && (pi.writePermission == null) ||
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004570 (pm.checkUidPermission(pi.writePermission, uid)
Dianne Hackborn48058e82010-09-27 16:53:23 -07004571 == PackageManager.PERMISSION_GRANTED)) {
4572 writePerm = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004573 }
4574 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004575
4576 // Acceptable if there is a path permission matching the URI that
4577 // the target holds the permission on.
4578 PathPermission[] pps = pi.pathPermissions;
4579 if (pps != null && (!readPerm || !writePerm)) {
4580 final String path = uri.getPath();
4581 int i = pps.length;
4582 while (i > 0 && (!readPerm || !writePerm)) {
4583 i--;
4584 PathPermission pp = pps[i];
4585 if (!readPerm) {
4586 final String pprperm = pp.getReadPermission();
4587 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking read perm for "
4588 + pprperm + " for " + pp.getPath()
4589 + ": match=" + pp.match(path)
4590 + " check=" + pm.checkUidPermission(pprperm, uid));
4591 if (pprperm != null && pp.match(path) &&
4592 (pm.checkUidPermission(pprperm, uid)
4593 == PackageManager.PERMISSION_GRANTED)) {
4594 readPerm = true;
4595 }
4596 }
4597 if (!writePerm) {
4598 final String ppwperm = pp.getWritePermission();
4599 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking write perm "
4600 + ppwperm + " for " + pp.getPath()
4601 + ": match=" + pp.match(path)
4602 + " check=" + pm.checkUidPermission(ppwperm, uid));
4603 if (ppwperm != null && pp.match(path) &&
4604 (pm.checkUidPermission(ppwperm, uid)
4605 == PackageManager.PERMISSION_GRANTED)) {
4606 writePerm = true;
4607 }
4608 }
4609 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07004610 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004611 } catch (RemoteException e) {
4612 return false;
4613 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004614
4615 return readPerm && writePerm;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004616 }
4617
4618 private final boolean checkUriPermissionLocked(Uri uri, int uid,
4619 int modeFlags) {
4620 // Root gets to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07004621 if (uid == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004622 return true;
4623 }
4624 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(uid);
4625 if (perms == null) return false;
4626 UriPermission perm = perms.get(uri);
4627 if (perm == null) return false;
4628 return (modeFlags&perm.modeFlags) == modeFlags;
4629 }
4630
4631 public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004632 enforceNotIsolatedCaller("checkUriPermission");
4633
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004634 // Another redirected-binder-call permissions check as in
4635 // {@link checkComponentPermission}.
4636 Identity tlsIdentity = sCallerIdentity.get();
4637 if (tlsIdentity != null) {
4638 uid = tlsIdentity.uid;
4639 pid = tlsIdentity.pid;
4640 }
4641
Amith Yamasani742a6712011-05-04 14:49:28 -07004642 uid = UserId.getAppId(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004643 // Our own process gets to do everything.
4644 if (pid == MY_PID) {
4645 return PackageManager.PERMISSION_GRANTED;
4646 }
4647 synchronized(this) {
4648 return checkUriPermissionLocked(uri, uid, modeFlags)
4649 ? PackageManager.PERMISSION_GRANTED
4650 : PackageManager.PERMISSION_DENIED;
4651 }
4652 }
4653
Dianne Hackborn39792d22010-08-19 18:01:52 -07004654 /**
4655 * Check if the targetPkg can be granted permission to access uri by
4656 * the callingUid using the given modeFlags. Throws a security exception
4657 * if callingUid is not allowed to do this. Returns the uid of the target
4658 * if the URI permission grant should be performed; returns -1 if it is not
4659 * needed (for example targetPkg already has permission to access the URI).
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004660 * If you already know the uid of the target, you can supply it in
4661 * lastTargetUid else set that to -1.
Dianne Hackborn39792d22010-08-19 18:01:52 -07004662 */
4663 int checkGrantUriPermissionLocked(int callingUid, String targetPkg,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004664 Uri uri, int modeFlags, int lastTargetUid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004665 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4666 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4667 if (modeFlags == 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004668 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004669 }
4670
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004671 if (targetPkg != null) {
4672 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4673 "Checking grant " + targetPkg + " permission to " + uri);
4674 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004675
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004676 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004677
4678 // If this is not a content: uri, we can't do anything with it.
4679 if (!ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004680 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004681 "Can't grant URI permission for non-content URI: " + uri);
Dianne Hackborn39792d22010-08-19 18:01:52 -07004682 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004683 }
4684
4685 String name = uri.getAuthority();
4686 ProviderInfo pi = null;
Amith Yamasani742a6712011-05-04 14:49:28 -07004687 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
4688 UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004689 if (cpr != null) {
4690 pi = cpr.info;
4691 } else {
4692 try {
4693 pi = pm.resolveContentProvider(name,
4694 PackageManager.GET_URI_PERMISSION_PATTERNS);
4695 } catch (RemoteException ex) {
4696 }
4697 }
4698 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07004699 Slog.w(TAG, "No content provider found for permission check: " + uri.toSafeString());
Dianne Hackborn39792d22010-08-19 18:01:52 -07004700 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004701 }
4702
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004703 int targetUid = lastTargetUid;
4704 if (targetUid < 0 && targetPkg != null) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004705 try {
4706 targetUid = pm.getPackageUid(targetPkg);
4707 if (targetUid < 0) {
4708 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4709 "Can't grant URI permission no uid for: " + targetPkg);
4710 return -1;
4711 }
4712 } catch (RemoteException ex) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004713 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004714 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004715 }
4716
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004717 if (targetUid >= 0) {
4718 // First... does the target actually need this permission?
4719 if (checkHoldingPermissionsLocked(pm, pi, uri, targetUid, modeFlags)) {
4720 // No need to grant the target this permission.
4721 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4722 "Target " + targetPkg + " already has full permission to " + uri);
4723 return -1;
4724 }
4725 } else {
4726 // First... there is no target package, so can anyone access it?
4727 boolean allowed = pi.exported;
4728 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
4729 if (pi.readPermission != null) {
4730 allowed = false;
4731 }
4732 }
4733 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
4734 if (pi.writePermission != null) {
4735 allowed = false;
4736 }
4737 }
4738 if (allowed) {
4739 return -1;
4740 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004741 }
4742
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004743 // Second... is the provider allowing granting of URI permissions?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004744 if (!pi.grantUriPermissions) {
4745 throw new SecurityException("Provider " + pi.packageName
4746 + "/" + pi.name
4747 + " does not allow granting of Uri permissions (uri "
4748 + uri + ")");
4749 }
4750 if (pi.uriPermissionPatterns != null) {
4751 final int N = pi.uriPermissionPatterns.length;
4752 boolean allowed = false;
4753 for (int i=0; i<N; i++) {
4754 if (pi.uriPermissionPatterns[i] != null
4755 && pi.uriPermissionPatterns[i].match(uri.getPath())) {
4756 allowed = true;
4757 break;
4758 }
4759 }
4760 if (!allowed) {
4761 throw new SecurityException("Provider " + pi.packageName
4762 + "/" + pi.name
4763 + " does not allow granting of permission to path of Uri "
4764 + uri);
4765 }
4766 }
4767
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004768 // Third... does the caller itself have permission to access
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004769 // this uri?
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004770 if (callingUid != Process.myUid()) {
4771 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
4772 if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
4773 throw new SecurityException("Uid " + callingUid
4774 + " does not have permission to uri " + uri);
4775 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004776 }
4777 }
4778
Dianne Hackborn39792d22010-08-19 18:01:52 -07004779 return targetUid;
4780 }
4781
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004782 public int checkGrantUriPermission(int callingUid, String targetPkg,
4783 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004784 enforceNotIsolatedCaller("checkGrantUriPermission");
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004785 synchronized(this) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004786 return checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004787 }
4788 }
4789
Dianne Hackborn39792d22010-08-19 18:01:52 -07004790 void grantUriPermissionUncheckedLocked(int targetUid, String targetPkg,
4791 Uri uri, int modeFlags, UriPermissionOwner owner) {
4792 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4793 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4794 if (modeFlags == 0) {
4795 return;
4796 }
4797
4798 // So here we are: the caller has the assumed permission
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004799 // to the uri, and the target doesn't. Let's now give this to
4800 // the target.
4801
Joe Onorato8a9b2202010-02-26 18:56:32 -08004802 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn39792d22010-08-19 18:01:52 -07004803 "Granting " + targetPkg + "/" + targetUid + " permission to " + uri);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004804
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004805 HashMap<Uri, UriPermission> targetUris
4806 = mGrantedUriPermissions.get(targetUid);
4807 if (targetUris == null) {
4808 targetUris = new HashMap<Uri, UriPermission>();
4809 mGrantedUriPermissions.put(targetUid, targetUris);
4810 }
4811
4812 UriPermission perm = targetUris.get(uri);
4813 if (perm == null) {
4814 perm = new UriPermission(targetUid, uri);
4815 targetUris.put(uri, perm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004816 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07004817
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004818 perm.modeFlags |= modeFlags;
Dianne Hackborn39792d22010-08-19 18:01:52 -07004819 if (owner == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004820 perm.globalModeFlags |= modeFlags;
Vairavan Srinivasan91c12c22011-01-21 18:26:06 -08004821 } else {
4822 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
4823 perm.readOwners.add(owner);
4824 owner.addReadPermission(perm);
4825 }
4826 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
4827 perm.writeOwners.add(owner);
4828 owner.addWritePermission(perm);
4829 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004830 }
4831 }
4832
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004833 void grantUriPermissionLocked(int callingUid, String targetPkg, Uri uri,
4834 int modeFlags, UriPermissionOwner owner) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004835 if (targetPkg == null) {
4836 throw new NullPointerException("targetPkg");
4837 }
4838
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004839 int targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn39792d22010-08-19 18:01:52 -07004840 if (targetUid < 0) {
4841 return;
4842 }
4843
4844 grantUriPermissionUncheckedLocked(targetUid, targetPkg, uri, modeFlags, owner);
4845 }
4846
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004847 static class NeededUriGrants extends ArrayList<Uri> {
4848 final String targetPkg;
4849 final int targetUid;
4850 final int flags;
4851
4852 NeededUriGrants(String _targetPkg, int _targetUid, int _flags) {
4853 targetPkg = _targetPkg;
4854 targetUid = _targetUid;
4855 flags = _flags;
4856 }
4857 }
4858
Dianne Hackborn39792d22010-08-19 18:01:52 -07004859 /**
4860 * Like checkGrantUriPermissionLocked, but takes an Intent.
4861 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004862 NeededUriGrants checkGrantUriPermissionFromIntentLocked(int callingUid,
4863 String targetPkg, Intent intent, int mode, NeededUriGrants needed) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07004864 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004865 "Checking URI perm to data=" + (intent != null ? intent.getData() : null)
4866 + " clip=" + (intent != null ? intent.getClipData() : null)
Dianne Hackbornb424b632010-08-18 15:59:05 -07004867 + " from " + intent + "; flags=0x"
4868 + Integer.toHexString(intent != null ? intent.getFlags() : 0));
4869
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004870 if (targetPkg == null) {
4871 throw new NullPointerException("targetPkg");
4872 }
4873
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004874 if (intent == null) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004875 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004876 }
4877 Uri data = intent.getData();
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004878 ClipData clip = intent.getClipData();
4879 if (data == null && clip == null) {
4880 return null;
Dianne Hackborn39792d22010-08-19 18:01:52 -07004881 }
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004882 if (data != null) {
4883 int target = checkGrantUriPermissionLocked(callingUid, targetPkg, data,
4884 mode, needed != null ? needed.targetUid : -1);
4885 if (target > 0) {
4886 if (needed == null) {
4887 needed = new NeededUriGrants(targetPkg, target, mode);
4888 }
4889 needed.add(data);
4890 }
4891 }
4892 if (clip != null) {
4893 for (int i=0; i<clip.getItemCount(); i++) {
4894 Uri uri = clip.getItemAt(i).getUri();
4895 if (uri != null) {
4896 int target = -1;
4897 target = checkGrantUriPermissionLocked(callingUid, targetPkg, uri,
4898 mode, needed != null ? needed.targetUid : -1);
4899 if (target > 0) {
4900 if (needed == null) {
4901 needed = new NeededUriGrants(targetPkg, target, mode);
4902 }
4903 needed.add(uri);
4904 }
4905 } else {
4906 Intent clipIntent = clip.getItemAt(i).getIntent();
4907 if (clipIntent != null) {
4908 NeededUriGrants newNeeded = checkGrantUriPermissionFromIntentLocked(
4909 callingUid, targetPkg, clipIntent, mode, needed);
4910 if (newNeeded != null) {
4911 needed = newNeeded;
4912 }
4913 }
4914 }
4915 }
4916 }
4917
4918 return needed;
Dianne Hackborn39792d22010-08-19 18:01:52 -07004919 }
4920
4921 /**
4922 * Like grantUriPermissionUncheckedLocked, but takes an Intent.
4923 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004924 void grantUriPermissionUncheckedFromIntentLocked(NeededUriGrants needed,
4925 UriPermissionOwner owner) {
4926 if (needed != null) {
4927 for (int i=0; i<needed.size(); i++) {
4928 grantUriPermissionUncheckedLocked(needed.targetUid, needed.targetPkg,
4929 needed.get(i), needed.flags, owner);
4930 }
4931 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07004932 }
4933
4934 void grantUriPermissionFromIntentLocked(int callingUid,
4935 String targetPkg, Intent intent, UriPermissionOwner owner) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004936 NeededUriGrants needed = checkGrantUriPermissionFromIntentLocked(callingUid, targetPkg,
4937 intent, intent.getFlags(), null);
4938 if (needed == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004939 return;
4940 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07004941
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004942 grantUriPermissionUncheckedFromIntentLocked(needed, owner);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004943 }
4944
4945 public void grantUriPermission(IApplicationThread caller, String targetPkg,
4946 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004947 enforceNotIsolatedCaller("grantUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004948 synchronized(this) {
4949 final ProcessRecord r = getRecordForAppLocked(caller);
4950 if (r == null) {
4951 throw new SecurityException("Unable to find app for caller "
4952 + caller
4953 + " when granting permission to uri " + uri);
4954 }
4955 if (targetPkg == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07004956 throw new IllegalArgumentException("null target");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004957 }
4958 if (uri == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07004959 throw new IllegalArgumentException("null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004960 }
4961
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004962 grantUriPermissionLocked(r.uid, targetPkg, uri, modeFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004963 null);
4964 }
4965 }
4966
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004967 void removeUriPermissionIfNeededLocked(UriPermission perm) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004968 if ((perm.modeFlags&(Intent.FLAG_GRANT_READ_URI_PERMISSION
4969 |Intent.FLAG_GRANT_WRITE_URI_PERMISSION)) == 0) {
4970 HashMap<Uri, UriPermission> perms
4971 = mGrantedUriPermissions.get(perm.uid);
4972 if (perms != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004973 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004974 "Removing " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004975 perms.remove(perm.uri);
4976 if (perms.size() == 0) {
4977 mGrantedUriPermissions.remove(perm.uid);
4978 }
4979 }
4980 }
4981 }
4982
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004983 private void revokeUriPermissionLocked(int callingUid, Uri uri,
4984 int modeFlags) {
4985 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4986 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4987 if (modeFlags == 0) {
4988 return;
4989 }
4990
Joe Onorato8a9b2202010-02-26 18:56:32 -08004991 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004992 "Revoking all granted permissions to " + uri);
4993
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004994 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004995
4996 final String authority = uri.getAuthority();
4997 ProviderInfo pi = null;
Amith Yamasani742a6712011-05-04 14:49:28 -07004998 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority,
4999 UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005000 if (cpr != null) {
5001 pi = cpr.info;
5002 } else {
5003 try {
5004 pi = pm.resolveContentProvider(authority,
5005 PackageManager.GET_URI_PERMISSION_PATTERNS);
5006 } catch (RemoteException ex) {
5007 }
5008 }
5009 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005010 Slog.w(TAG, "No content provider found for permission revoke: " + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005011 return;
5012 }
5013
5014 // Does the caller have this permission on the URI?
Dianne Hackborn48058e82010-09-27 16:53:23 -07005015 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005016 // Right now, if you are not the original owner of the permission,
5017 // you are not allowed to revoke it.
5018 //if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5019 throw new SecurityException("Uid " + callingUid
5020 + " does not have permission to uri " + uri);
5021 //}
5022 }
5023
5024 // Go through all of the permissions and remove any that match.
5025 final List<String> SEGMENTS = uri.getPathSegments();
5026 if (SEGMENTS != null) {
5027 final int NS = SEGMENTS.size();
5028 int N = mGrantedUriPermissions.size();
5029 for (int i=0; i<N; i++) {
5030 HashMap<Uri, UriPermission> perms
5031 = mGrantedUriPermissions.valueAt(i);
5032 Iterator<UriPermission> it = perms.values().iterator();
5033 toploop:
5034 while (it.hasNext()) {
5035 UriPermission perm = it.next();
5036 Uri targetUri = perm.uri;
5037 if (!authority.equals(targetUri.getAuthority())) {
5038 continue;
5039 }
5040 List<String> targetSegments = targetUri.getPathSegments();
5041 if (targetSegments == null) {
5042 continue;
5043 }
5044 if (targetSegments.size() < NS) {
5045 continue;
5046 }
5047 for (int j=0; j<NS; j++) {
5048 if (!SEGMENTS.get(j).equals(targetSegments.get(j))) {
5049 continue toploop;
5050 }
5051 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08005052 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005053 "Revoking " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005054 perm.clearModes(modeFlags);
5055 if (perm.modeFlags == 0) {
5056 it.remove();
5057 }
5058 }
5059 if (perms.size() == 0) {
5060 mGrantedUriPermissions.remove(
5061 mGrantedUriPermissions.keyAt(i));
5062 N--;
5063 i--;
5064 }
5065 }
5066 }
5067 }
5068
5069 public void revokeUriPermission(IApplicationThread caller, Uri uri,
5070 int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005071 enforceNotIsolatedCaller("revokeUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005072 synchronized(this) {
5073 final ProcessRecord r = getRecordForAppLocked(caller);
5074 if (r == null) {
5075 throw new SecurityException("Unable to find app for caller "
5076 + caller
5077 + " when revoking permission to uri " + uri);
5078 }
5079 if (uri == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005080 Slog.w(TAG, "revokeUriPermission: null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005081 return;
5082 }
5083
5084 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5085 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5086 if (modeFlags == 0) {
5087 return;
5088 }
5089
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005090 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005091
5092 final String authority = uri.getAuthority();
5093 ProviderInfo pi = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005094 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005095 if (cpr != null) {
5096 pi = cpr.info;
5097 } else {
5098 try {
5099 pi = pm.resolveContentProvider(authority,
5100 PackageManager.GET_URI_PERMISSION_PATTERNS);
5101 } catch (RemoteException ex) {
5102 }
5103 }
5104 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005105 Slog.w(TAG, "No content provider found for permission revoke: "
5106 + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005107 return;
5108 }
5109
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005110 revokeUriPermissionLocked(r.uid, uri, modeFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005111 }
5112 }
5113
Dianne Hackborn7e269642010-08-25 19:50:20 -07005114 @Override
5115 public IBinder newUriPermissionOwner(String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005116 enforceNotIsolatedCaller("newUriPermissionOwner");
Dianne Hackborn7e269642010-08-25 19:50:20 -07005117 synchronized(this) {
5118 UriPermissionOwner owner = new UriPermissionOwner(this, name);
5119 return owner.getExternalTokenLocked();
5120 }
5121 }
5122
5123 @Override
5124 public void grantUriPermissionFromOwner(IBinder token, int fromUid, String targetPkg,
5125 Uri uri, int modeFlags) {
5126 synchronized(this) {
5127 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5128 if (owner == null) {
5129 throw new IllegalArgumentException("Unknown owner: " + token);
5130 }
5131 if (fromUid != Binder.getCallingUid()) {
5132 if (Binder.getCallingUid() != Process.myUid()) {
5133 // Only system code can grant URI permissions on behalf
5134 // of other users.
5135 throw new SecurityException("nice try");
5136 }
5137 }
5138 if (targetPkg == null) {
5139 throw new IllegalArgumentException("null target");
5140 }
5141 if (uri == null) {
5142 throw new IllegalArgumentException("null uri");
5143 }
5144
5145 grantUriPermissionLocked(fromUid, targetPkg, uri, modeFlags, owner);
5146 }
5147 }
5148
5149 @Override
5150 public void revokeUriPermissionFromOwner(IBinder token, Uri uri, int mode) {
5151 synchronized(this) {
5152 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5153 if (owner == null) {
5154 throw new IllegalArgumentException("Unknown owner: " + token);
5155 }
5156
5157 if (uri == null) {
5158 owner.removeUriPermissionsLocked(mode);
5159 } else {
5160 owner.removeUriPermissionLocked(uri, mode);
5161 }
5162 }
5163 }
5164
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005165 public void showWaitingForDebugger(IApplicationThread who, boolean waiting) {
5166 synchronized (this) {
5167 ProcessRecord app =
5168 who != null ? getRecordForAppLocked(who) : null;
5169 if (app == null) return;
5170
5171 Message msg = Message.obtain();
5172 msg.what = WAIT_FOR_DEBUGGER_MSG;
5173 msg.obj = app;
5174 msg.arg1 = waiting ? 1 : 0;
5175 mHandler.sendMessage(msg);
5176 }
5177 }
5178
5179 public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07005180 final long homeAppMem = mProcessList.getMemLevel(ProcessList.HOME_APP_ADJ);
5181 final long hiddenAppMem = mProcessList.getMemLevel(ProcessList.HIDDEN_APP_MIN_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005182 outInfo.availMem = Process.getFreeMemory();
Dianne Hackborn7d608422011-08-07 16:24:18 -07005183 outInfo.threshold = homeAppMem;
5184 outInfo.lowMemory = outInfo.availMem < (homeAppMem + ((hiddenAppMem-homeAppMem)/2));
5185 outInfo.hiddenAppThreshold = hiddenAppMem;
5186 outInfo.secondaryServerThreshold = mProcessList.getMemLevel(
Dianne Hackborne02c88a2011-10-28 13:58:15 -07005187 ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07005188 outInfo.visibleAppThreshold = mProcessList.getMemLevel(
5189 ProcessList.VISIBLE_APP_ADJ);
5190 outInfo.foregroundAppThreshold = mProcessList.getMemLevel(
5191 ProcessList.FOREGROUND_APP_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005192 }
5193
5194 // =========================================================
5195 // TASK MANAGEMENT
5196 // =========================================================
5197
5198 public List getTasks(int maxNum, int flags,
5199 IThumbnailReceiver receiver) {
5200 ArrayList list = new ArrayList();
5201
5202 PendingThumbnailsRecord pending = null;
5203 IApplicationThread topThumbnail = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005204 ActivityRecord topRecord = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005205
5206 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005207 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005208 TAG, "getTasks: max=" + maxNum + ", flags=" + flags
5209 + ", receiver=" + receiver);
5210
5211 if (checkCallingPermission(android.Manifest.permission.GET_TASKS)
5212 != PackageManager.PERMISSION_GRANTED) {
5213 if (receiver != null) {
5214 // If the caller wants to wait for pending thumbnails,
5215 // it ain't gonna get them.
5216 try {
5217 receiver.finished();
5218 } catch (RemoteException ex) {
5219 }
5220 }
5221 String msg = "Permission Denial: getTasks() from pid="
5222 + Binder.getCallingPid()
5223 + ", uid=" + Binder.getCallingUid()
5224 + " requires " + android.Manifest.permission.GET_TASKS;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005225 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005226 throw new SecurityException(msg);
5227 }
5228
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005229 int pos = mMainStack.mHistory.size()-1;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005230 ActivityRecord next =
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005231 pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005232 ActivityRecord top = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005233 TaskRecord curTask = null;
5234 int numActivities = 0;
5235 int numRunning = 0;
5236 while (pos >= 0 && maxNum > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005237 final ActivityRecord r = next;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005238 pos--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005239 next = pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005240
5241 // Initialize state for next task if needed.
5242 if (top == null ||
5243 (top.state == ActivityState.INITIALIZING
5244 && top.task == r.task)) {
5245 top = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005246 curTask = r.task;
5247 numActivities = numRunning = 0;
5248 }
5249
5250 // Add 'r' into the current task.
5251 numActivities++;
5252 if (r.app != null && r.app.thread != null) {
5253 numRunning++;
5254 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005255
Joe Onorato8a9b2202010-02-26 18:56:32 -08005256 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005257 TAG, r.intent.getComponent().flattenToShortString()
5258 + ": task=" + r.task);
5259
5260 // If the next one is a different task, generate a new
5261 // TaskInfo entry for what we have.
5262 if (next == null || next.task != curTask) {
5263 ActivityManager.RunningTaskInfo ci
5264 = new ActivityManager.RunningTaskInfo();
5265 ci.id = curTask.taskId;
5266 ci.baseActivity = r.intent.getComponent();
5267 ci.topActivity = top.intent.getComponent();
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005268 if (top.thumbHolder != null) {
5269 ci.description = top.thumbHolder.lastDescription;
5270 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005271 ci.numActivities = numActivities;
5272 ci.numRunning = numRunning;
5273 //System.out.println(
5274 // "#" + maxNum + ": " + " descr=" + ci.description);
5275 if (ci.thumbnail == null && receiver != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005276 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005277 TAG, "State=" + top.state + "Idle=" + top.idle
5278 + " app=" + top.app
5279 + " thr=" + (top.app != null ? top.app.thread : null));
5280 if (top.state == ActivityState.RESUMED
5281 || top.state == ActivityState.PAUSING) {
5282 if (top.idle && top.app != null
5283 && top.app.thread != null) {
5284 topRecord = top;
5285 topThumbnail = top.app.thread;
5286 } else {
5287 top.thumbnailNeeded = true;
5288 }
5289 }
5290 if (pending == null) {
5291 pending = new PendingThumbnailsRecord(receiver);
5292 }
5293 pending.pendingRecords.add(top);
5294 }
5295 list.add(ci);
5296 maxNum--;
5297 top = null;
5298 }
5299 }
5300
5301 if (pending != null) {
5302 mPendingThumbnails.add(pending);
5303 }
5304 }
5305
Joe Onorato8a9b2202010-02-26 18:56:32 -08005306 if (localLOGV) Slog.v(TAG, "We have pending thumbnails: " + pending);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005307
5308 if (topThumbnail != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005309 if (localLOGV) Slog.v(TAG, "Requesting top thumbnail");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005310 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08005311 topThumbnail.requestThumbnail(topRecord.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005312 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005313 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005314 sendPendingThumbnail(null, topRecord.appToken, null, null, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005315 }
5316 }
5317
5318 if (pending == null && receiver != null) {
5319 // In this case all thumbnails were available and the client
5320 // is being asked to be told when the remaining ones come in...
5321 // which is unusually, since the top-most currently running
5322 // activity should never have a canned thumbnail! Oh well.
5323 try {
5324 receiver.finished();
5325 } catch (RemoteException ex) {
5326 }
5327 }
5328
5329 return list;
5330 }
5331
5332 public List<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum,
5333 int flags) {
Amith Yamasani742a6712011-05-04 14:49:28 -07005334 final int callingUid = Binder.getCallingUid();
5335 // If it's the system uid asking, then use the current user id.
5336 // TODO: Make sure that there aren't any other legitimate calls from the system uid that
5337 // require the entire list.
5338 final int callingUserId = callingUid == Process.SYSTEM_UID
5339 ? mCurrentUserId : UserId.getUserId(callingUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005340 synchronized (this) {
5341 enforceCallingPermission(android.Manifest.permission.GET_TASKS,
5342 "getRecentTasks()");
5343
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005344 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005345
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005346 final int N = mRecentTasks.size();
5347 ArrayList<ActivityManager.RecentTaskInfo> res
5348 = new ArrayList<ActivityManager.RecentTaskInfo>(
5349 maxNum < N ? maxNum : N);
5350 for (int i=0; i<N && maxNum > 0; i++) {
5351 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005352 // Only add calling user's recent tasks
5353 if (tr.userId != callingUserId) continue;
Dianne Hackborn905577f2011-09-07 18:31:28 -07005354 // Return the entry if desired by the caller. We always return
5355 // the first entry, because callers always expect this to be the
Amith Yamasani742a6712011-05-04 14:49:28 -07005356 // foreground app. We may filter others if the caller has
Dianne Hackborn905577f2011-09-07 18:31:28 -07005357 // not supplied RECENT_WITH_EXCLUDED and there is some reason
5358 // we should exclude the entry.
Amith Yamasani742a6712011-05-04 14:49:28 -07005359
Dianne Hackborn905577f2011-09-07 18:31:28 -07005360 if (i == 0
5361 || ((flags&ActivityManager.RECENT_WITH_EXCLUDED) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005362 || (tr.intent == null)
5363 || ((tr.intent.getFlags()
5364 &Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) == 0)) {
5365 ActivityManager.RecentTaskInfo rti
5366 = new ActivityManager.RecentTaskInfo();
5367 rti.id = tr.numActivities > 0 ? tr.taskId : -1;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005368 rti.persistentId = tr.taskId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005369 rti.baseIntent = new Intent(
5370 tr.intent != null ? tr.intent : tr.affinityIntent);
5371 rti.origActivity = tr.origActivity;
Dianne Hackbornd2835932010-12-13 16:28:46 -08005372 rti.description = tr.lastDescription;
5373
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005374 if ((flags&ActivityManager.RECENT_IGNORE_UNAVAILABLE) != 0) {
5375 // Check whether this activity is currently available.
5376 try {
5377 if (rti.origActivity != null) {
5378 if (pm.getActivityInfo(rti.origActivity, 0) == null) {
5379 continue;
5380 }
5381 } else if (rti.baseIntent != null) {
5382 if (pm.queryIntentActivities(rti.baseIntent,
5383 null, 0) == null) {
5384 continue;
5385 }
5386 }
5387 } catch (RemoteException e) {
5388 // Will never happen.
5389 }
5390 }
5391
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005392 res.add(rti);
5393 maxNum--;
5394 }
5395 }
5396 return res;
5397 }
5398 }
5399
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005400 private TaskRecord taskForIdLocked(int id) {
5401 final int N = mRecentTasks.size();
5402 for (int i=0; i<N; i++) {
5403 TaskRecord tr = mRecentTasks.get(i);
5404 if (tr.taskId == id) {
5405 return tr;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005406 }
5407 }
5408 return null;
5409 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005410
5411 public ActivityManager.TaskThumbnails getTaskThumbnails(int id) {
5412 synchronized (this) {
5413 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
5414 "getTaskThumbnails()");
5415 TaskRecord tr = taskForIdLocked(id);
5416 if (tr != null) {
5417 return mMainStack.getTaskThumbnailsLocked(tr);
5418 }
5419 }
5420 return null;
5421 }
5422
5423 public boolean removeSubTask(int taskId, int subTaskIndex) {
5424 synchronized (this) {
5425 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5426 "removeSubTask()");
5427 long ident = Binder.clearCallingIdentity();
5428 try {
5429 return mMainStack.removeTaskActivitiesLocked(taskId, subTaskIndex) != null;
5430 } finally {
5431 Binder.restoreCallingIdentity(ident);
5432 }
5433 }
5434 }
5435
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005436 private void cleanUpRemovedTaskLocked(ActivityRecord root, boolean killProcesses) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005437 TaskRecord tr = root.task;
5438 Intent baseIntent = new Intent(
5439 tr.intent != null ? tr.intent : tr.affinityIntent);
5440 ComponentName component = baseIntent.getComponent();
5441 if (component == null) {
5442 Slog.w(TAG, "Now component for base intent of task: " + tr);
5443 return;
5444 }
5445
5446 // Find any running services associated with this app.
5447 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
Amith Yamasani742a6712011-05-04 14:49:28 -07005448 for (ServiceRecord sr : mServiceMap.getAllServices(root.userId)) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005449 if (sr.packageName.equals(component.getPackageName())) {
5450 services.add(sr);
5451 }
5452 }
5453
5454 // Take care of any running services associated with the app.
5455 for (int i=0; i<services.size(); i++) {
5456 ServiceRecord sr = services.get(i);
5457 if (sr.startRequested) {
5458 if ((sr.serviceInfo.flags&ServiceInfo.FLAG_STOP_WITH_TASK) != 0) {
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005459 Slog.i(TAG, "Stopping service " + sr.shortName + ": remove task");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005460 stopServiceLocked(sr);
5461 } else {
5462 sr.pendingStarts.add(new ServiceRecord.StartItem(sr, true,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005463 sr.makeNextStartId(), baseIntent, null));
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005464 if (sr.app != null && sr.app.thread != null) {
5465 sendServiceArgsLocked(sr, false);
5466 }
5467 }
5468 }
5469 }
5470
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005471 if (killProcesses) {
5472 // Find any running processes associated with this app.
5473 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
5474 SparseArray<ProcessRecord> appProcs
5475 = mProcessNames.getMap().get(component.getPackageName());
5476 if (appProcs != null) {
5477 for (int i=0; i<appProcs.size(); i++) {
5478 procs.add(appProcs.valueAt(i));
5479 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005480 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005481
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005482 // Kill the running processes.
5483 for (int i=0; i<procs.size(); i++) {
5484 ProcessRecord pr = procs.get(i);
5485 if (pr.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
5486 Slog.i(TAG, "Killing " + pr.toShortString() + ": remove task");
5487 EventLog.writeEvent(EventLogTags.AM_KILL, pr.pid,
5488 pr.processName, pr.setAdj, "remove task");
5489 Process.killProcessQuiet(pr.pid);
5490 } else {
5491 pr.waitingToKill = "remove task";
5492 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005493 }
5494 }
5495 }
5496
5497 public boolean removeTask(int taskId, int flags) {
5498 synchronized (this) {
5499 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5500 "removeTask()");
5501 long ident = Binder.clearCallingIdentity();
5502 try {
5503 ActivityRecord r = mMainStack.removeTaskActivitiesLocked(taskId, -1);
5504 if (r != null) {
5505 mRecentTasks.remove(r.task);
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005506 cleanUpRemovedTaskLocked(r,
5507 (flags&ActivityManager.REMOVE_TASK_KILL_PROCESS) != 0);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005508 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005509 } else {
5510 TaskRecord tr = null;
5511 int i=0;
5512 while (i < mRecentTasks.size()) {
5513 TaskRecord t = mRecentTasks.get(i);
5514 if (t.taskId == taskId) {
5515 tr = t;
5516 break;
5517 }
5518 i++;
5519 }
5520 if (tr != null) {
5521 if (tr.numActivities <= 0) {
5522 // Caller is just removing a recent task that is
5523 // not actively running. That is easy!
5524 mRecentTasks.remove(i);
5525 } else {
5526 Slog.w(TAG, "removeTask: task " + taskId
5527 + " does not have activities to remove, "
5528 + " but numActivities=" + tr.numActivities
5529 + ": " + tr);
5530 }
5531 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005532 }
5533 } finally {
5534 Binder.restoreCallingIdentity(ident);
5535 }
5536 }
5537 return false;
5538 }
Dianne Hackbornd94df452011-02-16 18:53:31 -08005539
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005540 private final int findAffinityTaskTopLocked(int startIndex, String affinity) {
5541 int j;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005542 TaskRecord startTask = ((ActivityRecord)mMainStack.mHistory.get(startIndex)).task;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005543 TaskRecord jt = startTask;
5544
5545 // First look backwards
5546 for (j=startIndex-1; j>=0; j--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005547 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005548 if (r.task != jt) {
5549 jt = r.task;
5550 if (affinity.equals(jt.affinity)) {
5551 return j;
5552 }
5553 }
5554 }
5555
5556 // Now look forwards
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005557 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005558 jt = startTask;
5559 for (j=startIndex+1; j<N; j++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005560 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005561 if (r.task != jt) {
5562 if (affinity.equals(jt.affinity)) {
5563 return j;
5564 }
5565 jt = r.task;
5566 }
5567 }
5568
5569 // Might it be at the top?
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005570 if (affinity.equals(((ActivityRecord)mMainStack.mHistory.get(N-1)).task.affinity)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005571 return N-1;
5572 }
5573
5574 return -1;
5575 }
5576
5577 /**
Dianne Hackbornb06ea702009-07-13 13:07:51 -07005578 * TODO: Add mController hook
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005579 */
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005580 public void moveTaskToFront(int task, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005581 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5582 "moveTaskToFront()");
5583
5584 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005585 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5586 Binder.getCallingUid(), "Task to front")) {
5587 return;
5588 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005589 final long origId = Binder.clearCallingIdentity();
5590 try {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005591 TaskRecord tr = taskForIdLocked(task);
5592 if (tr != null) {
5593 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5594 mMainStack.mUserLeaving = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005595 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005596 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5597 // Caller wants the home activity moved with it. To accomplish this,
5598 // we'll just move the home task to the top first.
5599 mMainStack.moveHomeToFrontLocked();
5600 }
5601 mMainStack.moveTaskToFrontLocked(tr, null);
5602 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005603 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005604 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
5605 ActivityRecord hr = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005606 if (hr.task.taskId == task) {
Dianne Hackbornd94df452011-02-16 18:53:31 -08005607 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5608 mMainStack.mUserLeaving = true;
5609 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005610 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5611 // Caller wants the home activity moved with it. To accomplish this,
5612 // we'll just move the home task to the top first.
5613 mMainStack.moveHomeToFrontLocked();
5614 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005615 mMainStack.moveTaskToFrontLocked(hr.task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005616 return;
5617 }
5618 }
5619 } finally {
5620 Binder.restoreCallingIdentity(origId);
5621 }
5622 }
5623 }
5624
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005625 public void moveTaskToBack(int task) {
5626 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5627 "moveTaskToBack()");
5628
5629 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005630 if (mMainStack.mResumedActivity != null
5631 && mMainStack.mResumedActivity.task.taskId == task) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005632 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5633 Binder.getCallingUid(), "Task to back")) {
5634 return;
5635 }
5636 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005637 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005638 mMainStack.moveTaskToBackLocked(task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005639 Binder.restoreCallingIdentity(origId);
5640 }
5641 }
5642
5643 /**
5644 * Moves an activity, and all of the other activities within the same task, to the bottom
5645 * of the history stack. The activity's order within the task is unchanged.
5646 *
5647 * @param token A reference to the activity we wish to move
5648 * @param nonRoot If false then this only works if the activity is the root
5649 * of a task; if true it will work for any activity in a task.
5650 * @return Returns true if the move completed, false if not.
5651 */
5652 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005653 enforceNotIsolatedCaller("moveActivityTaskToBack");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005654 synchronized(this) {
5655 final long origId = Binder.clearCallingIdentity();
5656 int taskId = getTaskForActivityLocked(token, !nonRoot);
5657 if (taskId >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005658 return mMainStack.moveTaskToBackLocked(taskId, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005659 }
5660 Binder.restoreCallingIdentity(origId);
5661 }
5662 return false;
5663 }
5664
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005665 public void moveTaskBackwards(int task) {
5666 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5667 "moveTaskBackwards()");
5668
5669 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005670 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5671 Binder.getCallingUid(), "Task backwards")) {
5672 return;
5673 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005674 final long origId = Binder.clearCallingIdentity();
5675 moveTaskBackwardsLocked(task);
5676 Binder.restoreCallingIdentity(origId);
5677 }
5678 }
5679
5680 private final void moveTaskBackwardsLocked(int task) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005681 Slog.e(TAG, "moveTaskBackwards not yet implemented!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005682 }
5683
5684 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
5685 synchronized(this) {
5686 return getTaskForActivityLocked(token, onlyRoot);
5687 }
5688 }
5689
5690 int getTaskForActivityLocked(IBinder token, boolean onlyRoot) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005691 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005692 TaskRecord lastTask = null;
5693 for (int i=0; i<N; i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005694 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005695 if (r.appToken == token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005696 if (!onlyRoot || lastTask != r.task) {
5697 return r.task.taskId;
5698 }
5699 return -1;
5700 }
5701 lastTask = r.task;
5702 }
5703
5704 return -1;
5705 }
5706
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005707 // =========================================================
5708 // THUMBNAILS
5709 // =========================================================
5710
5711 public void reportThumbnail(IBinder token,
5712 Bitmap thumbnail, CharSequence description) {
5713 //System.out.println("Report thumbnail for " + token + ": " + thumbnail);
5714 final long origId = Binder.clearCallingIdentity();
5715 sendPendingThumbnail(null, token, thumbnail, description, true);
5716 Binder.restoreCallingIdentity(origId);
5717 }
5718
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005719 final void sendPendingThumbnail(ActivityRecord r, IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005720 Bitmap thumbnail, CharSequence description, boolean always) {
5721 TaskRecord task = null;
5722 ArrayList receivers = null;
5723
5724 //System.out.println("Send pending thumbnail: " + r);
5725
5726 synchronized(this) {
5727 if (r == null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07005728 r = mMainStack.isInStackLocked(token);
5729 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005730 return;
5731 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005732 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005733 if (thumbnail == null && r.thumbHolder != null) {
5734 thumbnail = r.thumbHolder.lastThumbnail;
5735 description = r.thumbHolder.lastDescription;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005736 }
5737 if (thumbnail == null && !always) {
5738 // If there is no thumbnail, and this entry is not actually
5739 // going away, then abort for now and pick up the next
5740 // thumbnail we get.
5741 return;
5742 }
5743 task = r.task;
5744
5745 int N = mPendingThumbnails.size();
5746 int i=0;
5747 while (i<N) {
5748 PendingThumbnailsRecord pr =
5749 (PendingThumbnailsRecord)mPendingThumbnails.get(i);
5750 //System.out.println("Looking in " + pr.pendingRecords);
5751 if (pr.pendingRecords.remove(r)) {
5752 if (receivers == null) {
5753 receivers = new ArrayList();
5754 }
5755 receivers.add(pr);
5756 if (pr.pendingRecords.size() == 0) {
5757 pr.finished = true;
5758 mPendingThumbnails.remove(i);
5759 N--;
5760 continue;
5761 }
5762 }
5763 i++;
5764 }
5765 }
5766
5767 if (receivers != null) {
5768 final int N = receivers.size();
5769 for (int i=0; i<N; i++) {
5770 try {
5771 PendingThumbnailsRecord pr =
5772 (PendingThumbnailsRecord)receivers.get(i);
5773 pr.receiver.newThumbnail(
5774 task != null ? task.taskId : -1, thumbnail, description);
5775 if (pr.finished) {
5776 pr.receiver.finished();
5777 }
5778 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005779 Slog.w(TAG, "Exception thrown when sending thumbnail", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005780 }
5781 }
5782 }
5783 }
5784
5785 // =========================================================
5786 // CONTENT PROVIDERS
5787 // =========================================================
5788
Jeff Brown10e89712011-07-08 18:52:57 -07005789 private final List<ProviderInfo> generateApplicationProvidersLocked(ProcessRecord app) {
5790 List<ProviderInfo> providers = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005791 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005792 providers = AppGlobals.getPackageManager().
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005793 queryContentProviders(app.processName, app.uid,
Dianne Hackborn1655be42009-05-08 14:29:01 -07005794 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005795 } catch (RemoteException ex) {
5796 }
Amith Yamasani742a6712011-05-04 14:49:28 -07005797 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005798 Slog.v(TAG_MU, "generateApplicationProvidersLocked, app.info.uid = " + app.uid);
5799 int userId = app.userId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005800 if (providers != null) {
5801 final int N = providers.size();
5802 for (int i=0; i<N; i++) {
5803 ProviderInfo cpi =
5804 (ProviderInfo)providers.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005805
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07005806 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07005807 ContentProviderRecord cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005808 if (cpr == null) {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08005809 cpr = new ContentProviderRecord(this, cpi, app.info, comp);
Amith Yamasani742a6712011-05-04 14:49:28 -07005810 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005811 }
Amith Yamasani742a6712011-05-04 14:49:28 -07005812 if (DEBUG_MU)
5813 Slog.v(TAG_MU, "generateApplicationProvidersLocked, cpi.uid = " + cpr.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005814 app.pubProviders.put(cpi.name, cpr);
5815 app.addPackage(cpi.applicationInfo.packageName);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07005816 ensurePackageDexOpt(cpi.applicationInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005817 }
5818 }
5819 return providers;
5820 }
5821
5822 private final String checkContentProviderPermissionLocked(
Dianne Hackbornb424b632010-08-18 15:59:05 -07005823 ProviderInfo cpi, ProcessRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005824 final int callingPid = (r != null) ? r.pid : Binder.getCallingPid();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005825 final int callingUid = (r != null) ? r.uid : Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005826 if (checkComponentPermission(cpi.readPermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005827 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005828 == PackageManager.PERMISSION_GRANTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005829 return null;
5830 }
5831 if (checkComponentPermission(cpi.writePermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005832 cpi.applicationInfo.uid, cpi.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005833 == PackageManager.PERMISSION_GRANTED) {
5834 return null;
5835 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07005836
5837 PathPermission[] pps = cpi.pathPermissions;
5838 if (pps != null) {
5839 int i = pps.length;
5840 while (i > 0) {
5841 i--;
5842 PathPermission pp = pps[i];
5843 if (checkComponentPermission(pp.getReadPermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005844 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005845 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07005846 return null;
5847 }
5848 if (checkComponentPermission(pp.getWritePermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005849 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackborn2af632f2009-07-08 14:56:37 -07005850 == PackageManager.PERMISSION_GRANTED) {
5851 return null;
5852 }
5853 }
5854 }
5855
Dianne Hackbornb424b632010-08-18 15:59:05 -07005856 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(callingUid);
5857 if (perms != null) {
5858 for (Map.Entry<Uri, UriPermission> uri : perms.entrySet()) {
5859 if (uri.getKey().getAuthority().equals(cpi.authority)) {
5860 return null;
5861 }
5862 }
5863 }
5864
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005865 String msg;
5866 if (!cpi.exported) {
5867 msg = "Permission Denial: opening provider " + cpi.name
5868 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
5869 + ", uid=" + callingUid + ") that is not exported from uid "
5870 + cpi.applicationInfo.uid;
5871 } else {
5872 msg = "Permission Denial: opening provider " + cpi.name
5873 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
5874 + ", uid=" + callingUid + ") requires "
5875 + cpi.readPermission + " or " + cpi.writePermission;
5876 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08005877 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005878 return msg;
5879 }
5880
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08005881 boolean incProviderCount(ProcessRecord r, final ContentProviderRecord cpr,
5882 IBinder externalProcessToken) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005883 if (r != null) {
5884 Integer cnt = r.conProviders.get(cpr);
5885 if (DEBUG_PROVIDER) Slog.v(TAG,
5886 "Adding provider requested by "
5887 + r.processName + " from process "
5888 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
5889 + " cnt=" + (cnt == null ? 1 : cnt));
5890 if (cnt == null) {
5891 cpr.clients.add(r);
5892 r.conProviders.put(cpr, new Integer(1));
5893 return true;
5894 } else {
5895 r.conProviders.put(cpr, new Integer(cnt.intValue()+1));
5896 }
5897 } else {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08005898 cpr.addExternalProcessHandleLocked(externalProcessToken);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005899 }
5900 return false;
5901 }
5902
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08005903 boolean decProviderCount(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 "Removing provider requested by "
5909 + r.processName + " from process "
5910 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
5911 + " cnt=" + cnt);
5912 if (cnt == null || cnt.intValue() <= 1) {
5913 cpr.clients.remove(r);
5914 r.conProviders.remove(cpr);
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.removeExternalProcessHandleLocked(externalProcessToken);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005921 }
5922 return false;
5923 }
5924
Amith Yamasani742a6712011-05-04 14:49:28 -07005925 private final ContentProviderHolder getContentProviderImpl(IApplicationThread caller,
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08005926 String name, IBinder token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005927 ContentProviderRecord cpr;
5928 ProviderInfo cpi = null;
5929
5930 synchronized(this) {
5931 ProcessRecord r = null;
5932 if (caller != null) {
5933 r = getRecordForAppLocked(caller);
5934 if (r == null) {
5935 throw new SecurityException(
5936 "Unable to find app for caller " + caller
5937 + " (pid=" + Binder.getCallingPid()
5938 + ") when getting content provider " + name);
5939 }
5940 }
5941
5942 // First check if this content provider has been published...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005943 int userId = UserId.getUserId(r != null ? r.uid : Binder.getCallingUid());
Amith Yamasani742a6712011-05-04 14:49:28 -07005944 cpr = mProviderMap.getProviderByName(name, userId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005945 boolean providerRunning = cpr != null;
5946 if (providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005947 cpi = cpr.info;
Dianne Hackbornb424b632010-08-18 15:59:05 -07005948 String msg;
5949 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
5950 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005951 }
5952
5953 if (r != null && cpr.canRunHere(r)) {
5954 // This provider has been published or is in the process
5955 // of being published... but it is also allowed to run
5956 // in the caller's process, so don't make a connection
5957 // and just let the caller instantiate its own instance.
5958 if (cpr.provider != null) {
5959 // don't give caller the provider object, it needs
5960 // to make its own.
5961 cpr = new ContentProviderRecord(cpr);
5962 }
5963 return cpr;
5964 }
5965
5966 final long origId = Binder.clearCallingIdentity();
5967
Dianne Hackborna1e989b2009-09-01 19:54:29 -07005968 // In this case the provider instance already exists, so we can
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005969 // return it right away.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08005970 final boolean countChanged = incProviderCount(r, cpr, token);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005971 if (countChanged) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07005972 if (cpr.proc != null && r.setAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005973 // If this is a perceptible app accessing the provider,
Dianne Hackborn906497c2010-05-10 15:57:38 -07005974 // make sure to count it as being accessed and thus
5975 // back up on the LRU list. This is good because
5976 // content providers are often expensive to start.
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07005977 updateLruProcessLocked(cpr.proc, false, true);
Dianne Hackborn906497c2010-05-10 15:57:38 -07005978 }
Dianne Hackborn6f86c0e2010-05-11 14:20:52 -07005979 }
5980
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07005981 if (cpr.proc != null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005982 if (false) {
5983 if (cpr.name.flattenToShortString().equals(
5984 "com.android.providers.calendar/.CalendarProvider2")) {
5985 Slog.v(TAG, "****************** KILLING "
5986 + cpr.name.flattenToShortString());
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07005987 Process.killProcess(cpr.proc.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005988 }
5989 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07005990 boolean success = updateOomAdjLocked(cpr.proc);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005991 if (DEBUG_PROVIDER) Slog.i(TAG, "Adjust success: " + success);
5992 // NOTE: there is still a race here where a signal could be
5993 // pending on the process even though we managed to update its
5994 // adj level. Not sure what to do about this, but at least
5995 // the race is now smaller.
5996 if (!success) {
5997 // Uh oh... it looks like the provider's process
5998 // has been killed on us. We need to wait for a new
5999 // process to be started, and make sure its death
6000 // doesn't kill our process.
6001 Slog.i(TAG,
6002 "Existing provider " + cpr.name.flattenToShortString()
6003 + " is crashing; detaching " + r);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006004 boolean lastRef = decProviderCount(r, cpr, token);
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006005 appDiedLocked(cpr.proc, cpr.proc.pid, cpr.proc.thread);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006006 if (!lastRef) {
6007 // This wasn't the last ref our process had on
6008 // the provider... we have now been killed, bail.
6009 return null;
6010 }
6011 providerRunning = false;
6012 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006013 }
6014
6015 Binder.restoreCallingIdentity(origId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006016 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006017
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006018 if (!providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006019 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006020 cpi = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07006021 resolveContentProvider(name,
6022 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006023 } catch (RemoteException ex) {
6024 }
6025 if (cpi == null) {
6026 return null;
6027 }
6028
Amith Yamasani742a6712011-05-04 14:49:28 -07006029 cpi.applicationInfo = getAppInfoForUser(cpi.applicationInfo,
6030 Binder.getOrigCallingUser());
6031
Dianne Hackbornb424b632010-08-18 15:59:05 -07006032 String msg;
6033 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6034 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006035 }
6036
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07006037 if (!mProcessesReady && !mDidUpdate && !mWaitingUpdate
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006038 && !cpi.processName.equals("system")) {
6039 // If this content provider does not run in the system
6040 // process, and the system is not yet ready to run other
6041 // processes, then fail fast instead of hanging.
6042 throw new IllegalArgumentException(
6043 "Attempt to launch content provider before system ready");
6044 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006045
6046 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006047 cpr = mProviderMap.getProviderByClass(comp, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006048 final boolean firstClass = cpr == null;
6049 if (firstClass) {
6050 try {
6051 ApplicationInfo ai =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006052 AppGlobals.getPackageManager().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006053 getApplicationInfo(
6054 cpi.applicationInfo.packageName,
Dianne Hackborn1655be42009-05-08 14:29:01 -07006055 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006056 if (ai == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006057 Slog.w(TAG, "No package info for content provider "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006058 + cpi.name);
6059 return null;
6060 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006061 ai = getAppInfoForUser(ai, Binder.getOrigCallingUser());
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006062 cpr = new ContentProviderRecord(this, cpi, ai, comp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006063 } catch (RemoteException ex) {
6064 // pm is in same process, this will never happen.
6065 }
6066 }
6067
6068 if (r != null && cpr.canRunHere(r)) {
6069 // If this is a multiprocess provider, then just return its
6070 // info and allow the caller to instantiate it. Only do
6071 // this if the provider is the same user as the caller's
6072 // process, or can run as root (so can be in any process).
6073 return cpr;
6074 }
6075
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006076 if (DEBUG_PROVIDER) {
6077 RuntimeException e = new RuntimeException("here");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006078 Slog.w(TAG, "LAUNCHING REMOTE PROVIDER (myuid " + r.uid
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006079 + " pruid " + cpr.appInfo.uid + "): " + cpr.info.name, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006080 }
6081
6082 // This is single process, and our app is now connecting to it.
6083 // See if we are already in the process of launching this
6084 // provider.
6085 final int N = mLaunchingProviders.size();
6086 int i;
6087 for (i=0; i<N; i++) {
6088 if (mLaunchingProviders.get(i) == cpr) {
6089 break;
6090 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006091 }
6092
6093 // If the provider is not already being launched, then get it
6094 // started.
6095 if (i >= N) {
6096 final long origId = Binder.clearCallingIdentity();
Dianne Hackborne7f97212011-02-24 14:40:20 -08006097
6098 try {
6099 // Content provider is now in use, its package can't be stopped.
6100 try {
6101 AppGlobals.getPackageManager().setPackageStoppedState(
6102 cpr.appInfo.packageName, false);
6103 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006104 } catch (IllegalArgumentException e) {
6105 Slog.w(TAG, "Failed trying to unstop package "
6106 + cpr.appInfo.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006107 }
6108
6109 ProcessRecord proc = startProcessLocked(cpi.processName,
6110 cpr.appInfo, false, 0, "content provider",
6111 new ComponentName(cpi.applicationInfo.packageName,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006112 cpi.name), false, false);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006113 if (proc == null) {
6114 Slog.w(TAG, "Unable to launch app "
6115 + cpi.applicationInfo.packageName + "/"
6116 + cpi.applicationInfo.uid + " for provider "
6117 + name + ": process is bad");
6118 return null;
6119 }
6120 cpr.launchingApp = proc;
6121 mLaunchingProviders.add(cpr);
6122 } finally {
6123 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006124 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006125 }
6126
6127 // Make sure the provider is published (the same provider class
6128 // may be published under multiple names).
6129 if (firstClass) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006130 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006131 }
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006132
Amith Yamasani742a6712011-05-04 14:49:28 -07006133 mProviderMap.putProviderByName(name, cpr);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006134 incProviderCount(r, cpr, token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006135 }
6136 }
6137
6138 // Wait for the provider to be published...
6139 synchronized (cpr) {
6140 while (cpr.provider == null) {
6141 if (cpr.launchingApp == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006142 Slog.w(TAG, "Unable to launch app "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006143 + cpi.applicationInfo.packageName + "/"
6144 + cpi.applicationInfo.uid + " for provider "
6145 + name + ": launching app became null");
Doug Zongker2bec3d42009-12-04 12:52:44 -08006146 EventLog.writeEvent(EventLogTags.AM_PROVIDER_LOST_PROCESS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006147 cpi.applicationInfo.packageName,
6148 cpi.applicationInfo.uid, name);
6149 return null;
6150 }
6151 try {
Amith Yamasani742a6712011-05-04 14:49:28 -07006152 if (DEBUG_MU) {
6153 Slog.v(TAG_MU, "Waiting to start provider " + cpr + " launchingApp="
6154 + cpr.launchingApp);
6155 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006156 cpr.wait();
6157 } catch (InterruptedException ex) {
6158 }
6159 }
6160 }
6161 return cpr;
6162 }
6163
6164 public final ContentProviderHolder getContentProvider(
6165 IApplicationThread caller, String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006166 enforceNotIsolatedCaller("getContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006167 if (caller == null) {
6168 String msg = "null IApplicationThread when getting content provider "
6169 + name;
Joe Onorato8a9b2202010-02-26 18:56:32 -08006170 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006171 throw new SecurityException(msg);
6172 }
6173
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006174 return getContentProviderImpl(caller, name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006175 }
6176
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006177 public ContentProviderHolder getContentProviderExternal(String name, IBinder token) {
6178 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6179 "Do not have permission in call getContentProviderExternal()");
6180 return getContentProviderExternalUnchecked(name, token);
6181 }
6182
6183 private ContentProviderHolder getContentProviderExternalUnchecked(String name,IBinder token) {
6184 return getContentProviderImpl(null, name, token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006185 }
6186
6187 /**
6188 * Drop a content provider from a ProcessRecord's bookkeeping
6189 * @param cpr
6190 */
6191 public void removeContentProvider(IApplicationThread caller, String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006192 enforceNotIsolatedCaller("removeContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006193 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006194 int userId = UserId.getUserId(Binder.getCallingUid());
6195 ContentProviderRecord cpr = mProviderMap.getProviderByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006196 if(cpr == null) {
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006197 // remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006198 if (DEBUG_PROVIDER) Slog.v(TAG, name +
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006199 " provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006200 return;
6201 }
6202 final ProcessRecord r = getRecordForAppLocked(caller);
6203 if (r == null) {
6204 throw new SecurityException(
6205 "Unable to find app for caller " + caller +
6206 " when removing content provider " + name);
6207 }
6208 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006209 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006210 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp, userId);
6211 if (DEBUG_PROVIDER) Slog.v(TAG, "Removing provider requested by "
6212 + r.info.processName + " from process "
6213 + localCpr.appInfo.processName);
6214 if (localCpr.launchingApp == r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006215 //should not happen. taken care of as a local provider
Joe Onorato8a9b2202010-02-26 18:56:32 -08006216 Slog.w(TAG, "removeContentProvider called on local provider: "
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006217 + cpr.info.name + " in process " + r.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006218 return;
6219 } else {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006220 if (decProviderCount(r, localCpr, null)) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006221 updateOomAdjLocked();
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07006222 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006223 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006224 }
6225 }
6226
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006227 public void removeContentProviderExternal(String name, IBinder token) {
6228 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6229 "Do not have permission in call removeContentProviderExternal()");
6230 removeContentProviderExternalUnchecked(name, token);
6231 }
6232
6233 private void removeContentProviderExternalUnchecked(String name, IBinder token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006234 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006235 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
6236 Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006237 if(cpr == null) {
6238 //remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006239 if(localLOGV) Slog.v(TAG, name+" content provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006240 return;
6241 }
6242
6243 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006244 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006245 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp,
6246 Binder.getOrigCallingUser());
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006247 if (localCpr.hasExternalProcessHandles()) {
6248 if (localCpr.removeExternalProcessHandleLocked(token)) {
6249 updateOomAdjLocked();
6250 } else {
6251 Slog.e(TAG, "Attmpt to remove content provider " + localCpr
6252 + " with no external reference for token: "
6253 + token + ".");
6254 }
6255 } else {
6256 Slog.e(TAG, "Attmpt to remove content provider: " + localCpr
6257 + " with no external references.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006258 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006259 }
6260 }
6261
6262 public final void publishContentProviders(IApplicationThread caller,
6263 List<ContentProviderHolder> providers) {
6264 if (providers == null) {
6265 return;
6266 }
6267
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006268 enforceNotIsolatedCaller("publishContentProviders");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006269 synchronized(this) {
6270 final ProcessRecord r = getRecordForAppLocked(caller);
Amith Yamasani742a6712011-05-04 14:49:28 -07006271 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006272 Slog.v(TAG_MU, "ProcessRecord uid = " + r.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006273 if (r == null) {
6274 throw new SecurityException(
6275 "Unable to find app for caller " + caller
6276 + " (pid=" + Binder.getCallingPid()
6277 + ") when publishing content providers");
6278 }
6279
6280 final long origId = Binder.clearCallingIdentity();
6281
6282 final int N = providers.size();
6283 for (int i=0; i<N; i++) {
6284 ContentProviderHolder src = providers.get(i);
6285 if (src == null || src.info == null || src.provider == null) {
6286 continue;
6287 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07006288 ContentProviderRecord dst = r.pubProviders.get(src.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006289 if (DEBUG_MU)
6290 Slog.v(TAG_MU, "ContentProviderRecord uid = " + dst.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006291 if (dst != null) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006292 ComponentName comp = new ComponentName(dst.info.packageName, dst.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006293 mProviderMap.putProviderByClass(comp, dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006294 String names[] = dst.info.authority.split(";");
6295 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006296 mProviderMap.putProviderByName(names[j], dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006297 }
6298
6299 int NL = mLaunchingProviders.size();
6300 int j;
6301 for (j=0; j<NL; j++) {
6302 if (mLaunchingProviders.get(j) == dst) {
6303 mLaunchingProviders.remove(j);
6304 j--;
6305 NL--;
6306 }
6307 }
6308 synchronized (dst) {
6309 dst.provider = src.provider;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006310 dst.proc = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006311 dst.notifyAll();
6312 }
6313 updateOomAdjLocked(r);
6314 }
6315 }
6316
6317 Binder.restoreCallingIdentity(origId);
6318 }
6319 }
6320
6321 public static final void installSystemProviders() {
Jeff Brown10e89712011-07-08 18:52:57 -07006322 List<ProviderInfo> providers;
Josh Bartel2ecce342010-02-25 10:55:48 -06006323 synchronized (mSelf) {
6324 ProcessRecord app = mSelf.mProcessNames.get("system", Process.SYSTEM_UID);
6325 providers = mSelf.generateApplicationProvidersLocked(app);
Dianne Hackborn5c83a5f2010-03-12 16:46:46 -08006326 if (providers != null) {
6327 for (int i=providers.size()-1; i>=0; i--) {
6328 ProviderInfo pi = (ProviderInfo)providers.get(i);
6329 if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6330 Slog.w(TAG, "Not installing system proc provider " + pi.name
6331 + ": not system .apk");
6332 providers.remove(i);
6333 }
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006334 }
6335 }
6336 }
Josh Bartel2ecce342010-02-25 10:55:48 -06006337 if (providers != null) {
6338 mSystemThread.installSystemProviders(providers);
6339 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08006340
6341 mSelf.mCoreSettingsObserver = new CoreSettingsObserver(mSelf);
Mark Brophyc6350272011-08-05 16:16:39 +01006342
6343 mSelf.mUsageStatsService.monitorPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006344 }
6345
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006346 /**
6347 * Allows app to retrieve the MIME type of a URI without having permission
6348 * to access its content provider.
6349 *
6350 * CTS tests for this functionality can be run with "runtest cts-appsecurity".
6351 *
6352 * Test cases are at cts/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/
6353 * src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java
6354 */
6355 public String getProviderMimeType(Uri uri) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006356 enforceNotIsolatedCaller("getProviderMimeType");
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006357 final String name = uri.getAuthority();
6358 final long ident = Binder.clearCallingIdentity();
6359 ContentProviderHolder holder = null;
6360
6361 try {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006362 holder = getContentProviderExternalUnchecked(name, null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006363 if (holder != null) {
6364 return holder.provider.getType(uri);
6365 }
6366 } catch (RemoteException e) {
6367 Log.w(TAG, "Content provider dead retrieving " + uri, e);
6368 return null;
6369 } finally {
6370 if (holder != null) {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006371 removeContentProviderExternalUnchecked(name, null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006372 }
6373 Binder.restoreCallingIdentity(ident);
6374 }
6375
6376 return null;
6377 }
6378
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006379 // =========================================================
6380 // GLOBAL MANAGEMENT
6381 // =========================================================
6382
6383 final ProcessRecord newProcessRecordLocked(IApplicationThread thread,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006384 ApplicationInfo info, String customProcess, boolean isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006385 String proc = customProcess != null ? customProcess : info.processName;
6386 BatteryStatsImpl.Uid.Proc ps = null;
6387 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006388 int uid = info.uid;
6389 if (isolated) {
6390 int userId = UserId.getUserId(uid);
6391 int stepsLeft = Process.LAST_ISOLATED_UID - Process.FIRST_ISOLATED_UID + 1;
6392 uid = 0;
6393 while (true) {
6394 if (mNextIsolatedProcessUid < Process.FIRST_ISOLATED_UID
6395 || mNextIsolatedProcessUid > Process.LAST_ISOLATED_UID) {
6396 mNextIsolatedProcessUid = Process.FIRST_ISOLATED_UID;
6397 }
6398 uid = UserId.getUid(userId, mNextIsolatedProcessUid);
6399 mNextIsolatedProcessUid++;
6400 if (mIsolatedProcesses.indexOfKey(uid) < 0) {
6401 // No process for this uid, use it.
6402 break;
6403 }
6404 stepsLeft--;
6405 if (stepsLeft <= 0) {
6406 return null;
6407 }
6408 }
6409 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006410 synchronized (stats) {
6411 ps = stats.getProcessStatsLocked(info.uid, proc);
6412 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006413 return new ProcessRecord(ps, thread, info, proc, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006414 }
6415
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006416 final ProcessRecord addAppLocked(ApplicationInfo info, boolean isolated) {
6417 ProcessRecord app;
6418 if (!isolated) {
6419 app = getProcessRecordLocked(info.processName, info.uid);
6420 } else {
6421 app = null;
6422 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006423
6424 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006425 app = newProcessRecordLocked(null, info, null, isolated);
6426 mProcessNames.put(info.processName, app.uid, app);
6427 if (isolated) {
6428 mIsolatedProcesses.put(app.uid, app);
6429 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08006430 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006431 }
6432
Dianne Hackborne7f97212011-02-24 14:40:20 -08006433 // This package really, really can not be stopped.
6434 try {
6435 AppGlobals.getPackageManager().setPackageStoppedState(
6436 info.packageName, false);
6437 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006438 } catch (IllegalArgumentException e) {
6439 Slog.w(TAG, "Failed trying to unstop package "
6440 + info.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006441 }
6442
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006443 if ((info.flags&(ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT))
6444 == (ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT)) {
6445 app.persistent = true;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07006446 app.maxAdj = ProcessList.PERSISTENT_PROC_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006447 }
6448 if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) {
6449 mPersistentStartingProcesses.add(app);
6450 startProcessLocked(app, "added application", app.processName);
6451 }
6452
6453 return app;
6454 }
6455
6456 public void unhandledBack() {
6457 enforceCallingPermission(android.Manifest.permission.FORCE_BACK,
6458 "unhandledBack()");
6459
6460 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006461 int count = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08006462 if (DEBUG_SWITCH) Slog.d(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006463 TAG, "Performing unhandledBack(): stack size = " + count);
6464 if (count > 1) {
6465 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006466 mMainStack.finishActivityLocked((ActivityRecord)mMainStack.mHistory.get(count-1),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006467 count-1, Activity.RESULT_CANCELED, null, "unhandled-back");
6468 Binder.restoreCallingIdentity(origId);
6469 }
6470 }
6471 }
6472
6473 public ParcelFileDescriptor openContentUri(Uri uri) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006474 enforceNotIsolatedCaller("openContentUri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006475 String name = uri.getAuthority();
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006476 ContentProviderHolder cph = getContentProviderExternalUnchecked(name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006477 ParcelFileDescriptor pfd = null;
6478 if (cph != null) {
6479 // We record the binder invoker's uid in thread-local storage before
6480 // going to the content provider to open the file. Later, in the code
6481 // that handles all permissions checks, we look for this uid and use
6482 // that rather than the Activity Manager's own uid. The effect is that
6483 // we do the check against the caller's permissions even though it looks
6484 // to the content provider like the Activity Manager itself is making
6485 // the request.
6486 sCallerIdentity.set(new Identity(
6487 Binder.getCallingPid(), Binder.getCallingUid()));
6488 try {
6489 pfd = cph.provider.openFile(uri, "r");
6490 } catch (FileNotFoundException e) {
6491 // do nothing; pfd will be returned null
6492 } finally {
6493 // Ensure that whatever happens, we clean up the identity state
6494 sCallerIdentity.remove();
6495 }
6496
6497 // We've got the fd now, so we're done with the provider.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006498 removeContentProviderExternalUnchecked(name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006499 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006500 Slog.d(TAG, "Failed to get provider for authority '" + name + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006501 }
6502 return pfd;
6503 }
6504
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006505 // Actually is sleeping or shutting down or whatever else in the future
6506 // is an inactive state.
6507 public boolean isSleeping() {
6508 return mSleeping || mShuttingDown;
6509 }
6510
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006511 public void goingToSleep() {
6512 synchronized(this) {
6513 mSleeping = true;
6514 mWindowManager.setEventDispatching(false);
6515
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006516 mMainStack.stopIfSleepingLocked();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006517
6518 // Initialize the wake times of all processes.
Dianne Hackborn287952c2010-09-22 22:34:31 -07006519 checkExcessivePowerUsageLocked(false);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006520 mHandler.removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
6521 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07006522 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006523 }
6524 }
6525
Dianne Hackborn55280a92009-05-07 15:53:46 -07006526 public boolean shutdown(int timeout) {
6527 if (checkCallingPermission(android.Manifest.permission.SHUTDOWN)
6528 != PackageManager.PERMISSION_GRANTED) {
6529 throw new SecurityException("Requires permission "
6530 + android.Manifest.permission.SHUTDOWN);
6531 }
6532
6533 boolean timedout = false;
6534
6535 synchronized(this) {
6536 mShuttingDown = true;
6537 mWindowManager.setEventDispatching(false);
6538
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006539 if (mMainStack.mResumedActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006540 mMainStack.stopIfSleepingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07006541 final long endTime = System.currentTimeMillis() + timeout;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006542 while (mMainStack.mResumedActivity != null
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08006543 || mMainStack.mPausingActivity != null) {
Dianne Hackborn55280a92009-05-07 15:53:46 -07006544 long delay = endTime - System.currentTimeMillis();
6545 if (delay <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006546 Slog.w(TAG, "Activity manager shutdown timed out");
Dianne Hackborn55280a92009-05-07 15:53:46 -07006547 timedout = true;
6548 break;
6549 }
6550 try {
6551 this.wait();
6552 } catch (InterruptedException e) {
6553 }
6554 }
6555 }
6556 }
6557
6558 mUsageStatsService.shutdown();
6559 mBatteryStatsService.shutdown();
6560
6561 return timedout;
6562 }
6563
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006564 public final void activitySlept(IBinder token) {
6565 if (localLOGV) Slog.v(
6566 TAG, "Activity slept: token=" + token);
6567
6568 ActivityRecord r = null;
6569
6570 final long origId = Binder.clearCallingIdentity();
6571
6572 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006573 r = mMainStack.isInStackLocked(token);
6574 if (r != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006575 mMainStack.activitySleptLocked(r);
6576 }
6577 }
6578
6579 Binder.restoreCallingIdentity(origId);
6580 }
6581
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006582 public void wakingUp() {
6583 synchronized(this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006584 mWindowManager.setEventDispatching(true);
6585 mSleeping = false;
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006586 mMainStack.awakeFromSleepingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006587 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006588 }
6589 }
6590
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006591 public void stopAppSwitches() {
6592 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
6593 != PackageManager.PERMISSION_GRANTED) {
6594 throw new SecurityException("Requires permission "
6595 + android.Manifest.permission.STOP_APP_SWITCHES);
6596 }
6597
6598 synchronized(this) {
6599 mAppSwitchesAllowedTime = SystemClock.uptimeMillis()
6600 + APP_SWITCH_DELAY_TIME;
6601 mDidAppSwitch = false;
6602 mHandler.removeMessages(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
6603 Message msg = mHandler.obtainMessage(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
6604 mHandler.sendMessageDelayed(msg, APP_SWITCH_DELAY_TIME);
6605 }
6606 }
6607
6608 public void resumeAppSwitches() {
6609 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
6610 != PackageManager.PERMISSION_GRANTED) {
6611 throw new SecurityException("Requires permission "
6612 + android.Manifest.permission.STOP_APP_SWITCHES);
6613 }
6614
6615 synchronized(this) {
6616 // Note that we don't execute any pending app switches... we will
6617 // let those wait until either the timeout, or the next start
6618 // activity request.
6619 mAppSwitchesAllowedTime = 0;
6620 }
6621 }
6622
6623 boolean checkAppSwitchAllowedLocked(int callingPid, int callingUid,
6624 String name) {
6625 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
6626 return true;
6627 }
6628
6629 final int perm = checkComponentPermission(
6630 android.Manifest.permission.STOP_APP_SWITCHES, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006631 callingUid, -1, true);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006632 if (perm == PackageManager.PERMISSION_GRANTED) {
6633 return true;
6634 }
6635
Joe Onorato8a9b2202010-02-26 18:56:32 -08006636 Slog.w(TAG, name + " request from " + callingUid + " stopped");
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006637 return false;
6638 }
6639
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006640 public void setDebugApp(String packageName, boolean waitForDebugger,
6641 boolean persistent) {
6642 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
6643 "setDebugApp()");
6644
6645 // Note that this is not really thread safe if there are multiple
6646 // callers into it at the same time, but that's not a situation we
6647 // care about.
6648 if (persistent) {
6649 final ContentResolver resolver = mContext.getContentResolver();
6650 Settings.System.putString(
6651 resolver, Settings.System.DEBUG_APP,
6652 packageName);
6653 Settings.System.putInt(
6654 resolver, Settings.System.WAIT_FOR_DEBUGGER,
6655 waitForDebugger ? 1 : 0);
6656 }
6657
6658 synchronized (this) {
6659 if (!persistent) {
6660 mOrigDebugApp = mDebugApp;
6661 mOrigWaitForDebugger = mWaitForDebugger;
6662 }
6663 mDebugApp = packageName;
6664 mWaitForDebugger = waitForDebugger;
6665 mDebugTransient = !persistent;
6666 if (packageName != null) {
6667 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -07006668 forceStopPackageLocked(packageName, -1, false, false, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006669 Binder.restoreCallingIdentity(origId);
6670 }
6671 }
6672 }
6673
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07006674 void setProfileApp(ApplicationInfo app, String processName, String profileFile,
6675 ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
6676 synchronized (this) {
6677 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
6678 if (!isDebuggable) {
6679 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
6680 throw new SecurityException("Process not debuggable: " + app.packageName);
6681 }
6682 }
6683 mProfileApp = processName;
6684 mProfileFile = profileFile;
6685 if (mProfileFd != null) {
6686 try {
6687 mProfileFd.close();
6688 } catch (IOException e) {
6689 }
6690 mProfileFd = null;
6691 }
6692 mProfileFd = profileFd;
6693 mProfileType = 0;
6694 mAutoStopProfiler = autoStopProfiler;
6695 }
6696 }
6697
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006698 public void setAlwaysFinish(boolean enabled) {
6699 enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH,
6700 "setAlwaysFinish()");
6701
6702 Settings.System.putInt(
6703 mContext.getContentResolver(),
6704 Settings.System.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0);
6705
6706 synchronized (this) {
6707 mAlwaysFinishActivities = enabled;
6708 }
6709 }
6710
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006711 public void setActivityController(IActivityController controller) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006712 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006713 "setActivityController()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006714 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006715 mController = controller;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006716 }
6717 }
6718
Dianne Hackborn9327f4f2010-01-29 10:38:29 -08006719 public boolean isUserAMonkey() {
6720 // For now the fact that there is a controller implies
6721 // we have a monkey.
6722 synchronized (this) {
6723 return mController != null;
6724 }
6725 }
6726
Jeff Sharkeya4620792011-05-20 15:29:23 -07006727 public void registerProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08006728 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
6729 "registerProcessObserver()");
6730 synchronized (this) {
6731 mProcessObservers.register(observer);
6732 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07006733 }
6734
6735 public void unregisterProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08006736 synchronized (this) {
6737 mProcessObservers.unregister(observer);
6738 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07006739 }
6740
Daniel Sandler69a48172010-06-23 16:29:36 -04006741 public void setImmersive(IBinder token, boolean immersive) {
6742 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006743 ActivityRecord r = mMainStack.isInStackLocked(token);
6744 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04006745 throw new IllegalArgumentException();
6746 }
Daniel Sandler69a48172010-06-23 16:29:36 -04006747 r.immersive = immersive;
6748 }
6749 }
6750
6751 public boolean isImmersive(IBinder token) {
6752 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006753 ActivityRecord r = mMainStack.isInStackLocked(token);
6754 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04006755 throw new IllegalArgumentException();
6756 }
Daniel Sandler69a48172010-06-23 16:29:36 -04006757 return r.immersive;
6758 }
6759 }
6760
6761 public boolean isTopActivityImmersive() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006762 enforceNotIsolatedCaller("startActivity");
Daniel Sandler69a48172010-06-23 16:29:36 -04006763 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006764 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Daniel Sandler69a48172010-06-23 16:29:36 -04006765 return (r != null) ? r.immersive : false;
6766 }
6767 }
6768
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006769 public final void enterSafeMode() {
6770 synchronized(this) {
6771 // It only makes sense to do this before the system is ready
6772 // and started launching other packages.
6773 if (!mSystemReady) {
6774 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006775 AppGlobals.getPackageManager().enterSafeMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006776 } catch (RemoteException e) {
6777 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006778 }
6779 }
6780 }
6781
Jeff Brownb09abc12011-01-13 21:08:27 -08006782 public final void showSafeModeOverlay() {
6783 View v = LayoutInflater.from(mContext).inflate(
6784 com.android.internal.R.layout.safe_mode, null);
6785 WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
6786 lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
6787 lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
6788 lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
6789 lp.gravity = Gravity.BOTTOM | Gravity.LEFT;
6790 lp.format = v.getBackground().getOpacity();
6791 lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
6792 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
6793 ((WindowManager)mContext.getSystemService(
6794 Context.WINDOW_SERVICE)).addView(v, lp);
6795 }
6796
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006797 public void noteWakeupAlarm(IIntentSender sender) {
6798 if (!(sender instanceof PendingIntentRecord)) {
6799 return;
6800 }
6801 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
6802 synchronized (stats) {
6803 if (mBatteryStatsService.isOnBattery()) {
6804 mBatteryStatsService.enforceCallingPermission();
6805 PendingIntentRecord rec = (PendingIntentRecord)sender;
6806 int MY_UID = Binder.getCallingUid();
6807 int uid = rec.uid == MY_UID ? Process.SYSTEM_UID : rec.uid;
6808 BatteryStatsImpl.Uid.Pkg pkg =
6809 stats.getPackageStatsLocked(uid, rec.key.packageName);
6810 pkg.incWakeupsLocked();
6811 }
6812 }
6813 }
6814
Dianne Hackborn64825172011-03-02 21:32:58 -08006815 public boolean killPids(int[] pids, String pReason, boolean secure) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006816 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006817 throw new SecurityException("killPids only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006818 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006819 String reason = (pReason == null) ? "Unknown" : pReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006820 // XXX Note: don't acquire main activity lock here, because the window
6821 // manager calls in with its locks held.
6822
6823 boolean killed = false;
6824 synchronized (mPidsSelfLocked) {
6825 int[] types = new int[pids.length];
6826 int worstType = 0;
6827 for (int i=0; i<pids.length; i++) {
6828 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
6829 if (proc != null) {
6830 int type = proc.setAdj;
6831 types[i] = type;
6832 if (type > worstType) {
6833 worstType = type;
6834 }
6835 }
6836 }
6837
Dianne Hackborn64825172011-03-02 21:32:58 -08006838 // If the worst oom_adj is somewhere in the hidden proc LRU range,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006839 // then constrain it so we will kill all hidden procs.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07006840 if (worstType < ProcessList.HIDDEN_APP_MAX_ADJ
6841 && worstType > ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07006842 worstType = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006843 }
Dianne Hackborn64825172011-03-02 21:32:58 -08006844
6845 // If this is not a secure call, don't let it kill processes that
6846 // are important.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07006847 if (!secure && worstType < ProcessList.SERVICE_ADJ) {
6848 worstType = ProcessList.SERVICE_ADJ;
Dianne Hackborn64825172011-03-02 21:32:58 -08006849 }
6850
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006851 Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006852 for (int i=0; i<pids.length; i++) {
6853 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
6854 if (proc == null) {
6855 continue;
6856 }
6857 int adj = proc.setAdj;
Dianne Hackborn906497c2010-05-10 15:57:38 -07006858 if (adj >= worstType && !proc.killedBackground) {
Dianne Hackborn8633e682010-04-22 16:03:41 -07006859 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006860 EventLog.writeEvent(EventLogTags.AM_KILL, proc.pid,
6861 proc.processName, adj, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006862 killed = true;
Dianne Hackborn906497c2010-05-10 15:57:38 -07006863 proc.killedBackground = true;
6864 Process.killProcessQuiet(pids[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006865 }
6866 }
6867 }
6868 return killed;
6869 }
6870
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006871 public final void startRunning(String pkg, String cls, String action,
6872 String data) {
6873 synchronized(this) {
6874 if (mStartRunning) {
6875 return;
6876 }
6877 mStartRunning = true;
6878 mTopComponent = pkg != null && cls != null
6879 ? new ComponentName(pkg, cls) : null;
6880 mTopAction = action != null ? action : Intent.ACTION_MAIN;
6881 mTopData = data;
6882 if (!mSystemReady) {
6883 return;
6884 }
6885 }
6886
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07006887 systemReady(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006888 }
6889
6890 private void retrieveSettings() {
6891 final ContentResolver resolver = mContext.getContentResolver();
6892 String debugApp = Settings.System.getString(
6893 resolver, Settings.System.DEBUG_APP);
6894 boolean waitForDebugger = Settings.System.getInt(
6895 resolver, Settings.System.WAIT_FOR_DEBUGGER, 0) != 0;
6896 boolean alwaysFinishActivities = Settings.System.getInt(
6897 resolver, Settings.System.ALWAYS_FINISH_ACTIVITIES, 0) != 0;
6898
6899 Configuration configuration = new Configuration();
6900 Settings.System.getConfiguration(resolver, configuration);
6901
6902 synchronized (this) {
6903 mDebugApp = mOrigDebugApp = debugApp;
6904 mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger;
6905 mAlwaysFinishActivities = alwaysFinishActivities;
6906 // This happens before any activities are started, so we can
6907 // change mConfiguration in-place.
Dianne Hackborn813075a62011-11-14 17:45:19 -08006908 updateConfigurationLocked(configuration, null, false, true);
Joe Onorato8a9b2202010-02-26 18:56:32 -08006909 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Initial config: " + mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006910 }
6911 }
6912
6913 public boolean testIsSystemReady() {
6914 // no need to synchronize(this) just to read & return the value
6915 return mSystemReady;
6916 }
6917
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006918 private static File getCalledPreBootReceiversFile() {
6919 File dataDir = Environment.getDataDirectory();
6920 File systemDir = new File(dataDir, "system");
6921 File fname = new File(systemDir, "called_pre_boots.dat");
6922 return fname;
6923 }
Dianne Hackborn661cd522011-08-22 00:26:20 -07006924
6925 static final int LAST_DONE_VERSION = 10000;
6926
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006927 private static ArrayList<ComponentName> readLastDonePreBootReceivers() {
6928 ArrayList<ComponentName> lastDoneReceivers = new ArrayList<ComponentName>();
6929 File file = getCalledPreBootReceiversFile();
6930 FileInputStream fis = null;
6931 try {
6932 fis = new FileInputStream(file);
6933 DataInputStream dis = new DataInputStream(new BufferedInputStream(fis, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07006934 int fvers = dis.readInt();
6935 if (fvers == LAST_DONE_VERSION) {
6936 String vers = dis.readUTF();
6937 String codename = dis.readUTF();
6938 String build = dis.readUTF();
6939 if (android.os.Build.VERSION.RELEASE.equals(vers)
6940 && android.os.Build.VERSION.CODENAME.equals(codename)
6941 && android.os.Build.VERSION.INCREMENTAL.equals(build)) {
6942 int num = dis.readInt();
6943 while (num > 0) {
6944 num--;
6945 String pkg = dis.readUTF();
6946 String cls = dis.readUTF();
6947 lastDoneReceivers.add(new ComponentName(pkg, cls));
6948 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006949 }
6950 }
6951 } catch (FileNotFoundException e) {
6952 } catch (IOException e) {
6953 Slog.w(TAG, "Failure reading last done pre-boot receivers", e);
6954 } finally {
6955 if (fis != null) {
6956 try {
6957 fis.close();
6958 } catch (IOException e) {
6959 }
6960 }
6961 }
6962 return lastDoneReceivers;
6963 }
6964
6965 private static void writeLastDonePreBootReceivers(ArrayList<ComponentName> list) {
6966 File file = getCalledPreBootReceiversFile();
6967 FileOutputStream fos = null;
6968 DataOutputStream dos = null;
6969 try {
6970 Slog.i(TAG, "Writing new set of last done pre-boot receivers...");
6971 fos = new FileOutputStream(file);
6972 dos = new DataOutputStream(new BufferedOutputStream(fos, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07006973 dos.writeInt(LAST_DONE_VERSION);
6974 dos.writeUTF(android.os.Build.VERSION.RELEASE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006975 dos.writeUTF(android.os.Build.VERSION.CODENAME);
Dianne Hackborn661cd522011-08-22 00:26:20 -07006976 dos.writeUTF(android.os.Build.VERSION.INCREMENTAL);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006977 dos.writeInt(list.size());
6978 for (int i=0; i<list.size(); i++) {
6979 dos.writeUTF(list.get(i).getPackageName());
6980 dos.writeUTF(list.get(i).getClassName());
6981 }
6982 } catch (IOException e) {
6983 Slog.w(TAG, "Failure writing last done pre-boot receivers", e);
6984 file.delete();
6985 } finally {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07006986 FileUtils.sync(fos);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006987 if (dos != null) {
6988 try {
6989 dos.close();
6990 } catch (IOException e) {
6991 // TODO Auto-generated catch block
6992 e.printStackTrace();
6993 }
6994 }
6995 }
6996 }
6997
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07006998 public void systemReady(final Runnable goingCallback) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006999 synchronized(this) {
7000 if (mSystemReady) {
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007001 if (goingCallback != null) goingCallback.run();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007002 return;
7003 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007004
7005 // Check to see if there are any update receivers to run.
7006 if (!mDidUpdate) {
7007 if (mWaitingUpdate) {
7008 return;
7009 }
7010 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
7011 List<ResolveInfo> ris = null;
7012 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007013 ris = AppGlobals.getPackageManager().queryIntentReceivers(
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007014 intent, null, 0);
7015 } catch (RemoteException e) {
7016 }
7017 if (ris != null) {
7018 for (int i=ris.size()-1; i>=0; i--) {
7019 if ((ris.get(i).activityInfo.applicationInfo.flags
7020 &ApplicationInfo.FLAG_SYSTEM) == 0) {
7021 ris.remove(i);
7022 }
7023 }
7024 intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007025
7026 ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers();
7027
7028 final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007029 for (int i=0; i<ris.size(); i++) {
7030 ActivityInfo ai = ris.get(i).activityInfo;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007031 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7032 if (lastDoneReceivers.contains(comp)) {
7033 ris.remove(i);
7034 i--;
7035 }
7036 }
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07007037
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007038 for (int i=0; i<ris.size(); i++) {
7039 ActivityInfo ai = ris.get(i).activityInfo;
7040 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7041 doneReceivers.add(comp);
7042 intent.setComponent(comp);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007043 IIntentReceiver finisher = null;
Dianne Hackbornd6847842010-01-12 18:14:19 -08007044 if (i == ris.size()-1) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007045 finisher = new IIntentReceiver.Stub() {
7046 public void performReceive(Intent intent, int resultCode,
Dianne Hackborn68d881c2009-10-05 13:58:17 -07007047 String data, Bundle extras, boolean ordered,
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007048 boolean sticky) {
7049 // The raw IIntentReceiver interface is called
7050 // with the AM lock held, so redispatch to
7051 // execute our code without the lock.
7052 mHandler.post(new Runnable() {
7053 public void run() {
7054 synchronized (ActivityManagerService.this) {
7055 mDidUpdate = true;
7056 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007057 writeLastDonePreBootReceivers(doneReceivers);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007058 showBootMessage(mContext.getText(
7059 R.string.android_upgrading_complete),
7060 false);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007061 systemReady(goingCallback);
7062 }
7063 });
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007064 }
7065 };
7066 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08007067 Slog.i(TAG, "Sending system update to: " + intent.getComponent());
Amith Yamasani742a6712011-05-04 14:49:28 -07007068 /* TODO: Send this to all users */
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007069 broadcastIntentLocked(null, null, intent, null, finisher,
Amith Yamasani742a6712011-05-04 14:49:28 -07007070 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID,
Amith Yamasanic600e21f2012-02-14 16:08:07 -08007071 0 /* UserId zero */);
Dianne Hackbornd6847842010-01-12 18:14:19 -08007072 if (finisher != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007073 mWaitingUpdate = true;
7074 }
7075 }
7076 }
7077 if (mWaitingUpdate) {
7078 return;
7079 }
7080 mDidUpdate = true;
7081 }
7082
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007083 mSystemReady = true;
7084 if (!mStartRunning) {
7085 return;
7086 }
7087 }
7088
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007089 ArrayList<ProcessRecord> procsToKill = null;
7090 synchronized(mPidsSelfLocked) {
7091 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
7092 ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7093 if (!isAllowedWhileBooting(proc.info)){
7094 if (procsToKill == null) {
7095 procsToKill = new ArrayList<ProcessRecord>();
7096 }
7097 procsToKill.add(proc);
7098 }
7099 }
7100 }
7101
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007102 synchronized(this) {
7103 if (procsToKill != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007104 for (int i=procsToKill.size()-1; i>=0; i--) {
7105 ProcessRecord proc = procsToKill.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007106 Slog.i(TAG, "Removing system update proc: " + proc);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007107 removeProcessLocked(proc, true, false, "system update done");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007108 }
7109 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007110
7111 // Now that we have cleaned up any update processes, we
7112 // are ready to start launching real processes and know that
7113 // we won't trample on them any more.
7114 mProcessesReady = true;
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007115 }
7116
Joe Onorato8a9b2202010-02-26 18:56:32 -08007117 Slog.i(TAG, "System now ready");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007118 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007119 SystemClock.uptimeMillis());
7120
7121 synchronized(this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007122 // Make sure we have no pre-ready processes sitting around.
7123
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007124 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
7125 ResolveInfo ri = mContext.getPackageManager()
7126 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST),
Dianne Hackborn1655be42009-05-08 14:29:01 -07007127 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007128 CharSequence errorMsg = null;
7129 if (ri != null) {
7130 ActivityInfo ai = ri.activityInfo;
7131 ApplicationInfo app = ai.applicationInfo;
7132 if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7133 mTopAction = Intent.ACTION_FACTORY_TEST;
7134 mTopData = null;
7135 mTopComponent = new ComponentName(app.packageName,
7136 ai.name);
7137 } else {
7138 errorMsg = mContext.getResources().getText(
7139 com.android.internal.R.string.factorytest_not_system);
7140 }
7141 } else {
7142 errorMsg = mContext.getResources().getText(
7143 com.android.internal.R.string.factorytest_no_action);
7144 }
7145 if (errorMsg != null) {
7146 mTopAction = null;
7147 mTopData = null;
7148 mTopComponent = null;
7149 Message msg = Message.obtain();
7150 msg.what = SHOW_FACTORY_ERROR_MSG;
7151 msg.getData().putCharSequence("msg", errorMsg);
7152 mHandler.sendMessage(msg);
7153 }
7154 }
7155 }
7156
7157 retrieveSettings();
7158
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007159 if (goingCallback != null) goingCallback.run();
7160
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007161 synchronized (this) {
7162 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
7163 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007164 List apps = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07007165 getPersistentApplications(STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007166 if (apps != null) {
7167 int N = apps.size();
7168 int i;
7169 for (i=0; i<N; i++) {
7170 ApplicationInfo info
7171 = (ApplicationInfo)apps.get(i);
7172 if (info != null &&
7173 !info.packageName.equals("android")) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007174 addAppLocked(info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007175 }
7176 }
7177 }
7178 } catch (RemoteException ex) {
7179 // pm is in same process, this will never happen.
7180 }
7181 }
7182
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007183 // Start up initial activity.
7184 mBooting = true;
7185
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007186 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007187 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007188 Message msg = Message.obtain();
7189 msg.what = SHOW_UID_ERROR_MSG;
7190 mHandler.sendMessage(msg);
7191 }
7192 } catch (RemoteException e) {
7193 }
7194
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007195 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007196 }
7197 }
7198
Dan Egnorb7f03672009-12-09 16:22:32 -08007199 private boolean makeAppCrashingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007200 String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007201 app.crashing = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007202 app.crashingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007203 ActivityManager.ProcessErrorStateInfo.CRASHED, null, shortMsg, longMsg, stackTrace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007204 startAppProblemLocked(app);
7205 app.stopFreezingAllLocked();
7206 return handleAppCrashLocked(app);
7207 }
7208
Dan Egnorb7f03672009-12-09 16:22:32 -08007209 private void makeAppNotRespondingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007210 String activity, String shortMsg, String longMsg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007211 app.notResponding = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007212 app.notRespondingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007213 ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING,
7214 activity, shortMsg, longMsg, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007215 startAppProblemLocked(app);
7216 app.stopFreezingAllLocked();
7217 }
7218
7219 /**
7220 * Generate a process error record, suitable for attachment to a ProcessRecord.
7221 *
7222 * @param app The ProcessRecord in which the error occurred.
7223 * @param condition Crashing, Application Not Responding, etc. Values are defined in
7224 * ActivityManager.AppErrorStateInfo
Dan Egnor60d87622009-12-16 16:32:58 -08007225 * @param activity The activity associated with the crash, if known.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007226 * @param shortMsg Short message describing the crash.
7227 * @param longMsg Long message describing the crash.
Dan Egnorb7f03672009-12-09 16:22:32 -08007228 * @param stackTrace Full crash stack trace, may be null.
7229 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007230 * @return Returns a fully-formed AppErrorStateInfo record.
7231 */
7232 private ActivityManager.ProcessErrorStateInfo generateProcessError(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007233 int condition, String activity, String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007234 ActivityManager.ProcessErrorStateInfo report = new ActivityManager.ProcessErrorStateInfo();
Dan Egnorb7f03672009-12-09 16:22:32 -08007235
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007236 report.condition = condition;
7237 report.processName = app.processName;
7238 report.pid = app.pid;
7239 report.uid = app.info.uid;
Dan Egnor60d87622009-12-16 16:32:58 -08007240 report.tag = activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007241 report.shortMsg = shortMsg;
7242 report.longMsg = longMsg;
Dan Egnorb7f03672009-12-09 16:22:32 -08007243 report.stackTrace = stackTrace;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007244
7245 return report;
7246 }
7247
Dan Egnor42471dd2010-01-07 17:25:22 -08007248 void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007249 synchronized (this) {
7250 app.crashing = false;
7251 app.crashingReport = null;
7252 app.notResponding = false;
7253 app.notRespondingReport = null;
7254 if (app.anrDialog == fromDialog) {
7255 app.anrDialog = null;
7256 }
7257 if (app.waitDialog == fromDialog) {
7258 app.waitDialog = null;
7259 }
7260 if (app.pid > 0 && app.pid != MY_PID) {
Dan Egnor42471dd2010-01-07 17:25:22 -08007261 handleAppCrashLocked(app);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007262 Slog.i(ActivityManagerService.TAG, "Killing " + app + ": user's request");
Dianne Hackborn8633e682010-04-22 16:03:41 -07007263 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
7264 app.processName, app.setAdj, "user's request after error");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007265 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007266 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007267 }
7268 }
Dan Egnor42471dd2010-01-07 17:25:22 -08007269
Dan Egnorb7f03672009-12-09 16:22:32 -08007270 private boolean handleAppCrashLocked(ProcessRecord app) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007271 long now = SystemClock.uptimeMillis();
7272
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007273 Long crashTime;
7274 if (!app.isolated) {
7275 crashTime = mProcessCrashTimes.get(app.info.processName, app.uid);
7276 } else {
7277 crashTime = null;
7278 }
Dianne Hackborn7d608422011-08-07 16:24:18 -07007279 if (crashTime != null && now < crashTime+ProcessList.MIN_CRASH_INTERVAL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007280 // This process loses!
Joe Onorato8a9b2202010-02-26 18:56:32 -08007281 Slog.w(TAG, "Process " + app.info.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007282 + " has crashed too many times: killing!");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007283 EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007284 app.info.processName, app.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007285 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
7286 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007287 if (r.app == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007288 Slog.w(TAG, " Force finishing activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007289 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007290 r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED, null, "crashed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007291 }
7292 }
7293 if (!app.persistent) {
7294 // We don't want to start this process again until the user
7295 // explicitly does so... but for persistent process, we really
7296 // need to keep it running. If a persistent process is actually
7297 // repeatedly crashing, then badness for everyone.
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007298 EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007299 app.info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007300 if (!app.isolated) {
7301 // XXX We don't have a way to mark isolated processes
7302 // as bad, since they don't have a peristent identity.
7303 mBadProcesses.put(app.info.processName, app.uid, now);
7304 mProcessCrashTimes.remove(app.info.processName, app.uid);
7305 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007306 app.bad = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007307 app.removed = true;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07007308 // Don't let services in this process be restarted and potentially
7309 // annoy the user repeatedly. Unless it is persistent, since those
7310 // processes run critical code.
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007311 removeProcessLocked(app, false, false, "crash");
Dianne Hackborncb44d962011-03-10 17:02:27 -08007312 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007313 return false;
7314 }
Dianne Hackborncb44d962011-03-10 17:02:27 -08007315 mMainStack.resumeTopActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007316 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007317 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007318 if (r.app == app) {
7319 // If the top running activity is from this crashing
7320 // process, then terminate it to avoid getting in a loop.
7321 Slog.w(TAG, " Force finishing activity "
7322 + r.intent.getComponent().flattenToShortString());
Dianne Hackbornbe707852011-11-11 14:32:10 -08007323 int index = mMainStack.indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007324 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007325 Activity.RESULT_CANCELED, null, "crashed");
Dianne Hackborn070783f2010-12-29 16:46:28 -08007326 // Also terminate any activities below it that aren't yet
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007327 // stopped, to avoid a situation where one will get
7328 // re-start our crashing activity once it gets resumed again.
7329 index--;
7330 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007331 r = (ActivityRecord)mMainStack.mHistory.get(index);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007332 if (r.state == ActivityState.RESUMED
7333 || r.state == ActivityState.PAUSING
7334 || r.state == ActivityState.PAUSED) {
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08007335 if (!r.isHomeActivity || mHomeProcess != r.app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007336 Slog.w(TAG, " Force finishing activity "
7337 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007338 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007339 Activity.RESULT_CANCELED, null, "crashed");
7340 }
7341 }
7342 }
7343 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007344 }
7345
7346 // Bump up the crash count of any services currently running in the proc.
7347 if (app.services.size() != 0) {
7348 // Any services running in the application need to be placed
7349 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -07007350 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007351 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07007352 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007353 sr.crashCount++;
7354 }
7355 }
Mattias Larssona4fd0072010-06-22 22:37:03 +02007356
7357 // If the crashing process is what we consider to be the "home process" and it has been
7358 // replaced by a third-party app, clear the package preferred activities from packages
7359 // with a home activity running in the process to prevent a repeatedly crashing app
7360 // from blocking the user to manually clear the list.
7361 if (app == mHomeProcess && mHomeProcess.activities.size() > 0
7362 && (mHomeProcess.info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
7363 Iterator it = mHomeProcess.activities.iterator();
7364 while (it.hasNext()) {
Jean-Baptiste Queru5ea89f72010-07-30 09:30:31 -07007365 ActivityRecord r = (ActivityRecord)it.next();
Mattias Larssona4fd0072010-06-22 22:37:03 +02007366 if (r.isHomeActivity) {
7367 Log.i(TAG, "Clearing package preferred activities from " + r.packageName);
7368 try {
7369 ActivityThread.getPackageManager()
7370 .clearPackagePreferredActivities(r.packageName);
7371 } catch (RemoteException c) {
7372 // pm is in same process, this will never happen.
7373 }
7374 }
7375 }
7376 }
7377
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007378 if (!app.isolated) {
7379 // XXX Can't keep track of crash times for isolated processes,
7380 // because they don't have a perisistent identity.
7381 mProcessCrashTimes.put(app.info.processName, app.uid, now);
7382 }
7383
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007384 return true;
7385 }
7386
7387 void startAppProblemLocked(ProcessRecord app) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08007388 app.errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver(
7389 mContext, app.info.packageName, app.info.flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007390 skipCurrentReceiverLocked(app);
7391 }
7392
7393 void skipCurrentReceiverLocked(ProcessRecord app) {
Christopher Tatef46723b2012-01-26 14:19:24 -08007394 for (BroadcastQueue queue : mBroadcastQueues) {
7395 queue.skipCurrentReceiverLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007396 }
7397 }
7398
Dan Egnor60d87622009-12-16 16:32:58 -08007399 /**
7400 * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes.
7401 * The application process will exit immediately after this call returns.
7402 * @param app object of the crashing app, null for the system server
7403 * @param crashInfo describing the exception
7404 */
7405 public void handleApplicationCrash(IBinder app, ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007406 ProcessRecord r = findAppProcess(app, "Crash");
Jeff Sharkeya353d262011-10-28 11:12:06 -07007407 final String processName = app == null ? "system_server"
7408 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08007409
7410 EventLog.writeEvent(EventLogTags.AM_CRASH, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07007411 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08007412 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08007413 crashInfo.exceptionClassName,
7414 crashInfo.exceptionMessage,
7415 crashInfo.throwFileName,
7416 crashInfo.throwLineNumber);
7417
Jeff Sharkeya353d262011-10-28 11:12:06 -07007418 addErrorToDropBox("crash", r, processName, null, null, null, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08007419
7420 crashApplication(r, crashInfo);
7421 }
7422
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007423 public void handleApplicationStrictModeViolation(
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007424 IBinder app,
7425 int violationMask,
7426 StrictMode.ViolationInfo info) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007427 ProcessRecord r = findAppProcess(app, "StrictMode");
7428 if (r == null) {
7429 return;
7430 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007431
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007432 if ((violationMask & StrictMode.PENALTY_DROPBOX) != 0) {
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08007433 Integer stackFingerprint = info.hashCode();
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007434 boolean logIt = true;
7435 synchronized (mAlreadyLoggedViolatedStacks) {
7436 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) {
7437 logIt = false;
7438 // TODO: sub-sample into EventLog for these, with
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007439 // the info.durationMillis? Then we'd get
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007440 // the relative pain numbers, without logging all
7441 // the stack traces repeatedly. We'd want to do
7442 // likewise in the client code, which also does
7443 // dup suppression, before the Binder call.
7444 } else {
7445 if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) {
7446 mAlreadyLoggedViolatedStacks.clear();
7447 }
7448 mAlreadyLoggedViolatedStacks.add(stackFingerprint);
7449 }
7450 }
7451 if (logIt) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007452 logStrictModeViolationToDropBox(r, info);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007453 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007454 }
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007455
7456 if ((violationMask & StrictMode.PENALTY_DIALOG) != 0) {
7457 AppErrorResult result = new AppErrorResult();
7458 synchronized (this) {
7459 final long origId = Binder.clearCallingIdentity();
7460
7461 Message msg = Message.obtain();
7462 msg.what = SHOW_STRICT_MODE_VIOLATION_MSG;
7463 HashMap<String, Object> data = new HashMap<String, Object>();
7464 data.put("result", result);
7465 data.put("app", r);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007466 data.put("violationMask", violationMask);
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007467 data.put("info", info);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007468 msg.obj = data;
7469 mHandler.sendMessage(msg);
7470
7471 Binder.restoreCallingIdentity(origId);
7472 }
7473 int res = result.get();
Dianne Hackbornb424b632010-08-18 15:59:05 -07007474 Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007475 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007476 }
7477
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007478 // Depending on the policy in effect, there could be a bunch of
7479 // these in quick succession so we try to batch these together to
7480 // minimize disk writes, number of dropbox entries, and maximize
7481 // compression, by having more fewer, larger records.
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007482 private void logStrictModeViolationToDropBox(
7483 ProcessRecord process,
7484 StrictMode.ViolationInfo info) {
7485 if (info == null) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007486 return;
7487 }
7488 final boolean isSystemApp = process == null ||
7489 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM |
7490 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07007491 final String processName = process == null ? "unknown" : process.processName;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007492 final String dropboxTag = isSystemApp ? "system_app_strictmode" : "data_app_strictmode";
7493 final DropBoxManager dbox = (DropBoxManager)
7494 mContext.getSystemService(Context.DROPBOX_SERVICE);
7495
7496 // Exit early if the dropbox isn't configured to accept this report type.
7497 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
7498
7499 boolean bufferWasEmpty;
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007500 boolean needsFlush;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007501 final StringBuilder sb = isSystemApp ? mStrictModeBuffer : new StringBuilder(1024);
7502 synchronized (sb) {
7503 bufferWasEmpty = sb.length() == 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07007504 appendDropBoxProcessHeaders(process, processName, sb);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007505 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
7506 sb.append("System-App: ").append(isSystemApp).append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007507 sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n");
7508 if (info.violationNumThisLoop != 0) {
7509 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n");
7510 }
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07007511 if (info.numAnimationsRunning != 0) {
7512 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n");
7513 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07007514 if (info.broadcastIntentAction != null) {
7515 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n");
7516 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08007517 if (info.durationMillis != -1) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007518 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n");
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007519 }
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08007520 if (info.numInstances != -1) {
7521 sb.append("Instance-Count: ").append(info.numInstances).append("\n");
7522 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08007523 if (info.tags != null) {
7524 for (String tag : info.tags) {
7525 sb.append("Span-Tag: ").append(tag).append("\n");
7526 }
7527 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007528 sb.append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007529 if (info.crashInfo != null && info.crashInfo.stackTrace != null) {
7530 sb.append(info.crashInfo.stackTrace);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007531 }
7532 sb.append("\n");
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007533
7534 // Only buffer up to ~64k. Various logging bits truncate
7535 // things at 128k.
7536 needsFlush = (sb.length() > 64 * 1024);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007537 }
7538
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007539 // Flush immediately if the buffer's grown too large, or this
7540 // is a non-system app. Non-system apps are isolated with a
7541 // different tag & policy and not batched.
7542 //
7543 // Batching is useful during internal testing with
7544 // StrictMode settings turned up high. Without batching,
7545 // thousands of separate files could be created on boot.
7546 if (!isSystemApp || needsFlush) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007547 new Thread("Error dump: " + dropboxTag) {
7548 @Override
7549 public void run() {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007550 String report;
7551 synchronized (sb) {
7552 report = sb.toString();
7553 sb.delete(0, sb.length());
7554 sb.trimToSize();
7555 }
7556 if (report.length() != 0) {
7557 dbox.addText(dropboxTag, report);
7558 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007559 }
7560 }.start();
7561 return;
7562 }
7563
7564 // System app batching:
7565 if (!bufferWasEmpty) {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007566 // An existing dropbox-writing thread is outstanding, so
7567 // we don't need to start it up. The existing thread will
7568 // catch the buffer appends we just did.
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007569 return;
7570 }
7571
7572 // Worker thread to both batch writes and to avoid blocking the caller on I/O.
7573 // (After this point, we shouldn't access AMS internal data structures.)
7574 new Thread("Error dump: " + dropboxTag) {
7575 @Override
7576 public void run() {
7577 // 5 second sleep to let stacks arrive and be batched together
7578 try {
7579 Thread.sleep(5000); // 5 seconds
7580 } catch (InterruptedException e) {}
7581
7582 String errorReport;
7583 synchronized (mStrictModeBuffer) {
7584 errorReport = mStrictModeBuffer.toString();
7585 if (errorReport.length() == 0) {
7586 return;
7587 }
7588 mStrictModeBuffer.delete(0, mStrictModeBuffer.length());
7589 mStrictModeBuffer.trimToSize();
7590 }
7591 dbox.addText(dropboxTag, errorReport);
7592 }
7593 }.start();
7594 }
7595
Dan Egnor60d87622009-12-16 16:32:58 -08007596 /**
7597 * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors.
7598 * @param app object of the crashing app, null for the system server
7599 * @param tag reported by the caller
7600 * @param crashInfo describing the context of the error
7601 * @return true if the process should exit immediately (WTF is fatal)
7602 */
7603 public boolean handleApplicationWtf(IBinder app, String tag,
Dan Egnorb7f03672009-12-09 16:22:32 -08007604 ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007605 ProcessRecord r = findAppProcess(app, "WTF");
Jeff Sharkeya353d262011-10-28 11:12:06 -07007606 final String processName = app == null ? "system_server"
7607 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08007608
7609 EventLog.writeEvent(EventLogTags.AM_WTF, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07007610 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08007611 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08007612 tag, crashInfo.exceptionMessage);
7613
Jeff Sharkeya353d262011-10-28 11:12:06 -07007614 addErrorToDropBox("wtf", r, processName, null, null, tag, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08007615
Dianne Hackborn1ab43772011-03-15 14:38:02 -07007616 if (r != null && r.pid != Process.myPid() &&
7617 Settings.Secure.getInt(mContext.getContentResolver(),
7618 Settings.Secure.WTF_IS_FATAL, 0) != 0) {
Dan Egnor60d87622009-12-16 16:32:58 -08007619 crashApplication(r, crashInfo);
7620 return true;
7621 } else {
7622 return false;
7623 }
7624 }
7625
7626 /**
7627 * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit})
7628 * @return the corresponding {@link ProcessRecord} object, or null if none could be found
7629 */
Dianne Hackborncb44d962011-03-10 17:02:27 -08007630 private ProcessRecord findAppProcess(IBinder app, String reason) {
Dan Egnor60d87622009-12-16 16:32:58 -08007631 if (app == null) {
7632 return null;
7633 }
7634
7635 synchronized (this) {
7636 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
7637 final int NA = apps.size();
7638 for (int ia=0; ia<NA; ia++) {
7639 ProcessRecord p = apps.valueAt(ia);
7640 if (p.thread != null && p.thread.asBinder() == app) {
7641 return p;
7642 }
7643 }
7644 }
7645
Dianne Hackborncb44d962011-03-10 17:02:27 -08007646 Slog.w(TAG, "Can't find mystery application for " + reason
7647 + " from pid=" + Binder.getCallingPid()
7648 + " uid=" + Binder.getCallingUid() + ": " + app);
Dan Egnor60d87622009-12-16 16:32:58 -08007649 return null;
7650 }
7651 }
7652
7653 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007654 * Utility function for addErrorToDropBox and handleStrictModeViolation's logging
7655 * to append various headers to the dropbox log text.
Dan Egnor60d87622009-12-16 16:32:58 -08007656 */
Jeff Sharkeya353d262011-10-28 11:12:06 -07007657 private void appendDropBoxProcessHeaders(ProcessRecord process, String processName,
7658 StringBuilder sb) {
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08007659 // Watchdog thread ends up invoking this function (with
7660 // a null ProcessRecord) to add the stack file to dropbox.
7661 // Do not acquire a lock on this (am) in such cases, as it
7662 // could cause a potential deadlock, if and when watchdog
7663 // is invoked due to unavailability of lock on am and it
7664 // would prevent watchdog from killing system_server.
7665 if (process == null) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07007666 sb.append("Process: ").append(processName).append("\n");
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08007667 return;
7668 }
Brad Fitzpatrick1e02d362010-09-10 09:19:50 -07007669 // Note: ProcessRecord 'process' is guarded by the service
7670 // instance. (notably process.pkgList, which could otherwise change
7671 // concurrently during execution of this method)
7672 synchronized (this) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07007673 sb.append("Process: ").append(processName).append("\n");
Dan Egnora455d192010-03-12 08:52:28 -08007674 int flags = process.info.flags;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007675 IPackageManager pm = AppGlobals.getPackageManager();
Dan Egnora455d192010-03-12 08:52:28 -08007676 sb.append("Flags: 0x").append(Integer.toString(flags, 16)).append("\n");
7677 for (String pkg : process.pkgList) {
7678 sb.append("Package: ").append(pkg);
Dan Egnor42471dd2010-01-07 17:25:22 -08007679 try {
Dan Egnora455d192010-03-12 08:52:28 -08007680 PackageInfo pi = pm.getPackageInfo(pkg, 0);
7681 if (pi != null) {
7682 sb.append(" v").append(pi.versionCode);
7683 if (pi.versionName != null) {
7684 sb.append(" (").append(pi.versionName).append(")");
7685 }
7686 }
7687 } catch (RemoteException e) {
7688 Slog.e(TAG, "Error getting package info: " + pkg, e);
Dan Egnor60d87622009-12-16 16:32:58 -08007689 }
Dan Egnora455d192010-03-12 08:52:28 -08007690 sb.append("\n");
Dan Egnor60d87622009-12-16 16:32:58 -08007691 }
Dan Egnora455d192010-03-12 08:52:28 -08007692 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007693 }
7694
7695 private static String processClass(ProcessRecord process) {
7696 if (process == null || process.pid == MY_PID) {
7697 return "system_server";
7698 } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
7699 return "system_app";
7700 } else {
7701 return "data_app";
7702 }
7703 }
7704
7705 /**
7706 * Write a description of an error (crash, WTF, ANR) to the drop box.
7707 * @param eventType to include in the drop box tag ("crash", "wtf", etc.)
7708 * @param process which caused the error, null means the system server
7709 * @param activity which triggered the error, null if unknown
7710 * @param parent activity related to the error, null if unknown
7711 * @param subject line related to the error, null if absent
7712 * @param report in long form describing the error, null if absent
7713 * @param logFile to include in the report, null if none
7714 * @param crashInfo giving an application stack trace, null if absent
7715 */
7716 public void addErrorToDropBox(String eventType,
Jeff Sharkeya353d262011-10-28 11:12:06 -07007717 ProcessRecord process, String processName, ActivityRecord activity,
7718 ActivityRecord parent, String subject,
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007719 final String report, final File logFile,
7720 final ApplicationErrorReport.CrashInfo crashInfo) {
7721 // NOTE -- this must never acquire the ActivityManagerService lock,
7722 // otherwise the watchdog may be prevented from resetting the system.
7723
7724 final String dropboxTag = processClass(process) + "_" + eventType;
7725 final DropBoxManager dbox = (DropBoxManager)
7726 mContext.getSystemService(Context.DROPBOX_SERVICE);
7727
7728 // Exit early if the dropbox isn't configured to accept this report type.
7729 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
7730
7731 final StringBuilder sb = new StringBuilder(1024);
Jeff Sharkeya353d262011-10-28 11:12:06 -07007732 appendDropBoxProcessHeaders(process, processName, sb);
Dan Egnora455d192010-03-12 08:52:28 -08007733 if (activity != null) {
7734 sb.append("Activity: ").append(activity.shortComponentName).append("\n");
7735 }
7736 if (parent != null && parent.app != null && parent.app.pid != process.pid) {
7737 sb.append("Parent-Process: ").append(parent.app.processName).append("\n");
7738 }
7739 if (parent != null && parent != activity) {
7740 sb.append("Parent-Activity: ").append(parent.shortComponentName).append("\n");
7741 }
7742 if (subject != null) {
7743 sb.append("Subject: ").append(subject).append("\n");
7744 }
7745 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
Christian Lindeberg03d2ca62010-09-28 14:52:20 +02007746 if (Debug.isDebuggerConnected()) {
7747 sb.append("Debugger: Connected\n");
7748 }
Dan Egnora455d192010-03-12 08:52:28 -08007749 sb.append("\n");
7750
7751 // Do the rest in a worker thread to avoid blocking the caller on I/O
7752 // (After this point, we shouldn't access AMS internal data structures.)
7753 Thread worker = new Thread("Error dump: " + dropboxTag) {
7754 @Override
7755 public void run() {
7756 if (report != null) {
7757 sb.append(report);
7758 }
7759 if (logFile != null) {
7760 try {
7761 sb.append(FileUtils.readTextFile(logFile, 128 * 1024, "\n\n[[TRUNCATED]]"));
7762 } catch (IOException e) {
7763 Slog.e(TAG, "Error reading " + logFile, e);
7764 }
7765 }
7766 if (crashInfo != null && crashInfo.stackTrace != null) {
7767 sb.append(crashInfo.stackTrace);
7768 }
7769
7770 String setting = Settings.Secure.ERROR_LOGCAT_PREFIX + dropboxTag;
7771 int lines = Settings.Secure.getInt(mContext.getContentResolver(), setting, 0);
7772 if (lines > 0) {
7773 sb.append("\n");
7774
7775 // Merge several logcat streams, and take the last N lines
7776 InputStreamReader input = null;
7777 try {
7778 java.lang.Process logcat = new ProcessBuilder("/system/bin/logcat",
7779 "-v", "time", "-b", "events", "-b", "system", "-b", "main",
7780 "-t", String.valueOf(lines)).redirectErrorStream(true).start();
7781
7782 try { logcat.getOutputStream().close(); } catch (IOException e) {}
7783 try { logcat.getErrorStream().close(); } catch (IOException e) {}
7784 input = new InputStreamReader(logcat.getInputStream());
7785
7786 int num;
7787 char[] buf = new char[8192];
7788 while ((num = input.read(buf)) > 0) sb.append(buf, 0, num);
7789 } catch (IOException e) {
7790 Slog.e(TAG, "Error running logcat", e);
7791 } finally {
7792 if (input != null) try { input.close(); } catch (IOException e) {}
7793 }
7794 }
7795
7796 dbox.addText(dropboxTag, sb.toString());
Dan Egnor60d87622009-12-16 16:32:58 -08007797 }
Dan Egnora455d192010-03-12 08:52:28 -08007798 };
7799
7800 if (process == null || process.pid == MY_PID) {
7801 worker.run(); // We may be about to die -- need to run this synchronously
7802 } else {
7803 worker.start();
Dan Egnor60d87622009-12-16 16:32:58 -08007804 }
7805 }
7806
7807 /**
7808 * Bring up the "unexpected error" dialog box for a crashing app.
7809 * Deal with edge cases (intercepts from instrumented applications,
7810 * ActivityController, error intent receivers, that sort of thing).
7811 * @param r the application crashing
7812 * @param crashInfo describing the failure
7813 */
7814 private void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) {
Dan Egnorb7f03672009-12-09 16:22:32 -08007815 long timeMillis = System.currentTimeMillis();
7816 String shortMsg = crashInfo.exceptionClassName;
7817 String longMsg = crashInfo.exceptionMessage;
7818 String stackTrace = crashInfo.stackTrace;
7819 if (shortMsg != null && longMsg != null) {
7820 longMsg = shortMsg + ": " + longMsg;
7821 } else if (shortMsg != null) {
7822 longMsg = shortMsg;
7823 }
7824
Dan Egnor60d87622009-12-16 16:32:58 -08007825 AppErrorResult result = new AppErrorResult();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007826 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007827 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007828 try {
7829 String name = r != null ? r.processName : null;
7830 int pid = r != null ? r.pid : Binder.getCallingPid();
Dan Egnor60d87622009-12-16 16:32:58 -08007831 if (!mController.appCrashed(name, pid,
Dan Egnorb7f03672009-12-09 16:22:32 -08007832 shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007833 Slog.w(TAG, "Force-killing crashed app " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007834 + " at watcher's request");
7835 Process.killProcess(pid);
Dan Egnorb7f03672009-12-09 16:22:32 -08007836 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007837 }
7838 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007839 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007840 }
7841 }
7842
7843 final long origId = Binder.clearCallingIdentity();
7844
7845 // If this process is running instrumentation, finish it.
7846 if (r != null && r.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007847 Slog.w(TAG, "Error in app " + r.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007848 + " running instrumentation " + r.instrumentationClass + ":");
Joe Onorato8a9b2202010-02-26 18:56:32 -08007849 if (shortMsg != null) Slog.w(TAG, " " + shortMsg);
7850 if (longMsg != null) Slog.w(TAG, " " + longMsg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007851 Bundle info = new Bundle();
7852 info.putString("shortMsg", shortMsg);
7853 info.putString("longMsg", longMsg);
7854 finishInstrumentationLocked(r, Activity.RESULT_CANCELED, info);
7855 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08007856 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007857 }
7858
Dan Egnor60d87622009-12-16 16:32:58 -08007859 // If we can't identify the process or it's already exceeded its crash quota,
7860 // quit right away without showing a crash dialog.
7861 if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007862 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08007863 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007864 }
7865
7866 Message msg = Message.obtain();
7867 msg.what = SHOW_ERROR_MSG;
7868 HashMap data = new HashMap();
7869 data.put("result", result);
7870 data.put("app", r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007871 msg.obj = data;
7872 mHandler.sendMessage(msg);
7873
7874 Binder.restoreCallingIdentity(origId);
7875 }
7876
7877 int res = result.get();
7878
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007879 Intent appErrorIntent = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007880 synchronized (this) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007881 if (r != null && !r.isolated) {
7882 // XXX Can't keep track of crash time for isolated processes,
7883 // since they don't have a persistent identity.
7884 mProcessCrashTimes.put(r.info.processName, r.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007885 SystemClock.uptimeMillis());
7886 }
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007887 if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) {
Dan Egnorb7f03672009-12-09 16:22:32 -08007888 appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007889 }
7890 }
7891
7892 if (appErrorIntent != null) {
7893 try {
7894 mContext.startActivity(appErrorIntent);
7895 } catch (ActivityNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007896 Slog.w(TAG, "bug report receiver dissappeared", e);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007897 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007898 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007899 }
Dan Egnorb7f03672009-12-09 16:22:32 -08007900
7901 Intent createAppErrorIntentLocked(ProcessRecord r,
7902 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
7903 ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007904 if (report == null) {
7905 return null;
7906 }
7907 Intent result = new Intent(Intent.ACTION_APP_ERROR);
7908 result.setComponent(r.errorReportReceiver);
7909 result.putExtra(Intent.EXTRA_BUG_REPORT, report);
7910 result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
7911 return result;
7912 }
7913
Dan Egnorb7f03672009-12-09 16:22:32 -08007914 private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r,
7915 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007916 if (r.errorReportReceiver == null) {
7917 return null;
7918 }
7919
7920 if (!r.crashing && !r.notResponding) {
7921 return null;
7922 }
7923
Dan Egnorb7f03672009-12-09 16:22:32 -08007924 ApplicationErrorReport report = new ApplicationErrorReport();
7925 report.packageName = r.info.packageName;
7926 report.installerPackageName = r.errorReportReceiver.getPackageName();
7927 report.processName = r.processName;
7928 report.time = timeMillis;
Jacek Surazskie0ee6ef2010-01-07 16:23:03 +01007929 report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007930
Dan Egnorb7f03672009-12-09 16:22:32 -08007931 if (r.crashing) {
7932 report.type = ApplicationErrorReport.TYPE_CRASH;
7933 report.crashInfo = crashInfo;
7934 } else if (r.notResponding) {
7935 report.type = ApplicationErrorReport.TYPE_ANR;
7936 report.anrInfo = new ApplicationErrorReport.AnrInfo();
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007937
Dan Egnorb7f03672009-12-09 16:22:32 -08007938 report.anrInfo.activity = r.notRespondingReport.tag;
7939 report.anrInfo.cause = r.notRespondingReport.shortMsg;
7940 report.anrInfo.info = r.notRespondingReport.longMsg;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007941 }
7942
Dan Egnorb7f03672009-12-09 16:22:32 -08007943 return report;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007944 }
7945
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007946 public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08007947 enforceNotIsolatedCaller("getProcessesInErrorState");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007948 // assume our apps are happy - lazy create the list
7949 List<ActivityManager.ProcessErrorStateInfo> errList = null;
7950
7951 synchronized (this) {
7952
7953 // iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08007954 for (int i=mLruProcesses.size()-1; i>=0; i--) {
7955 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007956 if ((app.thread != null) && (app.crashing || app.notResponding)) {
7957 // This one's in trouble, so we'll generate a report for it
7958 // crashes are higher priority (in case there's a crash *and* an anr)
7959 ActivityManager.ProcessErrorStateInfo report = null;
7960 if (app.crashing) {
7961 report = app.crashingReport;
7962 } else if (app.notResponding) {
7963 report = app.notRespondingReport;
7964 }
7965
7966 if (report != null) {
7967 if (errList == null) {
7968 errList = new ArrayList<ActivityManager.ProcessErrorStateInfo>(1);
7969 }
7970 errList.add(report);
7971 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007972 Slog.w(TAG, "Missing app error report, app = " + app.processName +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007973 " crashing = " + app.crashing +
7974 " notResponding = " + app.notResponding);
7975 }
7976 }
7977 }
7978 }
7979
7980 return errList;
7981 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07007982
7983 static int oomAdjToImportance(int adj, ActivityManager.RunningAppProcessInfo currApp) {
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007984 if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07007985 if (currApp != null) {
7986 currApp.lru = adj - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
7987 }
7988 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007989 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
7990 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
Dianne Hackborn905577f2011-09-07 18:31:28 -07007991 } else if (adj >= ProcessList.HOME_APP_ADJ) {
7992 if (currApp != null) {
7993 currApp.lru = 0;
7994 }
7995 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007996 } else if (adj >= ProcessList.SERVICE_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07007997 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
7998 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
7999 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
8000 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
8001 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
8002 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
8003 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
8004 } else {
8005 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
8006 }
8007 }
8008
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008009 private void fillInProcMemInfo(ProcessRecord app,
8010 ActivityManager.RunningAppProcessInfo outInfo) {
8011 outInfo.pid = app.pid;
8012 outInfo.uid = app.info.uid;
8013 if (mHeavyWeightProcess == app) {
8014 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_CANT_SAVE_STATE;
8015 }
8016 if (app.persistent) {
8017 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_PERSISTENT;
8018 }
8019 outInfo.lastTrimLevel = app.trimMemoryLevel;
8020 int adj = app.curAdj;
8021 outInfo.importance = oomAdjToImportance(adj, outInfo);
8022 outInfo.importanceReasonCode = app.adjTypeCode;
8023 }
8024
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008025 public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008026 enforceNotIsolatedCaller("getRunningAppProcesses");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008027 // Lazy instantiation of list
8028 List<ActivityManager.RunningAppProcessInfo> runList = null;
8029 synchronized (this) {
8030 // Iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008031 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8032 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008033 if ((app.thread != null) && (!app.crashing && !app.notResponding)) {
8034 // Generate process state info for running application
8035 ActivityManager.RunningAppProcessInfo currApp =
8036 new ActivityManager.RunningAppProcessInfo(app.processName,
8037 app.pid, app.getPackageList());
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008038 fillInProcMemInfo(app, currApp);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008039 if (app.adjSource instanceof ProcessRecord) {
8040 currApp.importanceReasonPid = ((ProcessRecord)app.adjSource).pid;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008041 currApp.importanceReasonImportance = oomAdjToImportance(
8042 app.adjSourceOom, null);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008043 } else if (app.adjSource instanceof ActivityRecord) {
8044 ActivityRecord r = (ActivityRecord)app.adjSource;
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008045 if (r.app != null) currApp.importanceReasonPid = r.app.pid;
8046 }
8047 if (app.adjTarget instanceof ComponentName) {
8048 currApp.importanceReasonComponent = (ComponentName)app.adjTarget;
8049 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08008050 //Slog.v(TAG, "Proc " + app.processName + ": imp=" + currApp.importance
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008051 // + " lru=" + currApp.lru);
8052 if (runList == null) {
8053 runList = new ArrayList<ActivityManager.RunningAppProcessInfo>();
8054 }
8055 runList.add(currApp);
8056 }
8057 }
8058 }
8059 return runList;
8060 }
8061
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008062 public List<ApplicationInfo> getRunningExternalApplications() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008063 enforceNotIsolatedCaller("getRunningExternalApplications");
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008064 List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses();
8065 List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>();
8066 if (runningApps != null && runningApps.size() > 0) {
8067 Set<String> extList = new HashSet<String>();
8068 for (ActivityManager.RunningAppProcessInfo app : runningApps) {
8069 if (app.pkgList != null) {
8070 for (String pkg : app.pkgList) {
8071 extList.add(pkg);
8072 }
8073 }
8074 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008075 IPackageManager pm = AppGlobals.getPackageManager();
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008076 for (String pkg : extList) {
8077 try {
8078 ApplicationInfo info = pm.getApplicationInfo(pkg, 0);
8079 if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
8080 retList.add(info);
8081 }
8082 } catch (RemoteException e) {
8083 }
8084 }
8085 }
8086 return retList;
8087 }
8088
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008089 @Override
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008090 public void getMyMemoryState(ActivityManager.RunningAppProcessInfo outInfo) {
8091 enforceNotIsolatedCaller("getMyMemoryState");
8092 synchronized (this) {
8093 ProcessRecord proc;
8094 synchronized (mPidsSelfLocked) {
8095 proc = mPidsSelfLocked.get(Binder.getCallingPid());
8096 }
8097 fillInProcMemInfo(proc, outInfo);
8098 }
8099 }
8100
8101 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008102 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008103 if (checkCallingPermission(android.Manifest.permission.DUMP)
8104 != PackageManager.PERMISSION_GRANTED) {
8105 pw.println("Permission Denial: can't dump ActivityManager from from pid="
8106 + Binder.getCallingPid()
8107 + ", uid=" + Binder.getCallingUid()
8108 + " without permission "
8109 + android.Manifest.permission.DUMP);
8110 return;
8111 }
8112
8113 boolean dumpAll = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008114 boolean dumpClient = false;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008115 String dumpPackage = null;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008116
8117 int opti = 0;
8118 while (opti < args.length) {
8119 String opt = args[opti];
8120 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
8121 break;
8122 }
8123 opti++;
8124 if ("-a".equals(opt)) {
8125 dumpAll = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008126 } else if ("-c".equals(opt)) {
8127 dumpClient = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008128 } else if ("-h".equals(opt)) {
8129 pw.println("Activity manager dump options:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008130 pw.println(" [-a] [-c] [-h] [cmd] ...");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008131 pw.println(" cmd may be one of:");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008132 pw.println(" a[ctivities]: activity stack state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008133 pw.println(" b[roadcasts] [PACKAGE_NAME]: broadcast state");
8134 pw.println(" i[ntents] [PACKAGE_NAME]: pending intent state");
8135 pw.println(" p[rocesses] [PACKAGE_NAME]: process state");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008136 pw.println(" o[om]: out of memory management");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008137 pw.println(" prov[iders] [COMP_SPEC ...]: content provider state");
Marco Nelissen18cb2872011-11-15 11:19:53 -08008138 pw.println(" provider [COMP_SPEC]: provider client-side state");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008139 pw.println(" s[ervices] [COMP_SPEC ...]: service state");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008140 pw.println(" service [COMP_SPEC]: service client-side state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008141 pw.println(" package [PACKAGE_NAME]: all state related to given package");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008142 pw.println(" all: dump all activities");
8143 pw.println(" top: dump the top activity");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008144 pw.println(" cmd may also be a COMP_SPEC to dump activities.");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008145 pw.println(" COMP_SPEC may be a component name (com.foo/.myApp),");
8146 pw.println(" a partial substring in a component name, a");
8147 pw.println(" hex object identifier.");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008148 pw.println(" -a: include all available server state.");
8149 pw.println(" -c: include client state.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008150 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008151 } else {
8152 pw.println("Unknown argument: " + opt + "; use -h for help");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008153 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008154 }
8155
8156 // Is the caller requesting to dump a particular piece of data?
8157 if (opti < args.length) {
8158 String cmd = args[opti];
8159 opti++;
8160 if ("activities".equals(cmd) || "a".equals(cmd)) {
8161 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008162 dumpActivitiesLocked(fd, pw, args, opti, true, dumpClient, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008163 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008164 return;
8165 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008166 String[] newArgs;
8167 String name;
8168 if (opti >= args.length) {
8169 name = null;
8170 newArgs = EMPTY_STRING_ARRAY;
8171 } else {
8172 name = args[opti];
8173 opti++;
8174 newArgs = new String[args.length - opti];
8175 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8176 args.length - opti);
8177 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008178 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008179 dumpBroadcastsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008180 }
8181 return;
8182 } else if ("intents".equals(cmd) || "i".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008183 String[] newArgs;
8184 String name;
8185 if (opti >= args.length) {
8186 name = null;
8187 newArgs = EMPTY_STRING_ARRAY;
8188 } else {
8189 name = args[opti];
8190 opti++;
8191 newArgs = new String[args.length - opti];
8192 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8193 args.length - opti);
8194 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008195 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008196 dumpPendingIntentsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008197 }
8198 return;
8199 } else if ("processes".equals(cmd) || "p".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008200 String[] newArgs;
8201 String name;
8202 if (opti >= args.length) {
8203 name = null;
8204 newArgs = EMPTY_STRING_ARRAY;
8205 } else {
8206 name = args[opti];
8207 opti++;
8208 newArgs = new String[args.length - opti];
8209 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8210 args.length - opti);
8211 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008212 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008213 dumpProcessesLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008214 }
8215 return;
Dianne Hackborn287952c2010-09-22 22:34:31 -07008216 } else if ("oom".equals(cmd) || "o".equals(cmd)) {
8217 synchronized (this) {
8218 dumpOomLocked(fd, pw, args, opti, true);
8219 }
8220 return;
Marco Nelissen18cb2872011-11-15 11:19:53 -08008221 } else if ("provider".equals(cmd)) {
8222 String[] newArgs;
8223 String name;
8224 if (opti >= args.length) {
8225 name = null;
8226 newArgs = EMPTY_STRING_ARRAY;
8227 } else {
8228 name = args[opti];
8229 opti++;
8230 newArgs = new String[args.length - opti];
8231 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
8232 }
8233 if (!dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) {
8234 pw.println("No providers match: " + name);
8235 pw.println("Use -h for help.");
8236 }
8237 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008238 } else if ("providers".equals(cmd) || "prov".equals(cmd)) {
8239 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008240 dumpProvidersLocked(fd, pw, args, opti, true, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008241 }
8242 return;
8243 } else if ("service".equals(cmd)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008244 String[] newArgs;
8245 String name;
8246 if (opti >= args.length) {
8247 name = null;
8248 newArgs = EMPTY_STRING_ARRAY;
8249 } else {
8250 name = args[opti];
8251 opti++;
8252 newArgs = new String[args.length - opti];
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008253 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8254 args.length - opti);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008255 }
8256 if (!dumpService(fd, pw, name, newArgs, 0, dumpAll)) {
8257 pw.println("No services match: " + name);
8258 pw.println("Use -h for help.");
8259 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008260 return;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008261 } else if ("package".equals(cmd)) {
8262 String[] newArgs;
8263 if (opti >= args.length) {
8264 pw.println("package: no package name specified");
8265 pw.println("Use -h for help.");
8266 return;
8267 } else {
8268 dumpPackage = args[opti];
8269 opti++;
8270 newArgs = new String[args.length - opti];
8271 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8272 args.length - opti);
8273 args = newArgs;
8274 opti = 0;
8275 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008276 } else if ("services".equals(cmd) || "s".equals(cmd)) {
8277 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008278 dumpServicesLocked(fd, pw, args, opti, true, dumpClient, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008279 }
8280 return;
Dianne Hackborn625ac272010-09-17 18:29:22 -07008281 } else {
8282 // Dumping a single activity?
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008283 if (!dumpActivity(fd, pw, cmd, args, opti, dumpAll)) {
8284 pw.println("Bad activity command, or no activities match: " + cmd);
8285 pw.println("Use -h for help.");
Dianne Hackborn625ac272010-09-17 18:29:22 -07008286 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08008287 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008288 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008289 }
8290
8291 // No piece of data specified, dump everything.
8292 synchronized (this) {
8293 boolean needSep;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008294 needSep = dumpPendingIntentsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008295 if (needSep) {
8296 pw.println(" ");
8297 }
8298 if (dumpAll) {
8299 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008300 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008301 needSep = dumpBroadcastsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008302 if (needSep) {
8303 pw.println(" ");
8304 }
8305 if (dumpAll) {
8306 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008307 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008308 needSep = dumpProvidersLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008309 if (needSep) {
8310 pw.println(" ");
8311 }
8312 if (dumpAll) {
8313 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008314 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008315 needSep = dumpServicesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008316 if (needSep) {
8317 pw.println(" ");
8318 }
8319 if (dumpAll) {
8320 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008321 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008322 needSep = dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008323 if (needSep) {
8324 pw.println(" ");
8325 }
8326 if (dumpAll) {
8327 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008328 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008329 dumpProcessesLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008330 }
8331 }
8332
8333 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008334 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008335 pw.println("ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
8336 pw.println(" Main stack:");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008337 dumpHistoryList(fd, pw, mMainStack.mHistory, " ", "Hist", true, !dumpAll, dumpClient,
8338 dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008339 pw.println(" ");
8340 pw.println(" Running activities (most recent first):");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008341 dumpHistoryList(fd, pw, mMainStack.mLRUActivities, " ", "Run", false, !dumpAll, false,
8342 dumpPackage);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008343 if (mMainStack.mWaitingVisibleActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008344 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008345 pw.println(" Activities waiting for another to become visible:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008346 dumpHistoryList(fd, pw, mMainStack.mWaitingVisibleActivities, " ", "Wait", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008347 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008348 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008349 if (mMainStack.mStoppingActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008350 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008351 pw.println(" Activities waiting to stop:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008352 dumpHistoryList(fd, pw, mMainStack.mStoppingActivities, " ", "Stop", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008353 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008354 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008355 if (mMainStack.mGoingToSleepActivities.size() > 0) {
8356 pw.println(" ");
8357 pw.println(" Activities waiting to sleep:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008358 dumpHistoryList(fd, pw, mMainStack.mGoingToSleepActivities, " ", "Sleep", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008359 !dumpAll, false, dumpPackage);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008360 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008361 if (mMainStack.mFinishingActivities.size() > 0) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008362 pw.println(" ");
8363 pw.println(" Activities waiting to finish:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008364 dumpHistoryList(fd, pw, mMainStack.mFinishingActivities, " ", "Fin", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008365 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008366 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008367
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008368 pw.println(" ");
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08008369 if (mMainStack.mPausingActivity != null) {
8370 pw.println(" mPausingActivity: " + mMainStack.mPausingActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008371 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008372 pw.println(" mResumedActivity: " + mMainStack.mResumedActivity);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008373 pw.println(" mFocusedActivity: " + mFocusedActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008374 if (dumpAll) {
8375 pw.println(" mLastPausedActivity: " + mMainStack.mLastPausedActivity);
8376 pw.println(" mSleepTimeout: " + mMainStack.mSleepTimeout);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07008377 pw.println(" mDismissKeyguardOnNextActivity: "
8378 + mMainStack.mDismissKeyguardOnNextActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008379 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008380
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008381 if (mRecentTasks.size() > 0) {
8382 pw.println();
8383 pw.println(" Recent tasks:");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008384
8385 final int N = mRecentTasks.size();
8386 for (int i=0; i<N; i++) {
8387 TaskRecord tr = mRecentTasks.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008388 if (dumpPackage != null) {
8389 if (tr.realActivity == null ||
8390 !dumpPackage.equals(tr.realActivity)) {
8391 continue;
8392 }
8393 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008394 pw.print(" * Recent #"); pw.print(i); pw.print(": ");
8395 pw.println(tr);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008396 if (dumpAll) {
8397 mRecentTasks.get(i).dump(pw, " ");
8398 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008399 }
8400 }
8401
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008402 if (dumpAll) {
8403 pw.println(" ");
8404 pw.println(" mCurTask: " + mCurTask);
8405 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008406
8407 return true;
8408 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008409
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008410 boolean dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008411 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008412 boolean needSep = false;
8413 int numPers = 0;
8414
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008415 pw.println("ACTIVITY MANAGER RUNNING PROCESSES (dumpsys activity processes)");
8416
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008417 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008418 for (SparseArray<ProcessRecord> procs : mProcessNames.getMap().values()) {
8419 final int NA = procs.size();
8420 for (int ia=0; ia<NA; ia++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008421 ProcessRecord r = procs.valueAt(ia);
8422 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8423 continue;
8424 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008425 if (!needSep) {
8426 pw.println(" All known processes:");
8427 needSep = true;
8428 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008429 pw.print(r.persistent ? " *PERS*" : " *APP*");
8430 pw.print(" UID "); pw.print(procs.keyAt(ia));
8431 pw.print(" "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008432 r.dump(pw, " ");
8433 if (r.persistent) {
8434 numPers++;
8435 }
8436 }
8437 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008438 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008439
8440 if (mIsolatedProcesses.size() > 0) {
8441 if (needSep) pw.println(" ");
8442 needSep = true;
8443 pw.println(" Isolated process list (sorted by uid):");
8444 for (int i=0; i<mIsolatedProcesses.size(); i++) {
8445 ProcessRecord r = mIsolatedProcesses.valueAt(i);
8446 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8447 continue;
8448 }
8449 pw.println(String.format("%sIsolated #%2d: %s",
8450 " ", i, r.toString()));
8451 }
8452 }
8453
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008454 if (mLruProcesses.size() > 0) {
8455 if (needSep) pw.println(" ");
8456 needSep = true;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008457 pw.println(" Process LRU list (sorted by oom_adj):");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008458 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008459 "Proc", "PERS", false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008460 needSep = true;
8461 }
8462
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008463 if (dumpAll) {
8464 synchronized (mPidsSelfLocked) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008465 boolean printed = false;
8466 for (int i=0; i<mPidsSelfLocked.size(); i++) {
8467 ProcessRecord r = mPidsSelfLocked.valueAt(i);
8468 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8469 continue;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008470 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008471 if (!printed) {
8472 if (needSep) pw.println(" ");
8473 needSep = true;
8474 pw.println(" PID mappings:");
8475 printed = true;
8476 }
8477 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i));
8478 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008479 }
8480 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008481 }
8482
8483 if (mForegroundProcesses.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008484 synchronized (mPidsSelfLocked) {
8485 boolean printed = false;
8486 for (int i=0; i<mForegroundProcesses.size(); i++) {
8487 ProcessRecord r = mPidsSelfLocked.get(
8488 mForegroundProcesses.valueAt(i).pid);
8489 if (dumpPackage != null && (r == null
8490 || !dumpPackage.equals(r.info.packageName))) {
8491 continue;
8492 }
8493 if (!printed) {
8494 if (needSep) pw.println(" ");
8495 needSep = true;
8496 pw.println(" Foreground Processes:");
8497 printed = true;
8498 }
8499 pw.print(" PID #"); pw.print(mForegroundProcesses.keyAt(i));
8500 pw.print(": "); pw.println(mForegroundProcesses.valueAt(i));
8501 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008502 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008503 }
8504
8505 if (mPersistentStartingProcesses.size() > 0) {
8506 if (needSep) pw.println(" ");
8507 needSep = true;
8508 pw.println(" Persisent processes that are starting:");
8509 dumpProcessList(pw, this, mPersistentStartingProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008510 "Starting Norm", "Restarting PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008511 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008512
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008513 if (mRemovedProcesses.size() > 0) {
8514 if (needSep) pw.println(" ");
8515 needSep = true;
8516 pw.println(" Processes that are being removed:");
8517 dumpProcessList(pw, this, mRemovedProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008518 "Removed Norm", "Removed PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008519 }
8520
8521 if (mProcessesOnHold.size() > 0) {
8522 if (needSep) pw.println(" ");
8523 needSep = true;
8524 pw.println(" Processes that are on old until the system is ready:");
8525 dumpProcessList(pw, this, mProcessesOnHold, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008526 "OnHold Norm", "OnHold PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008527 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008528
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008529 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008530
8531 if (mProcessCrashTimes.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008532 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008533 long now = SystemClock.uptimeMillis();
8534 for (Map.Entry<String, SparseArray<Long>> procs
8535 : mProcessCrashTimes.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008536 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008537 SparseArray<Long> uids = procs.getValue();
8538 final int N = uids.size();
8539 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008540 int puid = uids.keyAt(i);
8541 ProcessRecord r = mProcessNames.get(pname, puid);
8542 if (dumpPackage != null && (r == null
8543 || !dumpPackage.equals(r.info.packageName))) {
8544 continue;
8545 }
8546 if (!printed) {
8547 if (needSep) pw.println(" ");
8548 needSep = true;
8549 pw.println(" Time since processes crashed:");
8550 printed = true;
8551 }
8552 pw.print(" Process "); pw.print(pname);
8553 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008554 pw.print(": last crashed ");
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008555 TimeUtils.formatDuration(now-uids.valueAt(i), pw);
8556 pw.println(" ago");
Dianne Hackbornfd12af42009-08-27 00:44:33 -07008557 }
8558 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008559 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008560
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008561 if (mBadProcesses.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008562 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008563 for (Map.Entry<String, SparseArray<Long>> procs
8564 : mBadProcesses.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008565 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008566 SparseArray<Long> uids = procs.getValue();
8567 final int N = uids.size();
8568 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008569 int puid = uids.keyAt(i);
8570 ProcessRecord r = mProcessNames.get(pname, puid);
8571 if (dumpPackage != null && (r == null
8572 || !dumpPackage.equals(r.info.packageName))) {
8573 continue;
8574 }
8575 if (!printed) {
8576 if (needSep) pw.println(" ");
8577 needSep = true;
8578 pw.println(" Bad processes:");
8579 }
8580 pw.print(" Bad process "); pw.print(pname);
8581 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008582 pw.print(": crashed at time ");
8583 pw.println(uids.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008584 }
8585 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008586 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008587
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008588 pw.println();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008589 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07008590 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn50685602011-12-01 12:23:37 -08008591 if (dumpAll) {
8592 StringBuilder sb = new StringBuilder(128);
8593 sb.append(" mPreviousProcessVisibleTime: ");
8594 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
8595 pw.println(sb);
8596 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07008597 if (mHeavyWeightProcess != null) {
8598 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
8599 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008600 pw.println(" mConfiguration: " + mConfiguration);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008601 if (dumpAll) {
8602 pw.println(" mConfigWillChange: " + mMainStack.mConfigWillChange);
Dianne Hackborn3d0724d2011-05-12 15:39:41 -07008603 if (mCompatModePackages.getPackages().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008604 boolean printed = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07008605 for (Map.Entry<String, Integer> entry
8606 : mCompatModePackages.getPackages().entrySet()) {
8607 String pkg = entry.getKey();
8608 int mode = entry.getValue();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008609 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
8610 continue;
8611 }
8612 if (!printed) {
8613 pw.println(" mScreenCompatPackages:");
8614 printed = true;
8615 }
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07008616 pw.print(" "); pw.print(pkg); pw.print(": ");
8617 pw.print(mode); pw.println();
8618 }
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07008619 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008620 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008621 pw.println(" mSleeping=" + mSleeping + " mShuttingDown=" + mShuttingDown);
8622 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
8623 || mOrigWaitForDebugger) {
8624 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp
8625 + " mDebugTransient=" + mDebugTransient
8626 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger);
8627 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07008628 if (mProfileApp != null || mProfileProc != null || mProfileFile != null
8629 || mProfileFd != null) {
8630 pw.println(" mProfileApp=" + mProfileApp + " mProfileProc=" + mProfileProc);
8631 pw.println(" mProfileFile=" + mProfileFile + " mProfileFd=" + mProfileFd);
8632 pw.println(" mProfileType=" + mProfileType + " mAutoStopProfiler="
8633 + mAutoStopProfiler);
8634 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008635 if (mAlwaysFinishActivities || mController != null) {
8636 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities
8637 + " mController=" + mController);
8638 }
8639 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008640 pw.println(" Total persistent processes: " + numPers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008641 pw.println(" mStartRunning=" + mStartRunning
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07008642 + " mProcessesReady=" + mProcessesReady
8643 + " mSystemReady=" + mSystemReady);
8644 pw.println(" mBooting=" + mBooting
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008645 + " mBooted=" + mBooted
8646 + " mFactoryTest=" + mFactoryTest);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008647 pw.print(" mLastPowerCheckRealtime=");
8648 TimeUtils.formatDuration(mLastPowerCheckRealtime, pw);
8649 pw.println("");
8650 pw.print(" mLastPowerCheckUptime=");
8651 TimeUtils.formatDuration(mLastPowerCheckUptime, pw);
8652 pw.println("");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008653 pw.println(" mGoingToSleep=" + mMainStack.mGoingToSleep);
8654 pw.println(" mLaunchingActivity=" + mMainStack.mLaunchingActivity);
Dianne Hackborn906497c2010-05-10 15:57:38 -07008655 pw.println(" mAdjSeq=" + mAdjSeq + " mLruSeq=" + mLruSeq);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008656 pw.println(" mNumServiceProcs=" + mNumServiceProcs
8657 + " mNewNumServiceProcs=" + mNewNumServiceProcs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008658 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008659
8660 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008661 }
8662
Dianne Hackborn287952c2010-09-22 22:34:31 -07008663 boolean dumpProcessesToGc(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008664 int opti, boolean needSep, boolean dumpAll, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07008665 if (mProcessesToGc.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008666 boolean printed = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -07008667 long now = SystemClock.uptimeMillis();
8668 for (int i=0; i<mProcessesToGc.size(); i++) {
8669 ProcessRecord proc = mProcessesToGc.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008670 if (dumpPackage != null && !dumpPackage.equals(proc.info.packageName)) {
8671 continue;
8672 }
8673 if (!printed) {
8674 if (needSep) pw.println(" ");
8675 needSep = true;
8676 pw.println(" Processes that are waiting to GC:");
8677 printed = true;
8678 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008679 pw.print(" Process "); pw.println(proc);
8680 pw.print(" lowMem="); pw.print(proc.reportLowMemory);
8681 pw.print(", last gced=");
8682 pw.print(now-proc.lastRequestedGc);
8683 pw.print(" ms ago, last lowMem=");
8684 pw.print(now-proc.lastLowMemory);
8685 pw.println(" ms ago");
8686
8687 }
8688 }
8689 return needSep;
8690 }
8691
8692 boolean dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args,
8693 int opti, boolean dumpAll) {
8694 boolean needSep = false;
8695
8696 if (mLruProcesses.size() > 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07008697 if (needSep) pw.println(" ");
8698 needSep = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -07008699 pw.println(" OOM levels:");
Dianne Hackborn7d608422011-08-07 16:24:18 -07008700 pw.print(" SYSTEM_ADJ: "); pw.println(ProcessList.SYSTEM_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008701 pw.print(" PERSISTENT_PROC_ADJ: "); pw.println(ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07008702 pw.print(" FOREGROUND_APP_ADJ: "); pw.println(ProcessList.FOREGROUND_APP_ADJ);
8703 pw.print(" VISIBLE_APP_ADJ: "); pw.println(ProcessList.VISIBLE_APP_ADJ);
8704 pw.print(" PERCEPTIBLE_APP_ADJ: "); pw.println(ProcessList.PERCEPTIBLE_APP_ADJ);
8705 pw.print(" HEAVY_WEIGHT_APP_ADJ: "); pw.println(ProcessList.HEAVY_WEIGHT_APP_ADJ);
8706 pw.print(" BACKUP_APP_ADJ: "); pw.println(ProcessList.BACKUP_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008707 pw.print(" SERVICE_ADJ: "); pw.println(ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07008708 pw.print(" HOME_APP_ADJ: "); pw.println(ProcessList.HOME_APP_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07008709 pw.print(" PREVIOUS_APP_ADJ: "); pw.println(ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008710 pw.print(" SERVICE_B_ADJ: "); pw.println(ProcessList.SERVICE_B_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07008711 pw.print(" HIDDEN_APP_MIN_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008712 pw.print(" HIDDEN_APP_MAX_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MAX_ADJ);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07008713
8714 if (needSep) pw.println(" ");
8715 needSep = true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07008716 pw.println(" Process OOM control:");
Dianne Hackborn905577f2011-09-07 18:31:28 -07008717 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008718 "Proc", "PERS", true, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008719 needSep = true;
8720 }
8721
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008722 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008723
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008724 pw.println();
Dianne Hackborn287952c2010-09-22 22:34:31 -07008725 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07008726 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008727 if (mHeavyWeightProcess != null) {
8728 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
8729 }
8730
8731 return true;
8732 }
8733
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008734 /**
8735 * There are three ways to call this:
8736 * - no service specified: dump all the services
8737 * - a flattened component name that matched an existing service was specified as the
8738 * first arg: dump that one service
8739 * - the first arg isn't the flattened component name of an existing service:
8740 * dump all services whose component contains the first arg as a substring
8741 */
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008742 protected boolean dumpService(FileDescriptor fd, PrintWriter pw, String name, String[] args,
8743 int opti, boolean dumpAll) {
8744 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008745
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008746 if ("all".equals(name)) {
Dianne Hackborn14bfa392010-07-24 19:58:06 -07008747 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07008748 try {
8749 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
8750 for (UserInfo user : users) {
8751 for (ServiceRecord r1 : mServiceMap.getAllServices(user.id)) {
8752 services.add(r1);
8753 }
8754 }
8755 } catch (RemoteException re) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008756 }
8757 }
8758 } else {
8759 ComponentName componentName = name != null
8760 ? ComponentName.unflattenFromString(name) : null;
8761 int objectId = 0;
8762 if (componentName == null) {
8763 // Not a '/' separated full component name; maybe an object ID?
8764 try {
8765 objectId = Integer.parseInt(name, 16);
8766 name = null;
8767 componentName = null;
8768 } catch (RuntimeException e) {
8769 }
8770 }
8771
8772 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07008773 try {
8774 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
8775 for (UserInfo user : users) {
8776 for (ServiceRecord r1 : mServiceMap.getAllServices(user.id)) {
8777 if (componentName != null) {
8778 if (r1.name.equals(componentName)) {
8779 services.add(r1);
8780 }
8781 } else if (name != null) {
8782 if (r1.name.flattenToString().contains(name)) {
8783 services.add(r1);
8784 }
8785 } else if (System.identityHashCode(r1) == objectId) {
8786 services.add(r1);
8787 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008788 }
Dianne Hackborn14bfa392010-07-24 19:58:06 -07008789 }
Amith Yamasani742a6712011-05-04 14:49:28 -07008790 } catch (RemoteException re) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008791 }
8792 }
8793 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008794
8795 if (services.size() <= 0) {
8796 return false;
8797 }
8798
8799 boolean needSep = false;
8800 for (int i=0; i<services.size(); i++) {
8801 if (needSep) {
8802 pw.println();
8803 }
8804 needSep = true;
8805 dumpService("", fd, pw, services.get(i), args, dumpAll);
8806 }
8807 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008808 }
8809
8810 /**
8811 * Invokes IApplicationThread.dumpService() on the thread of the specified service if
8812 * there is a thread associated with the service.
8813 */
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008814 private void dumpService(String prefix, FileDescriptor fd, PrintWriter pw,
8815 final ServiceRecord r, String[] args, boolean dumpAll) {
8816 String innerPrefix = prefix + " ";
8817 synchronized (this) {
8818 pw.print(prefix); pw.print("SERVICE ");
8819 pw.print(r.shortName); pw.print(" ");
8820 pw.print(Integer.toHexString(System.identityHashCode(r)));
8821 pw.print(" pid=");
8822 if (r.app != null) pw.println(r.app.pid);
8823 else pw.println("(not running)");
8824 if (dumpAll) {
8825 r.dump(pw, innerPrefix);
8826 }
8827 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008828 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008829 pw.print(prefix); pw.println(" Client:");
8830 pw.flush();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008831 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008832 TransferPipe tp = new TransferPipe();
8833 try {
8834 r.app.thread.dumpService(tp.getWriteFd().getFileDescriptor(), r, args);
8835 tp.setBufferPrefix(prefix + " ");
8836 tp.go(fd);
8837 } finally {
8838 tp.kill();
8839 }
8840 } catch (IOException e) {
8841 pw.println(prefix + " Failure while dumping the service: " + e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008842 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008843 pw.println(prefix + " Got a RemoteException while dumping the service");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008844 }
8845 }
8846 }
8847
Marco Nelissen18cb2872011-11-15 11:19:53 -08008848 /**
8849 * There are three ways to call this:
8850 * - no provider specified: dump all the providers
8851 * - a flattened component name that matched an existing provider was specified as the
8852 * first arg: dump that one provider
8853 * - the first arg isn't the flattened component name of an existing provider:
8854 * dump all providers whose component contains the first arg as a substring
8855 */
8856 protected boolean dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args,
8857 int opti, boolean dumpAll) {
Marco Nelissende7408c2012-02-08 14:57:38 -08008858 return mProviderMap.dumpProvider(fd, pw, name, args, opti, dumpAll);
Marco Nelissen18cb2872011-11-15 11:19:53 -08008859 }
8860
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008861 static class ItemMatcher {
8862 ArrayList<ComponentName> components;
8863 ArrayList<String> strings;
8864 ArrayList<Integer> objects;
8865 boolean all;
8866
8867 ItemMatcher() {
8868 all = true;
8869 }
8870
8871 void build(String name) {
8872 ComponentName componentName = ComponentName.unflattenFromString(name);
8873 if (componentName != null) {
8874 if (components == null) {
8875 components = new ArrayList<ComponentName>();
8876 }
8877 components.add(componentName);
8878 all = false;
8879 } else {
8880 int objectId = 0;
8881 // Not a '/' separated full component name; maybe an object ID?
8882 try {
8883 objectId = Integer.parseInt(name, 16);
8884 if (objects == null) {
8885 objects = new ArrayList<Integer>();
8886 }
8887 objects.add(objectId);
8888 all = false;
8889 } catch (RuntimeException e) {
8890 // Not an integer; just do string match.
8891 if (strings == null) {
8892 strings = new ArrayList<String>();
8893 }
8894 strings.add(name);
8895 all = false;
8896 }
8897 }
8898 }
8899
8900 int build(String[] args, int opti) {
8901 for (; opti<args.length; opti++) {
8902 String name = args[opti];
8903 if ("--".equals(name)) {
8904 return opti+1;
8905 }
8906 build(name);
8907 }
8908 return opti;
8909 }
8910
8911 boolean match(Object object, ComponentName comp) {
8912 if (all) {
8913 return true;
8914 }
8915 if (components != null) {
8916 for (int i=0; i<components.size(); i++) {
8917 if (components.get(i).equals(comp)) {
8918 return true;
8919 }
8920 }
8921 }
8922 if (objects != null) {
8923 for (int i=0; i<objects.size(); i++) {
8924 if (System.identityHashCode(object) == objects.get(i)) {
8925 return true;
8926 }
8927 }
8928 }
8929 if (strings != null) {
8930 String flat = comp.flattenToString();
8931 for (int i=0; i<strings.size(); i++) {
8932 if (flat.contains(strings.get(i))) {
8933 return true;
8934 }
8935 }
8936 }
8937 return false;
8938 }
8939 }
8940
Dianne Hackborn625ac272010-09-17 18:29:22 -07008941 /**
8942 * There are three things that cmd can be:
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008943 * - a flattened component name that matches an existing activity
Dianne Hackborn625ac272010-09-17 18:29:22 -07008944 * - the cmd arg isn't the flattened component name of an existing activity:
8945 * dump all activity whose component contains the cmd as a substring
8946 * - A hex number of the ActivityRecord object instance.
8947 */
8948 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
8949 int opti, boolean dumpAll) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07008950 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008951
8952 if ("all".equals(name)) {
8953 synchronized (this) {
8954 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07008955 activities.add(r1);
8956 }
8957 }
Dianne Hackbornf9302322011-06-14 18:36:14 -07008958 } else if ("top".equals(name)) {
8959 synchronized (this) {
8960 final int N = mMainStack.mHistory.size();
8961 if (N > 0) {
8962 activities.add((ActivityRecord)mMainStack.mHistory.get(N-1));
8963 }
8964 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008965 } else {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008966 ItemMatcher matcher = new ItemMatcher();
8967 matcher.build(name);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008968
8969 synchronized (this) {
8970 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008971 if (matcher.match(r1, r1.intent.getComponent())) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008972 activities.add(r1);
8973 }
8974 }
8975 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07008976 }
8977
8978 if (activities.size() <= 0) {
8979 return false;
8980 }
8981
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008982 String[] newArgs = new String[args.length - opti];
8983 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
8984
Dianne Hackborn30d71892010-12-11 10:37:55 -08008985 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008986 boolean needSep = false;
Dianne Hackborn30d71892010-12-11 10:37:55 -08008987 for (int i=activities.size()-1; i>=0; i--) {
8988 ActivityRecord r = (ActivityRecord)activities.get(i);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008989 if (needSep) {
8990 pw.println();
8991 }
8992 needSep = true;
8993 synchronized (this) {
8994 if (lastTask != r.task) {
8995 lastTask = r.task;
8996 pw.print("TASK "); pw.print(lastTask.affinity);
8997 pw.print(" id="); pw.println(lastTask.taskId);
8998 if (dumpAll) {
8999 lastTask.dump(pw, " ");
9000 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08009001 }
9002 }
9003 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009004 }
9005 return true;
9006 }
9007
9008 /**
9009 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
9010 * there is a thread associated with the activity.
9011 */
Dianne Hackborn30d71892010-12-11 10:37:55 -08009012 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009013 final ActivityRecord r, String[] args, boolean dumpAll) {
9014 String innerPrefix = prefix + " ";
Dianne Hackborn30d71892010-12-11 10:37:55 -08009015 synchronized (this) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009016 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
9017 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
9018 pw.print(" pid=");
Dianne Hackborn30d71892010-12-11 10:37:55 -08009019 if (r.app != null) pw.println(r.app.pid);
9020 else pw.println("(not running)");
9021 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009022 r.dump(pw, innerPrefix);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009023 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009024 }
9025 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009026 // flush anything that is already in the PrintWriter since the thread is going
9027 // to write to the file descriptor directly
9028 pw.flush();
Dianne Hackborn625ac272010-09-17 18:29:22 -07009029 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009030 TransferPipe tp = new TransferPipe();
9031 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009032 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9033 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009034 tp.go(fd);
9035 } finally {
9036 tp.kill();
9037 }
9038 } catch (IOException e) {
9039 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009040 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009041 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
Dianne Hackborn625ac272010-09-17 18:29:22 -07009042 }
9043 }
9044 }
9045
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009046 boolean dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009047 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009048 boolean needSep = false;
9049
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009050 pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009051 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009052 if (mRegisteredReceivers.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009053 boolean printed = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009054 Iterator it = mRegisteredReceivers.values().iterator();
9055 while (it.hasNext()) {
9056 ReceiverList r = (ReceiverList)it.next();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009057 if (dumpPackage != null && (r.app == null ||
9058 !dumpPackage.equals(r.app.info.packageName))) {
9059 continue;
9060 }
9061 if (!printed) {
9062 pw.println(" Registered Receivers:");
9063 needSep = true;
9064 printed = true;
9065 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009066 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009067 r.dump(pw, " ");
9068 }
9069 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009070
9071 if (mReceiverResolver.dump(pw, needSep ?
9072 "\n Receiver Resolver Table:" : " Receiver Resolver Table:",
9073 " ", dumpPackage, false)) {
9074 needSep = true;
9075 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009076 }
Christopher Tatef46723b2012-01-26 14:19:24 -08009077
9078 for (BroadcastQueue q : mBroadcastQueues) {
9079 needSep = q.dumpLocked(fd, pw, args, opti, dumpAll, dumpPackage, needSep);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009080 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009081
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009082 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009083
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009084 if (mStickyBroadcasts != null && dumpPackage == null) {
9085 if (needSep) {
9086 pw.println();
9087 }
9088 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009089 pw.println(" Sticky broadcasts:");
9090 StringBuilder sb = new StringBuilder(128);
9091 for (Map.Entry<String, ArrayList<Intent>> ent
9092 : mStickyBroadcasts.entrySet()) {
9093 pw.print(" * Sticky action "); pw.print(ent.getKey());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009094 if (dumpAll) {
9095 pw.println(":");
9096 ArrayList<Intent> intents = ent.getValue();
9097 final int N = intents.size();
9098 for (int i=0; i<N; i++) {
9099 sb.setLength(0);
9100 sb.append(" Intent: ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009101 intents.get(i).toShortString(sb, false, true, false, false);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009102 pw.println(sb.toString());
9103 Bundle bundle = intents.get(i).getExtras();
9104 if (bundle != null) {
9105 pw.print(" ");
9106 pw.println(bundle.toString());
9107 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009108 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009109 } else {
9110 pw.println("");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009111 }
9112 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009113 needSep = true;
9114 }
9115
9116 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009117 pw.println();
Christopher Tatef46723b2012-01-26 14:19:24 -08009118 for (BroadcastQueue queue : mBroadcastQueues) {
9119 pw.println(" mBroadcastsScheduled [" + queue.mQueueName + "]="
9120 + queue.mBroadcastsScheduled);
9121 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009122 pw.println(" mHandler:");
9123 mHandler.dump(new PrintWriterPrinter(pw), " ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009124 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009125 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009126
9127 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009128 }
9129
Marco Nelissen18cb2872011-11-15 11:19:53 -08009130 /**
9131 * Prints a list of ServiceRecords (dumpsys activity services)
9132 */
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009133 boolean dumpServicesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009134 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009135 boolean needSep = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009136
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009137 ItemMatcher matcher = new ItemMatcher();
9138 matcher.build(args, opti);
9139
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009140 pw.println("ACTIVITY MANAGER SERVICES (dumpsys activity services)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009141 try {
9142 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
9143 for (UserInfo user : users) {
9144 if (mServiceMap.getAllServices(user.id).size() > 0) {
9145 boolean printed = false;
9146 long nowReal = SystemClock.elapsedRealtime();
9147 Iterator<ServiceRecord> it = mServiceMap.getAllServices(
9148 user.id).iterator();
9149 needSep = false;
9150 while (it.hasNext()) {
9151 ServiceRecord r = it.next();
9152 if (!matcher.match(r, r.name)) {
9153 continue;
9154 }
9155 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9156 continue;
9157 }
9158 if (!printed) {
9159 pw.println(" Active services:");
9160 printed = true;
9161 }
9162 if (needSep) {
9163 pw.println();
9164 }
9165 pw.print(" * ");
9166 pw.println(r);
9167 if (dumpAll) {
9168 r.dump(pw, " ");
9169 needSep = true;
9170 } else {
9171 pw.print(" app=");
9172 pw.println(r.app);
9173 pw.print(" created=");
9174 TimeUtils.formatDuration(r.createTime, nowReal, pw);
9175 pw.print(" started=");
9176 pw.print(r.startRequested);
9177 pw.print(" connections=");
9178 pw.println(r.connections.size());
9179 if (r.connections.size() > 0) {
9180 pw.println(" Connections:");
9181 for (ArrayList<ConnectionRecord> clist : r.connections.values()) {
9182 for (int i = 0; i < clist.size(); i++) {
9183 ConnectionRecord conn = clist.get(i);
9184 pw.print(" ");
9185 pw.print(conn.binding.intent.intent.getIntent()
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009186 .toShortString(false, false, false, false));
Amith Yamasani742a6712011-05-04 14:49:28 -07009187 pw.print(" -> ");
9188 ProcessRecord proc = conn.binding.client;
9189 pw.println(proc != null ? proc.toShortString() : "null");
9190 }
9191 }
Dianne Hackborn8ec8d412011-11-14 18:27:24 -08009192 }
9193 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009194 if (dumpClient && r.app != null && r.app.thread != null) {
9195 pw.println(" Client:");
9196 pw.flush();
9197 try {
9198 TransferPipe tp = new TransferPipe();
9199 try {
9200 r.app.thread.dumpService(tp.getWriteFd().getFileDescriptor(),
9201 r, args);
9202 tp.setBufferPrefix(" ");
9203 // Short timeout, since blocking here can
9204 // deadlock with the application.
9205 tp.go(fd, 2000);
9206 } finally {
9207 tp.kill();
9208 }
9209 } catch (IOException e) {
9210 pw.println(" Failure while dumping the service: " + e);
9211 } catch (RemoteException e) {
9212 pw.println(" Got a RemoteException while dumping the service");
9213 }
9214 needSep = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009215 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009216 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009217 needSep = printed;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009218 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009219 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009220 } catch (RemoteException re) {
9221
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009222 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009223
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009224 if (mPendingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009225 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009226 for (int i=0; i<mPendingServices.size(); i++) {
9227 ServiceRecord r = mPendingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009228 if (!matcher.match(r, r.name)) {
9229 continue;
9230 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009231 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9232 continue;
9233 }
9234 if (!printed) {
9235 if (needSep) pw.println(" ");
9236 needSep = true;
9237 pw.println(" Pending services:");
9238 printed = true;
9239 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009240 pw.print(" * Pending "); pw.println(r);
9241 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009242 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009243 needSep = true;
9244 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009245
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009246 if (mRestartingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009247 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009248 for (int i=0; i<mRestartingServices.size(); i++) {
9249 ServiceRecord r = mRestartingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009250 if (!matcher.match(r, r.name)) {
9251 continue;
9252 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009253 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9254 continue;
9255 }
9256 if (!printed) {
9257 if (needSep) pw.println(" ");
9258 needSep = true;
9259 pw.println(" Restarting services:");
9260 printed = true;
9261 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009262 pw.print(" * Restarting "); pw.println(r);
9263 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009264 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009265 needSep = true;
9266 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009267
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009268 if (mStoppingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009269 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009270 for (int i=0; i<mStoppingServices.size(); i++) {
9271 ServiceRecord r = mStoppingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009272 if (!matcher.match(r, r.name)) {
9273 continue;
9274 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009275 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9276 continue;
9277 }
9278 if (!printed) {
9279 if (needSep) pw.println(" ");
9280 needSep = true;
9281 pw.println(" Stopping services:");
9282 printed = true;
9283 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009284 pw.print(" * Stopping "); pw.println(r);
9285 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009286 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009287 needSep = true;
9288 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009289
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009290 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009291 if (mServiceConnections.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009292 boolean printed = false;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009293 Iterator<ArrayList<ConnectionRecord>> it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009294 = mServiceConnections.values().iterator();
9295 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009296 ArrayList<ConnectionRecord> r = it.next();
9297 for (int i=0; i<r.size(); i++) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009298 ConnectionRecord cr = r.get(i);
9299 if (!matcher.match(cr.binding.service, cr.binding.service.name)) {
9300 continue;
9301 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009302 if (dumpPackage != null && (cr.binding.client == null
9303 || !dumpPackage.equals(cr.binding.client.info.packageName))) {
9304 continue;
9305 }
9306 if (!printed) {
9307 if (needSep) pw.println(" ");
9308 needSep = true;
9309 pw.println(" Connection bindings to services:");
9310 printed = true;
9311 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009312 pw.print(" * "); pw.println(cr);
9313 cr.dump(pw, " ");
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009314 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009315 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009316 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009317 }
9318 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009319
9320 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009321 }
9322
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009323 boolean dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009324 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009325 boolean needSep = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009326
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009327 ItemMatcher matcher = new ItemMatcher();
9328 matcher.build(args, opti);
9329
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009330 pw.println("ACTIVITY MANAGER CONTENT PROVIDERS (dumpsys activity providers)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009331
9332 mProviderMap.dumpProvidersLocked(pw, dumpAll);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009333
9334 if (mLaunchingProviders.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009335 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009336 for (int i=mLaunchingProviders.size()-1; i>=0; i--) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009337 ContentProviderRecord r = mLaunchingProviders.get(i);
9338 if (dumpPackage != null && !dumpPackage.equals(r.name.getPackageName())) {
9339 continue;
9340 }
9341 if (!printed) {
9342 if (needSep) pw.println(" ");
9343 needSep = true;
9344 pw.println(" Launching content providers:");
9345 printed = true;
9346 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009347 pw.print(" Launching #"); pw.print(i); pw.print(": ");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009348 pw.println(r);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009349 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009350 }
9351
9352 if (mGrantedUriPermissions.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009353 if (needSep) pw.println();
9354 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009355 pw.println("Granted Uri Permissions:");
9356 for (int i=0; i<mGrantedUriPermissions.size(); i++) {
9357 int uid = mGrantedUriPermissions.keyAt(i);
9358 HashMap<Uri, UriPermission> perms
9359 = mGrantedUriPermissions.valueAt(i);
9360 pw.print(" * UID "); pw.print(uid);
9361 pw.println(" holds:");
9362 for (UriPermission perm : perms.values()) {
9363 pw.print(" "); pw.println(perm);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009364 if (dumpAll) {
9365 perm.dump(pw, " ");
9366 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009367 }
9368 }
9369 needSep = true;
9370 }
9371
9372 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009373 }
9374
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009375 boolean dumpPendingIntentsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009376 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009377 boolean needSep = false;
9378
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009379 if (mIntentSenderRecords.size() > 0) {
9380 boolean printed = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009381 Iterator<WeakReference<PendingIntentRecord>> it
9382 = mIntentSenderRecords.values().iterator();
9383 while (it.hasNext()) {
9384 WeakReference<PendingIntentRecord> ref = it.next();
9385 PendingIntentRecord rec = ref != null ? ref.get(): null;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009386 if (dumpPackage != null && (rec == null
9387 || !dumpPackage.equals(rec.key.packageName))) {
9388 continue;
9389 }
9390 if (!printed) {
9391 pw.println("ACTIVITY MANAGER PENDING INTENTS (dumpsys activity intents)");
9392 printed = true;
9393 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009394 needSep = true;
9395 if (rec != null) {
9396 pw.print(" * "); pw.println(rec);
9397 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009398 rec.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009399 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009400 } else {
9401 pw.print(" * "); pw.println(ref);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009402 }
9403 }
9404 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009405
9406 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009407 }
9408
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009409 private static final void dumpHistoryList(FileDescriptor fd, PrintWriter pw, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009410 String prefix, String label, boolean complete, boolean brief, boolean client,
9411 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009412 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009413 boolean needNL = false;
9414 final String innerPrefix = prefix + " ";
9415 final String[] args = new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009416 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009417 final ActivityRecord r = (ActivityRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009418 if (dumpPackage != null && !dumpPackage.equals(r.packageName)) {
9419 continue;
9420 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07009421 final boolean full = !brief && (complete || !r.isInHistory());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009422 if (needNL) {
9423 pw.println(" ");
9424 needNL = false;
9425 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009426 if (lastTask != r.task) {
9427 lastTask = r.task;
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009428 pw.print(prefix);
9429 pw.print(full ? "* " : " ");
9430 pw.println(lastTask);
9431 if (full) {
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009432 lastTask.dump(pw, prefix + " ");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009433 } else if (complete) {
9434 // Complete + brief == give a summary. Isn't that obvious?!?
9435 if (lastTask.intent != null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009436 pw.print(prefix); pw.print(" ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009437 pw.println(lastTask.intent.toInsecureStringWithClip());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009438 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009439 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009440 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009441 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label);
9442 pw.print(" #"); pw.print(i); pw.print(": ");
9443 pw.println(r);
9444 if (full) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009445 r.dump(pw, innerPrefix);
9446 } else if (complete) {
9447 // Complete + brief == give a summary. Isn't that obvious?!?
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009448 pw.print(innerPrefix); pw.println(r.intent.toInsecureString());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009449 if (r.app != null) {
9450 pw.print(innerPrefix); pw.println(r.app);
9451 }
9452 }
9453 if (client && r.app != null && r.app.thread != null) {
9454 // flush anything that is already in the PrintWriter since the thread is going
9455 // to write to the file descriptor directly
9456 pw.flush();
9457 try {
9458 TransferPipe tp = new TransferPipe();
9459 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009460 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9461 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009462 // Short timeout, since blocking here can
9463 // deadlock with the application.
9464 tp.go(fd, 2000);
9465 } finally {
9466 tp.kill();
9467 }
9468 } catch (IOException e) {
9469 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
9470 } catch (RemoteException e) {
9471 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
9472 }
9473 needNL = true;
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009474 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009475 }
9476 }
9477
Dianne Hackborn09c916b2009-12-08 14:50:51 -08009478 private static String buildOomTag(String prefix, String space, int val, int base) {
9479 if (val == base) {
9480 if (space == null) return prefix;
9481 return prefix + " ";
9482 }
9483 return prefix + "+" + Integer.toString(val-base);
9484 }
9485
9486 private static final int dumpProcessList(PrintWriter pw,
9487 ActivityManagerService service, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009488 String prefix, String normalLabel, String persistentLabel,
9489 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009490 int numPers = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07009491 final int N = list.size()-1;
9492 for (int i=N; i>=0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009493 ProcessRecord r = (ProcessRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009494 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9495 continue;
9496 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009497 pw.println(String.format("%s%s #%2d: %s",
9498 prefix, (r.persistent ? persistentLabel : normalLabel),
9499 i, r.toString()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009500 if (r.persistent) {
9501 numPers++;
9502 }
9503 }
9504 return numPers;
9505 }
9506
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009507 private static final boolean dumpProcessOomList(PrintWriter pw,
Dianne Hackborn905577f2011-09-07 18:31:28 -07009508 ActivityManagerService service, List<ProcessRecord> origList,
Dianne Hackborn287952c2010-09-22 22:34:31 -07009509 String prefix, String normalLabel, String persistentLabel,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009510 boolean inclDetails, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009511
Dianne Hackborn905577f2011-09-07 18:31:28 -07009512 ArrayList<Pair<ProcessRecord, Integer>> list
9513 = new ArrayList<Pair<ProcessRecord, Integer>>(origList.size());
9514 for (int i=0; i<origList.size(); i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009515 ProcessRecord r = origList.get(i);
9516 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9517 continue;
9518 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07009519 list.add(new Pair<ProcessRecord, Integer>(origList.get(i), i));
9520 }
9521
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009522 if (list.size() <= 0) {
9523 return false;
9524 }
9525
Dianne Hackborn905577f2011-09-07 18:31:28 -07009526 Comparator<Pair<ProcessRecord, Integer>> comparator
9527 = new Comparator<Pair<ProcessRecord, Integer>>() {
9528 @Override
9529 public int compare(Pair<ProcessRecord, Integer> object1,
9530 Pair<ProcessRecord, Integer> object2) {
9531 if (object1.first.setAdj != object2.first.setAdj) {
9532 return object1.first.setAdj > object2.first.setAdj ? -1 : 1;
9533 }
9534 if (object1.second.intValue() != object2.second.intValue()) {
9535 return object1.second.intValue() > object2.second.intValue() ? -1 : 1;
9536 }
9537 return 0;
9538 }
9539 };
9540
9541 Collections.sort(list, comparator);
9542
Dianne Hackborn287952c2010-09-22 22:34:31 -07009543 final long curRealtime = SystemClock.elapsedRealtime();
9544 final long realtimeSince = curRealtime - service.mLastPowerCheckRealtime;
9545 final long curUptime = SystemClock.uptimeMillis();
9546 final long uptimeSince = curUptime - service.mLastPowerCheckUptime;
9547
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009548 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07009549 ProcessRecord r = list.get(i).first;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009550 String oomAdj;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009551 if (r.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07009552 oomAdj = buildOomTag("bak", " ", r.setAdj, ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009553 } else if (r.setAdj >= ProcessList.SERVICE_B_ADJ) {
9554 oomAdj = buildOomTag("svcb ", null, r.setAdj, ProcessList.SERVICE_B_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009555 } else if (r.setAdj >= ProcessList.PREVIOUS_APP_ADJ) {
9556 oomAdj = buildOomTag("prev ", null, r.setAdj, ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009557 } else if (r.setAdj >= ProcessList.HOME_APP_ADJ) {
9558 oomAdj = buildOomTag("home ", null, r.setAdj, ProcessList.HOME_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009559 } else if (r.setAdj >= ProcessList.SERVICE_ADJ) {
9560 oomAdj = buildOomTag("svc ", null, r.setAdj, ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009561 } else if (r.setAdj >= ProcessList.BACKUP_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08009562 oomAdj = buildOomTag("bkup ", null, r.setAdj, ProcessList.BACKUP_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009563 } else if (r.setAdj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
9564 oomAdj = buildOomTag("hvy ", null, r.setAdj, ProcessList.HEAVY_WEIGHT_APP_ADJ);
9565 } else if (r.setAdj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
9566 oomAdj = buildOomTag("prcp ", null, r.setAdj, ProcessList.PERCEPTIBLE_APP_ADJ);
9567 } else if (r.setAdj >= ProcessList.VISIBLE_APP_ADJ) {
9568 oomAdj = buildOomTag("vis ", null, r.setAdj, ProcessList.VISIBLE_APP_ADJ);
9569 } else if (r.setAdj >= ProcessList.FOREGROUND_APP_ADJ) {
9570 oomAdj = buildOomTag("fore ", null, r.setAdj, ProcessList.FOREGROUND_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009571 } else if (r.setAdj >= ProcessList.PERSISTENT_PROC_ADJ) {
9572 oomAdj = buildOomTag("pers ", null, r.setAdj, ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009573 } else if (r.setAdj >= ProcessList.SYSTEM_ADJ) {
9574 oomAdj = buildOomTag("sys ", null, r.setAdj, ProcessList.SYSTEM_ADJ);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009575 } else {
9576 oomAdj = Integer.toString(r.setAdj);
9577 }
9578 String schedGroup;
9579 switch (r.setSchedGroup) {
9580 case Process.THREAD_GROUP_BG_NONINTERACTIVE:
9581 schedGroup = "B";
9582 break;
9583 case Process.THREAD_GROUP_DEFAULT:
9584 schedGroup = "F";
9585 break;
9586 default:
9587 schedGroup = Integer.toString(r.setSchedGroup);
9588 break;
9589 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07009590 String foreground;
9591 if (r.foregroundActivities) {
9592 foreground = "A";
9593 } else if (r.foregroundServices) {
9594 foreground = "S";
9595 } else {
9596 foreground = " ";
9597 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07009598 pw.println(String.format("%s%s #%2d: adj=%s/%s%s trm=%2d %s (%s)",
Dianne Hackborn287952c2010-09-22 22:34:31 -07009599 prefix, (r.persistent ? persistentLabel : normalLabel),
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009600 (origList.size()-1)-list.get(i).second, oomAdj, schedGroup,
9601 foreground, r.trimMemoryLevel, r.toShortString(), r.adjType));
Dianne Hackborn287952c2010-09-22 22:34:31 -07009602 if (r.adjSource != null || r.adjTarget != null) {
9603 pw.print(prefix);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009604 pw.print(" ");
Dianne Hackborn287952c2010-09-22 22:34:31 -07009605 if (r.adjTarget instanceof ComponentName) {
9606 pw.print(((ComponentName)r.adjTarget).flattenToShortString());
9607 } else if (r.adjTarget != null) {
9608 pw.print(r.adjTarget.toString());
9609 } else {
9610 pw.print("{null}");
9611 }
9612 pw.print("<=");
9613 if (r.adjSource instanceof ProcessRecord) {
9614 pw.print("Proc{");
9615 pw.print(((ProcessRecord)r.adjSource).toShortString());
9616 pw.println("}");
9617 } else if (r.adjSource != null) {
9618 pw.println(r.adjSource.toString());
9619 } else {
9620 pw.println("{null}");
9621 }
9622 }
9623 if (inclDetails) {
9624 pw.print(prefix);
9625 pw.print(" ");
9626 pw.print("oom: max="); pw.print(r.maxAdj);
9627 pw.print(" hidden="); pw.print(r.hiddenAdj);
9628 pw.print(" curRaw="); pw.print(r.curRawAdj);
9629 pw.print(" setRaw="); pw.print(r.setRawAdj);
9630 pw.print(" cur="); pw.print(r.curAdj);
9631 pw.print(" set="); pw.println(r.setAdj);
9632 pw.print(prefix);
9633 pw.print(" ");
9634 pw.print("keeping="); pw.print(r.keeping);
9635 pw.print(" hidden="); pw.print(r.hidden);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009636 pw.print(" empty="); pw.print(r.empty);
9637 pw.print(" hasAboveClient="); pw.println(r.hasAboveClient);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009638
9639 if (!r.keeping) {
9640 if (r.lastWakeTime != 0) {
9641 long wtime;
9642 BatteryStatsImpl stats = service.mBatteryStatsService.getActiveStatistics();
9643 synchronized (stats) {
9644 wtime = stats.getProcessWakeTime(r.info.uid,
9645 r.pid, curRealtime);
9646 }
9647 long timeUsed = wtime - r.lastWakeTime;
9648 pw.print(prefix);
9649 pw.print(" ");
9650 pw.print("keep awake over ");
9651 TimeUtils.formatDuration(realtimeSince, pw);
9652 pw.print(" used ");
9653 TimeUtils.formatDuration(timeUsed, pw);
9654 pw.print(" (");
9655 pw.print((timeUsed*100)/realtimeSince);
9656 pw.println("%)");
9657 }
9658 if (r.lastCpuTime != 0) {
9659 long timeUsed = r.curCpuTime - r.lastCpuTime;
9660 pw.print(prefix);
9661 pw.print(" ");
9662 pw.print("run cpu over ");
9663 TimeUtils.formatDuration(uptimeSince, pw);
9664 pw.print(" used ");
9665 TimeUtils.formatDuration(timeUsed, pw);
9666 pw.print(" (");
9667 pw.print((timeUsed*100)/uptimeSince);
9668 pw.println("%)");
9669 }
9670 }
9671 }
9672 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009673 return true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009674 }
9675
Dianne Hackbornb437e092011-08-05 17:50:29 -07009676 ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, String[] args) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009677 ArrayList<ProcessRecord> procs;
9678 synchronized (this) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009679 if (args != null && args.length > start
9680 && args[start].charAt(0) != '-') {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009681 procs = new ArrayList<ProcessRecord>();
9682 int pid = -1;
9683 try {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009684 pid = Integer.parseInt(args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009685 } catch (NumberFormatException e) {
9686
9687 }
9688 for (int i=mLruProcesses.size()-1; i>=0; i--) {
9689 ProcessRecord proc = mLruProcesses.get(i);
9690 if (proc.pid == pid) {
9691 procs.add(proc);
Dianne Hackbornb437e092011-08-05 17:50:29 -07009692 } else if (proc.processName.equals(args[start])) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009693 procs.add(proc);
9694 }
9695 }
9696 if (procs.size() <= 0) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009697 pw.println("No process found for: " + args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009698 return null;
9699 }
9700 } else {
9701 procs = new ArrayList<ProcessRecord>(mLruProcesses);
9702 }
9703 }
9704 return procs;
9705 }
9706
9707 final void dumpGraphicsHardwareUsage(FileDescriptor fd,
9708 PrintWriter pw, String[] args) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009709 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009710 if (procs == null) {
9711 return;
9712 }
9713
9714 long uptime = SystemClock.uptimeMillis();
9715 long realtime = SystemClock.elapsedRealtime();
9716 pw.println("Applications Graphics Acceleration Info:");
9717 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
9718
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009719 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
9720 ProcessRecord r = procs.get(i);
Chet Haase9c1e23b2011-03-24 10:51:31 -07009721 if (r.thread != null) {
9722 pw.println("\n** Graphics info for pid " + r.pid + " [" + r.processName + "] **");
9723 pw.flush();
9724 try {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009725 TransferPipe tp = new TransferPipe();
9726 try {
9727 r.thread.dumpGfxInfo(tp.getWriteFd().getFileDescriptor(), args);
9728 tp.go(fd);
9729 } finally {
9730 tp.kill();
9731 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009732 } catch (IOException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009733 pw.println("Failure while dumping the app: " + r);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009734 pw.flush();
Chet Haase9c1e23b2011-03-24 10:51:31 -07009735 } catch (RemoteException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009736 pw.println("Got a RemoteException while dumping the app " + r);
Chet Haase9c1e23b2011-03-24 10:51:31 -07009737 pw.flush();
9738 }
9739 }
9740 }
Chet Haase9c1e23b2011-03-24 10:51:31 -07009741 }
9742
Jeff Brown6754ba22011-12-14 20:20:01 -08009743 final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) {
9744 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
9745 if (procs == null) {
9746 return;
9747 }
9748
9749 pw.println("Applications Database Info:");
9750
9751 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
9752 ProcessRecord r = procs.get(i);
9753 if (r.thread != null) {
9754 pw.println("\n** Database info for pid " + r.pid + " [" + r.processName + "] **");
9755 pw.flush();
9756 try {
9757 TransferPipe tp = new TransferPipe();
9758 try {
9759 r.thread.dumpDbInfo(tp.getWriteFd().getFileDescriptor(), args);
9760 tp.go(fd);
9761 } finally {
9762 tp.kill();
9763 }
9764 } catch (IOException e) {
9765 pw.println("Failure while dumping the app: " + r);
9766 pw.flush();
9767 } catch (RemoteException e) {
9768 pw.println("Got a RemoteException while dumping the app " + r);
9769 pw.flush();
9770 }
9771 }
9772 }
9773 }
9774
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009775 final static class MemItem {
9776 final String label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009777 final String shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009778 final long pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009779 final int id;
Dianne Hackborna4bacb82011-08-24 15:12:38 -07009780 ArrayList<MemItem> subitems;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009781
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009782 public MemItem(String _label, String _shortLabel, long _pss, int _id) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009783 label = _label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009784 shortLabel = _shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009785 pss = _pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009786 id = _id;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009787 }
9788 }
9789
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009790 static final void dumpMemItems(PrintWriter pw, String prefix, ArrayList<MemItem> items,
Dianne Hackbornb437e092011-08-05 17:50:29 -07009791 boolean sort) {
9792 if (sort) {
9793 Collections.sort(items, new Comparator<MemItem>() {
9794 @Override
9795 public int compare(MemItem lhs, MemItem rhs) {
9796 if (lhs.pss < rhs.pss) {
9797 return 1;
9798 } else if (lhs.pss > rhs.pss) {
9799 return -1;
9800 }
9801 return 0;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009802 }
Dianne Hackbornb437e092011-08-05 17:50:29 -07009803 });
9804 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009805
9806 for (int i=0; i<items.size(); i++) {
9807 MemItem mi = items.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009808 pw.print(prefix); pw.printf("%7d kB: ", mi.pss); pw.println(mi.label);
Dianne Hackborna4bacb82011-08-24 15:12:38 -07009809 if (mi.subitems != null) {
9810 dumpMemItems(pw, prefix + " ", mi.subitems, true);
9811 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009812 }
9813 }
9814
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009815 // These are in KB.
9816 static final long[] DUMP_MEM_BUCKETS = new long[] {
9817 5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024,
9818 120*1024, 160*1024, 200*1024,
9819 250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024,
9820 1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024
9821 };
9822
Dianne Hackborn672342c2011-11-29 11:29:02 -08009823 static final void appendMemBucket(StringBuilder out, long memKB, String label,
9824 boolean stackLike) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009825 int start = label.lastIndexOf('.');
9826 if (start >= 0) start++;
9827 else start = 0;
9828 int end = label.length();
9829 for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) {
9830 if (DUMP_MEM_BUCKETS[i] >= memKB) {
9831 long bucket = DUMP_MEM_BUCKETS[i]/1024;
9832 out.append(bucket);
Dianne Hackborn672342c2011-11-29 11:29:02 -08009833 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009834 out.append(label, start, end);
9835 return;
9836 }
9837 }
9838 out.append(memKB/1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -08009839 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009840 out.append(label, start, end);
9841 }
9842
9843 static final int[] DUMP_MEM_OOM_ADJ = new int[] {
9844 ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ, ProcessList.FOREGROUND_APP_ADJ,
9845 ProcessList.VISIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ,
9846 ProcessList.BACKUP_APP_ADJ, ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ,
9847 ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.HIDDEN_APP_MAX_ADJ
9848 };
9849 static final String[] DUMP_MEM_OOM_LABEL = new String[] {
9850 "System", "Persistent", "Foreground",
9851 "Visible", "Perceptible", "Heavy Weight",
9852 "Backup", "A Services", "Home", "Previous",
9853 "B Services", "Background"
9854 };
9855
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009856 final void dumpApplicationMemoryUsage(FileDescriptor fd,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08009857 PrintWriter pw, String prefix, String[] args, boolean brief,
Dianne Hackborn672342c2011-11-29 11:29:02 -08009858 PrintWriter categoryPw, StringBuilder outTag, StringBuilder outStack) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009859 boolean dumpAll = false;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08009860 boolean oomOnly = false;
Dianne Hackbornb437e092011-08-05 17:50:29 -07009861
9862 int opti = 0;
9863 while (opti < args.length) {
9864 String opt = args[opti];
9865 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
9866 break;
9867 }
9868 opti++;
9869 if ("-a".equals(opt)) {
9870 dumpAll = true;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08009871 } else if ("--oom".equals(opt)) {
9872 oomOnly = true;
Dianne Hackbornb437e092011-08-05 17:50:29 -07009873 } else if ("-h".equals(opt)) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08009874 pw.println("meminfo dump options: [-a] [--oom] [process]");
Dianne Hackbornb437e092011-08-05 17:50:29 -07009875 pw.println(" -a: include all available information for each process.");
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08009876 pw.println(" --oom: only show processes organized by oom adj.");
Dianne Hackbornb437e092011-08-05 17:50:29 -07009877 pw.println("If [process] is specified it can be the name or ");
9878 pw.println("pid of a specific process to dump.");
9879 return;
9880 } else {
9881 pw.println("Unknown argument: " + opt + "; use -h for help");
9882 }
9883 }
9884
9885 ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009886 if (procs == null) {
9887 return;
9888 }
9889
Dianne Hackborn6447ca32009-04-07 19:50:08 -07009890 final boolean isCheckinRequest = scanArgs(args, "--checkin");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009891 long uptime = SystemClock.uptimeMillis();
9892 long realtime = SystemClock.elapsedRealtime();
Dianne Hackbornb437e092011-08-05 17:50:29 -07009893
9894 if (procs.size() == 1 || isCheckinRequest) {
9895 dumpAll = true;
9896 }
9897
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009898 if (isCheckinRequest) {
9899 // short checkin version
9900 pw.println(uptime + "," + realtime);
9901 pw.flush();
9902 } else {
9903 pw.println("Applications Memory Usage (kB):");
9904 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
9905 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009906
Dianne Hackbornb437e092011-08-05 17:50:29 -07009907 String[] innerArgs = new String[args.length-opti];
9908 System.arraycopy(args, opti, innerArgs, 0, args.length-opti);
9909
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009910 ArrayList<MemItem> procMems = new ArrayList<MemItem>();
9911 long nativePss=0, dalvikPss=0, otherPss=0;
9912 long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
9913
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009914 long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length];
9915 ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[])
9916 new ArrayList[DUMP_MEM_OOM_LABEL.length];
Dianne Hackbornb437e092011-08-05 17:50:29 -07009917
9918 long totalPss = 0;
9919
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009920 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
9921 ProcessRecord r = procs.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009922 if (r.thread != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009923 if (!isCheckinRequest && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009924 pw.println("\n** MEMINFO in pid " + r.pid + " [" + r.processName + "] **");
9925 pw.flush();
9926 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009927 Debug.MemoryInfo mi = null;
Dianne Hackbornb437e092011-08-05 17:50:29 -07009928 if (dumpAll) {
9929 try {
9930 mi = r.thread.dumpMemInfo(fd, isCheckinRequest, dumpAll, innerArgs);
9931 } catch (RemoteException e) {
9932 if (!isCheckinRequest) {
9933 pw.println("Got RemoteException!");
9934 pw.flush();
9935 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009936 }
Dianne Hackbornb437e092011-08-05 17:50:29 -07009937 } else {
9938 mi = new Debug.MemoryInfo();
9939 Debug.getMemoryInfo(r.pid, mi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009940 }
Dianne Hackbornb437e092011-08-05 17:50:29 -07009941
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009942 if (!isCheckinRequest && mi != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009943 long myTotalPss = mi.getTotalPss();
9944 totalPss += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -07009945 MemItem pssItem = new MemItem(r.processName + " (pid " + r.pid + ")",
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009946 r.processName, myTotalPss, 0);
Dianne Hackborna4bacb82011-08-24 15:12:38 -07009947 procMems.add(pssItem);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009948
9949 nativePss += mi.nativePss;
9950 dalvikPss += mi.dalvikPss;
9951 otherPss += mi.otherPss;
9952 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
9953 long mem = mi.getOtherPss(j);
9954 miscPss[j] += mem;
9955 otherPss -= mem;
9956 }
Dianne Hackbornb437e092011-08-05 17:50:29 -07009957
9958 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009959 if (r.setAdj <= DUMP_MEM_OOM_ADJ[oomIndex]
9960 || oomIndex == (oomPss.length-1)) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009961 oomPss[oomIndex] += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -07009962 if (oomProcs[oomIndex] == null) {
9963 oomProcs[oomIndex] = new ArrayList<MemItem>();
9964 }
9965 oomProcs[oomIndex].add(pssItem);
Dianne Hackbornb437e092011-08-05 17:50:29 -07009966 break;
9967 }
9968 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009969 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009970 }
9971 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009972
9973 if (!isCheckinRequest && procs.size() > 1) {
9974 ArrayList<MemItem> catMems = new ArrayList<MemItem>();
9975
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009976 catMems.add(new MemItem("Native", "Native", nativePss, -1));
9977 catMems.add(new MemItem("Dalvik", "Dalvik", dalvikPss, -2));
9978 catMems.add(new MemItem("Unknown", "Unknown", otherPss, -3));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009979 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009980 String label = Debug.MemoryInfo.getOtherLabel(j);
9981 catMems.add(new MemItem(label, label, miscPss[j], j));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009982 }
9983
Dianne Hackbornb437e092011-08-05 17:50:29 -07009984 ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
9985 for (int j=0; j<oomPss.length; j++) {
9986 if (oomPss[j] != 0) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009987 String label = DUMP_MEM_OOM_LABEL[j];
9988 MemItem item = new MemItem(label, label, oomPss[j],
9989 DUMP_MEM_OOM_ADJ[j]);
Dianne Hackborna4bacb82011-08-24 15:12:38 -07009990 item.subitems = oomProcs[j];
9991 oomMems.add(item);
Dianne Hackbornb437e092011-08-05 17:50:29 -07009992 }
9993 }
9994
Dianne Hackborn672342c2011-11-29 11:29:02 -08009995 if (outTag != null || outStack != null) {
9996 if (outTag != null) {
9997 appendMemBucket(outTag, totalPss, "total", false);
9998 }
9999 if (outStack != null) {
10000 appendMemBucket(outStack, totalPss, "total", true);
10001 }
10002 boolean firstLine = true;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010003 for (int i=0; i<oomMems.size(); i++) {
10004 MemItem miCat = oomMems.get(i);
10005 if (miCat.subitems == null || miCat.subitems.size() < 1) {
10006 continue;
10007 }
10008 if (miCat.id < ProcessList.SERVICE_ADJ
10009 || miCat.id == ProcessList.HOME_APP_ADJ
10010 || miCat.id == ProcessList.PREVIOUS_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010011 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10012 outTag.append(" / ");
10013 }
10014 if (outStack != null) {
10015 if (miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10016 if (firstLine) {
10017 outStack.append(":");
10018 firstLine = false;
10019 }
10020 outStack.append("\n\t at ");
10021 } else {
10022 outStack.append("$");
10023 }
10024 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010025 for (int j=0; j<miCat.subitems.size(); j++) {
10026 MemItem mi = miCat.subitems.get(j);
10027 if (j > 0) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010028 if (outTag != null) {
10029 outTag.append(" ");
10030 }
10031 if (outStack != null) {
10032 outStack.append("$");
10033 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010034 }
Dianne Hackborn672342c2011-11-29 11:29:02 -080010035 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10036 appendMemBucket(outTag, mi.pss, mi.shortLabel, false);
10037 }
10038 if (outStack != null) {
10039 appendMemBucket(outStack, mi.pss, mi.shortLabel, true);
10040 }
10041 }
10042 if (outStack != null && miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10043 outStack.append("(");
10044 for (int k=0; k<DUMP_MEM_OOM_ADJ.length; k++) {
10045 if (DUMP_MEM_OOM_ADJ[k] == miCat.id) {
10046 outStack.append(DUMP_MEM_OOM_LABEL[k]);
10047 outStack.append(":");
10048 outStack.append(DUMP_MEM_OOM_ADJ[k]);
10049 }
10050 }
10051 outStack.append(")");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010052 }
10053 }
10054 }
10055 }
10056
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010057 if (!brief && !oomOnly) {
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010058 pw.println();
10059 pw.println("Total PSS by process:");
10060 dumpMemItems(pw, " ", procMems, true);
10061 pw.println();
10062 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010063 pw.println("Total PSS by OOM adjustment:");
10064 dumpMemItems(pw, " ", oomMems, false);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010065 if (!oomOnly) {
10066 PrintWriter out = categoryPw != null ? categoryPw : pw;
10067 out.println();
10068 out.println("Total PSS by category:");
10069 dumpMemItems(out, " ", catMems, true);
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010070 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010071 pw.println();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010072 pw.print("Total PSS: "); pw.print(totalPss); pw.println(" kB");
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010073 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010074 }
10075
10076 /**
10077 * Searches array of arguments for the specified string
10078 * @param args array of argument strings
10079 * @param value value to search for
10080 * @return true if the value is contained in the array
10081 */
10082 private static boolean scanArgs(String[] args, String value) {
10083 if (args != null) {
10084 for (String arg : args) {
10085 if (value.equals(arg)) {
10086 return true;
10087 }
10088 }
10089 }
10090 return false;
10091 }
10092
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010093 private final void killServicesLocked(ProcessRecord app,
10094 boolean allowRestart) {
10095 // Report disconnected services.
10096 if (false) {
10097 // XXX we are letting the client link to the service for
10098 // death notifications.
10099 if (app.services.size() > 0) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010100 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010101 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010102 ServiceRecord r = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010103 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010104 Iterator<ArrayList<ConnectionRecord>> jt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010105 = r.connections.values().iterator();
10106 while (jt.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010107 ArrayList<ConnectionRecord> cl = jt.next();
10108 for (int i=0; i<cl.size(); i++) {
10109 ConnectionRecord c = cl.get(i);
10110 if (c.binding.client != app) {
10111 try {
10112 //c.conn.connected(r.className, null);
10113 } catch (Exception e) {
10114 // todo: this should be asynchronous!
10115 Slog.w(TAG, "Exception thrown disconnected servce "
10116 + r.shortName
10117 + " from app " + app.processName, e);
10118 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010119 }
10120 }
10121 }
10122 }
10123 }
10124 }
10125 }
10126
10127 // Clean up any connections this application has to other services.
10128 if (app.connections.size() > 0) {
10129 Iterator<ConnectionRecord> it = app.connections.iterator();
10130 while (it.hasNext()) {
10131 ConnectionRecord r = it.next();
10132 removeConnectionLocked(r, app, null);
10133 }
10134 }
10135 app.connections.clear();
10136
10137 if (app.services.size() != 0) {
10138 // Any services running in the application need to be placed
10139 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -070010140 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010141 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010142 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010143 synchronized (sr.stats.getBatteryStats()) {
10144 sr.stats.stopLaunchedLocked();
10145 }
10146 sr.app = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010147 sr.isolatedProc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010148 sr.executeNesting = 0;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010149 if (mStoppingServices.remove(sr)) {
10150 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
10151 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010152
10153 boolean hasClients = sr.bindings.size() > 0;
10154 if (hasClients) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010155 Iterator<IntentBindRecord> bindings
10156 = sr.bindings.values().iterator();
10157 while (bindings.hasNext()) {
10158 IntentBindRecord b = bindings.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -080010159 if (DEBUG_SERVICE) Slog.v(TAG, "Killing binding " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010160 + ": shouldUnbind=" + b.hasBound);
10161 b.binder = null;
10162 b.requested = b.received = b.hasBound = false;
10163 }
10164 }
10165
Dianne Hackborn070783f2010-12-29 16:46:28 -080010166 if (sr.crashCount >= 2 && (sr.serviceInfo.applicationInfo.flags
10167 &ApplicationInfo.FLAG_PERSISTENT) == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010168 Slog.w(TAG, "Service crashed " + sr.crashCount
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010169 + " times, stopping: " + sr);
Doug Zongker2bec3d42009-12-04 12:52:44 -080010170 EventLog.writeEvent(EventLogTags.AM_SERVICE_CRASHED_TOO_MUCH,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010171 sr.crashCount, sr.shortName, app.pid);
10172 bringDownServiceLocked(sr, true);
10173 } else if (!allowRestart) {
10174 bringDownServiceLocked(sr, true);
10175 } else {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010176 boolean canceled = scheduleServiceRestartLocked(sr, true);
10177
10178 // Should the service remain running? Note that in the
10179 // extreme case of so many attempts to deliver a command
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010180 // that it failed we also will stop it here.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010181 if (sr.startRequested && (sr.stopIfKilled || canceled)) {
10182 if (sr.pendingStarts.size() == 0) {
10183 sr.startRequested = false;
10184 if (!hasClients) {
10185 // Whoops, no reason to restart!
10186 bringDownServiceLocked(sr, true);
10187 }
10188 }
10189 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010190 }
10191 }
10192
10193 if (!allowRestart) {
10194 app.services.clear();
10195 }
10196 }
10197
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010198 // Make sure we have no more records on the stopping list.
10199 int i = mStoppingServices.size();
10200 while (i > 0) {
10201 i--;
10202 ServiceRecord sr = mStoppingServices.get(i);
10203 if (sr.app == app) {
10204 mStoppingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010205 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010206 }
10207 }
10208
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010209 app.executingServices.clear();
10210 }
10211
10212 private final void removeDyingProviderLocked(ProcessRecord proc,
10213 ContentProviderRecord cpr) {
10214 synchronized (cpr) {
10215 cpr.launchingApp = null;
10216 cpr.notifyAll();
10217 }
10218
Amith Yamasani742a6712011-05-04 14:49:28 -070010219 mProviderMap.removeProviderByClass(cpr.name, UserId.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010220 String names[] = cpr.info.authority.split(";");
10221 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010222 mProviderMap.removeProviderByName(names[j], UserId.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010223 }
10224
10225 Iterator<ProcessRecord> cit = cpr.clients.iterator();
10226 while (cit.hasNext()) {
10227 ProcessRecord capp = cit.next();
10228 if (!capp.persistent && capp.thread != null
10229 && capp.pid != 0
10230 && capp.pid != MY_PID) {
Dianne Hackborn8633e682010-04-22 16:03:41 -070010231 Slog.i(TAG, "Kill " + capp.processName
10232 + " (pid " + capp.pid + "): provider " + cpr.info.name
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010233 + " in dying process " + (proc != null ? proc.processName : "??"));
Dianne Hackborn8633e682010-04-22 16:03:41 -070010234 EventLog.writeEvent(EventLogTags.AM_KILL, capp.pid,
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010235 capp.processName, capp.setAdj, "dying provider "
10236 + cpr.name.toShortString());
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070010237 Process.killProcessQuiet(capp.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010238 }
10239 }
10240
10241 mLaunchingProviders.remove(cpr);
10242 }
10243
10244 /**
10245 * Main code for cleaning up a process when it has gone away. This is
10246 * called both as a result of the process dying, or directly when stopping
10247 * a process when running in single process mode.
10248 */
10249 private final void cleanUpApplicationRecordLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010250 boolean restarting, boolean allowRestart, int index) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010251 if (index >= 0) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010252 mLruProcesses.remove(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010253 }
10254
Dianne Hackborn36124872009-10-08 16:22:03 -070010255 mProcessesToGc.remove(app);
10256
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010257 // Dismiss any open dialogs.
10258 if (app.crashDialog != null) {
10259 app.crashDialog.dismiss();
10260 app.crashDialog = null;
10261 }
10262 if (app.anrDialog != null) {
10263 app.anrDialog.dismiss();
10264 app.anrDialog = null;
10265 }
10266 if (app.waitDialog != null) {
10267 app.waitDialog.dismiss();
10268 app.waitDialog = null;
10269 }
10270
10271 app.crashing = false;
10272 app.notResponding = false;
10273
10274 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -070010275 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010276 app.thread = null;
10277 app.forcingToForeground = null;
10278 app.foregroundServices = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010279 app.foregroundActivities = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070010280 app.hasShownUi = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010281 app.hasAboveClient = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010282
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010283 killServicesLocked(app, allowRestart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010284
10285 boolean restart = false;
10286
10287 int NL = mLaunchingProviders.size();
10288
10289 // Remove published content providers.
10290 if (!app.pubProviders.isEmpty()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010291 Iterator<ContentProviderRecord> it = app.pubProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010292 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010293 ContentProviderRecord cpr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010294 cpr.provider = null;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010295 cpr.proc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010296
10297 // See if someone is waiting for this provider... in which
10298 // case we don't remove it, but just let it restart.
10299 int i = 0;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010300 if (!app.bad && allowRestart) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010301 for (; i<NL; i++) {
10302 if (mLaunchingProviders.get(i) == cpr) {
10303 restart = true;
10304 break;
10305 }
10306 }
10307 } else {
10308 i = NL;
10309 }
10310
10311 if (i >= NL) {
10312 removeDyingProviderLocked(app, cpr);
10313 NL = mLaunchingProviders.size();
10314 }
10315 }
10316 app.pubProviders.clear();
10317 }
10318
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010319 // Take care of any launching providers waiting for this process.
10320 if (checkAppInLaunchingProvidersLocked(app, false)) {
10321 restart = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010322 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010323
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010324 // Unregister from connected content providers.
10325 if (!app.conProviders.isEmpty()) {
Dianne Hackborn0c3154d2009-10-06 17:18:05 -070010326 Iterator it = app.conProviders.keySet().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010327 while (it.hasNext()) {
10328 ContentProviderRecord cpr = (ContentProviderRecord)it.next();
10329 cpr.clients.remove(app);
10330 }
10331 app.conProviders.clear();
10332 }
10333
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010334 // At this point there may be remaining entries in mLaunchingProviders
10335 // where we were the only one waiting, so they are no longer of use.
10336 // Look for these and clean up if found.
10337 // XXX Commented out for now. Trying to figure out a way to reproduce
10338 // the actual situation to identify what is actually going on.
10339 if (false) {
10340 for (int i=0; i<NL; i++) {
10341 ContentProviderRecord cpr = (ContentProviderRecord)
10342 mLaunchingProviders.get(i);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080010343 if (cpr.clients.size() <= 0 && !cpr.hasExternalProcessHandles()) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010344 synchronized (cpr) {
10345 cpr.launchingApp = null;
10346 cpr.notifyAll();
10347 }
10348 }
10349 }
10350 }
10351
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010352 skipCurrentReceiverLocked(app);
10353
10354 // Unregister any receivers.
10355 if (app.receivers.size() > 0) {
10356 Iterator<ReceiverList> it = app.receivers.iterator();
10357 while (it.hasNext()) {
10358 removeReceiverLocked(it.next());
10359 }
10360 app.receivers.clear();
10361 }
10362
Christopher Tate181fafa2009-05-14 11:12:14 -070010363 // If the app is undergoing backup, tell the backup manager about it
10364 if (mBackupTarget != null && app.pid == mBackupTarget.app.pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010365 if (DEBUG_BACKUP) Slog.d(TAG, "App " + mBackupTarget.appInfo + " died during backup");
Christopher Tate181fafa2009-05-14 11:12:14 -070010366 try {
10367 IBackupManager bm = IBackupManager.Stub.asInterface(
10368 ServiceManager.getService(Context.BACKUP_SERVICE));
10369 bm.agentDisconnected(app.info.packageName);
10370 } catch (RemoteException e) {
10371 // can't happen; backup manager is local
10372 }
10373 }
10374
Jeff Sharkey287bd832011-05-28 19:36:26 -070010375 mHandler.obtainMessage(DISPATCH_PROCESS_DIED, app.pid, app.info.uid, null).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010376
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010377 // If the caller is restarting this app, then leave it in its
10378 // current lists and let the caller take care of it.
10379 if (restarting) {
10380 return;
10381 }
10382
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010383 if (!app.persistent || app.isolated) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010384 if (DEBUG_PROCESSES) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010385 "Removing non-persistent process during cleanup: " + app);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010386 mProcessNames.remove(app.processName, app.uid);
10387 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -070010388 if (mHeavyWeightProcess == app) {
10389 mHeavyWeightProcess = null;
10390 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
10391 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010392 } else if (!app.removed) {
10393 // This app is persistent, so we need to keep its record around.
10394 // If it is not already on the pending app list, add it there
10395 // and start a new process for it.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010396 if (mPersistentStartingProcesses.indexOf(app) < 0) {
10397 mPersistentStartingProcesses.add(app);
10398 restart = true;
10399 }
10400 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070010401 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
10402 "Clean-up removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010403 mProcessesOnHold.remove(app);
10404
The Android Open Source Project4df24232009-03-05 14:34:35 -080010405 if (app == mHomeProcess) {
10406 mHomeProcess = null;
10407 }
Dianne Hackbornf35fe232011-11-01 19:25:20 -070010408 if (app == mPreviousProcess) {
10409 mPreviousProcess = null;
10410 }
10411
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010412 if (restart && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010413 // We have components that still need to be running in the
10414 // process, so re-launch it.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010415 mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010416 startProcessLocked(app, "restart", app.processName);
10417 } else if (app.pid > 0 && app.pid != MY_PID) {
10418 // Goodbye!
10419 synchronized (mPidsSelfLocked) {
10420 mPidsSelfLocked.remove(app.pid);
10421 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
10422 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010423 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010424 }
10425 }
10426
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010427 boolean checkAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) {
10428 // Look through the content providers we are waiting to have launched,
10429 // and if any run in this process then either schedule a restart of
10430 // the process or kill the client waiting for it if this process has
10431 // gone bad.
10432 int NL = mLaunchingProviders.size();
10433 boolean restart = false;
10434 for (int i=0; i<NL; i++) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010435 ContentProviderRecord cpr = mLaunchingProviders.get(i);
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010436 if (cpr.launchingApp == app) {
10437 if (!alwaysBad && !app.bad) {
10438 restart = true;
10439 } else {
10440 removeDyingProviderLocked(app, cpr);
10441 NL = mLaunchingProviders.size();
10442 }
10443 }
10444 }
10445 return restart;
10446 }
10447
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010448 // =========================================================
10449 // SERVICES
10450 // =========================================================
10451
10452 ActivityManager.RunningServiceInfo makeRunningServiceInfoLocked(ServiceRecord r) {
10453 ActivityManager.RunningServiceInfo info =
10454 new ActivityManager.RunningServiceInfo();
10455 info.service = r.name;
10456 if (r.app != null) {
10457 info.pid = r.app.pid;
10458 }
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010459 info.uid = r.appInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010460 info.process = r.processName;
10461 info.foreground = r.isForeground;
10462 info.activeSince = r.createTime;
10463 info.started = r.startRequested;
10464 info.clientCount = r.connections.size();
10465 info.crashCount = r.crashCount;
10466 info.lastActivityTime = r.lastActivity;
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010467 if (r.isForeground) {
10468 info.flags |= ActivityManager.RunningServiceInfo.FLAG_FOREGROUND;
10469 }
10470 if (r.startRequested) {
10471 info.flags |= ActivityManager.RunningServiceInfo.FLAG_STARTED;
10472 }
Dan Egnor42471dd2010-01-07 17:25:22 -080010473 if (r.app != null && r.app.pid == MY_PID) {
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010474 info.flags |= ActivityManager.RunningServiceInfo.FLAG_SYSTEM_PROCESS;
10475 }
10476 if (r.app != null && r.app.persistent) {
10477 info.flags |= ActivityManager.RunningServiceInfo.FLAG_PERSISTENT_PROCESS;
10478 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010479
10480 for (ArrayList<ConnectionRecord> connl : r.connections.values()) {
10481 for (int i=0; i<connl.size(); i++) {
10482 ConnectionRecord conn = connl.get(i);
10483 if (conn.clientLabel != 0) {
10484 info.clientPackage = conn.binding.client.info.packageName;
10485 info.clientLabel = conn.clientLabel;
10486 return info;
10487 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010488 }
10489 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010490 return info;
10491 }
10492
10493 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum,
10494 int flags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010495 enforceNotIsolatedCaller("getServices");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010496 synchronized (this) {
10497 ArrayList<ActivityManager.RunningServiceInfo> res
10498 = new ArrayList<ActivityManager.RunningServiceInfo>();
10499
Amith Yamasani742a6712011-05-04 14:49:28 -070010500 int userId = UserId.getUserId(Binder.getCallingUid());
10501 if (mServiceMap.getAllServices(userId).size() > 0) {
10502 Iterator<ServiceRecord> it
10503 = mServiceMap.getAllServices(userId).iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010504 while (it.hasNext() && res.size() < maxNum) {
10505 res.add(makeRunningServiceInfoLocked(it.next()));
10506 }
10507 }
10508
10509 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
10510 ServiceRecord r = mRestartingServices.get(i);
10511 ActivityManager.RunningServiceInfo info =
10512 makeRunningServiceInfoLocked(r);
10513 info.restarting = r.nextRestartTime;
10514 res.add(info);
10515 }
10516
10517 return res;
10518 }
10519 }
10520
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010521 public PendingIntent getRunningServiceControlPanel(ComponentName name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010522 enforceNotIsolatedCaller("getRunningServiceControlPanel");
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010523 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010524 int userId = UserId.getUserId(Binder.getCallingUid());
10525 ServiceRecord r = mServiceMap.getServiceByName(name, userId);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010526 if (r != null) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010527 for (ArrayList<ConnectionRecord> conn : r.connections.values()) {
10528 for (int i=0; i<conn.size(); i++) {
10529 if (conn.get(i).clientIntent != null) {
10530 return conn.get(i).clientIntent;
10531 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010532 }
10533 }
10534 }
10535 }
10536 return null;
10537 }
10538
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010539 private final ServiceRecord findServiceLocked(ComponentName name,
10540 IBinder token) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010541 ServiceRecord r = mServiceMap.getServiceByName(name, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010542 return r == token ? r : null;
10543 }
10544
10545 private final class ServiceLookupResult {
10546 final ServiceRecord record;
10547 final String permission;
10548
10549 ServiceLookupResult(ServiceRecord _record, String _permission) {
10550 record = _record;
10551 permission = _permission;
10552 }
10553 };
10554
10555 private ServiceLookupResult findServiceLocked(Intent service,
10556 String resolvedType) {
10557 ServiceRecord r = null;
10558 if (service.getComponent() != null) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010559 r = mServiceMap.getServiceByName(service.getComponent(), Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010560 }
10561 if (r == null) {
10562 Intent.FilterComparison filter = new Intent.FilterComparison(service);
Amith Yamasani742a6712011-05-04 14:49:28 -070010563 r = mServiceMap.getServiceByIntent(filter, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010564 }
10565
10566 if (r == null) {
10567 try {
10568 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070010569 AppGlobals.getPackageManager().resolveService(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010570 service, resolvedType, 0);
10571 ServiceInfo sInfo =
10572 rInfo != null ? rInfo.serviceInfo : null;
10573 if (sInfo == null) {
10574 return null;
10575 }
10576
10577 ComponentName name = new ComponentName(
10578 sInfo.applicationInfo.packageName, sInfo.name);
Amith Yamasani742a6712011-05-04 14:49:28 -070010579 r = mServiceMap.getServiceByName(name, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010580 } catch (RemoteException ex) {
10581 // pm is in same process, this will never happen.
10582 }
10583 }
10584 if (r != null) {
10585 int callingPid = Binder.getCallingPid();
10586 int callingUid = Binder.getCallingUid();
10587 if (checkComponentPermission(r.permission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010588 callingPid, callingUid, r.appInfo.uid, r.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010589 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010590 if (!r.exported) {
10591 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
10592 + " from pid=" + callingPid
10593 + ", uid=" + callingUid
10594 + " that is not exported from uid " + r.appInfo.uid);
10595 return new ServiceLookupResult(null, "not exported from uid "
10596 + r.appInfo.uid);
10597 }
Joe Onorato8a9b2202010-02-26 18:56:32 -080010598 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010599 + " from pid=" + callingPid
10600 + ", uid=" + callingUid
10601 + " requires " + r.permission);
10602 return new ServiceLookupResult(null, r.permission);
10603 }
10604 return new ServiceLookupResult(r, null);
10605 }
10606 return null;
10607 }
10608
10609 private class ServiceRestarter implements Runnable {
10610 private ServiceRecord mService;
10611
10612 void setService(ServiceRecord service) {
10613 mService = service;
10614 }
10615
10616 public void run() {
10617 synchronized(ActivityManagerService.this) {
10618 performServiceRestartLocked(mService);
10619 }
10620 }
10621 }
10622
10623 private ServiceLookupResult retrieveServiceLocked(Intent service,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010624 String resolvedType, int callingPid, int callingUid, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010625 ServiceRecord r = null;
Amith Yamasani742a6712011-05-04 14:49:28 -070010626 if (DEBUG_SERVICE)
10627 Slog.v(TAG, "retrieveServiceLocked: " + service + " type=" + resolvedType
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010628 + " callingUid=" + callingUid);
Amith Yamasani742a6712011-05-04 14:49:28 -070010629
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010630 if (service.getComponent() != null) {
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010631 r = mServiceMap.getServiceByName(service.getComponent(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010632 }
Amith Yamasani742a6712011-05-04 14:49:28 -070010633 if (r == null) {
10634 Intent.FilterComparison filter = new Intent.FilterComparison(service);
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010635 r = mServiceMap.getServiceByIntent(filter, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -070010636 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010637 if (r == null) {
10638 try {
10639 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070010640 AppGlobals.getPackageManager().resolveService(
Dianne Hackborn1655be42009-05-08 14:29:01 -070010641 service, resolvedType, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010642 ServiceInfo sInfo =
10643 rInfo != null ? rInfo.serviceInfo : null;
10644 if (sInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010645 Slog.w(TAG, "Unable to start service " + service +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010646 ": not found");
10647 return null;
10648 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010649 if (userId > 0) {
10650 sInfo.applicationInfo = getAppInfoForUser(sInfo.applicationInfo, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -070010651 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010652 ComponentName name = new ComponentName(
10653 sInfo.applicationInfo.packageName, sInfo.name);
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010654 r = mServiceMap.getServiceByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010655 if (r == null) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010656 Intent.FilterComparison filter = new Intent.FilterComparison(
10657 service.cloneFilter());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010658 ServiceRestarter res = new ServiceRestarter();
10659 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
10660 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
10661 synchronized (stats) {
10662 ss = stats.getServiceStatsLocked(
10663 sInfo.applicationInfo.uid, sInfo.packageName,
10664 sInfo.name);
10665 }
Dianne Hackbornb1c4a2a2010-01-19 15:36:42 -080010666 r = new ServiceRecord(this, ss, name, filter, sInfo, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010667 res.setService(r);
Amith Yamasani742a6712011-05-04 14:49:28 -070010668 mServiceMap.putServiceByName(name, UserId.getUserId(r.appInfo.uid), r);
10669 mServiceMap.putServiceByIntent(filter, UserId.getUserId(r.appInfo.uid), r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010670
10671 // Make sure this component isn't in the pending list.
10672 int N = mPendingServices.size();
10673 for (int i=0; i<N; i++) {
10674 ServiceRecord pr = mPendingServices.get(i);
10675 if (pr.name.equals(name)) {
10676 mPendingServices.remove(i);
10677 i--;
10678 N--;
10679 }
10680 }
10681 }
10682 } catch (RemoteException ex) {
10683 // pm is in same process, this will never happen.
10684 }
10685 }
10686 if (r != null) {
10687 if (checkComponentPermission(r.permission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010688 callingPid, callingUid, r.appInfo.uid, r.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010689 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010690 if (!r.exported) {
10691 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
10692 + " from pid=" + callingPid
10693 + ", uid=" + callingUid
10694 + " that is not exported from uid " + r.appInfo.uid);
10695 return new ServiceLookupResult(null, "not exported from uid "
10696 + r.appInfo.uid);
10697 }
Joe Onorato8a9b2202010-02-26 18:56:32 -080010698 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010699 + " from pid=" + callingPid
10700 + ", uid=" + callingUid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010701 + " requires " + r.permission);
10702 return new ServiceLookupResult(null, r.permission);
10703 }
10704 return new ServiceLookupResult(r, null);
10705 }
10706 return null;
10707 }
10708
Dianne Hackborn287952c2010-09-22 22:34:31 -070010709 private final void bumpServiceExecutingLocked(ServiceRecord r, String why) {
10710 if (DEBUG_SERVICE) Log.v(TAG, ">>> EXECUTING "
10711 + why + " of " + r + " in app " + r.app);
10712 else if (DEBUG_SERVICE_EXECUTING) Log.v(TAG, ">>> EXECUTING "
10713 + why + " of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010714 long now = SystemClock.uptimeMillis();
10715 if (r.executeNesting == 0 && r.app != null) {
10716 if (r.app.executingServices.size() == 0) {
10717 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
10718 msg.obj = r.app;
10719 mHandler.sendMessageAtTime(msg, now+SERVICE_TIMEOUT);
10720 }
10721 r.app.executingServices.add(r);
10722 }
10723 r.executeNesting++;
10724 r.executingStart = now;
10725 }
10726
10727 private final void sendServiceArgsLocked(ServiceRecord r,
10728 boolean oomAdjusted) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010729 final int N = r.pendingStarts.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010730 if (N == 0) {
10731 return;
10732 }
10733
Dianne Hackborn39792d22010-08-19 18:01:52 -070010734 while (r.pendingStarts.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010735 try {
Dianne Hackborn39792d22010-08-19 18:01:52 -070010736 ServiceRecord.StartItem si = r.pendingStarts.remove(0);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010737 if (DEBUG_SERVICE) Slog.v(TAG, "Sending arguments to: "
10738 + r + " " + r.intent + " args=" + si.intent);
Dianne Hackborn3a28f222011-03-01 12:25:54 -080010739 if (si.intent == null && N > 1) {
10740 // If somehow we got a dummy null intent in the middle,
10741 // then skip it. DO NOT skip a null intent when it is
10742 // the only one in the list -- this is to support the
10743 // onStartCommand(null) case.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010744 continue;
10745 }
Dianne Hackborn39792d22010-08-19 18:01:52 -070010746 si.deliveredTime = SystemClock.uptimeMillis();
10747 r.deliveredStarts.add(si);
10748 si.deliveryCount++;
Dianne Hackborn21c241e2012-03-08 13:57:23 -080010749 if (si.neededGrants != null) {
10750 grantUriPermissionUncheckedFromIntentLocked(si.neededGrants,
10751 si.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -070010752 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070010753 bumpServiceExecutingLocked(r, "start");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010754 if (!oomAdjusted) {
10755 oomAdjusted = true;
10756 updateOomAdjLocked(r.app);
10757 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010758 int flags = 0;
10759 if (si.deliveryCount > 0) {
10760 flags |= Service.START_FLAG_RETRY;
10761 }
10762 if (si.doneExecutingCount > 0) {
10763 flags |= Service.START_FLAG_REDELIVERY;
10764 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070010765 r.app.thread.scheduleServiceArgs(r, si.taskRemoved, si.id, flags, si.intent);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010766 } catch (RemoteException e) {
10767 // Remote process gone... we'll let the normal cleanup take
10768 // care of this.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010769 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while scheduling start: " + r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010770 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010771 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010772 Slog.w(TAG, "Unexpected exception", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010773 break;
10774 }
10775 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010776 }
10777
10778 private final boolean requestServiceBindingLocked(ServiceRecord r,
10779 IntentBindRecord i, boolean rebind) {
10780 if (r.app == null || r.app.thread == null) {
10781 // If service is not currently running, can't yet bind.
10782 return false;
10783 }
10784 if ((!i.requested || rebind) && i.apps.size() > 0) {
10785 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070010786 bumpServiceExecutingLocked(r, "bind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010787 r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind);
10788 if (!rebind) {
10789 i.requested = true;
10790 }
10791 i.hasBound = true;
10792 i.doRebind = false;
10793 } catch (RemoteException e) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010794 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while binding " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010795 return false;
10796 }
10797 }
10798 return true;
10799 }
10800
10801 private final void requestServiceBindingsLocked(ServiceRecord r) {
10802 Iterator<IntentBindRecord> bindings = r.bindings.values().iterator();
10803 while (bindings.hasNext()) {
10804 IntentBindRecord i = bindings.next();
10805 if (!requestServiceBindingLocked(r, i, false)) {
10806 break;
10807 }
10808 }
10809 }
10810
10811 private final void realStartServiceLocked(ServiceRecord r,
10812 ProcessRecord app) throws RemoteException {
10813 if (app.thread == null) {
10814 throw new RemoteException();
10815 }
Amith Yamasani742a6712011-05-04 14:49:28 -070010816 if (DEBUG_MU)
10817 Slog.v(TAG_MU, "realStartServiceLocked, ServiceRecord.uid = " + r.appInfo.uid
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010818 + ", ProcessRecord.uid = " + app.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010819 r.app = app;
The Android Open Source Project10592532009-03-18 17:39:46 -070010820 r.restartTime = r.lastActivity = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010821
10822 app.services.add(r);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010823 bumpServiceExecutingLocked(r, "create");
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010824 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010825
10826 boolean created = false;
10827 try {
Dianne Hackborna33e3f72009-09-29 17:28:24 -070010828 mStringBuilder.setLength(0);
Dianne Hackborn21c241e2012-03-08 13:57:23 -080010829 r.intent.getIntent().toShortString(mStringBuilder, true, false, true, false);
Doug Zongker2bec3d42009-12-04 12:52:44 -080010830 EventLog.writeEvent(EventLogTags.AM_CREATE_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010831 System.identityHashCode(r), r.shortName,
Dianne Hackborna33e3f72009-09-29 17:28:24 -070010832 mStringBuilder.toString(), r.app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010833 synchronized (r.stats.getBatteryStats()) {
10834 r.stats.startLaunchedLocked();
10835 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -070010836 ensurePackageDexOpt(r.serviceInfo.packageName);
Dianne Hackborne2515ee2011-04-27 18:52:56 -040010837 app.thread.scheduleCreateService(r, r.serviceInfo,
10838 compatibilityInfoForPackageLocked(r.serviceInfo.applicationInfo));
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070010839 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010840 created = true;
10841 } finally {
10842 if (!created) {
10843 app.services.remove(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010844 scheduleServiceRestartLocked(r, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010845 }
10846 }
10847
10848 requestServiceBindingsLocked(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010849
10850 // If the service is in the started state, and there are no
10851 // pending arguments, then fake up one so its onStartCommand() will
10852 // be called.
10853 if (r.startRequested && r.callStart && r.pendingStarts.size() == 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070010854 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Dianne Hackborn21c241e2012-03-08 13:57:23 -080010855 null, null));
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010856 }
10857
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010858 sendServiceArgsLocked(r, true);
10859 }
10860
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010861 private final boolean scheduleServiceRestartLocked(ServiceRecord r,
10862 boolean allowCancel) {
10863 boolean canceled = false;
10864
Dianne Hackbornfd12af42009-08-27 00:44:33 -070010865 final long now = SystemClock.uptimeMillis();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010866 long minDuration = SERVICE_RESTART_DURATION;
Dianne Hackborn6ccd2af2009-08-27 12:26:44 -070010867 long resetTime = SERVICE_RESET_RUN_DURATION;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010868
Dianne Hackborn070783f2010-12-29 16:46:28 -080010869 if ((r.serviceInfo.applicationInfo.flags
10870 &ApplicationInfo.FLAG_PERSISTENT) != 0) {
10871 minDuration /= 4;
10872 }
10873
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010874 // Any delivered but not yet finished starts should be put back
10875 // on the pending list.
10876 final int N = r.deliveredStarts.size();
10877 if (N > 0) {
10878 for (int i=N-1; i>=0; i--) {
10879 ServiceRecord.StartItem si = r.deliveredStarts.get(i);
Dianne Hackborn39792d22010-08-19 18:01:52 -070010880 si.removeUriPermissionsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010881 if (si.intent == null) {
10882 // We'll generate this again if needed.
10883 } else if (!allowCancel || (si.deliveryCount < ServiceRecord.MAX_DELIVERY_COUNT
10884 && si.doneExecutingCount < ServiceRecord.MAX_DONE_EXECUTING_COUNT)) {
10885 r.pendingStarts.add(0, si);
10886 long dur = SystemClock.uptimeMillis() - si.deliveredTime;
10887 dur *= 2;
10888 if (minDuration < dur) minDuration = dur;
10889 if (resetTime < dur) resetTime = dur;
10890 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010891 Slog.w(TAG, "Canceling start item " + si.intent + " in service "
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010892 + r.name);
10893 canceled = true;
10894 }
10895 }
10896 r.deliveredStarts.clear();
10897 }
10898
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010899 r.totalRestartCount++;
10900 if (r.restartDelay == 0) {
10901 r.restartCount++;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010902 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010903 } else {
10904 // If it has been a "reasonably long time" since the service
10905 // was started, then reset our restart duration back to
10906 // the beginning, so we don't infinitely increase the duration
10907 // on a service that just occasionally gets killed (which is
10908 // a normal case, due to process being killed to reclaim memory).
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010909 if (now > (r.restartTime+resetTime)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010910 r.restartCount = 1;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010911 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010912 } else {
Dianne Hackborn070783f2010-12-29 16:46:28 -080010913 if ((r.serviceInfo.applicationInfo.flags
10914 &ApplicationInfo.FLAG_PERSISTENT) != 0) {
10915 // Services in peristent processes will restart much more
10916 // quickly, since they are pretty important. (Think SystemUI).
10917 r.restartDelay += minDuration/2;
10918 } else {
10919 r.restartDelay *= SERVICE_RESTART_DURATION_FACTOR;
10920 if (r.restartDelay < minDuration) {
10921 r.restartDelay = minDuration;
10922 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010923 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010924 }
10925 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070010926
10927 r.nextRestartTime = now + r.restartDelay;
10928
10929 // Make sure that we don't end up restarting a bunch of services
10930 // all at the same time.
10931 boolean repeat;
10932 do {
10933 repeat = false;
10934 for (int i=mRestartingServices.size()-1; i>=0; i--) {
10935 ServiceRecord r2 = mRestartingServices.get(i);
10936 if (r2 != r && r.nextRestartTime
10937 >= (r2.nextRestartTime-SERVICE_MIN_RESTART_TIME_BETWEEN)
10938 && r.nextRestartTime
10939 < (r2.nextRestartTime+SERVICE_MIN_RESTART_TIME_BETWEEN)) {
10940 r.nextRestartTime = r2.nextRestartTime + SERVICE_MIN_RESTART_TIME_BETWEEN;
10941 r.restartDelay = r.nextRestartTime - now;
10942 repeat = true;
10943 break;
10944 }
10945 }
10946 } while (repeat);
10947
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010948 if (!mRestartingServices.contains(r)) {
10949 mRestartingServices.add(r);
10950 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070010951
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070010952 r.cancelNotification();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010953
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010954 mHandler.removeCallbacks(r.restarter);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070010955 mHandler.postAtTime(r.restarter, r.nextRestartTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010956 r.nextRestartTime = SystemClock.uptimeMillis() + r.restartDelay;
Joe Onorato8a9b2202010-02-26 18:56:32 -080010957 Slog.w(TAG, "Scheduling restart of crashed service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010958 + r.shortName + " in " + r.restartDelay + "ms");
Doug Zongker2bec3d42009-12-04 12:52:44 -080010959 EventLog.writeEvent(EventLogTags.AM_SCHEDULE_SERVICE_RESTART,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010960 r.shortName, r.restartDelay);
10961
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010962 return canceled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010963 }
10964
10965 final void performServiceRestartLocked(ServiceRecord r) {
10966 if (!mRestartingServices.contains(r)) {
10967 return;
10968 }
10969 bringUpServiceLocked(r, r.intent.getIntent().getFlags(), true);
10970 }
10971
10972 private final boolean unscheduleServiceRestartLocked(ServiceRecord r) {
10973 if (r.restartDelay == 0) {
10974 return false;
10975 }
10976 r.resetRestartCounter();
10977 mRestartingServices.remove(r);
10978 mHandler.removeCallbacks(r.restarter);
10979 return true;
10980 }
10981
10982 private final boolean bringUpServiceLocked(ServiceRecord r,
10983 int intentFlags, boolean whileRestarting) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010984 //Slog.i(TAG, "Bring up service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010985 //r.dump(" ");
10986
Dianne Hackborn36124872009-10-08 16:22:03 -070010987 if (r.app != null && r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010988 sendServiceArgsLocked(r, false);
10989 return true;
10990 }
10991
10992 if (!whileRestarting && r.restartDelay > 0) {
10993 // If waiting for a restart, then do nothing.
10994 return true;
10995 }
10996
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010997 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing up " + r + " " + r.intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010998
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010999 // We are now bringing the service up, so no longer in the
11000 // restarting state.
11001 mRestartingServices.remove(r);
11002
Dianne Hackborne7f97212011-02-24 14:40:20 -080011003 // Service is now being launched, its package can't be stopped.
11004 try {
11005 AppGlobals.getPackageManager().setPackageStoppedState(
11006 r.packageName, false);
11007 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080011008 } catch (IllegalArgumentException e) {
11009 Slog.w(TAG, "Failed trying to unstop package "
11010 + r.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080011011 }
11012
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011013 final boolean isolated = (r.serviceInfo.flags&ServiceInfo.FLAG_ISOLATED_PROCESS) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011014 final String appName = r.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011015 ProcessRecord app;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011016
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011017 if (!isolated) {
11018 app = getProcessRecordLocked(appName, r.appInfo.uid);
11019 if (DEBUG_MU)
11020 Slog.v(TAG_MU, "bringUpServiceLocked: appInfo.uid=" + r.appInfo.uid + " app=" + app);
11021 if (app != null && app.thread != null) {
11022 try {
11023 app.addPackage(r.appInfo.packageName);
11024 realStartServiceLocked(r, app);
11025 return true;
11026 } catch (RemoteException e) {
11027 Slog.w(TAG, "Exception when starting service " + r.shortName, e);
11028 }
11029
11030 // If a dead object exception was thrown -- fall through to
11031 // restart the application.
11032 }
11033 } else {
11034 // If this service runs in an isolated process, then each time
11035 // we call startProcessLocked() we will get a new isolated
11036 // process, starting another process if we are currently waiting
11037 // for a previous process to come up. To deal with this, we store
11038 // in the service any current isolated process it is running in or
11039 // waiting to have come up.
11040 app = r.isolatedProc;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011041 }
11042
Dianne Hackborn36124872009-10-08 16:22:03 -070011043 // Not running -- get it started, and enqueue this service record
11044 // to be executed when the app comes up.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011045 if (app == null) {
11046 if ((app=startProcessLocked(appName, r.appInfo, true, intentFlags,
11047 "service", r.name, false, isolated)) == null) {
11048 Slog.w(TAG, "Unable to launch app "
11049 + r.appInfo.packageName + "/"
11050 + r.appInfo.uid + " for service "
11051 + r.intent.getIntent() + ": process is bad");
11052 bringDownServiceLocked(r, true);
11053 return false;
11054 }
11055 if (isolated) {
11056 r.isolatedProc = app;
11057 }
Dianne Hackborn36124872009-10-08 16:22:03 -070011058 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011059
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011060 if (!mPendingServices.contains(r)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011061 mPendingServices.add(r);
11062 }
Dianne Hackborn36124872009-10-08 16:22:03 -070011063
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011064 return true;
11065 }
11066
11067 private final void bringDownServiceLocked(ServiceRecord r, boolean force) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011068 //Slog.i(TAG, "Bring down service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011069 //r.dump(" ");
11070
11071 // Does it still need to run?
11072 if (!force && r.startRequested) {
11073 return;
11074 }
11075 if (r.connections.size() > 0) {
11076 if (!force) {
11077 // XXX should probably keep a count of the number of auto-create
11078 // connections directly in the service.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011079 Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011080 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011081 ArrayList<ConnectionRecord> cr = it.next();
11082 for (int i=0; i<cr.size(); i++) {
11083 if ((cr.get(i).flags&Context.BIND_AUTO_CREATE) != 0) {
11084 return;
11085 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011086 }
11087 }
11088 }
11089
11090 // Report to all of the connections that the service is no longer
11091 // available.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011092 Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011093 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011094 ArrayList<ConnectionRecord> c = it.next();
11095 for (int i=0; i<c.size(); i++) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011096 ConnectionRecord cr = c.get(i);
11097 // There is still a connection to the service that is
11098 // being brought down. Mark it as dead.
11099 cr.serviceDead = true;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011100 try {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011101 cr.conn.connected(r.name, null);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011102 } catch (Exception e) {
11103 Slog.w(TAG, "Failure disconnecting service " + r.name +
11104 " to connection " + c.get(i).conn.asBinder() +
11105 " (in " + c.get(i).binding.client.processName + ")", e);
11106 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011107 }
11108 }
11109 }
11110
11111 // Tell the service that it has been unbound.
11112 if (r.bindings.size() > 0 && r.app != null && r.app.thread != null) {
11113 Iterator<IntentBindRecord> it = r.bindings.values().iterator();
11114 while (it.hasNext()) {
11115 IntentBindRecord ibr = it.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -080011116 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down binding " + ibr
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011117 + ": hasBound=" + ibr.hasBound);
11118 if (r.app != null && r.app.thread != null && ibr.hasBound) {
11119 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011120 bumpServiceExecutingLocked(r, "bring down unbind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011121 updateOomAdjLocked(r.app);
11122 ibr.hasBound = false;
11123 r.app.thread.scheduleUnbindService(r,
11124 ibr.intent.getIntent());
11125 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011126 Slog.w(TAG, "Exception when unbinding service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011127 + r.shortName, e);
11128 serviceDoneExecutingLocked(r, true);
11129 }
11130 }
11131 }
11132 }
11133
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011134 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down " + r + " " + r.intent);
Doug Zongker2bec3d42009-12-04 12:52:44 -080011135 EventLog.writeEvent(EventLogTags.AM_DESTROY_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011136 System.identityHashCode(r), r.shortName,
11137 (r.app != null) ? r.app.pid : -1);
11138
Amith Yamasani742a6712011-05-04 14:49:28 -070011139 mServiceMap.removeServiceByName(r.name, r.userId);
11140 mServiceMap.removeServiceByIntent(r.intent, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011141 r.totalRestartCount = 0;
11142 unscheduleServiceRestartLocked(r);
11143
11144 // Also make sure it is not on the pending list.
11145 int N = mPendingServices.size();
11146 for (int i=0; i<N; i++) {
11147 if (mPendingServices.get(i) == r) {
11148 mPendingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011149 if (DEBUG_SERVICE) Slog.v(TAG, "Removed pending: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011150 i--;
11151 N--;
11152 }
11153 }
11154
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011155 r.cancelNotification();
11156 r.isForeground = false;
11157 r.foregroundId = 0;
11158 r.foregroundNoti = null;
11159
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011160 // Clear start entries.
Dianne Hackborn39792d22010-08-19 18:01:52 -070011161 r.clearDeliveredStartsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011162 r.pendingStarts.clear();
11163
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011164 if (r.app != null) {
11165 synchronized (r.stats.getBatteryStats()) {
11166 r.stats.stopLaunchedLocked();
11167 }
11168 r.app.services.remove(r);
11169 if (r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011170 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011171 bumpServiceExecutingLocked(r, "stop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011172 mStoppingServices.add(r);
11173 updateOomAdjLocked(r.app);
11174 r.app.thread.scheduleStopService(r);
11175 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011176 Slog.w(TAG, "Exception when stopping service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011177 + r.shortName, e);
11178 serviceDoneExecutingLocked(r, true);
11179 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011180 updateServiceForegroundLocked(r.app, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011181 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011182 if (DEBUG_SERVICE) Slog.v(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011183 TAG, "Removed service that has no process: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011184 }
11185 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011186 if (DEBUG_SERVICE) Slog.v(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011187 TAG, "Removed service that is not running: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011188 }
Vairavan Srinivasana207ce22010-12-23 13:51:48 -080011189
11190 if (r.bindings.size() > 0) {
11191 r.bindings.clear();
11192 }
11193
11194 if (r.restarter instanceof ServiceRestarter) {
11195 ((ServiceRestarter)r.restarter).setService(null);
11196 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011197 }
11198
11199 ComponentName startServiceLocked(IApplicationThread caller,
11200 Intent service, String resolvedType,
11201 int callingPid, int callingUid) {
11202 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011203 if (DEBUG_SERVICE) Slog.v(TAG, "startService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011204 + " type=" + resolvedType + " args=" + service.getExtras());
11205
11206 if (caller != null) {
11207 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11208 if (callerApp == null) {
11209 throw new SecurityException(
11210 "Unable to find app for caller " + caller
11211 + " (pid=" + Binder.getCallingPid()
11212 + ") when starting service " + service);
11213 }
11214 }
11215
11216 ServiceLookupResult res =
11217 retrieveServiceLocked(service, resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011218 callingPid, callingUid, UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011219 if (res == null) {
11220 return null;
11221 }
11222 if (res.record == null) {
11223 return new ComponentName("!", res.permission != null
11224 ? res.permission : "private to package");
11225 }
11226 ServiceRecord r = res.record;
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011227 NeededUriGrants neededGrants = checkGrantUriPermissionFromIntentLocked(
11228 callingUid, r.packageName, service, service.getFlags(), null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011229 if (unscheduleServiceRestartLocked(r)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011230 if (DEBUG_SERVICE) Slog.v(TAG, "START SERVICE WHILE RESTART PENDING: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011231 }
11232 r.startRequested = true;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011233 r.callStart = false;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011234 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011235 service, neededGrants));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011236 r.lastActivity = SystemClock.uptimeMillis();
11237 synchronized (r.stats.getBatteryStats()) {
11238 r.stats.startRunningLocked();
11239 }
11240 if (!bringUpServiceLocked(r, service.getFlags(), false)) {
11241 return new ComponentName("!", "Service process is bad");
11242 }
11243 return r.name;
11244 }
11245 }
11246
11247 public ComponentName startService(IApplicationThread caller, Intent service,
11248 String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011249 enforceNotIsolatedCaller("startService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011250 // Refuse possible leaked file descriptors
11251 if (service != null && service.hasFileDescriptors() == true) {
11252 throw new IllegalArgumentException("File descriptors passed in Intent");
11253 }
11254
Amith Yamasani742a6712011-05-04 14:49:28 -070011255 if (DEBUG_SERVICE)
11256 Slog.v(TAG, "startService: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011257 synchronized(this) {
11258 final int callingPid = Binder.getCallingPid();
11259 final int callingUid = Binder.getCallingUid();
11260 final long origId = Binder.clearCallingIdentity();
11261 ComponentName res = startServiceLocked(caller, service,
11262 resolvedType, callingPid, callingUid);
11263 Binder.restoreCallingIdentity(origId);
11264 return res;
11265 }
11266 }
11267
11268 ComponentName startServiceInPackage(int uid,
11269 Intent service, String resolvedType) {
11270 synchronized(this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070011271 if (DEBUG_SERVICE)
11272 Slog.v(TAG, "startServiceInPackage: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011273 final long origId = Binder.clearCallingIdentity();
11274 ComponentName res = startServiceLocked(null, service,
11275 resolvedType, -1, uid);
11276 Binder.restoreCallingIdentity(origId);
11277 return res;
11278 }
11279 }
11280
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011281 private void stopServiceLocked(ServiceRecord service) {
11282 synchronized (service.stats.getBatteryStats()) {
11283 service.stats.stopRunningLocked();
11284 }
11285 service.startRequested = false;
11286 service.callStart = false;
11287 bringDownServiceLocked(service, false);
11288 }
11289
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011290 public int stopService(IApplicationThread caller, Intent service,
11291 String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011292 enforceNotIsolatedCaller("stopService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011293 // Refuse possible leaked file descriptors
11294 if (service != null && service.hasFileDescriptors() == true) {
11295 throw new IllegalArgumentException("File descriptors passed in Intent");
11296 }
11297
11298 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011299 if (DEBUG_SERVICE) Slog.v(TAG, "stopService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011300 + " type=" + resolvedType);
11301
11302 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11303 if (caller != null && callerApp == null) {
11304 throw new SecurityException(
11305 "Unable to find app for caller " + caller
11306 + " (pid=" + Binder.getCallingPid()
11307 + ") when stopping service " + service);
11308 }
11309
11310 // If this service is active, make sure it is stopped.
11311 ServiceLookupResult r = findServiceLocked(service, resolvedType);
11312 if (r != null) {
11313 if (r.record != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011314 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011315 try {
11316 stopServiceLocked(r.record);
11317 } finally {
11318 Binder.restoreCallingIdentity(origId);
11319 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011320 return 1;
11321 }
11322 return -1;
11323 }
11324 }
11325
11326 return 0;
11327 }
11328
11329 public IBinder peekService(Intent service, String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011330 enforceNotIsolatedCaller("peekService");
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 IBinder ret = null;
11337
11338 synchronized(this) {
11339 ServiceLookupResult r = findServiceLocked(service, resolvedType);
11340
11341 if (r != null) {
11342 // r.record is null if findServiceLocked() failed the caller permission check
11343 if (r.record == null) {
11344 throw new SecurityException(
11345 "Permission Denial: Accessing service " + r.record.name
11346 + " from pid=" + Binder.getCallingPid()
11347 + ", uid=" + Binder.getCallingUid()
11348 + " requires " + r.permission);
11349 }
11350 IntentBindRecord ib = r.record.bindings.get(r.record.intent);
11351 if (ib != null) {
11352 ret = ib.binder;
11353 }
11354 }
11355 }
11356
11357 return ret;
11358 }
11359
11360 public boolean stopServiceToken(ComponentName className, IBinder token,
11361 int startId) {
11362 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011363 if (DEBUG_SERVICE) Slog.v(TAG, "stopServiceToken: " + className
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011364 + " " + token + " startId=" + startId);
11365 ServiceRecord r = findServiceLocked(className, token);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011366 if (r != null) {
11367 if (startId >= 0) {
11368 // Asked to only stop if done with all work. Note that
11369 // to avoid leaks, we will take this as dropping all
11370 // start items up to and including this one.
11371 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
11372 if (si != null) {
11373 while (r.deliveredStarts.size() > 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -070011374 ServiceRecord.StartItem cur = r.deliveredStarts.remove(0);
11375 cur.removeUriPermissionsLocked();
11376 if (cur == si) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011377 break;
11378 }
11379 }
11380 }
11381
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011382 if (r.getLastStartId() != startId) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011383 return false;
11384 }
11385
11386 if (r.deliveredStarts.size() > 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011387 Slog.w(TAG, "stopServiceToken startId " + startId
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011388 + " is last, but have " + r.deliveredStarts.size()
11389 + " remaining args");
11390 }
11391 }
11392
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011393 synchronized (r.stats.getBatteryStats()) {
11394 r.stats.stopRunningLocked();
11395 r.startRequested = false;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011396 r.callStart = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011397 }
11398 final long origId = Binder.clearCallingIdentity();
11399 bringDownServiceLocked(r, false);
11400 Binder.restoreCallingIdentity(origId);
11401 return true;
11402 }
11403 }
11404 return false;
11405 }
11406
11407 public void setServiceForeground(ComponentName className, IBinder token,
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011408 int id, Notification notification, boolean removeNotification) {
11409 final long origId = Binder.clearCallingIdentity();
11410 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011411 synchronized(this) {
11412 ServiceRecord r = findServiceLocked(className, token);
11413 if (r != null) {
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011414 if (id != 0) {
11415 if (notification == null) {
11416 throw new IllegalArgumentException("null notification");
11417 }
11418 if (r.foregroundId != id) {
11419 r.cancelNotification();
11420 r.foregroundId = id;
11421 }
11422 notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
11423 r.foregroundNoti = notification;
11424 r.isForeground = true;
11425 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011426 if (r.app != null) {
11427 updateServiceForegroundLocked(r.app, true);
11428 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011429 } else {
11430 if (r.isForeground) {
11431 r.isForeground = false;
11432 if (r.app != null) {
Dianne Hackborn8633e682010-04-22 16:03:41 -070011433 updateLruProcessLocked(r.app, false, true);
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011434 updateServiceForegroundLocked(r.app, true);
11435 }
11436 }
11437 if (removeNotification) {
11438 r.cancelNotification();
11439 r.foregroundId = 0;
11440 r.foregroundNoti = null;
11441 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011442 }
11443 }
11444 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011445 } finally {
11446 Binder.restoreCallingIdentity(origId);
11447 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011448 }
11449
11450 public void updateServiceForegroundLocked(ProcessRecord proc, boolean oomAdj) {
11451 boolean anyForeground = false;
Dianne Hackborn860755f2010-06-03 18:47:52 -070011452 for (ServiceRecord sr : proc.services) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011453 if (sr.isForeground) {
11454 anyForeground = true;
11455 break;
11456 }
11457 }
11458 if (anyForeground != proc.foregroundServices) {
11459 proc.foregroundServices = anyForeground;
11460 if (oomAdj) {
11461 updateOomAdjLocked();
11462 }
11463 }
11464 }
11465
11466 public int bindService(IApplicationThread caller, IBinder token,
11467 Intent service, String resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011468 IServiceConnection connection, int flags, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011469 enforceNotIsolatedCaller("bindService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011470 // Refuse possible leaked file descriptors
11471 if (service != null && service.hasFileDescriptors() == true) {
11472 throw new IllegalArgumentException("File descriptors passed in Intent");
11473 }
11474
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011475 checkValidCaller(Binder.getCallingUid(), userId);
11476
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011477 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011478 if (DEBUG_SERVICE) Slog.v(TAG, "bindService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011479 + " type=" + resolvedType + " conn=" + connection.asBinder()
11480 + " flags=0x" + Integer.toHexString(flags));
Amith Yamasani742a6712011-05-04 14:49:28 -070011481 if (DEBUG_MU)
11482 Slog.i(TAG_MU, "bindService uid=" + Binder.getCallingUid() + " origUid="
11483 + Binder.getOrigCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011484 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11485 if (callerApp == null) {
11486 throw new SecurityException(
11487 "Unable to find app for caller " + caller
11488 + " (pid=" + Binder.getCallingPid()
11489 + ") when binding service " + service);
11490 }
11491
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011492 ActivityRecord activity = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011493 if (token != null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070011494 activity = mMainStack.isInStackLocked(token);
11495 if (activity == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011496 Slog.w(TAG, "Binding with unknown activity: " + token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011497 return 0;
11498 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011499 }
11500
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011501 int clientLabel = 0;
11502 PendingIntent clientIntent = null;
11503
11504 if (callerApp.info.uid == Process.SYSTEM_UID) {
11505 // Hacky kind of thing -- allow system stuff to tell us
11506 // what they are, so we can report this elsewhere for
11507 // others to know why certain services are running.
11508 try {
11509 clientIntent = (PendingIntent)service.getParcelableExtra(
11510 Intent.EXTRA_CLIENT_INTENT);
11511 } catch (RuntimeException e) {
11512 }
11513 if (clientIntent != null) {
11514 clientLabel = service.getIntExtra(Intent.EXTRA_CLIENT_LABEL, 0);
11515 if (clientLabel != 0) {
11516 // There are no useful extras in the intent, trash them.
11517 // System code calling with this stuff just needs to know
11518 // this will happen.
11519 service = service.cloneFilter();
11520 }
11521 }
11522 }
11523
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011524 ServiceLookupResult res =
11525 retrieveServiceLocked(service, resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011526 Binder.getCallingPid(), Binder.getCallingUid(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011527 if (res == null) {
11528 return 0;
11529 }
11530 if (res.record == null) {
11531 return -1;
11532 }
11533 ServiceRecord s = res.record;
11534
11535 final long origId = Binder.clearCallingIdentity();
11536
11537 if (unscheduleServiceRestartLocked(s)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011538 if (DEBUG_SERVICE) Slog.v(TAG, "BIND SERVICE WHILE RESTART PENDING: "
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011539 + s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011540 }
11541
11542 AppBindRecord b = s.retrieveAppBindingLocked(service, callerApp);
11543 ConnectionRecord c = new ConnectionRecord(b, activity,
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011544 connection, flags, clientLabel, clientIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011545
11546 IBinder binder = connection.asBinder();
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011547 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
11548 if (clist == null) {
11549 clist = new ArrayList<ConnectionRecord>();
11550 s.connections.put(binder, clist);
11551 }
11552 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011553 b.connections.add(c);
11554 if (activity != null) {
11555 if (activity.connections == null) {
11556 activity.connections = new HashSet<ConnectionRecord>();
11557 }
11558 activity.connections.add(c);
11559 }
11560 b.client.connections.add(c);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070011561 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
11562 b.client.hasAboveClient = true;
11563 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011564 clist = mServiceConnections.get(binder);
11565 if (clist == null) {
11566 clist = new ArrayList<ConnectionRecord>();
11567 mServiceConnections.put(binder, clist);
11568 }
11569 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011570
11571 if ((flags&Context.BIND_AUTO_CREATE) != 0) {
11572 s.lastActivity = SystemClock.uptimeMillis();
11573 if (!bringUpServiceLocked(s, service.getFlags(), false)) {
11574 return 0;
11575 }
11576 }
11577
11578 if (s.app != null) {
11579 // This could have made the service more important.
11580 updateOomAdjLocked(s.app);
11581 }
11582
Joe Onorato8a9b2202010-02-26 18:56:32 -080011583 if (DEBUG_SERVICE) Slog.v(TAG, "Bind " + s + " with " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011584 + ": received=" + b.intent.received
11585 + " apps=" + b.intent.apps.size()
11586 + " doRebind=" + b.intent.doRebind);
11587
11588 if (s.app != null && b.intent.received) {
11589 // Service is already running, so we can immediately
11590 // publish the connection.
11591 try {
11592 c.conn.connected(s.name, b.intent.binder);
11593 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011594 Slog.w(TAG, "Failure sending service " + s.shortName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011595 + " to connection " + c.conn.asBinder()
11596 + " (in " + c.binding.client.processName + ")", e);
11597 }
11598
11599 // If this is the first app connected back to this binding,
11600 // and the service had previously asked to be told when
11601 // rebound, then do so.
11602 if (b.intent.apps.size() == 1 && b.intent.doRebind) {
11603 requestServiceBindingLocked(s, b.intent, true);
11604 }
11605 } else if (!b.intent.requested) {
11606 requestServiceBindingLocked(s, b.intent, false);
11607 }
11608
11609 Binder.restoreCallingIdentity(origId);
11610 }
11611
11612 return 1;
11613 }
11614
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070011615 void removeConnectionLocked(
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011616 ConnectionRecord c, ProcessRecord skipApp, ActivityRecord skipAct) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011617 IBinder binder = c.conn.asBinder();
11618 AppBindRecord b = c.binding;
11619 ServiceRecord s = b.service;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011620 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
11621 if (clist != null) {
11622 clist.remove(c);
11623 if (clist.size() == 0) {
11624 s.connections.remove(binder);
11625 }
11626 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011627 b.connections.remove(c);
11628 if (c.activity != null && c.activity != skipAct) {
11629 if (c.activity.connections != null) {
11630 c.activity.connections.remove(c);
11631 }
11632 }
11633 if (b.client != skipApp) {
11634 b.client.connections.remove(c);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070011635 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
11636 b.client.updateHasAboveClientLocked();
11637 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011638 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011639 clist = mServiceConnections.get(binder);
11640 if (clist != null) {
11641 clist.remove(c);
11642 if (clist.size() == 0) {
11643 mServiceConnections.remove(binder);
11644 }
11645 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011646
11647 if (b.connections.size() == 0) {
11648 b.intent.apps.remove(b.client);
11649 }
11650
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011651 if (!c.serviceDead) {
11652 if (DEBUG_SERVICE) Slog.v(TAG, "Disconnecting binding " + b.intent
11653 + ": shouldUnbind=" + b.intent.hasBound);
11654 if (s.app != null && s.app.thread != null && b.intent.apps.size() == 0
11655 && b.intent.hasBound) {
11656 try {
11657 bumpServiceExecutingLocked(s, "unbind");
11658 updateOomAdjLocked(s.app);
11659 b.intent.hasBound = false;
11660 // Assume the client doesn't want to know about a rebind;
11661 // we will deal with that later if it asks for one.
11662 b.intent.doRebind = false;
11663 s.app.thread.scheduleUnbindService(s, b.intent.intent.getIntent());
11664 } catch (Exception e) {
11665 Slog.w(TAG, "Exception when unbinding service " + s.shortName, e);
11666 serviceDoneExecutingLocked(s, true);
11667 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011668 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011669
11670 if ((c.flags&Context.BIND_AUTO_CREATE) != 0) {
11671 bringDownServiceLocked(s, false);
11672 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011673 }
11674 }
11675
11676 public boolean unbindService(IServiceConnection connection) {
11677 synchronized (this) {
11678 IBinder binder = connection.asBinder();
Joe Onorato8a9b2202010-02-26 18:56:32 -080011679 if (DEBUG_SERVICE) Slog.v(TAG, "unbindService: conn=" + binder);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011680 ArrayList<ConnectionRecord> clist = mServiceConnections.get(binder);
11681 if (clist == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011682 Slog.w(TAG, "Unbind failed: could not find connection for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011683 + connection.asBinder());
11684 return false;
11685 }
11686
11687 final long origId = Binder.clearCallingIdentity();
11688
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011689 while (clist.size() > 0) {
11690 ConnectionRecord r = clist.get(0);
11691 removeConnectionLocked(r, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011692
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011693 if (r.binding.service.app != null) {
11694 // This could have made the service less important.
11695 updateOomAdjLocked(r.binding.service.app);
11696 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011697 }
11698
11699 Binder.restoreCallingIdentity(origId);
11700 }
11701
11702 return true;
11703 }
11704
11705 public void publishService(IBinder token, Intent intent, IBinder service) {
11706 // Refuse possible leaked file descriptors
11707 if (intent != null && intent.hasFileDescriptors() == true) {
11708 throw new IllegalArgumentException("File descriptors passed in Intent");
11709 }
11710
11711 synchronized(this) {
11712 if (!(token instanceof ServiceRecord)) {
11713 throw new IllegalArgumentException("Invalid service token");
11714 }
11715 ServiceRecord r = (ServiceRecord)token;
11716
11717 final long origId = Binder.clearCallingIdentity();
11718
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011719 if (DEBUG_SERVICE) Slog.v(TAG, "PUBLISHING " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011720 + " " + intent + ": " + service);
11721 if (r != null) {
11722 Intent.FilterComparison filter
11723 = new Intent.FilterComparison(intent);
11724 IntentBindRecord b = r.bindings.get(filter);
11725 if (b != null && !b.received) {
11726 b.binder = service;
11727 b.requested = true;
11728 b.received = true;
11729 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011730 Iterator<ArrayList<ConnectionRecord>> it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011731 = r.connections.values().iterator();
11732 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011733 ArrayList<ConnectionRecord> clist = it.next();
11734 for (int i=0; i<clist.size(); i++) {
11735 ConnectionRecord c = clist.get(i);
11736 if (!filter.equals(c.binding.intent.intent)) {
11737 if (DEBUG_SERVICE) Slog.v(
11738 TAG, "Not publishing to: " + c);
11739 if (DEBUG_SERVICE) Slog.v(
11740 TAG, "Bound intent: " + c.binding.intent.intent);
11741 if (DEBUG_SERVICE) Slog.v(
11742 TAG, "Published intent: " + intent);
11743 continue;
11744 }
11745 if (DEBUG_SERVICE) Slog.v(TAG, "Publishing to: " + c);
11746 try {
11747 c.conn.connected(r.name, service);
11748 } catch (Exception e) {
11749 Slog.w(TAG, "Failure sending service " + r.name +
11750 " to connection " + c.conn.asBinder() +
11751 " (in " + c.binding.client.processName + ")", e);
11752 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011753 }
11754 }
11755 }
11756 }
11757
11758 serviceDoneExecutingLocked(r, mStoppingServices.contains(r));
11759
11760 Binder.restoreCallingIdentity(origId);
11761 }
11762 }
11763 }
11764
11765 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
11766 // Refuse possible leaked file descriptors
11767 if (intent != null && intent.hasFileDescriptors() == true) {
11768 throw new IllegalArgumentException("File descriptors passed in Intent");
11769 }
11770
11771 synchronized(this) {
11772 if (!(token instanceof ServiceRecord)) {
11773 throw new IllegalArgumentException("Invalid service token");
11774 }
11775 ServiceRecord r = (ServiceRecord)token;
11776
11777 final long origId = Binder.clearCallingIdentity();
11778
11779 if (r != null) {
11780 Intent.FilterComparison filter
11781 = new Intent.FilterComparison(intent);
11782 IntentBindRecord b = r.bindings.get(filter);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011783 if (DEBUG_SERVICE) Slog.v(TAG, "unbindFinished in " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011784 + " at " + b + ": apps="
11785 + (b != null ? b.apps.size() : 0));
Per Edelberg78f9fff2010-08-30 20:01:35 +020011786
11787 boolean inStopping = mStoppingServices.contains(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011788 if (b != null) {
Per Edelberg78f9fff2010-08-30 20:01:35 +020011789 if (b.apps.size() > 0 && !inStopping) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011790 // Applications have already bound since the last
11791 // unbind, so just rebind right here.
11792 requestServiceBindingLocked(r, b, true);
11793 } else {
11794 // Note to tell the service the next time there is
11795 // a new client.
11796 b.doRebind = true;
11797 }
11798 }
11799
Per Edelberg78f9fff2010-08-30 20:01:35 +020011800 serviceDoneExecutingLocked(r, inStopping);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011801
11802 Binder.restoreCallingIdentity(origId);
11803 }
11804 }
11805 }
11806
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011807 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011808 synchronized(this) {
11809 if (!(token instanceof ServiceRecord)) {
11810 throw new IllegalArgumentException("Invalid service token");
11811 }
11812 ServiceRecord r = (ServiceRecord)token;
11813 boolean inStopping = mStoppingServices.contains(token);
11814 if (r != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011815 if (r != token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011816 Slog.w(TAG, "Done executing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011817 + " with incorrect token: given " + token
11818 + ", expected " + r);
11819 return;
11820 }
11821
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011822 if (type == 1) {
11823 // This is a call from a service start... take care of
11824 // book-keeping.
11825 r.callStart = true;
11826 switch (res) {
11827 case Service.START_STICKY_COMPATIBILITY:
11828 case Service.START_STICKY: {
11829 // We are done with the associated start arguments.
11830 r.findDeliveredStart(startId, true);
11831 // Don't stop if killed.
11832 r.stopIfKilled = false;
11833 break;
11834 }
11835 case Service.START_NOT_STICKY: {
11836 // We are done with the associated start arguments.
11837 r.findDeliveredStart(startId, true);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011838 if (r.getLastStartId() == startId) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011839 // There is no more work, and this service
11840 // doesn't want to hang around if killed.
11841 r.stopIfKilled = true;
11842 }
11843 break;
11844 }
11845 case Service.START_REDELIVER_INTENT: {
11846 // We'll keep this item until they explicitly
11847 // call stop for it, but keep track of the fact
11848 // that it was delivered.
11849 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
11850 if (si != null) {
11851 si.deliveryCount = 0;
11852 si.doneExecutingCount++;
11853 // Don't stop if killed.
11854 r.stopIfKilled = true;
11855 }
11856 break;
11857 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011858 case Service.START_TASK_REMOVED_COMPLETE: {
11859 // Special processing for onTaskRemoved(). Don't
11860 // impact normal onStartCommand() processing.
11861 r.findDeliveredStart(startId, true);
11862 break;
11863 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011864 default:
11865 throw new IllegalArgumentException(
11866 "Unknown service start result: " + res);
11867 }
11868 if (res == Service.START_STICKY_COMPATIBILITY) {
11869 r.callStart = false;
11870 }
11871 }
Amith Yamasani742a6712011-05-04 14:49:28 -070011872 if (DEBUG_MU)
11873 Slog.v(TAG_MU, "before serviceDontExecutingLocked, uid="
11874 + Binder.getOrigCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011875 final long origId = Binder.clearCallingIdentity();
11876 serviceDoneExecutingLocked(r, inStopping);
11877 Binder.restoreCallingIdentity(origId);
11878 } else {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011879 Slog.w(TAG, "Done executing unknown service from pid "
11880 + Binder.getCallingPid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011881 }
11882 }
11883 }
11884
11885 public void serviceDoneExecutingLocked(ServiceRecord r, boolean inStopping) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011886 if (DEBUG_SERVICE) Slog.v(TAG, "<<< DONE EXECUTING " + r
11887 + ": nesting=" + r.executeNesting
11888 + ", inStopping=" + inStopping + ", app=" + r.app);
Dianne Hackborn287952c2010-09-22 22:34:31 -070011889 else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG, "<<< DONE EXECUTING " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011890 r.executeNesting--;
11891 if (r.executeNesting <= 0 && r.app != null) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011892 if (DEBUG_SERVICE) Slog.v(TAG,
11893 "Nesting at 0 of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011894 r.app.executingServices.remove(r);
11895 if (r.app.executingServices.size() == 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011896 if (DEBUG_SERVICE || DEBUG_SERVICE_EXECUTING) Slog.v(TAG,
11897 "No more executingServices of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011898 mHandler.removeMessages(SERVICE_TIMEOUT_MSG, r.app);
11899 }
11900 if (inStopping) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011901 if (DEBUG_SERVICE) Slog.v(TAG,
11902 "doneExecuting remove stopping " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011903 mStoppingServices.remove(r);
Mattias Petersson3996b412010-10-27 09:32:51 +020011904 r.bindings.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011905 }
11906 updateOomAdjLocked(r.app);
11907 }
11908 }
11909
11910 void serviceTimeout(ProcessRecord proc) {
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011911 String anrMessage = null;
11912
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011913 synchronized(this) {
11914 if (proc.executingServices.size() == 0 || proc.thread == null) {
11915 return;
11916 }
11917 long maxTime = SystemClock.uptimeMillis() - SERVICE_TIMEOUT;
11918 Iterator<ServiceRecord> it = proc.executingServices.iterator();
11919 ServiceRecord timeout = null;
11920 long nextTime = 0;
11921 while (it.hasNext()) {
11922 ServiceRecord sr = it.next();
11923 if (sr.executingStart < maxTime) {
11924 timeout = sr;
11925 break;
11926 }
11927 if (sr.executingStart > nextTime) {
11928 nextTime = sr.executingStart;
11929 }
11930 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011931 if (timeout != null && mLruProcesses.contains(proc)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011932 Slog.w(TAG, "Timeout executing service: " + timeout);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011933 anrMessage = "Executing service " + timeout.shortName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011934 } else {
11935 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
11936 msg.obj = proc;
11937 mHandler.sendMessageAtTime(msg, nextTime+SERVICE_TIMEOUT);
11938 }
11939 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011940
11941 if (anrMessage != null) {
11942 appNotResponding(proc, null, null, anrMessage);
11943 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011944 }
11945
11946 // =========================================================
Christopher Tate181fafa2009-05-14 11:12:14 -070011947 // BACKUP AND RESTORE
11948 // =========================================================
11949
11950 // Cause the target app to be launched if necessary and its backup agent
11951 // instantiated. The backup agent will invoke backupAgentCreated() on the
11952 // activity manager to announce its creation.
11953 public boolean bindBackupAgent(ApplicationInfo app, int backupMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011954 if (DEBUG_BACKUP) Slog.v(TAG, "startBackupAgent: app=" + app + " mode=" + backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070011955 enforceCallingPermission("android.permission.BACKUP", "startBackupAgent");
11956
11957 synchronized(this) {
11958 // !!! TODO: currently no check here that we're already bound
11959 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
11960 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
11961 synchronized (stats) {
11962 ss = stats.getServiceStatsLocked(app.uid, app.packageName, app.name);
11963 }
11964
Dianne Hackborne7f97212011-02-24 14:40:20 -080011965 // Backup agent is now in use, its package can't be stopped.
11966 try {
11967 AppGlobals.getPackageManager().setPackageStoppedState(
11968 app.packageName, false);
11969 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080011970 } catch (IllegalArgumentException e) {
11971 Slog.w(TAG, "Failed trying to unstop package "
11972 + app.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080011973 }
11974
Christopher Tate181fafa2009-05-14 11:12:14 -070011975 BackupRecord r = new BackupRecord(ss, app, backupMode);
Christopher Tate4a627c72011-04-01 14:43:32 -070011976 ComponentName hostingName = (backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL)
11977 ? new ComponentName(app.packageName, app.backupAgentName)
11978 : new ComponentName("android", "FullBackupAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -070011979 // startProcessLocked() returns existing proc's record if it's already running
11980 ProcessRecord proc = startProcessLocked(app.processName, app,
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011981 false, 0, "backup", hostingName, false, false);
Christopher Tate181fafa2009-05-14 11:12:14 -070011982 if (proc == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011983 Slog.e(TAG, "Unable to start backup agent process " + r);
Christopher Tate181fafa2009-05-14 11:12:14 -070011984 return false;
11985 }
11986
11987 r.app = proc;
11988 mBackupTarget = r;
11989 mBackupAppName = app.packageName;
11990
Christopher Tate6fa95972009-06-05 18:43:55 -070011991 // Try not to kill the process during backup
11992 updateOomAdjLocked(proc);
11993
Christopher Tate181fafa2009-05-14 11:12:14 -070011994 // If the process is already attached, schedule the creation of the backup agent now.
11995 // If it is not yet live, this will be done when it attaches to the framework.
11996 if (proc.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011997 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc already running: " + proc);
Christopher Tate181fafa2009-05-14 11:12:14 -070011998 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040011999 proc.thread.scheduleCreateBackupAgent(app,
12000 compatibilityInfoForPackageLocked(app), backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070012001 } catch (RemoteException e) {
Christopher Tate436344a2009-09-30 16:17:37 -070012002 // Will time out on the backup manager side
Christopher Tate181fafa2009-05-14 11:12:14 -070012003 }
12004 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012005 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc not running, waiting for attach");
Christopher Tate181fafa2009-05-14 11:12:14 -070012006 }
12007 // Invariants: at this point, the target app process exists and the application
12008 // is either already running or in the process of coming up. mBackupTarget and
12009 // mBackupAppName describe the app, so that when it binds back to the AM we
12010 // know that it's scheduled for a backup-agent operation.
12011 }
12012
12013 return true;
12014 }
12015
12016 // A backup agent has just come up
12017 public void backupAgentCreated(String agentPackageName, IBinder agent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012018 if (DEBUG_BACKUP) Slog.v(TAG, "backupAgentCreated: " + agentPackageName
Christopher Tate181fafa2009-05-14 11:12:14 -070012019 + " = " + agent);
12020
12021 synchronized(this) {
12022 if (!agentPackageName.equals(mBackupAppName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012023 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
Christopher Tate181fafa2009-05-14 11:12:14 -070012024 return;
12025 }
Dianne Hackborn06740692010-09-22 22:46:21 -070012026 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012027
Dianne Hackborn06740692010-09-22 22:46:21 -070012028 long oldIdent = Binder.clearCallingIdentity();
12029 try {
12030 IBackupManager bm = IBackupManager.Stub.asInterface(
12031 ServiceManager.getService(Context.BACKUP_SERVICE));
12032 bm.agentConnected(agentPackageName, agent);
12033 } catch (RemoteException e) {
12034 // can't happen; the backup manager service is local
12035 } catch (Exception e) {
12036 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: ");
12037 e.printStackTrace();
12038 } finally {
12039 Binder.restoreCallingIdentity(oldIdent);
Christopher Tate181fafa2009-05-14 11:12:14 -070012040 }
12041 }
12042
12043 // done with this agent
12044 public void unbindBackupAgent(ApplicationInfo appInfo) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012045 if (DEBUG_BACKUP) Slog.v(TAG, "unbindBackupAgent: " + appInfo);
Christopher Tate8a27f922009-06-26 11:49:18 -070012046 if (appInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012047 Slog.w(TAG, "unbind backup agent for null app");
Christopher Tate8a27f922009-06-26 11:49:18 -070012048 return;
12049 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012050
12051 synchronized(this) {
Christopher Tate8a27f922009-06-26 11:49:18 -070012052 if (mBackupAppName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012053 Slog.w(TAG, "Unbinding backup agent with no active backup");
Christopher Tate8a27f922009-06-26 11:49:18 -070012054 return;
12055 }
12056
Christopher Tate181fafa2009-05-14 11:12:14 -070012057 if (!mBackupAppName.equals(appInfo.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012058 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
Christopher Tate181fafa2009-05-14 11:12:14 -070012059 return;
12060 }
12061
Christopher Tate6fa95972009-06-05 18:43:55 -070012062 ProcessRecord proc = mBackupTarget.app;
12063 mBackupTarget = null;
12064 mBackupAppName = null;
12065
12066 // Not backing this app up any more; reset its OOM adjustment
12067 updateOomAdjLocked(proc);
12068
Christopher Tatec7b31e32009-06-10 15:49:30 -070012069 // If the app crashed during backup, 'thread' will be null here
12070 if (proc.thread != null) {
12071 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040012072 proc.thread.scheduleDestroyBackupAgent(appInfo,
12073 compatibilityInfoForPackageLocked(appInfo));
Christopher Tatec7b31e32009-06-10 15:49:30 -070012074 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012075 Slog.e(TAG, "Exception when unbinding backup agent:");
Christopher Tatec7b31e32009-06-10 15:49:30 -070012076 e.printStackTrace();
12077 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012078 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012079 }
12080 }
12081 // =========================================================
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012082 // BROADCASTS
12083 // =========================================================
12084
Josh Bartel7f208742010-02-25 11:01:44 -060012085 private final List getStickiesLocked(String action, IntentFilter filter,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012086 List cur) {
12087 final ContentResolver resolver = mContext.getContentResolver();
12088 final ArrayList<Intent> list = mStickyBroadcasts.get(action);
12089 if (list == null) {
12090 return cur;
12091 }
12092 int N = list.size();
12093 for (int i=0; i<N; i++) {
12094 Intent intent = list.get(i);
12095 if (filter.match(resolver, intent, true, TAG) >= 0) {
12096 if (cur == null) {
12097 cur = new ArrayList<Intent>();
12098 }
12099 cur.add(intent);
12100 }
12101 }
12102 return cur;
12103 }
12104
Christopher Tatef46723b2012-01-26 14:19:24 -080012105 boolean isPendingBroadcastProcessLocked(int pid) {
12106 return mFgBroadcastQueue.isPendingBroadcastProcessLocked(pid)
12107 || mBgBroadcastQueue.isPendingBroadcastProcessLocked(pid);
12108 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012109
Christopher Tatef46723b2012-01-26 14:19:24 -080012110 void skipPendingBroadcastLocked(int pid) {
12111 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
12112 for (BroadcastQueue queue : mBroadcastQueues) {
12113 queue.skipPendingBroadcastLocked(pid);
12114 }
12115 }
12116
12117 // The app just attached; send any pending broadcasts that it should receive
12118 boolean sendPendingBroadcastsLocked(ProcessRecord app) {
12119 boolean didSomething = false;
12120 for (BroadcastQueue queue : mBroadcastQueues) {
12121 didSomething |= queue.sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012122 }
Christopher Tatef46723b2012-01-26 14:19:24 -080012123 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012124 }
12125
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012126 public Intent registerReceiver(IApplicationThread caller, String callerPackage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012127 IIntentReceiver receiver, IntentFilter filter, String permission) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012128 enforceNotIsolatedCaller("registerReceiver");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012129 synchronized(this) {
12130 ProcessRecord callerApp = null;
12131 if (caller != null) {
12132 callerApp = getRecordForAppLocked(caller);
12133 if (callerApp == null) {
12134 throw new SecurityException(
12135 "Unable to find app for caller " + caller
12136 + " (pid=" + Binder.getCallingPid()
12137 + ") when registering receiver " + receiver);
12138 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012139 if (callerApp.info.uid != Process.SYSTEM_UID &&
12140 !callerApp.pkgList.contains(callerPackage)) {
12141 throw new SecurityException("Given caller package " + callerPackage
12142 + " is not running in process " + callerApp);
12143 }
12144 } else {
12145 callerPackage = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012146 }
12147
12148 List allSticky = null;
12149
12150 // Look for any matching sticky broadcasts...
12151 Iterator actions = filter.actionsIterator();
12152 if (actions != null) {
12153 while (actions.hasNext()) {
12154 String action = (String)actions.next();
Josh Bartel7f208742010-02-25 11:01:44 -060012155 allSticky = getStickiesLocked(action, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012156 }
12157 } else {
Josh Bartel7f208742010-02-25 11:01:44 -060012158 allSticky = getStickiesLocked(null, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012159 }
12160
12161 // The first sticky in the list is returned directly back to
12162 // the client.
12163 Intent sticky = allSticky != null ? (Intent)allSticky.get(0) : null;
12164
Joe Onorato8a9b2202010-02-26 18:56:32 -080012165 if (DEBUG_BROADCAST) Slog.v(TAG, "Register receiver " + filter
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012166 + ": " + sticky);
12167
12168 if (receiver == null) {
12169 return sticky;
12170 }
12171
12172 ReceiverList rl
12173 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
12174 if (rl == null) {
12175 rl = new ReceiverList(this, callerApp,
12176 Binder.getCallingPid(),
12177 Binder.getCallingUid(), receiver);
12178 if (rl.app != null) {
12179 rl.app.receivers.add(rl);
12180 } else {
12181 try {
12182 receiver.asBinder().linkToDeath(rl, 0);
12183 } catch (RemoteException e) {
12184 return sticky;
12185 }
12186 rl.linkedToDeath = true;
12187 }
12188 mRegisteredReceivers.put(receiver.asBinder(), rl);
12189 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012190 BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage, permission);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012191 rl.add(bf);
12192 if (!bf.debugCheck()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012193 Slog.w(TAG, "==> For Dynamic broadast");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012194 }
12195 mReceiverResolver.addFilter(bf);
12196
12197 // Enqueue broadcasts for all existing stickies that match
12198 // this filter.
12199 if (allSticky != null) {
12200 ArrayList receivers = new ArrayList();
12201 receivers.add(bf);
12202
12203 int N = allSticky.size();
12204 for (int i=0; i<N; i++) {
12205 Intent intent = (Intent)allSticky.get(i);
Christopher Tatef46723b2012-01-26 14:19:24 -080012206 BroadcastQueue queue = broadcastQueueForIntent(intent);
12207 BroadcastRecord r = new BroadcastRecord(queue, intent, null,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012208 null, -1, -1, null, receivers, null, 0, null, null,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012209 false, true, true);
Christopher Tatef46723b2012-01-26 14:19:24 -080012210 queue.enqueueParallelBroadcastLocked(r);
12211 queue.scheduleBroadcastsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012212 }
12213 }
12214
12215 return sticky;
12216 }
12217 }
12218
12219 public void unregisterReceiver(IIntentReceiver receiver) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012220 if (DEBUG_BROADCAST) Slog.v(TAG, "Unregister receiver: " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012221
Christopher Tatef46723b2012-01-26 14:19:24 -080012222 final long origId = Binder.clearCallingIdentity();
12223 try {
12224 boolean doTrim = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012225
Christopher Tatef46723b2012-01-26 14:19:24 -080012226 synchronized(this) {
12227 ReceiverList rl
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012228 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
Christopher Tatef46723b2012-01-26 14:19:24 -080012229 if (rl != null) {
12230 if (rl.curBroadcast != null) {
12231 BroadcastRecord r = rl.curBroadcast;
12232 final boolean doNext = finishReceiverLocked(
12233 receiver.asBinder(), r.resultCode, r.resultData,
12234 r.resultExtras, r.resultAbort, true);
12235 if (doNext) {
12236 doTrim = true;
12237 r.queue.processNextBroadcast(false);
12238 }
12239 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012240
Christopher Tatef46723b2012-01-26 14:19:24 -080012241 if (rl.app != null) {
12242 rl.app.receivers.remove(rl);
12243 }
12244 removeReceiverLocked(rl);
12245 if (rl.linkedToDeath) {
12246 rl.linkedToDeath = false;
12247 rl.receiver.asBinder().unlinkToDeath(rl, 0);
12248 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012249 }
12250 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012251
Christopher Tatef46723b2012-01-26 14:19:24 -080012252 // If we actually concluded any broadcasts, we might now be able
12253 // to trim the recipients' apps from our working set
12254 if (doTrim) {
12255 trimApplications();
12256 return;
12257 }
12258
12259 } finally {
12260 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012261 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012262 }
12263
12264 void removeReceiverLocked(ReceiverList rl) {
12265 mRegisteredReceivers.remove(rl.receiver.asBinder());
12266 int N = rl.size();
12267 for (int i=0; i<N; i++) {
12268 mReceiverResolver.removeFilter(rl.get(i));
12269 }
12270 }
12271
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012272 private final void sendPackageBroadcastLocked(int cmd, String[] packages) {
12273 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
12274 ProcessRecord r = mLruProcesses.get(i);
12275 if (r.thread != null) {
12276 try {
12277 r.thread.dispatchPackageBroadcast(cmd, packages);
12278 } catch (RemoteException ex) {
12279 }
12280 }
12281 }
12282 }
12283
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012284 private final int broadcastIntentLocked(ProcessRecord callerApp,
12285 String callerPackage, Intent intent, String resolvedType,
12286 IIntentReceiver resultTo, int resultCode, String resultData,
12287 Bundle map, String requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070012288 boolean ordered, boolean sticky, int callingPid, int callingUid,
12289 int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012290 intent = new Intent(intent);
12291
Dianne Hackborne7f97212011-02-24 14:40:20 -080012292 // By default broadcasts do not go to stopped apps.
12293 intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
12294
Joe Onorato8a9b2202010-02-26 18:56:32 -080012295 if (DEBUG_BROADCAST_LIGHT) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012296 TAG, (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
12297 + " ordered=" + ordered);
12298 if ((resultTo != null) && !ordered) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012299 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012300 }
12301
12302 // Handle special intents: if this broadcast is from the package
12303 // manager about a package being removed, we need to remove all of
12304 // its activities from the history stack.
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012305 final boolean uidRemoved = Intent.ACTION_UID_REMOVED.equals(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012306 intent.getAction());
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012307 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())
12308 || Intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction())
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080012309 || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012310 || uidRemoved) {
12311 if (checkComponentPermission(
12312 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080012313 callingPid, callingUid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012314 == PackageManager.PERMISSION_GRANTED) {
12315 if (uidRemoved) {
12316 final Bundle intentExtras = intent.getExtras();
12317 final int uid = intentExtras != null
12318 ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
12319 if (uid >= 0) {
12320 BatteryStatsImpl bs = mBatteryStatsService.getActiveStatistics();
12321 synchronized (bs) {
12322 bs.removeUidStatsLocked(uid);
12323 }
12324 }
12325 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012326 // If resources are unvailble just force stop all
12327 // those packages and flush the attribute cache as well.
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080012328 if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012329 String list[] = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
12330 if (list != null && (list.length > 0)) {
12331 for (String pkg : list) {
Christopher Tate3dacd842011-08-19 14:56:15 -070012332 forceStopPackageLocked(pkg, -1, false, true, true, false);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012333 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012334 sendPackageBroadcastLocked(
12335 IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE, list);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012336 }
12337 } else {
12338 Uri data = intent.getData();
12339 String ssp;
12340 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
12341 if (!intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false)) {
12342 forceStopPackageLocked(ssp,
Christopher Tate3dacd842011-08-19 14:56:15 -070012343 intent.getIntExtra(Intent.EXTRA_UID, -1), false, true, true, false);
Dianne Hackbornde7faf62009-06-30 13:27:30 -070012344 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012345 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012346 sendPackageBroadcastLocked(IApplicationThread.PACKAGE_REMOVED,
12347 new String[] {ssp});
12348 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012349 }
12350 }
12351 }
12352 } else {
12353 String msg = "Permission Denial: " + intent.getAction()
12354 + " broadcast from " + callerPackage + " (pid=" + callingPid
12355 + ", uid=" + callingUid + ")"
12356 + " requires "
12357 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012358 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012359 throw new SecurityException(msg);
12360 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012361
12362 // Special case for adding a package: by default turn on compatibility
12363 // mode.
12364 } else if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -070012365 Uri data = intent.getData();
12366 String ssp;
12367 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
12368 mCompatModePackages.handlePackageAddedLocked(ssp,
12369 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false));
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012370 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012371 }
12372
12373 /*
12374 * If this is the time zone changed action, queue up a message that will reset the timezone
12375 * of all currently running processes. This message will get queued up before the broadcast
12376 * happens.
12377 */
12378 if (intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) {
12379 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
12380 }
12381
Robert Greenwalt03595d02010-11-02 14:08:23 -070012382 if (intent.ACTION_CLEAR_DNS_CACHE.equals(intent.getAction())) {
12383 mHandler.sendEmptyMessage(CLEAR_DNS_CACHE);
12384 }
12385
Robert Greenwalt434203a2010-10-11 16:00:27 -070012386 if (Proxy.PROXY_CHANGE_ACTION.equals(intent.getAction())) {
12387 ProxyProperties proxy = intent.getParcelableExtra("proxy");
12388 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY, proxy));
12389 }
12390
Dianne Hackborn854060af2009-07-09 18:14:31 -070012391 /*
12392 * Prevent non-system code (defined here to be non-persistent
12393 * processes) from sending protected broadcasts.
12394 */
12395 if (callingUid == Process.SYSTEM_UID || callingUid == Process.PHONE_UID
12396 || callingUid == Process.SHELL_UID || callingUid == 0) {
12397 // Always okay.
12398 } else if (callerApp == null || !callerApp.persistent) {
12399 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012400 if (AppGlobals.getPackageManager().isProtectedBroadcast(
Dianne Hackborn854060af2009-07-09 18:14:31 -070012401 intent.getAction())) {
12402 String msg = "Permission Denial: not allowed to send broadcast "
12403 + intent.getAction() + " from pid="
12404 + callingPid + ", uid=" + callingUid;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012405 Slog.w(TAG, msg);
Dianne Hackborn854060af2009-07-09 18:14:31 -070012406 throw new SecurityException(msg);
12407 }
12408 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012409 Slog.w(TAG, "Remote exception", e);
Dianne Hackborn854060af2009-07-09 18:14:31 -070012410 return BROADCAST_SUCCESS;
12411 }
12412 }
12413
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012414 // Add to the sticky list if requested.
12415 if (sticky) {
12416 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
12417 callingPid, callingUid)
12418 != PackageManager.PERMISSION_GRANTED) {
12419 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
12420 + callingPid + ", uid=" + callingUid
12421 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012422 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012423 throw new SecurityException(msg);
12424 }
12425 if (requiredPermission != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012426 Slog.w(TAG, "Can't broadcast sticky intent " + intent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012427 + " and enforce permission " + requiredPermission);
12428 return BROADCAST_STICKY_CANT_HAVE_PERMISSION;
12429 }
12430 if (intent.getComponent() != null) {
12431 throw new SecurityException(
12432 "Sticky broadcasts can't target a specific component");
12433 }
12434 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
12435 if (list == null) {
12436 list = new ArrayList<Intent>();
12437 mStickyBroadcasts.put(intent.getAction(), list);
12438 }
12439 int N = list.size();
12440 int i;
12441 for (i=0; i<N; i++) {
12442 if (intent.filterEquals(list.get(i))) {
12443 // This sticky already exists, replace it.
12444 list.set(i, new Intent(intent));
12445 break;
12446 }
12447 }
12448 if (i >= N) {
12449 list.add(new Intent(intent));
12450 }
12451 }
12452
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012453 // Figure out who all will receive this broadcast.
12454 List receivers = null;
12455 List<BroadcastFilter> registeredReceivers = null;
12456 try {
12457 if (intent.getComponent() != null) {
12458 // Broadcast is going to one specific receiver class...
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012459 ActivityInfo ai = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -070012460 getReceiverInfo(intent.getComponent(), STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012461 if (ai != null) {
12462 receivers = new ArrayList();
12463 ResolveInfo ri = new ResolveInfo();
Amith Yamasani742a6712011-05-04 14:49:28 -070012464 ri.activityInfo = getActivityInfoForUser(ai, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012465 receivers.add(ri);
12466 }
12467 } else {
Amith Yamasani742a6712011-05-04 14:49:28 -070012468 // TODO: Apply userId
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012469 // Need to resolve the intent to interested receivers...
12470 if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
12471 == 0) {
12472 receivers =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012473 AppGlobals.getPackageManager().queryIntentReceivers(
Dianne Hackborn1655be42009-05-08 14:29:01 -070012474 intent, resolvedType, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012475 }
Mihai Preda074edef2009-05-18 17:13:31 +020012476 registeredReceivers = mReceiverResolver.queryIntent(intent, resolvedType, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012477 }
12478 } catch (RemoteException ex) {
12479 // pm is in same process, this will never happen.
12480 }
12481
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012482 final boolean replacePending =
12483 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
12484
Joe Onorato8a9b2202010-02-26 18:56:32 -080012485 if (DEBUG_BROADCAST) Slog.v(TAG, "Enqueing broadcast: " + intent.getAction()
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012486 + " replacePending=" + replacePending);
12487
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012488 int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
12489 if (!ordered && NR > 0) {
12490 // If we are not serializing this broadcast, then send the
12491 // registered receivers separately so they don't wait for the
12492 // components to be launched.
Christopher Tatef46723b2012-01-26 14:19:24 -080012493 final BroadcastQueue queue = broadcastQueueForIntent(intent);
12494 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012495 callerPackage, callingPid, callingUid, requiredPermission,
12496 registeredReceivers, resultTo, resultCode, resultData, map,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012497 ordered, sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012498 if (DEBUG_BROADCAST) Slog.v(
Christopher Tatef46723b2012-01-26 14:19:24 -080012499 TAG, "Enqueueing parallel broadcast " + r);
12500 final boolean replaced = replacePending && queue.replaceParallelBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012501 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012502 queue.enqueueParallelBroadcastLocked(r);
12503 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012504 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012505 registeredReceivers = null;
12506 NR = 0;
12507 }
12508
12509 // Merge into one list.
12510 int ir = 0;
12511 if (receivers != null) {
12512 // A special case for PACKAGE_ADDED: do not allow the package
12513 // being added to see this broadcast. This prevents them from
12514 // using this as a back door to get run as soon as they are
12515 // installed. Maybe in the future we want to have a special install
12516 // broadcast or such for apps, but we'd like to deliberately make
12517 // this decision.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012518 String skipPackages[] = null;
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012519 if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
12520 || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
12521 || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012522 Uri data = intent.getData();
12523 if (data != null) {
12524 String pkgName = data.getSchemeSpecificPart();
12525 if (pkgName != null) {
12526 skipPackages = new String[] { pkgName };
12527 }
12528 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012529 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012530 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
The Android Open Source Project10592532009-03-18 17:39:46 -070012531 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012532 if (skipPackages != null && (skipPackages.length > 0)) {
12533 for (String skipPackage : skipPackages) {
12534 if (skipPackage != null) {
12535 int NT = receivers.size();
12536 for (int it=0; it<NT; it++) {
12537 ResolveInfo curt = (ResolveInfo)receivers.get(it);
12538 if (curt.activityInfo.packageName.equals(skipPackage)) {
12539 receivers.remove(it);
12540 it--;
12541 NT--;
12542 }
12543 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012544 }
12545 }
12546 }
12547
12548 int NT = receivers != null ? receivers.size() : 0;
12549 int it = 0;
12550 ResolveInfo curt = null;
12551 BroadcastFilter curr = null;
12552 while (it < NT && ir < NR) {
12553 if (curt == null) {
12554 curt = (ResolveInfo)receivers.get(it);
12555 }
12556 if (curr == null) {
12557 curr = registeredReceivers.get(ir);
12558 }
12559 if (curr.getPriority() >= curt.priority) {
12560 // Insert this broadcast record into the final list.
12561 receivers.add(it, curr);
12562 ir++;
12563 curr = null;
12564 it++;
12565 NT++;
12566 } else {
12567 // Skip to the next ResolveInfo in the final list.
12568 it++;
12569 curt = null;
12570 }
12571 }
12572 }
12573 while (ir < NR) {
12574 if (receivers == null) {
12575 receivers = new ArrayList();
12576 }
12577 receivers.add(registeredReceivers.get(ir));
12578 ir++;
12579 }
12580
12581 if ((receivers != null && receivers.size() > 0)
12582 || resultTo != null) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012583 BroadcastQueue queue = broadcastQueueForIntent(intent);
12584 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012585 callerPackage, callingPid, callingUid, requiredPermission,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012586 receivers, resultTo, resultCode, resultData, map, ordered,
12587 sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012588 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012589 TAG, "Enqueueing ordered broadcast " + r
Christopher Tatef46723b2012-01-26 14:19:24 -080012590 + ": prev had " + queue.mOrderedBroadcasts.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012591 if (DEBUG_BROADCAST) {
12592 int seq = r.intent.getIntExtra("seq", -1);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012593 Slog.i(TAG, "Enqueueing broadcast " + r.intent.getAction() + " seq=" + seq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012594 }
Christopher Tatef46723b2012-01-26 14:19:24 -080012595 boolean replaced = replacePending && queue.replaceOrderedBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012596 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012597 queue.enqueueOrderedBroadcastLocked(r);
12598 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012599 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012600 }
12601
12602 return BROADCAST_SUCCESS;
12603 }
12604
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012605 final Intent verifyBroadcastLocked(Intent intent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012606 // Refuse possible leaked file descriptors
12607 if (intent != null && intent.hasFileDescriptors() == true) {
12608 throw new IllegalArgumentException("File descriptors passed in Intent");
12609 }
12610
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012611 int flags = intent.getFlags();
12612
12613 if (!mProcessesReady) {
12614 // if the caller really truly claims to know what they're doing, go
12615 // ahead and allow the broadcast without launching any receivers
12616 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
12617 intent = new Intent(intent);
12618 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
12619 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
12620 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
12621 + " before boot completion");
12622 throw new IllegalStateException("Cannot broadcast before boot completed");
12623 }
12624 }
12625
12626 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
12627 throw new IllegalArgumentException(
12628 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
12629 }
12630
12631 return intent;
12632 }
12633
12634 public final int broadcastIntent(IApplicationThread caller,
12635 Intent intent, String resolvedType, IIntentReceiver resultTo,
12636 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070012637 String requiredPermission, boolean serialized, boolean sticky, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012638 enforceNotIsolatedCaller("broadcastIntent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012639 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012640 intent = verifyBroadcastLocked(intent);
Dianne Hackborn9acc0302009-08-25 00:27:12 -070012641
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012642 final ProcessRecord callerApp = getRecordForAppLocked(caller);
12643 final int callingPid = Binder.getCallingPid();
12644 final int callingUid = Binder.getCallingUid();
12645 final long origId = Binder.clearCallingIdentity();
12646 int res = broadcastIntentLocked(callerApp,
12647 callerApp != null ? callerApp.info.packageName : null,
12648 intent, resolvedType, resultTo,
Amith Yamasani742a6712011-05-04 14:49:28 -070012649 resultCode, resultData, map, requiredPermission, serialized, sticky,
12650 callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012651 Binder.restoreCallingIdentity(origId);
12652 return res;
12653 }
12654 }
12655
12656 int broadcastIntentInPackage(String packageName, int uid,
12657 Intent intent, String resolvedType, IIntentReceiver resultTo,
12658 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070012659 String requiredPermission, boolean serialized, boolean sticky, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012660 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012661 intent = verifyBroadcastLocked(intent);
12662
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012663 final long origId = Binder.clearCallingIdentity();
12664 int res = broadcastIntentLocked(null, packageName, intent, resolvedType,
12665 resultTo, resultCode, resultData, map, requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070012666 serialized, sticky, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012667 Binder.restoreCallingIdentity(origId);
12668 return res;
12669 }
12670 }
12671
Amith Yamasani742a6712011-05-04 14:49:28 -070012672 // TODO: Use the userId; maybe mStickyBroadcasts need to be tied to the user.
12673 public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012674 // Refuse possible leaked file descriptors
12675 if (intent != null && intent.hasFileDescriptors() == true) {
12676 throw new IllegalArgumentException("File descriptors passed in Intent");
12677 }
12678
12679 synchronized(this) {
12680 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
12681 != PackageManager.PERMISSION_GRANTED) {
12682 String msg = "Permission Denial: unbroadcastIntent() from pid="
12683 + Binder.getCallingPid()
12684 + ", uid=" + Binder.getCallingUid()
12685 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012686 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012687 throw new SecurityException(msg);
12688 }
12689 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
12690 if (list != null) {
12691 int N = list.size();
12692 int i;
12693 for (i=0; i<N; i++) {
12694 if (intent.filterEquals(list.get(i))) {
12695 list.remove(i);
12696 break;
12697 }
12698 }
12699 }
12700 }
12701 }
12702
12703 private final boolean finishReceiverLocked(IBinder receiver, int resultCode,
12704 String resultData, Bundle resultExtras, boolean resultAbort,
12705 boolean explicit) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012706 final BroadcastRecord r = broadcastRecordForReceiverLocked(receiver);
12707 if (r == null) {
12708 Slog.w(TAG, "finishReceiver called but not found on queue");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012709 return false;
12710 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012711
Christopher Tatef46723b2012-01-26 14:19:24 -080012712 return r.queue.finishReceiverLocked(r, resultCode, resultData, resultExtras, resultAbort,
12713 explicit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012714 }
12715
12716 public void finishReceiver(IBinder who, int resultCode, String resultData,
12717 Bundle resultExtras, boolean resultAbort) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012718 if (DEBUG_BROADCAST) Slog.v(TAG, "Finish receiver: " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012719
12720 // Refuse possible leaked file descriptors
12721 if (resultExtras != null && resultExtras.hasFileDescriptors()) {
12722 throw new IllegalArgumentException("File descriptors passed in Bundle");
12723 }
12724
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012725 final long origId = Binder.clearCallingIdentity();
Christopher Tatef46723b2012-01-26 14:19:24 -080012726 try {
12727 boolean doNext = false;
12728 BroadcastRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012729
Christopher Tatef46723b2012-01-26 14:19:24 -080012730 synchronized(this) {
12731 r = broadcastRecordForReceiverLocked(who);
12732 if (r != null) {
12733 doNext = r.queue.finishReceiverLocked(r, resultCode,
12734 resultData, resultExtras, resultAbort, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012735 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012736 }
Jeff Brown4d94a762010-09-23 11:33:28 -070012737
Christopher Tatef46723b2012-01-26 14:19:24 -080012738 if (doNext) {
12739 r.queue.processNextBroadcast(false);
12740 }
12741 trimApplications();
12742 } finally {
12743 Binder.restoreCallingIdentity(origId);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012744 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012745 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012746
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012747 // =========================================================
12748 // INSTRUMENTATION
12749 // =========================================================
12750
12751 public boolean startInstrumentation(ComponentName className,
12752 String profileFile, int flags, Bundle arguments,
12753 IInstrumentationWatcher watcher) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012754 enforceNotIsolatedCaller("startInstrumentation");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012755 // Refuse possible leaked file descriptors
12756 if (arguments != null && arguments.hasFileDescriptors()) {
12757 throw new IllegalArgumentException("File descriptors passed in Bundle");
12758 }
12759
12760 synchronized(this) {
12761 InstrumentationInfo ii = null;
12762 ApplicationInfo ai = null;
12763 try {
12764 ii = mContext.getPackageManager().getInstrumentationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070012765 className, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012766 ai = mContext.getPackageManager().getApplicationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070012767 ii.targetPackage, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012768 } catch (PackageManager.NameNotFoundException e) {
12769 }
12770 if (ii == null) {
12771 reportStartInstrumentationFailure(watcher, className,
12772 "Unable to find instrumentation info for: " + className);
12773 return false;
12774 }
12775 if (ai == null) {
12776 reportStartInstrumentationFailure(watcher, className,
12777 "Unable to find instrumentation target package: " + ii.targetPackage);
12778 return false;
12779 }
12780
12781 int match = mContext.getPackageManager().checkSignatures(
12782 ii.targetPackage, ii.packageName);
12783 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
12784 String msg = "Permission Denial: starting instrumentation "
12785 + className + " from pid="
12786 + Binder.getCallingPid()
12787 + ", uid=" + Binder.getCallingPid()
12788 + " not allowed because package " + ii.packageName
12789 + " does not have a signature matching the target "
12790 + ii.targetPackage;
12791 reportStartInstrumentationFailure(watcher, className, msg);
12792 throw new SecurityException(msg);
12793 }
12794
12795 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -070012796 // Instrumentation can kill and relaunch even persistent processes
12797 forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080012798 ProcessRecord app = addAppLocked(ai, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012799 app.instrumentationClass = className;
Dianne Hackborn1655be42009-05-08 14:29:01 -070012800 app.instrumentationInfo = ai;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012801 app.instrumentationProfileFile = profileFile;
12802 app.instrumentationArguments = arguments;
12803 app.instrumentationWatcher = watcher;
12804 app.instrumentationResultClass = className;
12805 Binder.restoreCallingIdentity(origId);
12806 }
12807
12808 return true;
12809 }
12810
12811 /**
12812 * Report errors that occur while attempting to start Instrumentation. Always writes the
12813 * error to the logs, but if somebody is watching, send the report there too. This enables
12814 * the "am" command to report errors with more information.
12815 *
12816 * @param watcher The IInstrumentationWatcher. Null if there isn't one.
12817 * @param cn The component name of the instrumentation.
12818 * @param report The error report.
12819 */
12820 private void reportStartInstrumentationFailure(IInstrumentationWatcher watcher,
12821 ComponentName cn, String report) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012822 Slog.w(TAG, report);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012823 try {
12824 if (watcher != null) {
12825 Bundle results = new Bundle();
12826 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
12827 results.putString("Error", report);
12828 watcher.instrumentationStatus(cn, -1, results);
12829 }
12830 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012831 Slog.w(TAG, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012832 }
12833 }
12834
12835 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
12836 if (app.instrumentationWatcher != null) {
12837 try {
12838 // NOTE: IInstrumentationWatcher *must* be oneway here
12839 app.instrumentationWatcher.instrumentationFinished(
12840 app.instrumentationClass,
12841 resultCode,
12842 results);
12843 } catch (RemoteException e) {
12844 }
12845 }
12846 app.instrumentationWatcher = null;
12847 app.instrumentationClass = null;
Dianne Hackborn1655be42009-05-08 14:29:01 -070012848 app.instrumentationInfo = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012849 app.instrumentationProfileFile = null;
12850 app.instrumentationArguments = null;
12851
Christopher Tate3dacd842011-08-19 14:56:15 -070012852 forceStopPackageLocked(app.processName, -1, false, false, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012853 }
12854
12855 public void finishInstrumentation(IApplicationThread target,
12856 int resultCode, Bundle results) {
12857 // Refuse possible leaked file descriptors
12858 if (results != null && results.hasFileDescriptors()) {
12859 throw new IllegalArgumentException("File descriptors passed in Intent");
12860 }
12861
12862 synchronized(this) {
12863 ProcessRecord app = getRecordForAppLocked(target);
12864 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012865 Slog.w(TAG, "finishInstrumentation: no app for " + target);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012866 return;
12867 }
12868 final long origId = Binder.clearCallingIdentity();
12869 finishInstrumentationLocked(app, resultCode, results);
12870 Binder.restoreCallingIdentity(origId);
12871 }
12872 }
12873
12874 // =========================================================
12875 // CONFIGURATION
12876 // =========================================================
12877
12878 public ConfigurationInfo getDeviceConfigurationInfo() {
12879 ConfigurationInfo config = new ConfigurationInfo();
12880 synchronized (this) {
12881 config.reqTouchScreen = mConfiguration.touchscreen;
12882 config.reqKeyboardType = mConfiguration.keyboard;
12883 config.reqNavigation = mConfiguration.navigation;
Dianne Hackbornfae76f52009-07-16 13:41:23 -070012884 if (mConfiguration.navigation == Configuration.NAVIGATION_DPAD
12885 || mConfiguration.navigation == Configuration.NAVIGATION_TRACKBALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012886 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
12887 }
Dianne Hackbornfae76f52009-07-16 13:41:23 -070012888 if (mConfiguration.keyboard != Configuration.KEYBOARD_UNDEFINED
12889 && mConfiguration.keyboard != Configuration.KEYBOARD_NOKEYS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012890 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
12891 }
Jack Palevichb90d28c2009-07-22 15:35:24 -070012892 config.reqGlEsVersion = GL_ES_VERSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012893 }
12894 return config;
12895 }
12896
12897 public Configuration getConfiguration() {
12898 Configuration ci;
12899 synchronized(this) {
12900 ci = new Configuration(mConfiguration);
12901 }
12902 return ci;
12903 }
12904
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012905 public void updatePersistentConfiguration(Configuration values) {
12906 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
12907 "updateConfiguration()");
12908 enforceCallingPermission(android.Manifest.permission.WRITE_SETTINGS,
12909 "updateConfiguration()");
12910 if (values == null) {
12911 throw new NullPointerException("Configuration must not be null");
12912 }
12913
12914 synchronized(this) {
12915 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn813075a62011-11-14 17:45:19 -080012916 updateConfigurationLocked(values, null, true, false);
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012917 Binder.restoreCallingIdentity(origId);
12918 }
12919 }
12920
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012921 public void updateConfiguration(Configuration values) {
12922 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
12923 "updateConfiguration()");
12924
12925 synchronized(this) {
12926 if (values == null && mWindowManager != null) {
12927 // sentinel: fetch the current configuration from the window manager
12928 values = mWindowManager.computeNewConfiguration();
12929 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012930
12931 if (mWindowManager != null) {
12932 mProcessList.applyDisplaySize(mWindowManager);
12933 }
12934
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012935 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012936 if (values != null) {
12937 Settings.System.clearConfiguration(values);
12938 }
Dianne Hackborn813075a62011-11-14 17:45:19 -080012939 updateConfigurationLocked(values, null, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012940 Binder.restoreCallingIdentity(origId);
12941 }
12942 }
12943
12944 /**
12945 * Do either or both things: (1) change the current configuration, and (2)
12946 * make sure the given activity is running with the (now) current
12947 * configuration. Returns true if the activity has been left running, or
12948 * false if <var>starting</var> is being destroyed to match the new
12949 * configuration.
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012950 * @param persistent TODO
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012951 */
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012952 boolean updateConfigurationLocked(Configuration values,
Dianne Hackborn813075a62011-11-14 17:45:19 -080012953 ActivityRecord starting, boolean persistent, boolean initLocale) {
Mike Lockwood3a74bd32011-08-12 13:55:22 -070012954 // do nothing if we are headless
12955 if (mHeadless) return true;
12956
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012957 int changes = 0;
12958
12959 boolean kept = true;
12960
12961 if (values != null) {
12962 Configuration newConfig = new Configuration(mConfiguration);
12963 changes = newConfig.updateFrom(values);
12964 if (changes != 0) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070012965 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012966 Slog.i(TAG, "Updating configuration to: " + values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012967 }
12968
Doug Zongker2bec3d42009-12-04 12:52:44 -080012969 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012970
Dianne Hackborn813075a62011-11-14 17:45:19 -080012971 if (values.locale != null && !initLocale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012972 saveLocaleLocked(values.locale,
12973 !values.locale.equals(mConfiguration.locale),
12974 values.userSetLocale);
12975 }
12976
Dianne Hackborne36d6e22010-02-17 19:46:25 -080012977 mConfigurationSeq++;
12978 if (mConfigurationSeq <= 0) {
12979 mConfigurationSeq = 1;
12980 }
12981 newConfig.seq = mConfigurationSeq;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012982 mConfiguration = newConfig;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012983 Slog.i(TAG, "Config changed: " + newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012984
12985 final Configuration configCopy = new Configuration(mConfiguration);
Joe Onorato54a4a412011-11-02 20:50:08 -070012986
12987 // TODO: If our config changes, should we auto dismiss any currently
12988 // showing dialogs?
12989 mShowDialogs = shouldShowDialogs(newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012990
Dianne Hackborn826d17c2009-11-12 12:55:51 -080012991 AttributeCache ac = AttributeCache.instance();
12992 if (ac != null) {
Dianne Hackborn813075a62011-11-14 17:45:19 -080012993 ac.updateConfiguration(configCopy);
Dianne Hackborn826d17c2009-11-12 12:55:51 -080012994 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012995
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070012996 // Make sure all resources in our process are updated
12997 // right now, so that anyone who is going to retrieve
12998 // resource values after we return will be sure to get
12999 // the new ones. This is especially important during
13000 // boot, where the first config change needs to guarantee
13001 // all resources have that config before following boot
13002 // code is executed.
Dianne Hackborn813075a62011-11-14 17:45:19 -080013003 mSystemThread.applyConfigurationToResources(configCopy);
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070013004
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013005 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080013006 Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013007 msg.obj = new Configuration(configCopy);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080013008 mHandler.sendMessage(msg);
13009 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013010
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013011 for (int i=mLruProcesses.size()-1; i>=0; i--) {
13012 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013013 try {
13014 if (app.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013015 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending to proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013016 + app.processName + " new config " + mConfiguration);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013017 app.thread.scheduleConfigurationChanged(configCopy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013018 }
13019 } catch (Exception e) {
13020 }
13021 }
13022 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080013023 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
13024 | Intent.FLAG_RECEIVER_REPLACE_PENDING);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013025 broadcastIntentLocked(null, null, intent, null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070013026 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080013027 if ((changes&ActivityInfo.CONFIG_LOCALE) != 0) {
13028 broadcastIntentLocked(null, null,
13029 new Intent(Intent.ACTION_LOCALE_CHANGED),
13030 null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070013031 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080013032 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013033 }
13034 }
13035
13036 if (changes != 0 && starting == null) {
13037 // If the configuration changed, and the caller is not already
13038 // in the process of starting an activity, then find the top
13039 // activity to check if its configuration needs to change.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013040 starting = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013041 }
13042
13043 if (starting != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013044 kept = mMainStack.ensureActivityConfigurationLocked(starting, changes);
Dianne Hackborn5f4d6432010-12-21 20:40:11 -080013045 // And we need to make sure at this point that all other activities
13046 // are made visible with the correct configuration.
13047 mMainStack.ensureActivitiesVisibleLocked(starting, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013048 }
13049
Dianne Hackborne36d6e22010-02-17 19:46:25 -080013050 if (values != null && mWindowManager != null) {
13051 mWindowManager.setNewConfiguration(mConfiguration);
13052 }
13053
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013054 return kept;
13055 }
Joe Onorato54a4a412011-11-02 20:50:08 -070013056
13057 /**
13058 * Decide based on the configuration whether we should shouw the ANR,
13059 * crash, etc dialogs. The idea is that if there is no affordnace to
13060 * press the on-screen buttons, we shouldn't show the dialog.
13061 *
13062 * A thought: SystemUI might also want to get told about this, the Power
13063 * dialog / global actions also might want different behaviors.
13064 */
13065 private static final boolean shouldShowDialogs(Configuration config) {
13066 return !(config.keyboard == Configuration.KEYBOARD_NOKEYS
13067 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH);
13068 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013069
13070 /**
13071 * Save the locale. You must be inside a synchronized (this) block.
13072 */
13073 private void saveLocaleLocked(Locale l, boolean isDiff, boolean isPersist) {
13074 if(isDiff) {
13075 SystemProperties.set("user.language", l.getLanguage());
13076 SystemProperties.set("user.region", l.getCountry());
13077 }
13078
13079 if(isPersist) {
13080 SystemProperties.set("persist.sys.language", l.getLanguage());
13081 SystemProperties.set("persist.sys.country", l.getCountry());
13082 SystemProperties.set("persist.sys.localevar", l.getVariant());
13083 }
13084 }
13085
13086 // =========================================================
13087 // LIFETIME MANAGEMENT
13088 // =========================================================
13089
Christopher Tatef46723b2012-01-26 14:19:24 -080013090 // Returns which broadcast queue the app is the current [or imminent] receiver
13091 // on, or 'null' if the app is not an active broadcast recipient.
13092 private BroadcastQueue isReceivingBroadcast(ProcessRecord app) {
13093 BroadcastRecord r = app.curReceiver;
13094 if (r != null) {
13095 return r.queue;
13096 }
13097
13098 // It's not the current receiver, but it might be starting up to become one
13099 synchronized (this) {
13100 for (BroadcastQueue queue : mBroadcastQueues) {
13101 r = queue.mPendingBroadcast;
13102 if (r != null && r.curApp == app) {
13103 // found it; report which queue it's in
13104 return queue;
13105 }
13106 }
13107 }
13108
13109 return null;
13110 }
13111
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013112 private final int computeOomAdjLocked(ProcessRecord app, int hiddenAdj,
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013113 ProcessRecord TOP_APP, boolean recursed, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013114 if (mAdjSeq == app.adjSeq) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013115 // This adjustment has already been computed. If we are calling
13116 // from the top, we may have already computed our adjustment with
13117 // an earlier hidden adjustment that isn't really for us... if
13118 // so, use the new hidden adjustment.
13119 if (!recursed && app.hidden) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013120 app.curAdj = app.curRawAdj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013121 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013122 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013123 }
13124
13125 if (app.thread == null) {
13126 app.adjSeq = mAdjSeq;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013127 app.curSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013128 return (app.curAdj=ProcessList.HIDDEN_APP_MAX_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013129 }
13130
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013131 app.adjTypeCode = ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN;
13132 app.adjSource = null;
13133 app.adjTarget = null;
13134 app.empty = false;
13135 app.hidden = false;
13136
13137 final int activitiesSize = app.activities.size();
13138
Dianne Hackborn7d608422011-08-07 16:24:18 -070013139 if (app.maxAdj <= ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013140 // The max adjustment doesn't allow this app to be anything
13141 // below foreground, so it is not worth doing work for it.
13142 app.adjType = "fixed";
13143 app.adjSeq = mAdjSeq;
13144 app.curRawAdj = app.maxAdj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013145 app.foregroundActivities = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013146 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013147 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013148 // System process can do UI, and when they do we want to have
13149 // them trim their memory after the user leaves the UI. To
13150 // facilitate this, here we need to determine whether or not it
13151 // is currently showing UI.
13152 app.systemNoUi = true;
13153 if (app == TOP_APP) {
13154 app.systemNoUi = false;
13155 } else if (activitiesSize > 0) {
13156 for (int j = 0; j < activitiesSize; j++) {
13157 final ActivityRecord r = app.activities.get(j);
13158 if (r.visible) {
13159 app.systemNoUi = false;
13160 break;
13161 }
13162 }
13163 }
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013164 return (app.curAdj=app.maxAdj);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013165 }
13166
13167 final boolean hadForegroundActivities = app.foregroundActivities;
13168
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013169 app.foregroundActivities = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013170 app.keeping = false;
13171 app.systemNoUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013172
The Android Open Source Project4df24232009-03-05 14:34:35 -080013173 // Determine the importance of the process, starting with most
13174 // important to least, and assign an appropriate OOM adjustment.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013175 int adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013176 int schedGroup;
Christopher Tatef46723b2012-01-26 14:19:24 -080013177 BroadcastQueue queue;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013178 if (app == TOP_APP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013179 // The last app on the list is the foreground app.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013180 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013181 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013182 app.adjType = "top-activity";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013183 app.foregroundActivities = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013184 } else if (app.instrumentationClass != null) {
13185 // Don't want to kill running instrumentation.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013186 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013187 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013188 app.adjType = "instrumentation";
Christopher Tatef46723b2012-01-26 14:19:24 -080013189 } else if ((queue = isReceivingBroadcast(app)) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013190 // An app that is currently receiving a broadcast also
Christopher Tatef46723b2012-01-26 14:19:24 -080013191 // counts as being in the foreground for OOM killer purposes.
13192 // It's placed in a sched group based on the nature of the
13193 // broadcast as reflected by which queue it's active in.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013194 adj = ProcessList.FOREGROUND_APP_ADJ;
Christopher Tatef46723b2012-01-26 14:19:24 -080013195 schedGroup = (queue == mFgBroadcastQueue)
13196 ? Process.THREAD_GROUP_DEFAULT : Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013197 app.adjType = "broadcast";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013198 } else if (app.executingServices.size() > 0) {
13199 // An app that is currently executing a service callback also
13200 // counts as being in the foreground.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013201 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013202 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013203 app.adjType = "exec-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013204 } else if (activitiesSize > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013205 // This app is in the background with paused activities.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013206 // We inspect activities to potentially upgrade adjustment further below.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013207 adj = hiddenAdj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013208 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013209 app.hidden = true;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013210 app.adjType = "bg-activities";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013211 } else {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013212 // A very not-needed process. If this is lower in the lru list,
13213 // we will push it in to the empty bucket.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013214 adj = hiddenAdj;
13215 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013216 app.hidden = true;
13217 app.empty = true;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013218 app.adjType = "bg-empty";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013219 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013220
13221 // Examine all activities if not already foreground.
13222 if (!app.foregroundActivities && activitiesSize > 0) {
13223 for (int j = 0; j < activitiesSize; j++) {
13224 final ActivityRecord r = app.activities.get(j);
13225 if (r.visible) {
13226 // App has a visible activity; only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013227 if (adj > ProcessList.VISIBLE_APP_ADJ) {
13228 adj = ProcessList.VISIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013229 app.adjType = "visible";
13230 }
13231 schedGroup = Process.THREAD_GROUP_DEFAULT;
13232 app.hidden = false;
13233 app.foregroundActivities = true;
13234 break;
13235 } else if (r.state == ActivityState.PAUSING || r.state == ActivityState.PAUSED
13236 || r.state == ActivityState.STOPPING) {
13237 // Only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013238 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13239 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013240 app.adjType = "stopping";
13241 }
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -080013242 app.hidden = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013243 app.foregroundActivities = true;
13244 }
13245 }
13246 }
13247
Dianne Hackborn7d608422011-08-07 16:24:18 -070013248 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013249 if (app.foregroundServices) {
13250 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013251 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013252 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013253 app.adjType = "foreground-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013254 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013255 } else if (app.forcingToForeground != null) {
13256 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013257 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013258 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013259 app.adjType = "force-foreground";
13260 app.adjSource = app.forcingToForeground;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013261 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013262 }
13263 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013264
Dianne Hackborn7d608422011-08-07 16:24:18 -070013265 if (adj > ProcessList.HEAVY_WEIGHT_APP_ADJ && app == mHeavyWeightProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013266 // We don't want to kill the current heavy-weight process.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013267 adj = ProcessList.HEAVY_WEIGHT_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013268 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013269 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013270 app.adjType = "heavy";
13271 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013272
Dianne Hackborn7d608422011-08-07 16:24:18 -070013273 if (adj > ProcessList.HOME_APP_ADJ && app == mHomeProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013274 // This process is hosting what we currently consider to be the
13275 // home app, so we don't want to let it go into the background.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013276 adj = ProcessList.HOME_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013277 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013278 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013279 app.adjType = "home";
13280 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013281
Dianne Hackbornf35fe232011-11-01 19:25:20 -070013282 if (adj > ProcessList.PREVIOUS_APP_ADJ && app == mPreviousProcess
13283 && app.activities.size() > 0) {
13284 // This was the previous process that showed UI to the user.
13285 // We want to try to keep it around more aggressively, to give
13286 // a good experience around switching between two apps.
13287 adj = ProcessList.PREVIOUS_APP_ADJ;
13288 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
13289 app.hidden = false;
13290 app.adjType = "previous";
13291 }
13292
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013293 if (false) Slog.i(TAG, "OOM " + app + ": initial adj=" + adj
13294 + " reason=" + app.adjType);
13295
The Android Open Source Project4df24232009-03-05 14:34:35 -080013296 // By default, we use the computed adjustment. It may be changed if
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013297 // there are applications dependent on our services or providers, but
13298 // this gives us a baseline and makes sure we don't get into an
13299 // infinite recursion.
13300 app.adjSeq = mAdjSeq;
13301 app.curRawAdj = adj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013302
Christopher Tate6fa95972009-06-05 18:43:55 -070013303 if (mBackupTarget != null && app == mBackupTarget.app) {
13304 // If possible we want to avoid killing apps while they're being backed up
Dianne Hackborn7d608422011-08-07 16:24:18 -070013305 if (adj > ProcessList.BACKUP_APP_ADJ) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013306 if (DEBUG_BACKUP) Slog.v(TAG, "oom BACKUP_APP_ADJ for " + app);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013307 adj = ProcessList.BACKUP_APP_ADJ;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013308 app.adjType = "backup";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013309 app.hidden = false;
Christopher Tate6fa95972009-06-05 18:43:55 -070013310 }
13311 }
13312
Dianne Hackborn7d608422011-08-07 16:24:18 -070013313 if (app.services.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013314 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013315 final long now = SystemClock.uptimeMillis();
13316 // This process is more important if the top activity is
13317 // bound to the service.
Dianne Hackborn860755f2010-06-03 18:47:52 -070013318 Iterator<ServiceRecord> jt = app.services.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013319 while (jt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013320 ServiceRecord s = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013321 if (s.startRequested) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013322 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013323 // If this process has shown some UI, let it immediately
13324 // go to the LRU list because it may be pretty heavy with
13325 // UI stuff. We'll tag it with a label just to help
13326 // debug and understand what is going on.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013327 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013328 app.adjType = "started-bg-ui-services";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013329 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013330 } else {
13331 if (now < (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
13332 // This service has seen some activity within
13333 // recent memory, so we will keep its process ahead
13334 // of the background processes.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013335 if (adj > ProcessList.SERVICE_ADJ) {
13336 adj = ProcessList.SERVICE_ADJ;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013337 app.adjType = "started-services";
13338 app.hidden = false;
13339 }
13340 }
13341 // If we have let the service slide into the background
13342 // state, still have some text describing what it is doing
13343 // even though the service no longer has an impact.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013344 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013345 app.adjType = "started-bg-services";
13346 }
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080013347 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013348 // Don't kill this process because it is doing work; it
13349 // has said it is doing work.
13350 app.keeping = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013351 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013352 if (s.connections.size() > 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013353 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013354 Iterator<ArrayList<ConnectionRecord>> kt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013355 = s.connections.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013356 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013357 ArrayList<ConnectionRecord> clist = kt.next();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013358 for (int i=0; i<clist.size() && adj > ProcessList.FOREGROUND_APP_ADJ; i++) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013359 // XXX should compute this based on the max of
13360 // all connected clients.
13361 ConnectionRecord cr = clist.get(i);
13362 if (cr.binding.client == app) {
13363 // Binding to ourself is not interesting.
13364 continue;
13365 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013366 if ((cr.flags&Context.BIND_WAIVE_PRIORITY) == 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013367 ProcessRecord client = cr.binding.client;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013368 int clientAdj = adj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013369 int myHiddenAdj = hiddenAdj;
13370 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013371 if (client.hiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013372 myHiddenAdj = client.hiddenAdj;
13373 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013374 myHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013375 }
13376 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013377 clientAdj = computeOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013378 client, myHiddenAdj, TOP_APP, true, doingAll);
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013379 String adjType = null;
13380 if ((cr.flags&Context.BIND_ALLOW_OOM_MANAGEMENT) != 0) {
13381 // Not doing bind OOM management, so treat
13382 // this guy more like a started service.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013383 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013384 // If this process has shown some UI, let it immediately
13385 // go to the LRU list because it may be pretty heavy with
13386 // UI stuff. We'll tag it with a label just to help
13387 // debug and understand what is going on.
13388 if (adj > clientAdj) {
13389 adjType = "bound-bg-ui-services";
13390 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013391 app.hidden = false;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013392 clientAdj = adj;
13393 } else {
13394 if (now >= (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
13395 // This service has not seen activity within
13396 // recent memory, so allow it to drop to the
13397 // LRU list if there is no other reason to keep
13398 // it around. We'll also tag it with a label just
13399 // to help debug and undertand what is going on.
13400 if (adj > clientAdj) {
13401 adjType = "bound-bg-services";
13402 }
13403 clientAdj = adj;
13404 }
13405 }
13406 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013407 if (adj > clientAdj) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013408 // If this process has recently shown UI, and
13409 // the process that is binding to it is less
13410 // important than being visible, then we don't
13411 // care about the binding as much as we care
13412 // about letting this process get into the LRU
13413 // list to be killed and restarted if needed for
13414 // memory.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013415 if (app.hasShownUi && app != mHomeProcess
13416 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013417 adjType = "bound-bg-ui-services";
13418 } else {
13419 if ((cr.flags&(Context.BIND_ABOVE_CLIENT
13420 |Context.BIND_IMPORTANT)) != 0) {
13421 adj = clientAdj;
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070013422 } else if ((cr.flags&Context.BIND_NOT_VISIBLE) != 0
13423 && clientAdj < ProcessList.PERCEPTIBLE_APP_ADJ
13424 && adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13425 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13426 } else if (clientAdj > ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013427 adj = clientAdj;
13428 } else {
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070013429 app.pendingUiClean = true;
13430 if (adj > ProcessList.VISIBLE_APP_ADJ) {
13431 adj = ProcessList.VISIBLE_APP_ADJ;
13432 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013433 }
13434 if (!client.hidden) {
13435 app.hidden = false;
13436 }
13437 if (client.keeping) {
13438 app.keeping = true;
13439 }
13440 adjType = "service";
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013441 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013442 }
13443 if (adjType != null) {
13444 app.adjType = adjType;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013445 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13446 .REASON_SERVICE_IN_USE;
13447 app.adjSource = cr.binding.client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013448 app.adjSourceOom = clientAdj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013449 app.adjTarget = s.name;
13450 }
13451 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
13452 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
13453 schedGroup = Process.THREAD_GROUP_DEFAULT;
13454 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013455 }
13456 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013457 if ((cr.flags&Context.BIND_ADJUST_WITH_ACTIVITY) != 0) {
13458 ActivityRecord a = cr.activity;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013459 if (a != null && adj > ProcessList.FOREGROUND_APP_ADJ &&
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013460 (a.visible || a.state == ActivityState.RESUMED
13461 || a.state == ActivityState.PAUSING)) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013462 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013463 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
13464 schedGroup = Process.THREAD_GROUP_DEFAULT;
13465 }
13466 app.hidden = false;
13467 app.adjType = "service";
13468 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13469 .REASON_SERVICE_IN_USE;
13470 app.adjSource = a;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013471 app.adjSourceOom = adj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013472 app.adjTarget = s.name;
13473 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013474 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013475 }
13476 }
13477 }
13478 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013479
Dianne Hackborn287952c2010-09-22 22:34:31 -070013480 // Finally, if this process has active services running in it, we
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013481 // would like to avoid killing it unless it would prevent the current
13482 // application from running. By default we put the process in
13483 // with the rest of the background processes; as we scan through
13484 // its services we may bump it up from there.
13485 if (adj > hiddenAdj) {
13486 adj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013487 app.hidden = false;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013488 app.adjType = "bg-services";
13489 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013490 }
13491
Dianne Hackborn7d608422011-08-07 16:24:18 -070013492 if (app.pubProviders.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013493 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013494 Iterator<ContentProviderRecord> jt = app.pubProviders.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013495 while (jt.hasNext() && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013496 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013497 ContentProviderRecord cpr = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013498 if (cpr.clients.size() != 0) {
13499 Iterator<ProcessRecord> kt = cpr.clients.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013500 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013501 ProcessRecord client = kt.next();
The Android Open Source Project10592532009-03-18 17:39:46 -070013502 if (client == app) {
13503 // Being our own client is not interesting.
13504 continue;
13505 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013506 int myHiddenAdj = hiddenAdj;
13507 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013508 if (client.hiddenAdj > ProcessList.FOREGROUND_APP_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013509 myHiddenAdj = client.hiddenAdj;
13510 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013511 myHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013512 }
13513 }
13514 int clientAdj = computeOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013515 client, myHiddenAdj, TOP_APP, true, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013516 if (adj > clientAdj) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013517 if (app.hasShownUi && app != mHomeProcess
13518 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013519 app.adjType = "bg-ui-provider";
13520 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013521 adj = clientAdj > ProcessList.FOREGROUND_APP_ADJ
13522 ? clientAdj : ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013523 app.adjType = "provider";
13524 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013525 if (!client.hidden) {
13526 app.hidden = false;
13527 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013528 if (client.keeping) {
13529 app.keeping = true;
13530 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070013531 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13532 .REASON_PROVIDER_IN_USE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013533 app.adjSource = client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013534 app.adjSourceOom = clientAdj;
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070013535 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013536 }
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013537 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
13538 schedGroup = Process.THREAD_GROUP_DEFAULT;
13539 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013540 }
13541 }
13542 // If the provider has external (non-framework) process
13543 // dependencies, ensure that its adjustment is at least
13544 // FOREGROUND_APP_ADJ.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080013545 if (cpr.hasExternalProcessHandles()) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013546 if (adj > ProcessList.FOREGROUND_APP_ADJ) {
13547 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013548 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013549 app.hidden = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013550 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013551 app.adjType = "provider";
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070013552 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013553 }
13554 }
13555 }
13556 }
13557
13558 app.curRawAdj = adj;
13559
Joe Onorato8a9b2202010-02-26 18:56:32 -080013560 //Slog.i(TAG, "OOM ADJ " + app + ": pid=" + app.pid +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013561 // " adj=" + adj + " curAdj=" + app.curAdj + " maxAdj=" + app.maxAdj);
13562 if (adj > app.maxAdj) {
13563 adj = app.maxAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013564 if (app.maxAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013565 schedGroup = Process.THREAD_GROUP_DEFAULT;
13566 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013567 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013568 if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070013569 app.keeping = true;
13570 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013571
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013572 if (app.hasAboveClient) {
13573 // If this process has bound to any services with BIND_ABOVE_CLIENT,
13574 // then we need to drop its adjustment to be lower than the service's
13575 // in order to honor the request. We want to drop it by one adjustment
13576 // level... but there is special meaning applied to various levels so
13577 // we will skip some of them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013578 if (adj < ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013579 // System process will not get dropped, ever
Dianne Hackborn7d608422011-08-07 16:24:18 -070013580 } else if (adj < ProcessList.VISIBLE_APP_ADJ) {
13581 adj = ProcessList.VISIBLE_APP_ADJ;
13582 } else if (adj < ProcessList.PERCEPTIBLE_APP_ADJ) {
13583 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13584 } else if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
13585 adj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013586 } else if (adj < ProcessList.HIDDEN_APP_MAX_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013587 adj++;
13588 }
13589 }
13590
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013591 if (adj == ProcessList.SERVICE_ADJ) {
13592 if (doingAll) {
13593 app.serviceb = mNewNumServiceProcs > (mNumServiceProcs/3);
13594 mNewNumServiceProcs++;
13595 }
13596 if (app.serviceb) {
13597 adj = ProcessList.SERVICE_B_ADJ;
13598 }
13599 } else {
13600 app.serviceb = false;
13601 }
13602
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013603 app.curAdj = adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013604 app.curSchedGroup = schedGroup;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013605
13606 if (hadForegroundActivities != app.foregroundActivities) {
Jeff Sharkey287bd832011-05-28 19:36:26 -070013607 mHandler.obtainMessage(DISPATCH_FOREGROUND_ACTIVITIES_CHANGED, app.pid, app.info.uid,
13608 app.foregroundActivities).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013609 }
13610
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013611 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013612 }
13613
13614 /**
13615 * Ask a given process to GC right now.
13616 */
13617 final void performAppGcLocked(ProcessRecord app) {
13618 try {
13619 app.lastRequestedGc = SystemClock.uptimeMillis();
13620 if (app.thread != null) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013621 if (app.reportLowMemory) {
13622 app.reportLowMemory = false;
13623 app.thread.scheduleLowMemory();
13624 } else {
13625 app.thread.processInBackground();
13626 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013627 }
13628 } catch (Exception e) {
13629 // whatever.
13630 }
13631 }
13632
13633 /**
13634 * Returns true if things are idle enough to perform GCs.
13635 */
Josh Bartel7f208742010-02-25 11:01:44 -060013636 private final boolean canGcNowLocked() {
Christopher Tatef46723b2012-01-26 14:19:24 -080013637 boolean processingBroadcasts = false;
13638 for (BroadcastQueue q : mBroadcastQueues) {
13639 if (q.mParallelBroadcasts.size() != 0 || q.mOrderedBroadcasts.size() != 0) {
13640 processingBroadcasts = true;
13641 }
13642 }
13643 return !processingBroadcasts
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013644 && (mSleeping || (mMainStack.mResumedActivity != null &&
13645 mMainStack.mResumedActivity.idle));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013646 }
13647
13648 /**
13649 * Perform GCs on all processes that are waiting for it, but only
13650 * if things are idle.
13651 */
13652 final void performAppGcsLocked() {
13653 final int N = mProcessesToGc.size();
13654 if (N <= 0) {
13655 return;
13656 }
Josh Bartel7f208742010-02-25 11:01:44 -060013657 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013658 while (mProcessesToGc.size() > 0) {
13659 ProcessRecord proc = mProcessesToGc.remove(0);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013660 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013661 if ((proc.lastRequestedGc+GC_MIN_INTERVAL)
13662 <= SystemClock.uptimeMillis()) {
13663 // To avoid spamming the system, we will GC processes one
13664 // at a time, waiting a few seconds between each.
13665 performAppGcLocked(proc);
13666 scheduleAppGcsLocked();
13667 return;
13668 } else {
13669 // It hasn't been long enough since we last GCed this
13670 // process... put it in the list to wait for its time.
13671 addProcessToGcListLocked(proc);
13672 break;
13673 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013674 }
13675 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013676
13677 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013678 }
13679 }
13680
13681 /**
13682 * If all looks good, perform GCs on all processes waiting for them.
13683 */
13684 final void performAppGcsIfAppropriateLocked() {
Josh Bartel7f208742010-02-25 11:01:44 -060013685 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013686 performAppGcsLocked();
13687 return;
13688 }
13689 // Still not idle, wait some more.
13690 scheduleAppGcsLocked();
13691 }
13692
13693 /**
13694 * Schedule the execution of all pending app GCs.
13695 */
13696 final void scheduleAppGcsLocked() {
13697 mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013698
13699 if (mProcessesToGc.size() > 0) {
13700 // Schedule a GC for the time to the next process.
13701 ProcessRecord proc = mProcessesToGc.get(0);
13702 Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG);
13703
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013704 long when = proc.lastRequestedGc + GC_MIN_INTERVAL;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013705 long now = SystemClock.uptimeMillis();
13706 if (when < (now+GC_TIMEOUT)) {
13707 when = now + GC_TIMEOUT;
13708 }
13709 mHandler.sendMessageAtTime(msg, when);
13710 }
13711 }
13712
13713 /**
13714 * Add a process to the array of processes waiting to be GCed. Keeps the
13715 * list in sorted order by the last GC time. The process can't already be
13716 * on the list.
13717 */
13718 final void addProcessToGcListLocked(ProcessRecord proc) {
13719 boolean added = false;
13720 for (int i=mProcessesToGc.size()-1; i>=0; i--) {
13721 if (mProcessesToGc.get(i).lastRequestedGc <
13722 proc.lastRequestedGc) {
13723 added = true;
13724 mProcessesToGc.add(i+1, proc);
13725 break;
13726 }
13727 }
13728 if (!added) {
13729 mProcessesToGc.add(0, proc);
13730 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013731 }
13732
13733 /**
13734 * Set up to ask a process to GC itself. This will either do it
13735 * immediately, or put it on the list of processes to gc the next
13736 * time things are idle.
13737 */
13738 final void scheduleAppGcLocked(ProcessRecord app) {
13739 long now = SystemClock.uptimeMillis();
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013740 if ((app.lastRequestedGc+GC_MIN_INTERVAL) > now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013741 return;
13742 }
13743 if (!mProcessesToGc.contains(app)) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013744 addProcessToGcListLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013745 scheduleAppGcsLocked();
13746 }
13747 }
13748
Dianne Hackborn287952c2010-09-22 22:34:31 -070013749 final void checkExcessivePowerUsageLocked(boolean doKills) {
13750 updateCpuStatsNow();
13751
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013752 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013753 boolean doWakeKills = doKills;
13754 boolean doCpuKills = doKills;
13755 if (mLastPowerCheckRealtime == 0) {
13756 doWakeKills = false;
13757 }
13758 if (mLastPowerCheckUptime == 0) {
13759 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013760 }
13761 if (stats.isScreenOn()) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070013762 doWakeKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013763 }
13764 final long curRealtime = SystemClock.elapsedRealtime();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013765 final long realtimeSince = curRealtime - mLastPowerCheckRealtime;
13766 final long curUptime = SystemClock.uptimeMillis();
13767 final long uptimeSince = curUptime - mLastPowerCheckUptime;
13768 mLastPowerCheckRealtime = curRealtime;
13769 mLastPowerCheckUptime = curUptime;
13770 if (realtimeSince < WAKE_LOCK_MIN_CHECK_DURATION) {
13771 doWakeKills = false;
13772 }
13773 if (uptimeSince < CPU_MIN_CHECK_DURATION) {
13774 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013775 }
13776 int i = mLruProcesses.size();
13777 while (i > 0) {
13778 i--;
13779 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013780 if (!app.keeping) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013781 long wtime;
13782 synchronized (stats) {
13783 wtime = stats.getProcessWakeTime(app.info.uid,
13784 app.pid, curRealtime);
13785 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013786 long wtimeUsed = wtime - app.lastWakeTime;
13787 long cputimeUsed = app.curCpuTime - app.lastCpuTime;
13788 if (DEBUG_POWER) {
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013789 StringBuilder sb = new StringBuilder(128);
13790 sb.append("Wake for ");
13791 app.toShortString(sb);
13792 sb.append(": over ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013793 TimeUtils.formatDuration(realtimeSince, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013794 sb.append(" used ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013795 TimeUtils.formatDuration(wtimeUsed, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013796 sb.append(" (");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013797 sb.append((wtimeUsed*100)/realtimeSince);
13798 sb.append("%)");
13799 Slog.i(TAG, sb.toString());
13800 sb.setLength(0);
13801 sb.append("CPU for ");
13802 app.toShortString(sb);
13803 sb.append(": over ");
13804 TimeUtils.formatDuration(uptimeSince, sb);
13805 sb.append(" used ");
13806 TimeUtils.formatDuration(cputimeUsed, sb);
13807 sb.append(" (");
13808 sb.append((cputimeUsed*100)/uptimeSince);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013809 sb.append("%)");
13810 Slog.i(TAG, sb.toString());
13811 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013812 // If a process has held a wake lock for more
13813 // than 50% of the time during this period,
13814 // that sounds pad. Kill!
Dianne Hackborn287952c2010-09-22 22:34:31 -070013815 if (doWakeKills && realtimeSince > 0
13816 && ((wtimeUsed*100)/realtimeSince) >= 50) {
13817 synchronized (stats) {
13818 stats.reportExcessiveWakeLocked(app.info.uid, app.processName,
13819 realtimeSince, wtimeUsed);
13820 }
13821 Slog.w(TAG, "Excessive wake lock in " + app.processName
13822 + " (pid " + app.pid + "): held " + wtimeUsed
13823 + " during " + realtimeSince);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013824 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13825 app.processName, app.setAdj, "excessive wake lock");
13826 Process.killProcessQuiet(app.pid);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013827 } else if (doCpuKills && uptimeSince > 0
13828 && ((cputimeUsed*100)/uptimeSince) >= 50) {
13829 synchronized (stats) {
13830 stats.reportExcessiveCpuLocked(app.info.uid, app.processName,
13831 uptimeSince, cputimeUsed);
13832 }
13833 Slog.w(TAG, "Excessive CPU in " + app.processName
13834 + " (pid " + app.pid + "): used " + cputimeUsed
13835 + " during " + uptimeSince);
13836 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13837 app.processName, app.setAdj, "excessive cpu");
13838 Process.killProcessQuiet(app.pid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013839 } else {
13840 app.lastWakeTime = wtime;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013841 app.lastCpuTime = app.curCpuTime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013842 }
13843 }
13844 }
13845 }
13846
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013847 private final boolean updateOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013848 ProcessRecord app, int hiddenAdj, ProcessRecord TOP_APP, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013849 app.hiddenAdj = hiddenAdj;
13850
13851 if (app.thread == null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013852 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013853 }
13854
Dianne Hackborn287952c2010-09-22 22:34:31 -070013855 final boolean wasKeeping = app.keeping;
13856
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013857 boolean success = true;
13858
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013859 computeOomAdjLocked(app, hiddenAdj, TOP_APP, false, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013860
Jeff Brown10e89712011-07-08 18:52:57 -070013861 if (app.curRawAdj != app.setRawAdj) {
Dianne Hackborn905577f2011-09-07 18:31:28 -070013862 if (false) {
13863 // Removing for now. Forcing GCs is not so useful anymore
13864 // with Dalvik, and the new memory level hint facility is
13865 // better for what we need to do these days.
13866 if (app.curRawAdj > ProcessList.FOREGROUND_APP_ADJ
13867 && app.setRawAdj <= ProcessList.FOREGROUND_APP_ADJ) {
13868 // If this app is transitioning from foreground to
13869 // non-foreground, have it do a gc.
13870 scheduleAppGcLocked(app);
13871 } else if (app.curRawAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13872 && app.setRawAdj < ProcessList.HIDDEN_APP_MIN_ADJ) {
13873 // Likewise do a gc when an app is moving in to the
13874 // background (such as a service stopping).
13875 scheduleAppGcLocked(app);
13876 }
Jeff Brown10e89712011-07-08 18:52:57 -070013877 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013878
Jeff Brown10e89712011-07-08 18:52:57 -070013879 if (wasKeeping && !app.keeping) {
13880 // This app is no longer something we want to keep. Note
13881 // its current wake lock time to later know to kill it if
13882 // it is not behaving well.
13883 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
13884 synchronized (stats) {
13885 app.lastWakeTime = stats.getProcessWakeTime(app.info.uid,
13886 app.pid, SystemClock.elapsedRealtime());
13887 }
13888 app.lastCpuTime = app.curCpuTime;
13889 }
13890
13891 app.setRawAdj = app.curRawAdj;
13892 }
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013893
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013894 if (app.curAdj != app.setAdj) {
13895 if (Process.setOomAdj(app.pid, app.curAdj)) {
Dianne Hackbornbbb09ac2011-11-30 11:31:29 -080013896 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013897 TAG, "Set " + app.pid + " " + app.processName +
13898 " adj " + app.curAdj + ": " + app.adjType);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013899 app.setAdj = app.curAdj;
Jeff Brown10e89712011-07-08 18:52:57 -070013900 } else {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013901 success = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013902 Slog.w(TAG, "Failed setting oom adj of " + app + " to " + app.curAdj);
Jeff Brown10e89712011-07-08 18:52:57 -070013903 }
13904 }
13905 if (app.setSchedGroup != app.curSchedGroup) {
13906 app.setSchedGroup = app.curSchedGroup;
13907 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
13908 "Setting process group of " + app.processName
13909 + " to " + app.curSchedGroup);
13910 if (app.waitingToKill != null &&
13911 app.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
13912 Slog.i(TAG, "Killing " + app.toShortString() + ": " + app.waitingToKill);
13913 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13914 app.processName, app.setAdj, app.waitingToKill);
13915 Process.killProcessQuiet(app.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013916 success = false;
Jeff Brown10e89712011-07-08 18:52:57 -070013917 } else {
13918 if (true) {
13919 long oldId = Binder.clearCallingIdentity();
13920 try {
13921 Process.setProcessGroup(app.pid, app.curSchedGroup);
13922 } catch (Exception e) {
13923 Slog.w(TAG, "Failed setting process group of " + app.pid
13924 + " to " + app.curSchedGroup);
13925 e.printStackTrace();
13926 } finally {
13927 Binder.restoreCallingIdentity(oldId);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013928 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013929 } else {
Jeff Brown10e89712011-07-08 18:52:57 -070013930 if (app.thread != null) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070013931 try {
Jeff Brown10e89712011-07-08 18:52:57 -070013932 app.thread.setSchedulingGroup(app.curSchedGroup);
13933 } catch (RemoteException e) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070013934 }
13935 }
13936 }
13937 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013938 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013939 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013940 }
13941
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013942 private final ActivityRecord resumedAppLocked() {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013943 ActivityRecord resumedActivity = mMainStack.mResumedActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013944 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -080013945 resumedActivity = mMainStack.mPausingActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013946 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013947 resumedActivity = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013948 }
13949 }
13950 return resumedActivity;
13951 }
13952
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013953 private final boolean updateOomAdjLocked(ProcessRecord app) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013954 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013955 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
13956 int curAdj = app.curAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013957 final boolean wasHidden = curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13958 && curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013959
13960 mAdjSeq++;
13961
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013962 boolean success = updateOomAdjLocked(app, app.hiddenAdj, TOP_APP, false);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013963 final boolean nowHidden = app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13964 && app.curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013965 if (nowHidden != wasHidden) {
13966 // Changed to/from hidden state, so apps after it in the LRU
13967 // list may also be changed.
13968 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013969 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013970 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013971 }
13972
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013973 final void updateOomAdjLocked() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013974 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013975 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
13976
13977 if (false) {
13978 RuntimeException e = new RuntimeException();
13979 e.fillInStackTrace();
Joe Onorato8a9b2202010-02-26 18:56:32 -080013980 Slog.i(TAG, "updateOomAdj: top=" + TOP_ACT, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013981 }
13982
13983 mAdjSeq++;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013984 mNewNumServiceProcs = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013985
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080013986 // Let's determine how many processes we have running vs.
13987 // how many slots we have for background processes; we may want
13988 // to put multiple processes in a slot of there are enough of
13989 // them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013990 int numSlots = ProcessList.HIDDEN_APP_MAX_ADJ - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080013991 int factor = (mLruProcesses.size()-4)/numSlots;
13992 if (factor < 1) factor = 1;
13993 int step = 0;
Dianne Hackborn8633e682010-04-22 16:03:41 -070013994 int numHidden = 0;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080013995
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013996 // First update the OOM adjustment for each of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013997 // application processes based on their current state.
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013998 int i = mLruProcesses.size();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013999 int curHiddenAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014000 while (i > 0) {
14001 i--;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014002 ProcessRecord app = mLruProcesses.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080014003 //Slog.i(TAG, "OOM " + app + ": cur hidden=" + curHiddenAdj);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014004 updateOomAdjLocked(app, curHiddenAdj, TOP_APP, true);
14005 if (curHiddenAdj < ProcessList.HIDDEN_APP_MAX_ADJ
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014006 && app.curAdj == curHiddenAdj) {
14007 step++;
14008 if (step >= factor) {
14009 step = 0;
14010 curHiddenAdj++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014011 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014012 }
14013 if (!app.killedBackground) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070014014 if (app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014015 numHidden++;
14016 if (numHidden > mProcessLimit) {
14017 Slog.i(TAG, "No longer want " + app.processName
14018 + " (pid " + app.pid + "): hidden #" + numHidden);
14019 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14020 app.processName, app.setAdj, "too many background");
14021 app.killedBackground = true;
14022 Process.killProcessQuiet(app.pid);
Dianne Hackborn8633e682010-04-22 16:03:41 -070014023 }
14024 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -080014025 if (!app.killedBackground && app.isolated && app.services.size() <= 0) {
14026 // If this is an isolated process, and there are no
14027 // services running in it, then the process is no longer
14028 // needed. We agressively kill these because we can by
14029 // definition not re-use the same process again, and it is
14030 // good to avoid having whatever code was running in them
14031 // left sitting around after no longer needed.
14032 Slog.i(TAG, "Isolated process " + app.processName
14033 + " (pid " + app.pid + ") no longer needed");
14034 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14035 app.processName, app.setAdj, "isolated not needed");
14036 app.killedBackground = true;
14037 Process.killProcessQuiet(app.pid);
14038 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014039 }
14040 }
14041
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014042 mNumServiceProcs = mNewNumServiceProcs;
14043
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014044 // Now determine the memory trimming level of background processes.
14045 // Unfortunately we need to start at the back of the list to do this
14046 // properly. We only do this if the number of background apps we
14047 // are managing to keep around is less than half the maximum we desire;
14048 // if we are keeping a good number around, we'll let them use whatever
14049 // memory they want.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014050 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/2)) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014051 final int N = mLruProcesses.size();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080014052 factor = numHidden/3;
14053 int minFactor = 2;
14054 if (mHomeProcess != null) minFactor++;
14055 if (mPreviousProcess != null) minFactor++;
14056 if (factor < minFactor) factor = minFactor;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014057 step = 0;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014058 int fgTrimLevel;
14059 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/5)) {
14060 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL;
14061 } else if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/3)) {
14062 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW;
14063 } else {
14064 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE;
14065 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014066 int curLevel = ComponentCallbacks2.TRIM_MEMORY_COMPLETE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014067 for (i=0; i<N; i++) {
14068 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080014069 if (app.curAdj >= ProcessList.HOME_APP_ADJ
14070 && app.curAdj != ProcessList.SERVICE_B_ADJ
14071 && !app.killedBackground) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014072 if (app.trimMemoryLevel < curLevel && app.thread != null) {
14073 try {
14074 app.thread.scheduleTrimMemory(curLevel);
14075 } catch (RemoteException e) {
14076 }
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080014077 if (false) {
14078 // For now we won't do this; our memory trimming seems
14079 // to be good enough at this point that destroying
14080 // activities causes more harm than good.
14081 if (curLevel >= ComponentCallbacks2.TRIM_MEMORY_COMPLETE
14082 && app != mHomeProcess && app != mPreviousProcess) {
14083 // For these apps we will also finish their activities
14084 // to help them free memory.
14085 mMainStack.destroyActivitiesLocked(app, false, "trim");
14086 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014087 }
14088 }
14089 app.trimMemoryLevel = curLevel;
14090 step++;
14091 if (step >= factor) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014092 step = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014093 switch (curLevel) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014094 case ComponentCallbacks2.TRIM_MEMORY_COMPLETE:
14095 curLevel = ComponentCallbacks2.TRIM_MEMORY_MODERATE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014096 break;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014097 case ComponentCallbacks2.TRIM_MEMORY_MODERATE:
14098 curLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014099 break;
14100 }
14101 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070014102 } else if (app.curAdj == ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014103 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014104 && app.thread != null) {
14105 try {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014106 app.thread.scheduleTrimMemory(
14107 ComponentCallbacks2.TRIM_MEMORY_BACKGROUND);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014108 } catch (RemoteException e) {
14109 }
14110 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014111 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014112 } else {
14113 if ((app.curAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
14114 && app.pendingUiClean) {
14115 // If this application is now in the background and it
14116 // had done UI, then give it the special trim level to
14117 // have it free UI resources.
14118 final int level = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
14119 if (app.trimMemoryLevel < level && app.thread != null) {
14120 try {
14121 app.thread.scheduleTrimMemory(level);
14122 } catch (RemoteException e) {
14123 }
14124 }
14125 app.pendingUiClean = false;
14126 }
14127 if (app.trimMemoryLevel < fgTrimLevel && app.thread != null) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014128 try {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014129 app.thread.scheduleTrimMemory(fgTrimLevel);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014130 } catch (RemoteException e) {
14131 }
14132 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014133 app.trimMemoryLevel = fgTrimLevel;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014134 }
14135 }
14136 } else {
14137 final int N = mLruProcesses.size();
14138 for (i=0; i<N; i++) {
14139 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -070014140 if ((app.curAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014141 && app.pendingUiClean) {
14142 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
14143 && app.thread != null) {
14144 try {
14145 app.thread.scheduleTrimMemory(
14146 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
14147 } catch (RemoteException e) {
14148 }
14149 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014150 app.pendingUiClean = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014151 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014152 app.trimMemoryLevel = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014153 }
14154 }
14155
14156 if (mAlwaysFinishActivities) {
Dianne Hackborn28695e02011-11-02 21:59:51 -070014157 mMainStack.destroyActivitiesLocked(null, false, "always-finish");
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014158 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014159 }
14160
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014161 final void trimApplications() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014162 synchronized (this) {
14163 int i;
14164
14165 // First remove any unused application processes whose package
14166 // has been removed.
14167 for (i=mRemovedProcesses.size()-1; i>=0; i--) {
14168 final ProcessRecord app = mRemovedProcesses.get(i);
14169 if (app.activities.size() == 0
14170 && app.curReceiver == null && app.services.size() == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080014171 Slog.i(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014172 TAG, "Exiting empty application process "
14173 + app.processName + " ("
14174 + (app.thread != null ? app.thread.asBinder() : null)
14175 + ")\n");
14176 if (app.pid > 0 && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070014177 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14178 app.processName, app.setAdj, "empty");
14179 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014180 } else {
14181 try {
14182 app.thread.scheduleExit();
14183 } catch (Exception e) {
14184 // Ignore exceptions.
14185 }
14186 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070014187 cleanUpApplicationRecordLocked(app, false, true, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014188 mRemovedProcesses.remove(i);
14189
14190 if (app.persistent) {
14191 if (app.persistent) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080014192 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014193 }
14194 }
14195 }
14196 }
14197
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014198 // Now update the oom adj for all processes.
14199 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014200 }
14201 }
14202
14203 /** This method sends the specified signal to each of the persistent apps */
14204 public void signalPersistentProcesses(int sig) throws RemoteException {
14205 if (sig != Process.SIGNAL_USR1) {
14206 throw new SecurityException("Only SIGNAL_USR1 is allowed");
14207 }
14208
14209 synchronized (this) {
14210 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
14211 != PackageManager.PERMISSION_GRANTED) {
14212 throw new SecurityException("Requires permission "
14213 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
14214 }
14215
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014216 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
14217 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014218 if (r.thread != null && r.persistent) {
14219 Process.sendSignal(r.pid, sig);
14220 }
14221 }
14222 }
14223 }
14224
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014225 private void stopProfilerLocked(ProcessRecord proc, String path, int profileType) {
14226 if (proc == null || proc == mProfileProc) {
14227 proc = mProfileProc;
14228 path = mProfileFile;
14229 profileType = mProfileType;
14230 clearProfilerLocked();
14231 }
14232 if (proc == null) {
14233 return;
14234 }
14235 try {
14236 proc.thread.profilerControl(false, path, null, profileType);
14237 } catch (RemoteException e) {
14238 throw new IllegalStateException("Process disappeared");
14239 }
14240 }
14241
14242 private void clearProfilerLocked() {
14243 if (mProfileFd != null) {
14244 try {
14245 mProfileFd.close();
14246 } catch (IOException e) {
14247 }
14248 }
14249 mProfileApp = null;
14250 mProfileProc = null;
14251 mProfileFile = null;
14252 mProfileType = 0;
14253 mAutoStopProfiler = false;
14254 }
14255
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014256 public boolean profileControl(String process, boolean start,
Romain Guy7eabe552011-07-21 14:56:34 -070014257 String path, ParcelFileDescriptor fd, int profileType) throws RemoteException {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014258
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014259 try {
14260 synchronized (this) {
14261 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14262 // its own permission.
14263 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14264 != PackageManager.PERMISSION_GRANTED) {
14265 throw new SecurityException("Requires permission "
14266 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014267 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014268
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014269 if (start && fd == null) {
14270 throw new IllegalArgumentException("null fd");
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014271 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014272
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014273 ProcessRecord proc = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014274 if (process != null) {
14275 try {
14276 int pid = Integer.parseInt(process);
14277 synchronized (mPidsSelfLocked) {
14278 proc = mPidsSelfLocked.get(pid);
14279 }
14280 } catch (NumberFormatException e) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014281 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014282
14283 if (proc == null) {
14284 HashMap<String, SparseArray<ProcessRecord>> all
14285 = mProcessNames.getMap();
14286 SparseArray<ProcessRecord> procs = all.get(process);
14287 if (procs != null && procs.size() > 0) {
14288 proc = procs.valueAt(0);
14289 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014290 }
14291 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014292
14293 if (start && (proc == null || proc.thread == null)) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014294 throw new IllegalArgumentException("Unknown process: " + process);
14295 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014296
14297 if (start) {
14298 stopProfilerLocked(null, null, 0);
14299 setProfileApp(proc.info, proc.processName, path, fd, false);
14300 mProfileProc = proc;
14301 mProfileType = profileType;
14302 try {
14303 fd = fd.dup();
14304 } catch (IOException e) {
14305 fd = null;
14306 }
14307 proc.thread.profilerControl(start, path, fd, profileType);
14308 fd = null;
14309 mProfileFd = null;
14310 } else {
14311 stopProfilerLocked(proc, path, profileType);
14312 if (fd != null) {
14313 try {
14314 fd.close();
14315 } catch (IOException e) {
14316 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014317 }
14318 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014319
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014320 return true;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014321 }
14322 } catch (RemoteException e) {
14323 throw new IllegalStateException("Process disappeared");
14324 } finally {
14325 if (fd != null) {
14326 try {
14327 fd.close();
14328 } catch (IOException e) {
14329 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014330 }
14331 }
14332 }
Andy McFadden824c5102010-07-09 16:26:57 -070014333
14334 public boolean dumpHeap(String process, boolean managed,
14335 String path, ParcelFileDescriptor fd) throws RemoteException {
14336
14337 try {
14338 synchronized (this) {
14339 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14340 // its own permission (same as profileControl).
14341 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14342 != PackageManager.PERMISSION_GRANTED) {
14343 throw new SecurityException("Requires permission "
14344 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
14345 }
14346
14347 if (fd == null) {
14348 throw new IllegalArgumentException("null fd");
14349 }
14350
14351 ProcessRecord proc = null;
14352 try {
14353 int pid = Integer.parseInt(process);
14354 synchronized (mPidsSelfLocked) {
14355 proc = mPidsSelfLocked.get(pid);
14356 }
14357 } catch (NumberFormatException e) {
14358 }
14359
14360 if (proc == null) {
14361 HashMap<String, SparseArray<ProcessRecord>> all
14362 = mProcessNames.getMap();
14363 SparseArray<ProcessRecord> procs = all.get(process);
14364 if (procs != null && procs.size() > 0) {
14365 proc = procs.valueAt(0);
14366 }
14367 }
14368
14369 if (proc == null || proc.thread == null) {
14370 throw new IllegalArgumentException("Unknown process: " + process);
14371 }
14372
Dianne Hackbornf02e57b2011-03-01 22:21:04 -080014373 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
14374 if (!isDebuggable) {
Andy McFadden824c5102010-07-09 16:26:57 -070014375 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
14376 throw new SecurityException("Process not debuggable: " + proc);
14377 }
14378 }
14379
14380 proc.thread.dumpHeap(managed, path, fd);
14381 fd = null;
14382 return true;
14383 }
14384 } catch (RemoteException e) {
14385 throw new IllegalStateException("Process disappeared");
14386 } finally {
14387 if (fd != null) {
14388 try {
14389 fd.close();
14390 } catch (IOException e) {
14391 }
14392 }
14393 }
14394 }
14395
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014396 /** In this method we try to acquire our lock to make sure that we have not deadlocked */
14397 public void monitor() {
14398 synchronized (this) { }
14399 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014400
Dianne Hackborna573f6a2012-02-09 16:12:18 -080014401 void onCoreSettingsChange(Bundle settings) {
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014402 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
14403 ProcessRecord processRecord = mLruProcesses.get(i);
14404 try {
14405 if (processRecord.thread != null) {
14406 processRecord.thread.setCoreSettings(settings);
14407 }
14408 } catch (RemoteException re) {
14409 /* ignore */
14410 }
14411 }
14412 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014413
14414 // Multi-user methods
14415
Amith Yamasani742a6712011-05-04 14:49:28 -070014416 private int mCurrentUserId;
14417 private SparseIntArray mLoggedInUsers = new SparseIntArray(5);
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014418 private ArrayList<UserListener> mUserListeners = new ArrayList<UserListener>(3);
14419
14420 public interface UserListener {
14421 public void onUserChanged(int userId);
14422
14423 public void onUserAdded(int userId);
14424
14425 public void onUserRemoved(int userId);
14426
14427 public void onUserLoggedOut(int userId);
14428 }
14429
14430 public void addUserListener(UserListener listener) {
14431 synchronized (this) {
14432 if (!mUserListeners.contains(listener)) {
14433 mUserListeners.add(listener);
14434 }
14435 }
14436 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014437
14438 public boolean switchUser(int userId) {
14439 final int callingUid = Binder.getCallingUid();
14440 if (callingUid != 0 && callingUid != Process.myUid()) {
14441 Slog.e(TAG, "Trying to switch user from unauthorized app");
14442 return false;
14443 }
14444 if (mCurrentUserId == userId)
14445 return true;
14446
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014447 ArrayList<UserListener> listeners;
14448
Amith Yamasani742a6712011-05-04 14:49:28 -070014449 synchronized (this) {
14450 // Check if user is already logged in, otherwise check if user exists first before
14451 // adding to the list of logged in users.
14452 if (mLoggedInUsers.indexOfKey(userId) < 0) {
14453 if (!userExists(userId)) {
14454 return false;
14455 }
14456 mLoggedInUsers.append(userId, userId);
14457 }
14458
14459 mCurrentUserId = userId;
14460 boolean haveActivities = mMainStack.switchUser(userId);
14461 if (!haveActivities) {
14462 startHomeActivityLocked(userId);
14463 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014464
14465 listeners = (ArrayList<UserListener>) mUserListeners.clone();
14466 }
14467 // Inform the listeners
14468 for (UserListener listener : listeners) {
14469 listener.onUserChanged(userId);
Amith Yamasani742a6712011-05-04 14:49:28 -070014470 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014471 return true;
14472 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014473
14474 private boolean userExists(int userId) {
14475 try {
14476 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
14477 for (UserInfo user : users) {
14478 if (user.id == userId) {
14479 return true;
14480 }
14481 }
14482 } catch (RemoteException re) {
14483 // Won't happen, in same process
14484 }
14485
14486 return false;
14487 }
14488
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014489 private void checkValidCaller(int uid, int userId) {
14490 if (UserId.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) return;
14491
14492 throw new SecurityException("Caller uid=" + uid
14493 + " is not privileged to communicate with user=" + userId);
14494 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014495
14496 private int applyUserId(int uid, int userId) {
14497 return UserId.getUid(userId, uid);
14498 }
14499
14500 private ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080014501 if (info == null) return null;
Amith Yamasani742a6712011-05-04 14:49:28 -070014502 ApplicationInfo newInfo = new ApplicationInfo(info);
14503 newInfo.uid = applyUserId(info.uid, userId);
14504 if (newInfo.uid >= Process.FIRST_APPLICATION_UID) {
14505 newInfo.dataDir = USER_DATA_DIR + userId + "/"
14506 + info.packageName;
14507 }
14508 return newInfo;
14509 }
14510
14511 ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080014512 if (aInfo == null || aInfo.applicationInfo.uid < Process.FIRST_APPLICATION_UID
Amith Yamasani742a6712011-05-04 14:49:28 -070014513 || userId < 1) {
14514 return aInfo;
14515 }
14516
14517 ActivityInfo info = new ActivityInfo(aInfo);
14518 info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId);
14519 return info;
14520 }
14521
14522 static class ServiceMap {
14523
14524 private final SparseArray<HashMap<ComponentName, ServiceRecord>> mServicesByNamePerUser
14525 = new SparseArray<HashMap<ComponentName, ServiceRecord>>();
14526 private final SparseArray<HashMap<Intent.FilterComparison, ServiceRecord>>
14527 mServicesByIntentPerUser = new SparseArray<
14528 HashMap<Intent.FilterComparison, ServiceRecord>>();
14529
14530 ServiceRecord getServiceByName(ComponentName name, int callingUser) {
14531 // TODO: Deal with global services
14532 if (DEBUG_MU)
14533 Slog.v(TAG_MU, "getServiceByName(" + name + "), callingUser = " + callingUser);
14534 return getServices(callingUser).get(name);
14535 }
14536
14537 ServiceRecord getServiceByName(ComponentName name) {
14538 return getServiceByName(name, -1);
14539 }
14540
14541 ServiceRecord getServiceByIntent(Intent.FilterComparison filter, int callingUser) {
14542 // TODO: Deal with global services
14543 if (DEBUG_MU)
14544 Slog.v(TAG_MU, "getServiceByIntent(" + filter + "), callingUser = " + callingUser);
14545 return getServicesByIntent(callingUser).get(filter);
14546 }
14547
14548 ServiceRecord getServiceByIntent(Intent.FilterComparison filter) {
14549 return getServiceByIntent(filter, -1);
14550 }
14551
14552 void putServiceByName(ComponentName name, int callingUser, ServiceRecord value) {
14553 // TODO: Deal with global services
14554 getServices(callingUser).put(name, value);
14555 }
14556
14557 void putServiceByIntent(Intent.FilterComparison filter, int callingUser,
14558 ServiceRecord value) {
14559 // TODO: Deal with global services
14560 getServicesByIntent(callingUser).put(filter, value);
14561 }
14562
14563 void removeServiceByName(ComponentName name, int callingUser) {
14564 // TODO: Deal with global services
14565 ServiceRecord removed = getServices(callingUser).remove(name);
14566 if (DEBUG_MU)
14567 Slog.v(TAG, "removeServiceByName user=" + callingUser + " name=" + name
14568 + " removed=" + removed);
14569 }
14570
14571 void removeServiceByIntent(Intent.FilterComparison filter, int callingUser) {
14572 // TODO: Deal with global services
14573 ServiceRecord removed = getServicesByIntent(callingUser).remove(filter);
14574 if (DEBUG_MU)
14575 Slog.v(TAG_MU, "removeServiceByIntent user=" + callingUser + " intent=" + filter
14576 + " removed=" + removed);
14577 }
14578
14579 Collection<ServiceRecord> getAllServices(int callingUser) {
14580 // TODO: Deal with global services
14581 return getServices(callingUser).values();
14582 }
14583
14584 private HashMap<ComponentName, ServiceRecord> getServices(int callingUser) {
14585 HashMap map = mServicesByNamePerUser.get(callingUser);
14586 if (map == null) {
14587 map = new HashMap<ComponentName, ServiceRecord>();
14588 mServicesByNamePerUser.put(callingUser, map);
14589 }
14590 return map;
14591 }
14592
14593 private HashMap<Intent.FilterComparison, ServiceRecord> getServicesByIntent(
14594 int callingUser) {
14595 HashMap map = mServicesByIntentPerUser.get(callingUser);
14596 if (map == null) {
14597 map = new HashMap<Intent.FilterComparison, ServiceRecord>();
14598 mServicesByIntentPerUser.put(callingUser, map);
14599 }
14600 return map;
14601 }
14602 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014603}