blob: 785212378ad4d6040276249f0d48743ab3e4d0aa [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;
Amith Yamasani37ce3a82012-02-06 12:04:42 -080052import android.app.WallpaperManager;
Christopher Tate45281862010-03-05 15:46:30 -080053import android.app.backup.IBackupManager;
Jacek Surazskif5b9c722009-05-18 12:09:59 +020054import android.content.ActivityNotFoundException;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -080055import android.content.BroadcastReceiver;
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;
Dianne Hackborncbb722e2012-02-07 18:33:49 -0800141import java.util.Arrays;
Amith Yamasani742a6712011-05-04 14:49:28 -0700142import java.util.Collection;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700143import java.util.Collections;
144import java.util.Comparator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800145import java.util.HashMap;
146import java.util.HashSet;
147import java.util.Iterator;
148import java.util.List;
149import java.util.Locale;
150import java.util.Map;
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -0700151import java.util.Set;
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700152import java.util.concurrent.atomic.AtomicBoolean;
153import java.util.concurrent.atomic.AtomicLong;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800154
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700155public final class ActivityManagerService extends ActivityManagerNative
156 implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
Amith Yamasani742a6712011-05-04 14:49:28 -0700157 private static final String USER_DATA_DIR = "/data/user/";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800158 static final String TAG = "ActivityManager";
Amith Yamasani742a6712011-05-04 14:49:28 -0700159 static final String TAG_MU = "ActivityManagerServiceMU";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800160 static final boolean DEBUG = false;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400161 static final boolean localLOGV = DEBUG;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800162 static final boolean DEBUG_SWITCH = localLOGV || false;
163 static final boolean DEBUG_TASKS = localLOGV || false;
164 static final boolean DEBUG_PAUSE = localLOGV || false;
165 static final boolean DEBUG_OOM_ADJ = localLOGV || false;
166 static final boolean DEBUG_TRANSITION = localLOGV || false;
167 static final boolean DEBUG_BROADCAST = localLOGV || false;
Christopher Tatef46723b2012-01-26 14:19:24 -0800168 static final boolean DEBUG_BACKGROUND_BROADCAST = DEBUG_BROADCAST || false;
Dianne Hackborn82f3f002009-06-16 18:49:05 -0700169 static final boolean DEBUG_BROADCAST_LIGHT = DEBUG_BROADCAST || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800170 static final boolean DEBUG_SERVICE = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700171 static final boolean DEBUG_SERVICE_EXECUTING = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800172 static final boolean DEBUG_VISBILITY = localLOGV || false;
173 static final boolean DEBUG_PROCESSES = localLOGV || false;
Dianne Hackborna1e989b2009-09-01 19:54:29 -0700174 static final boolean DEBUG_PROVIDER = localLOGV || false;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800175 static final boolean DEBUG_URI_PERMISSION = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800176 static final boolean DEBUG_USER_LEAVING = localLOGV || false;
The Android Open Source Project10592532009-03-18 17:39:46 -0700177 static final boolean DEBUG_RESULTS = localLOGV || false;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -0700178 static final boolean DEBUG_BACKUP = localLOGV || false;
Dianne Hackborndc6b6352009-09-30 14:20:09 -0700179 static final boolean DEBUG_CONFIGURATION = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700180 static final boolean DEBUG_POWER = localLOGV || false;
181 static final boolean DEBUG_POWER_QUICK = DEBUG_POWER || false;
Amith Yamasani742a6712011-05-04 14:49:28 -0700182 static final boolean DEBUG_MU = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800183 static final boolean VALIDATE_TOKENS = false;
184 static final boolean SHOW_ACTIVITY_START_TIME = true;
185
186 // Control over CPU and battery monitoring.
187 static final long BATTERY_STATS_TIME = 30*60*1000; // write battery stats every 30 minutes.
188 static final boolean MONITOR_CPU_USAGE = true;
189 static final long MONITOR_CPU_MIN_TIME = 5*1000; // don't sample cpu less than every 5 seconds.
190 static final long MONITOR_CPU_MAX_TIME = 0x0fffffff; // wait possibly forever for next cpu sample.
191 static final boolean MONITOR_THREAD_CPU_USAGE = false;
192
Dianne Hackborn1655be42009-05-08 14:29:01 -0700193 // The flags that are set for all calls we make to the package manager.
Dianne Hackborn11b822d2009-07-21 20:03:02 -0700194 static final int STOCK_PM_FLAGS = PackageManager.GET_SHARED_LIBRARY_FILES;
Dianne Hackborn1655be42009-05-08 14:29:01 -0700195
Dianne Hackbornf02e57b2011-03-01 22:21:04 -0800196 private static final String SYSTEM_DEBUGGABLE = "ro.debuggable";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800197
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800198 // Maximum number of recent tasks that we can remember.
199 static final int MAX_RECENT_TASKS = 20;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700200
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700201 // Amount of time after a call to stopAppSwitches() during which we will
202 // prevent further untrusted switches from happening.
203 static final long APP_SWITCH_DELAY_TIME = 5*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800204
205 // How long we wait for a launched process to attach to the activity manager
206 // before we decide it's never going to come up for real.
207 static final int PROC_START_TIMEOUT = 10*1000;
208
Jeff Brown3f9dd282011-07-08 20:02:19 -0700209 // How long we wait for a launched process to attach to the activity manager
210 // before we decide it's never going to come up for real, when the process was
211 // started with a wrapper for instrumentation (such as Valgrind) because it
212 // could take much longer than usual.
213 static final int PROC_START_TIMEOUT_WITH_WRAPPER = 300*1000;
214
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800215 // How long to wait after going idle before forcing apps to GC.
216 static final int GC_TIMEOUT = 5*1000;
217
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700218 // The minimum amount of time between successive GC requests for a process.
219 static final int GC_MIN_INTERVAL = 60*1000;
220
Dianne Hackborn287952c2010-09-22 22:34:31 -0700221 // The rate at which we check for apps using excessive power -- 15 mins.
222 static final int POWER_CHECK_DELAY = (DEBUG_POWER_QUICK ? 2 : 15) * 60*1000;
223
224 // The minimum sample duration we will allow before deciding we have
225 // enough data on wake locks to start killing things.
226 static final int WAKE_LOCK_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
227
228 // The minimum sample duration we will allow before deciding we have
229 // enough data on CPU usage to start killing things.
230 static final int CPU_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700231
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800232 // How long we allow a receiver to run before giving up on it.
Christopher Tatef46723b2012-01-26 14:19:24 -0800233 static final int BROADCAST_FG_TIMEOUT = 10*1000;
234 static final int BROADCAST_BG_TIMEOUT = 60*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800235
236 // How long we wait for a service to finish executing.
237 static final int SERVICE_TIMEOUT = 20*1000;
238
239 // How long a service needs to be running until restarting its process
240 // is no longer considered to be a relaunch of the service.
241 static final int SERVICE_RESTART_DURATION = 5*1000;
242
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700243 // How long a service needs to be running until it will start back at
244 // SERVICE_RESTART_DURATION after being killed.
245 static final int SERVICE_RESET_RUN_DURATION = 60*1000;
246
247 // Multiplying factor to increase restart duration time by, for each time
248 // a service is killed before it has run for SERVICE_RESET_RUN_DURATION.
249 static final int SERVICE_RESTART_DURATION_FACTOR = 4;
250
251 // The minimum amount of time between restarting services that we allow.
252 // That is, when multiple services are restarting, we won't allow each
253 // to restart less than this amount of time from the last one.
254 static final int SERVICE_MIN_RESTART_TIME_BETWEEN = 10*1000;
255
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800256 // Maximum amount of time for there to be no activity on a service before
257 // we consider it non-essential and allow its process to go on the
258 // LRU background list.
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700259 static final int MAX_SERVICE_INACTIVITY = 30*60*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800260
261 // How long we wait until we timeout on key dispatching.
262 static final int KEY_DISPATCHING_TIMEOUT = 5*1000;
263
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800264 // How long we wait until we timeout on key dispatching during instrumentation.
265 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT = 60*1000;
266
Dan Egnor42471dd2010-01-07 17:25:22 -0800267 static final int MY_PID = Process.myPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800268
269 static final String[] EMPTY_STRING_ARRAY = new String[0];
270
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700271 public ActivityStack mMainStack;
Mike Lockwood3a74bd32011-08-12 13:55:22 -0700272
273 private final boolean mHeadless;
274
Joe Onorato54a4a412011-11-02 20:50:08 -0700275 // Whether we should show our dialogs (ANR, crash, etc) or just perform their
276 // default actuion automatically. Important for devices without direct input
277 // devices.
278 private boolean mShowDialogs = true;
279
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800280 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700281 * Description of a request to start a new activity, which has been held
282 * due to app switches being disabled.
283 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700284 static class PendingActivityLaunch {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700285 ActivityRecord r;
286 ActivityRecord sourceRecord;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700287 Uri[] grantedUriPermissions;
288 int grantedMode;
289 boolean onlyIfNeeded;
290 }
291
292 final ArrayList<PendingActivityLaunch> mPendingActivityLaunches
293 = new ArrayList<PendingActivityLaunch>();
294
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800295
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800296 BroadcastQueue mFgBroadcastQueue;
297 BroadcastQueue mBgBroadcastQueue;
Christopher Tatef46723b2012-01-26 14:19:24 -0800298 // Convenient for easy iteration over the queues. Foreground is first
299 // so that dispatch of foreground broadcasts gets precedence.
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800300 final BroadcastQueue[] mBroadcastQueues = new BroadcastQueue[2];
Christopher Tatef46723b2012-01-26 14:19:24 -0800301
302 BroadcastQueue broadcastQueueForIntent(Intent intent) {
303 final boolean isFg = (intent.getFlags() & Intent.FLAG_RECEIVER_FOREGROUND) != 0;
304 if (DEBUG_BACKGROUND_BROADCAST) {
305 Slog.i(TAG, "Broadcast intent " + intent + " on "
306 + (isFg ? "foreground" : "background")
307 + " queue");
308 }
309 return (isFg) ? mFgBroadcastQueue : mBgBroadcastQueue;
310 }
311
312 BroadcastRecord broadcastRecordForReceiverLocked(IBinder receiver) {
313 for (BroadcastQueue queue : mBroadcastQueues) {
314 BroadcastRecord r = queue.getMatchingOrderedReceiver(receiver);
315 if (r != null) {
316 return r;
317 }
318 }
319 return null;
320 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800321
322 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800323 * Activity we have told the window manager to have key focus.
324 */
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700325 ActivityRecord mFocusedActivity = null;
Dianne Hackbornbfe319e2009-09-21 00:34:05 -0700326 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800327 * List of intents that were used to start the most recent tasks.
328 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700329 final ArrayList<TaskRecord> mRecentTasks = new ArrayList<TaskRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800330
331 /**
Dianne Hackborn7d608422011-08-07 16:24:18 -0700332 * Process management.
333 */
334 final ProcessList mProcessList = new ProcessList();
335
336 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800337 * All of the applications we currently have running organized by name.
338 * The keys are strings of the application package name (as
339 * returned by the package manager), and the keys are ApplicationRecord
340 * objects.
341 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700342 final ProcessMap<ProcessRecord> mProcessNames = new ProcessMap<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800343
344 /**
Dianne Hackborna0c283e2012-02-09 10:47:01 -0800345 * The currently running isolated processes.
346 */
347 final SparseArray<ProcessRecord> mIsolatedProcesses = new SparseArray<ProcessRecord>();
348
349 /**
350 * Counter for assigning isolated process uids, to avoid frequently reusing the
351 * same ones.
352 */
353 int mNextIsolatedProcessUid = 0;
354
355 /**
Dianne Hackborn860755f2010-06-03 18:47:52 -0700356 * The currently running heavy-weight process, if any.
357 */
358 ProcessRecord mHeavyWeightProcess = null;
359
360 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800361 * The last time that various processes have crashed.
362 */
363 final ProcessMap<Long> mProcessCrashTimes = new ProcessMap<Long>();
364
365 /**
366 * Set of applications that we consider to be bad, and will reject
367 * incoming broadcasts from (which the user has no control over).
368 * Processes are added to this set when they have crashed twice within
369 * a minimum amount of time; they are removed from it when they are
370 * later restarted (hopefully due to some user action). The value is the
371 * time it was added to the list.
372 */
373 final ProcessMap<Long> mBadProcesses = new ProcessMap<Long>();
374
375 /**
376 * All of the processes we currently have running organized by pid.
377 * The keys are the pid running the application.
378 *
379 * <p>NOTE: This object is protected by its own lock, NOT the global
380 * activity manager lock!
381 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700382 final SparseArray<ProcessRecord> mPidsSelfLocked = new SparseArray<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800383
384 /**
385 * All of the processes that have been forced to be foreground. The key
386 * is the pid of the caller who requested it (we hold a death
387 * link on it).
388 */
389 abstract class ForegroundToken implements IBinder.DeathRecipient {
390 int pid;
391 IBinder token;
392 }
393 final SparseArray<ForegroundToken> mForegroundProcesses
394 = new SparseArray<ForegroundToken>();
395
396 /**
397 * List of records for processes that someone had tried to start before the
398 * system was ready. We don't start them at that point, but ensure they
399 * are started by the time booting is complete.
400 */
401 final ArrayList<ProcessRecord> mProcessesOnHold
402 = new ArrayList<ProcessRecord>();
403
404 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800405 * List of persistent applications that are in the process
406 * of being started.
407 */
408 final ArrayList<ProcessRecord> mPersistentStartingProcesses
409 = new ArrayList<ProcessRecord>();
410
411 /**
412 * Processes that are being forcibly torn down.
413 */
414 final ArrayList<ProcessRecord> mRemovedProcesses
415 = new ArrayList<ProcessRecord>();
416
417 /**
418 * List of running applications, sorted by recent usage.
419 * The first entry in the list is the least recently used.
420 * It contains ApplicationRecord objects. This list does NOT include
421 * any persistent application records (since we never want to exit them).
422 */
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800423 final ArrayList<ProcessRecord> mLruProcesses
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800424 = new ArrayList<ProcessRecord>();
425
426 /**
427 * List of processes that should gc as soon as things are idle.
428 */
429 final ArrayList<ProcessRecord> mProcessesToGc
430 = new ArrayList<ProcessRecord>();
431
432 /**
The Android Open Source Project4df24232009-03-05 14:34:35 -0800433 * This is the process holding what we currently consider to be
434 * the "home" activity.
435 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700436 ProcessRecord mHomeProcess;
The Android Open Source Project4df24232009-03-05 14:34:35 -0800437
438 /**
Dianne Hackbornf35fe232011-11-01 19:25:20 -0700439 * This is the process holding the activity the user last visited that
440 * is in a different process from the one they are currently in.
441 */
442 ProcessRecord mPreviousProcess;
Dianne Hackborn50685602011-12-01 12:23:37 -0800443
444 /**
445 * The time at which the previous process was last visible.
446 */
447 long mPreviousProcessVisibleTime;
448
Dianne Hackbornf35fe232011-11-01 19:25:20 -0700449 /**
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400450 * Packages that the user has asked to have run in screen size
451 * compatibility mode instead of filling the screen.
452 */
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -0700453 final CompatModePackages mCompatModePackages;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400454
455 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800456 * Set of PendingResultRecord objects that are currently active.
457 */
458 final HashSet mPendingResultRecords = new HashSet();
459
460 /**
461 * Set of IntentSenderRecord objects that are currently active.
462 */
463 final HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>> mIntentSenderRecords
464 = new HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>>();
465
466 /**
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -0800467 * Fingerprints (hashCode()) of stack traces that we've
Brad Fitzpatrick143666f2010-06-14 12:40:21 -0700468 * already logged DropBox entries for. Guarded by itself. If
469 * something (rogue user app) forces this over
470 * MAX_DUP_SUPPRESSED_STACKS entries, the contents are cleared.
471 */
472 private final HashSet<Integer> mAlreadyLoggedViolatedStacks = new HashSet<Integer>();
473 private static final int MAX_DUP_SUPPRESSED_STACKS = 5000;
474
475 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -0700476 * Strict Mode background batched logging state.
477 *
478 * The string buffer is guarded by itself, and its lock is also
479 * used to determine if another batched write is already
480 * in-flight.
481 */
482 private final StringBuilder mStrictModeBuffer = new StringBuilder();
483
484 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800485 * Keeps track of all IIntentReceivers that have been registered for
486 * broadcasts. Hash keys are the receiver IBinder, hash value is
487 * a ReceiverList.
488 */
489 final HashMap mRegisteredReceivers = new HashMap();
490
491 /**
492 * Resolver for broadcast intents to registered receivers.
493 * Holds BroadcastFilter (subclass of IntentFilter).
494 */
495 final IntentResolver<BroadcastFilter, BroadcastFilter> mReceiverResolver
496 = new IntentResolver<BroadcastFilter, BroadcastFilter>() {
497 @Override
498 protected boolean allowFilterResult(
499 BroadcastFilter filter, List<BroadcastFilter> dest) {
500 IBinder target = filter.receiverList.receiver.asBinder();
501 for (int i=dest.size()-1; i>=0; i--) {
502 if (dest.get(i).receiverList.receiver.asBinder() == target) {
503 return false;
504 }
505 }
506 return true;
507 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700508
509 @Override
510 protected String packageForFilter(BroadcastFilter filter) {
511 return filter.packageName;
512 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800513 };
514
515 /**
516 * State of all active sticky broadcasts. Keys are the action of the
517 * sticky Intent, values are an ArrayList of all broadcasted intents with
518 * that action (which should usually be one).
519 */
520 final HashMap<String, ArrayList<Intent>> mStickyBroadcasts =
521 new HashMap<String, ArrayList<Intent>>();
522
Amith Yamasani742a6712011-05-04 14:49:28 -0700523 final ServiceMap mServiceMap = new ServiceMap();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800524
525 /**
526 * All currently bound service connections. Keys are the IBinder of
527 * the client's IServiceConnection.
528 */
Dianne Hackborn43d9ac82010-08-25 15:06:25 -0700529 final HashMap<IBinder, ArrayList<ConnectionRecord>> mServiceConnections
530 = new HashMap<IBinder, ArrayList<ConnectionRecord>>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800531
532 /**
533 * List of services that we have been asked to start,
534 * but haven't yet been able to. It is used to hold start requests
535 * while waiting for their corresponding application thread to get
536 * going.
537 */
538 final ArrayList<ServiceRecord> mPendingServices
539 = new ArrayList<ServiceRecord>();
540
541 /**
542 * List of services that are scheduled to restart following a crash.
543 */
544 final ArrayList<ServiceRecord> mRestartingServices
545 = new ArrayList<ServiceRecord>();
546
547 /**
548 * List of services that are in the process of being stopped.
549 */
550 final ArrayList<ServiceRecord> mStoppingServices
551 = new ArrayList<ServiceRecord>();
552
553 /**
Christopher Tate181fafa2009-05-14 11:12:14 -0700554 * Backup/restore process management
555 */
556 String mBackupAppName = null;
557 BackupRecord mBackupTarget = null;
558
559 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800560 * List of PendingThumbnailsRecord objects of clients who are still
561 * waiting to receive all of the thumbnails for a task.
562 */
563 final ArrayList mPendingThumbnails = new ArrayList();
564
565 /**
566 * List of HistoryRecord objects that have been finished and must
567 * still report back to a pending thumbnail receiver.
568 */
569 final ArrayList mCancelledThumbnails = new ArrayList();
570
Amith Yamasani742a6712011-05-04 14:49:28 -0700571 final ProviderMap mProviderMap = new ProviderMap();
572
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800573 /**
574 * List of content providers who have clients waiting for them. The
575 * application is currently being launched and the provider will be
576 * removed from this list once it is published.
577 */
Dianne Hackborn860755f2010-06-03 18:47:52 -0700578 final ArrayList<ContentProviderRecord> mLaunchingProviders
579 = new ArrayList<ContentProviderRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800580
581 /**
582 * Global set of specific Uri permissions that have been granted.
583 */
584 final private SparseArray<HashMap<Uri, UriPermission>> mGrantedUriPermissions
585 = new SparseArray<HashMap<Uri, UriPermission>>();
586
Svetoslav Ganov54d068e2011-03-02 12:58:40 -0800587 CoreSettingsObserver mCoreSettingsObserver;
588
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800589 /**
590 * Thread-local storage used to carry caller permissions over through
591 * indirect content-provider access.
592 * @see #ActivityManagerService.openContentUri()
593 */
594 private class Identity {
595 public int pid;
596 public int uid;
597
598 Identity(int _pid, int _uid) {
599 pid = _pid;
600 uid = _uid;
601 }
602 }
Amith Yamasani742a6712011-05-04 14:49:28 -0700603
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800604 private static ThreadLocal<Identity> sCallerIdentity = new ThreadLocal<Identity>();
605
606 /**
607 * All information we have collected about the runtime performance of
608 * any user id that can impact battery performance.
609 */
610 final BatteryStatsService mBatteryStatsService;
611
612 /**
613 * information about component usage
614 */
615 final UsageStatsService mUsageStatsService;
616
617 /**
618 * Current configuration information. HistoryRecord objects are given
619 * a reference to this object to indicate which configuration they are
620 * currently running in, so this object must be kept immutable.
621 */
622 Configuration mConfiguration = new Configuration();
623
624 /**
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800625 * Current sequencing integer of the configuration, for skipping old
626 * configurations.
627 */
628 int mConfigurationSeq = 0;
629
630 /**
Jack Palevichb90d28c2009-07-22 15:35:24 -0700631 * Hardware-reported OpenGLES version.
632 */
633 final int GL_ES_VERSION;
634
635 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800636 * List of initialization arguments to pass to all processes when binding applications to them.
637 * For example, references to the commonly used services.
638 */
639 HashMap<String, IBinder> mAppBindArgs;
640
641 /**
Dianne Hackbornf210d6b2009-04-13 18:42:49 -0700642 * Temporary to avoid allocations. Protected by main lock.
643 */
644 final StringBuilder mStringBuilder = new StringBuilder(256);
645
646 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800647 * Used to control how we initialize the service.
648 */
649 boolean mStartRunning = false;
650 ComponentName mTopComponent;
651 String mTopAction;
652 String mTopData;
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700653 boolean mProcessesReady = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800654 boolean mSystemReady = false;
655 boolean mBooting = false;
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700656 boolean mWaitingUpdate = false;
657 boolean mDidUpdate = false;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700658 boolean mOnBattery = false;
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700659 boolean mLaunchWarningShown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800660
661 Context mContext;
662
663 int mFactoryTest;
664
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -0700665 boolean mCheckedForSetup;
666
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800667 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700668 * The time at which we will allow normal application switches again,
669 * after a call to {@link #stopAppSwitches()}.
670 */
671 long mAppSwitchesAllowedTime;
672
673 /**
674 * This is set to true after the first switch after mAppSwitchesAllowedTime
675 * is set; any switches after that will clear the time.
676 */
677 boolean mDidAppSwitch;
678
679 /**
Dianne Hackborn287952c2010-09-22 22:34:31 -0700680 * Last time (in realtime) at which we checked for power usage.
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700681 */
Dianne Hackborn287952c2010-09-22 22:34:31 -0700682 long mLastPowerCheckRealtime;
683
684 /**
685 * Last time (in uptime) at which we checked for power usage.
686 */
687 long mLastPowerCheckUptime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700688
689 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800690 * Set while we are wanting to sleep, to prevent any
691 * activities from being started/resumed.
692 */
693 boolean mSleeping = false;
694
695 /**
Dianne Hackborn55280a92009-05-07 15:53:46 -0700696 * Set if we are shutting down the system, similar to sleeping.
697 */
698 boolean mShuttingDown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800699
700 /**
701 * Task identifier that activities are currently being started
702 * in. Incremented each time a new task is created.
703 * todo: Replace this with a TokenSpace class that generates non-repeating
704 * integers that won't wrap.
705 */
706 int mCurTask = 1;
707
708 /**
709 * Current sequence id for oom_adj computation traversal.
710 */
711 int mAdjSeq = 0;
712
713 /**
Dianne Hackborn906497c2010-05-10 15:57:38 -0700714 * Current sequence id for process LRU updating.
715 */
716 int mLruSeq = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800717
718 /**
Dianne Hackborne02c88a2011-10-28 13:58:15 -0700719 * Keep track of the number of service processes we last found, to
720 * determine on the next iteration which should be B services.
721 */
722 int mNumServiceProcs = 0;
723 int mNewNumServiceProcs = 0;
724
725 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800726 * System monitoring: number of processes that died since the last
727 * N procs were started.
728 */
729 int[] mProcDeaths = new int[20];
730
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700731 /**
732 * This is set if we had to do a delayed dexopt of an app before launching
733 * it, to increasing the ANR timeouts in that case.
734 */
735 boolean mDidDexOpt;
736
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800737 String mDebugApp = null;
738 boolean mWaitForDebugger = false;
739 boolean mDebugTransient = false;
740 String mOrigDebugApp = null;
741 boolean mOrigWaitForDebugger = false;
742 boolean mAlwaysFinishActivities = false;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700743 IActivityController mController = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700744 String mProfileApp = null;
745 ProcessRecord mProfileProc = null;
746 String mProfileFile;
747 ParcelFileDescriptor mProfileFd;
748 int mProfileType = 0;
749 boolean mAutoStopProfiler = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800750
Jeff Sharkeya4620792011-05-20 15:29:23 -0700751 final RemoteCallbackList<IProcessObserver> mProcessObservers
752 = new RemoteCallbackList<IProcessObserver>();
753
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800754 /**
755 * Callback of last caller to {@link #requestPss}.
756 */
757 Runnable mRequestPssCallback;
758
759 /**
760 * Remaining processes for which we are waiting results from the last
761 * call to {@link #requestPss}.
762 */
763 final ArrayList<ProcessRecord> mRequestPssList
764 = new ArrayList<ProcessRecord>();
765
766 /**
767 * Runtime statistics collection thread. This object's lock is used to
768 * protect all related state.
769 */
770 final Thread mProcessStatsThread;
771
772 /**
773 * Used to collect process stats when showing not responding dialog.
774 * Protected by mProcessStatsThread.
775 */
776 final ProcessStats mProcessStats = new ProcessStats(
777 MONITOR_THREAD_CPU_USAGE);
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700778 final AtomicLong mLastCpuTime = new AtomicLong(0);
779 final AtomicBoolean mProcessStatsMutexFree = new AtomicBoolean(true);
780
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800781 long mLastWriteTime = 0;
782
783 /**
784 * Set to true after the system has finished booting.
785 */
786 boolean mBooted = false;
787
Dianne Hackborn7d608422011-08-07 16:24:18 -0700788 int mProcessLimit = ProcessList.MAX_HIDDEN_APPS;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700789 int mProcessLimitOverride = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800790
791 WindowManagerService mWindowManager;
792
793 static ActivityManagerService mSelf;
794 static ActivityThread mSystemThread;
795
796 private final class AppDeathRecipient implements IBinder.DeathRecipient {
797 final ProcessRecord mApp;
798 final int mPid;
799 final IApplicationThread mAppThread;
800
801 AppDeathRecipient(ProcessRecord app, int pid,
802 IApplicationThread thread) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800803 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800804 TAG, "New death recipient " + this
805 + " for thread " + thread.asBinder());
806 mApp = app;
807 mPid = pid;
808 mAppThread = thread;
809 }
810
811 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800812 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800813 TAG, "Death received in " + this
814 + " for thread " + mAppThread.asBinder());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800815 synchronized(ActivityManagerService.this) {
816 appDiedLocked(mApp, mPid, mAppThread);
817 }
818 }
819 }
820
821 static final int SHOW_ERROR_MSG = 1;
822 static final int SHOW_NOT_RESPONDING_MSG = 2;
823 static final int SHOW_FACTORY_ERROR_MSG = 3;
824 static final int UPDATE_CONFIGURATION_MSG = 4;
825 static final int GC_BACKGROUND_PROCESSES_MSG = 5;
826 static final int WAIT_FOR_DEBUGGER_MSG = 6;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800827 static final int SERVICE_TIMEOUT_MSG = 12;
828 static final int UPDATE_TIME_ZONE = 13;
829 static final int SHOW_UID_ERROR_MSG = 14;
830 static final int IM_FEELING_LUCKY_MSG = 15;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800831 static final int PROC_START_TIMEOUT_MSG = 20;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700832 static final int DO_PENDING_ACTIVITY_LAUNCHES_MSG = 21;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -0700833 static final int KILL_APPLICATION_MSG = 22;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800834 static final int FINALIZE_PENDING_INTENT_MSG = 23;
Dianne Hackborn860755f2010-06-03 18:47:52 -0700835 static final int POST_HEAVY_NOTIFICATION_MSG = 24;
836 static final int CANCEL_HEAVY_NOTIFICATION_MSG = 25;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700837 static final int SHOW_STRICT_MODE_VIOLATION_MSG = 26;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700838 static final int CHECK_EXCESSIVE_WAKE_LOCKS_MSG = 27;
Robert Greenwalt03595d02010-11-02 14:08:23 -0700839 static final int CLEAR_DNS_CACHE = 28;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700840 static final int UPDATE_HTTP_PROXY = 29;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700841 static final int SHOW_COMPAT_MODE_DIALOG_MSG = 30;
Dianne Hackborn36f80f32011-05-31 18:26:45 -0700842 static final int DISPATCH_FOREGROUND_ACTIVITIES_CHANGED = 31;
843 static final int DISPATCH_PROCESS_DIED = 32;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700844 static final int REPORT_MEM_USAGE = 33;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800845
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800846 static final int FIRST_ACTIVITY_STACK_MSG = 100;
847 static final int FIRST_BROADCAST_QUEUE_MSG = 200;
848 static final int FIRST_COMPAT_MODE_MSG = 300;
849
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800850 AlertDialog mUidAlert;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700851 CompatModeDialog mCompatModeDialog;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700852 long mLastMemUsageReportTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800853
854 final Handler mHandler = new Handler() {
855 //public Handler() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800856 // if (localLOGV) Slog.v(TAG, "Handler started!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800857 //}
858
859 public void handleMessage(Message msg) {
860 switch (msg.what) {
861 case SHOW_ERROR_MSG: {
862 HashMap data = (HashMap) msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800863 synchronized (ActivityManagerService.this) {
864 ProcessRecord proc = (ProcessRecord)data.get("app");
865 if (proc != null && proc.crashDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800866 Slog.e(TAG, "App already has crash dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800867 return;
868 }
869 AppErrorResult res = (AppErrorResult) data.get("result");
Joe Onorato54a4a412011-11-02 20:50:08 -0700870 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Dan Egnorb7f03672009-12-09 16:22:32 -0800871 Dialog d = new AppErrorDialog(mContext, res, proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800872 d.show();
873 proc.crashDialog = d;
874 } else {
875 // The device is asleep, so just pretend that the user
876 // saw a crash dialog and hit "force quit".
877 res.set(0);
878 }
879 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700880
881 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800882 } break;
883 case SHOW_NOT_RESPONDING_MSG: {
884 synchronized (ActivityManagerService.this) {
885 HashMap data = (HashMap) msg.obj;
886 ProcessRecord proc = (ProcessRecord)data.get("app");
887 if (proc != null && proc.anrDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800888 Slog.e(TAG, "App already has anr dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800889 return;
890 }
The Android Open Source Project4df24232009-03-05 14:34:35 -0800891
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700892 Intent intent = new Intent("android.intent.action.ANR");
893 if (!mProcessesReady) {
Christopher Tatef46723b2012-01-26 14:19:24 -0800894 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
895 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700896 }
897 broadcastIntentLocked(null, null, intent,
The Android Open Source Project4df24232009-03-05 14:34:35 -0800898 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -0700899 false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
The Android Open Source Project4df24232009-03-05 14:34:35 -0800900
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800901 Dialog d = new AppNotRespondingDialog(ActivityManagerService.this,
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700902 mContext, proc, (ActivityRecord)data.get("activity"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800903 d.show();
904 proc.anrDialog = d;
905 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700906
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700907 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800908 } break;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700909 case SHOW_STRICT_MODE_VIOLATION_MSG: {
910 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj;
911 synchronized (ActivityManagerService.this) {
912 ProcessRecord proc = (ProcessRecord) data.get("app");
913 if (proc == null) {
914 Slog.e(TAG, "App not found when showing strict mode dialog.");
915 break;
916 }
917 if (proc.crashDialog != null) {
918 Slog.e(TAG, "App already has strict mode dialog: " + proc);
919 return;
920 }
921 AppErrorResult res = (AppErrorResult) data.get("result");
Joe Onorato54a4a412011-11-02 20:50:08 -0700922 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700923 Dialog d = new StrictModeViolationDialog(mContext, res, proc);
924 d.show();
925 proc.crashDialog = d;
926 } else {
927 // The device is asleep, so just pretend that the user
928 // saw a crash dialog and hit "force quit".
929 res.set(0);
930 }
931 }
932 ensureBootCompleted();
933 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800934 case SHOW_FACTORY_ERROR_MSG: {
935 Dialog d = new FactoryErrorDialog(
936 mContext, msg.getData().getCharSequence("msg"));
937 d.show();
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700938 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800939 } break;
940 case UPDATE_CONFIGURATION_MSG: {
941 final ContentResolver resolver = mContext.getContentResolver();
942 Settings.System.putConfiguration(resolver, (Configuration)msg.obj);
943 } break;
944 case GC_BACKGROUND_PROCESSES_MSG: {
945 synchronized (ActivityManagerService.this) {
946 performAppGcsIfAppropriateLocked();
947 }
948 } break;
949 case WAIT_FOR_DEBUGGER_MSG: {
950 synchronized (ActivityManagerService.this) {
951 ProcessRecord app = (ProcessRecord)msg.obj;
952 if (msg.arg1 != 0) {
953 if (!app.waitedForDebugger) {
954 Dialog d = new AppWaitingForDebuggerDialog(
955 ActivityManagerService.this,
956 mContext, app);
957 app.waitDialog = d;
958 app.waitedForDebugger = true;
959 d.show();
960 }
961 } else {
962 if (app.waitDialog != null) {
963 app.waitDialog.dismiss();
964 app.waitDialog = null;
965 }
966 }
967 }
968 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800969 case SERVICE_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700970 if (mDidDexOpt) {
971 mDidDexOpt = false;
972 Message nmsg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
973 nmsg.obj = msg.obj;
974 mHandler.sendMessageDelayed(nmsg, SERVICE_TIMEOUT);
975 return;
976 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800977 serviceTimeout((ProcessRecord)msg.obj);
978 } break;
979 case UPDATE_TIME_ZONE: {
980 synchronized (ActivityManagerService.this) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800981 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
982 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800983 if (r.thread != null) {
984 try {
985 r.thread.updateTimeZone();
986 } catch (RemoteException ex) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800987 Slog.w(TAG, "Failed to update time zone for: " + r.info.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800988 }
989 }
990 }
991 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700992 } break;
Robert Greenwalt03595d02010-11-02 14:08:23 -0700993 case CLEAR_DNS_CACHE: {
994 synchronized (ActivityManagerService.this) {
995 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
996 ProcessRecord r = mLruProcesses.get(i);
997 if (r.thread != null) {
998 try {
999 r.thread.clearDnsCache();
1000 } catch (RemoteException ex) {
1001 Slog.w(TAG, "Failed to clear dns cache for: " + r.info.processName);
1002 }
1003 }
1004 }
1005 }
1006 } break;
Robert Greenwalt434203a2010-10-11 16:00:27 -07001007 case UPDATE_HTTP_PROXY: {
1008 ProxyProperties proxy = (ProxyProperties)msg.obj;
1009 String host = "";
1010 String port = "";
1011 String exclList = "";
1012 if (proxy != null) {
1013 host = proxy.getHost();
1014 port = Integer.toString(proxy.getPort());
1015 exclList = proxy.getExclusionList();
1016 }
1017 synchronized (ActivityManagerService.this) {
1018 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1019 ProcessRecord r = mLruProcesses.get(i);
1020 if (r.thread != null) {
1021 try {
1022 r.thread.setHttpProxy(host, port, exclList);
1023 } catch (RemoteException ex) {
1024 Slog.w(TAG, "Failed to update http proxy for: " +
1025 r.info.processName);
1026 }
1027 }
1028 }
1029 }
1030 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001031 case SHOW_UID_ERROR_MSG: {
Joe Onorato54a4a412011-11-02 20:50:08 -07001032 String title = "System UIDs Inconsistent";
1033 String text = "UIDs on the system are inconsistent, you need to wipe your"
1034 + " data partition or your device will be unstable.";
1035 Log.e(TAG, title + ": " + text);
1036 if (mShowDialogs) {
1037 // XXX This is a temporary dialog, no need to localize.
1038 AlertDialog d = new BaseErrorDialog(mContext);
1039 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
1040 d.setCancelable(false);
1041 d.setTitle(title);
1042 d.setMessage(text);
1043 d.setButton(DialogInterface.BUTTON_POSITIVE, "I'm Feeling Lucky",
1044 mHandler.obtainMessage(IM_FEELING_LUCKY_MSG));
1045 mUidAlert = d;
1046 d.show();
1047 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001048 } break;
1049 case IM_FEELING_LUCKY_MSG: {
1050 if (mUidAlert != null) {
1051 mUidAlert.dismiss();
1052 mUidAlert = null;
1053 }
1054 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001055 case PROC_START_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001056 if (mDidDexOpt) {
1057 mDidDexOpt = false;
1058 Message nmsg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
1059 nmsg.obj = msg.obj;
1060 mHandler.sendMessageDelayed(nmsg, PROC_START_TIMEOUT);
1061 return;
1062 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001063 ProcessRecord app = (ProcessRecord)msg.obj;
1064 synchronized (ActivityManagerService.this) {
1065 processStartTimedOutLocked(app);
1066 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001067 } break;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07001068 case DO_PENDING_ACTIVITY_LAUNCHES_MSG: {
1069 synchronized (ActivityManagerService.this) {
1070 doPendingActivityLaunchesLocked(true);
1071 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001072 } break;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001073 case KILL_APPLICATION_MSG: {
1074 synchronized (ActivityManagerService.this) {
1075 int uid = msg.arg1;
1076 boolean restart = (msg.arg2 == 1);
1077 String pkg = (String) msg.obj;
Christopher Tate3dacd842011-08-19 14:56:15 -07001078 forceStopPackageLocked(pkg, uid, restart, false, true, false);
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001079 }
1080 } break;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001081 case FINALIZE_PENDING_INTENT_MSG: {
1082 ((PendingIntentRecord)msg.obj).completeFinalize();
1083 } break;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001084 case POST_HEAVY_NOTIFICATION_MSG: {
1085 INotificationManager inm = NotificationManager.getService();
1086 if (inm == null) {
1087 return;
1088 }
1089
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001090 ActivityRecord root = (ActivityRecord)msg.obj;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001091 ProcessRecord process = root.app;
1092 if (process == null) {
1093 return;
1094 }
1095
1096 try {
1097 Context context = mContext.createPackageContext(process.info.packageName, 0);
1098 String text = mContext.getString(R.string.heavy_weight_notification,
1099 context.getApplicationInfo().loadLabel(context.getPackageManager()));
1100 Notification notification = new Notification();
1101 notification.icon = com.android.internal.R.drawable.stat_sys_adb; //context.getApplicationInfo().icon;
1102 notification.when = 0;
1103 notification.flags = Notification.FLAG_ONGOING_EVENT;
1104 notification.tickerText = text;
1105 notification.defaults = 0; // please be quiet
1106 notification.sound = null;
1107 notification.vibrate = null;
1108 notification.setLatestEventInfo(context, text,
1109 mContext.getText(R.string.heavy_weight_notification_detail),
1110 PendingIntent.getActivity(mContext, 0, root.intent,
1111 PendingIntent.FLAG_CANCEL_CURRENT));
1112
1113 try {
1114 int[] outId = new int[1];
1115 inm.enqueueNotification("android", R.string.heavy_weight_notification,
1116 notification, outId);
1117 } catch (RuntimeException e) {
1118 Slog.w(ActivityManagerService.TAG,
1119 "Error showing notification for heavy-weight app", e);
1120 } catch (RemoteException e) {
1121 }
1122 } catch (NameNotFoundException e) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07001123 Slog.w(TAG, "Unable to create context for heavy notification", e);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001124 }
1125 } break;
1126 case CANCEL_HEAVY_NOTIFICATION_MSG: {
1127 INotificationManager inm = NotificationManager.getService();
1128 if (inm == null) {
1129 return;
1130 }
1131 try {
1132 inm.cancelNotification("android",
1133 R.string.heavy_weight_notification);
1134 } catch (RuntimeException e) {
1135 Slog.w(ActivityManagerService.TAG,
1136 "Error canceling notification for service", e);
1137 } catch (RemoteException e) {
1138 }
1139 } break;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001140 case CHECK_EXCESSIVE_WAKE_LOCKS_MSG: {
1141 synchronized (ActivityManagerService.this) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001142 checkExcessivePowerUsageLocked(true);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07001143 removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001144 Message nmsg = obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
1145 sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001146 }
1147 } break;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001148 case SHOW_COMPAT_MODE_DIALOG_MSG: {
1149 synchronized (ActivityManagerService.this) {
1150 ActivityRecord ar = (ActivityRecord)msg.obj;
1151 if (mCompatModeDialog != null) {
1152 if (mCompatModeDialog.mAppInfo.packageName.equals(
1153 ar.info.applicationInfo.packageName)) {
1154 return;
1155 }
1156 mCompatModeDialog.dismiss();
1157 mCompatModeDialog = null;
1158 }
Dianne Hackborn29478262011-06-07 15:44:22 -07001159 if (ar != null && false) {
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001160 if (mCompatModePackages.getPackageAskCompatModeLocked(
1161 ar.packageName)) {
1162 int mode = mCompatModePackages.computeCompatModeLocked(
1163 ar.info.applicationInfo);
1164 if (mode == ActivityManager.COMPAT_MODE_DISABLED
1165 || mode == ActivityManager.COMPAT_MODE_ENABLED) {
1166 mCompatModeDialog = new CompatModeDialog(
1167 ActivityManagerService.this, mContext,
1168 ar.info.applicationInfo);
1169 mCompatModeDialog.show();
1170 }
1171 }
1172 }
1173 }
Dianne Hackborn36f80f32011-05-31 18:26:45 -07001174 break;
1175 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001176 case DISPATCH_FOREGROUND_ACTIVITIES_CHANGED: {
Jeff Sharkey287bd832011-05-28 19:36:26 -07001177 final int pid = msg.arg1;
1178 final int uid = msg.arg2;
1179 final boolean foregroundActivities = (Boolean) msg.obj;
1180 dispatchForegroundActivitiesChanged(pid, uid, foregroundActivities);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001181 break;
1182 }
1183 case DISPATCH_PROCESS_DIED: {
Jeff Sharkey287bd832011-05-28 19:36:26 -07001184 final int pid = msg.arg1;
1185 final int uid = msg.arg2;
1186 dispatchProcessDied(pid, uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001187 break;
1188 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001189 case REPORT_MEM_USAGE: {
1190 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
1191 if (!isDebuggable) {
1192 return;
1193 }
1194 synchronized (ActivityManagerService.this) {
1195 long now = SystemClock.uptimeMillis();
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001196 if (now < (mLastMemUsageReportTime+5*60*1000)) {
1197 // Don't report more than every 5 minutes to somewhat
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001198 // avoid spamming.
1199 return;
1200 }
1201 mLastMemUsageReportTime = now;
1202 }
1203 Thread thread = new Thread() {
1204 @Override public void run() {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001205 StringBuilder dropBuilder = new StringBuilder(1024);
1206 StringBuilder logBuilder = new StringBuilder(1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -08001207 StringWriter oomSw = new StringWriter();
1208 PrintWriter oomPw = new PrintWriter(oomSw);
1209 StringWriter catSw = new StringWriter();
1210 PrintWriter catPw = new PrintWriter(catSw);
1211 String[] emptyArgs = new String[] { };
1212 StringBuilder tag = new StringBuilder(128);
1213 StringBuilder stack = new StringBuilder(128);
1214 tag.append("Low on memory -- ");
1215 dumpApplicationMemoryUsage(null, oomPw, " ", emptyArgs, true, catPw,
1216 tag, stack);
1217 dropBuilder.append(stack);
1218 dropBuilder.append('\n');
1219 dropBuilder.append('\n');
1220 String oomString = oomSw.toString();
1221 dropBuilder.append(oomString);
1222 dropBuilder.append('\n');
1223 logBuilder.append(oomString);
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001224 try {
1225 java.lang.Process proc = Runtime.getRuntime().exec(new String[] {
1226 "procrank", });
1227 final InputStreamReader converter = new InputStreamReader(
1228 proc.getInputStream());
1229 BufferedReader in = new BufferedReader(converter);
1230 String line;
1231 while (true) {
1232 line = in.readLine();
1233 if (line == null) {
1234 break;
1235 }
1236 if (line.length() > 0) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001237 logBuilder.append(line);
1238 logBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001239 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001240 dropBuilder.append(line);
1241 dropBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001242 }
1243 converter.close();
1244 } catch (IOException e) {
1245 }
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001246 synchronized (ActivityManagerService.this) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08001247 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001248 dumpProcessesLocked(null, catPw, emptyArgs, 0, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001249 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001250 dumpServicesLocked(null, catPw, emptyArgs, 0, false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001251 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001252 dumpActivitiesLocked(null, catPw, emptyArgs, 0, false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001253 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001254 dropBuilder.append(catSw.toString());
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001255 addErrorToDropBox("lowmem", null, "system_server", null,
1256 null, tag.toString(), dropBuilder.toString(), null, null);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001257 Slog.i(TAG, logBuilder.toString());
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001258 synchronized (ActivityManagerService.this) {
1259 long now = SystemClock.uptimeMillis();
1260 if (mLastMemUsageReportTime < now) {
1261 mLastMemUsageReportTime = now;
1262 }
1263 }
1264 }
1265 };
1266 thread.start();
1267 break;
1268 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001269 }
1270 }
1271 };
1272
1273 public static void setSystemProcess() {
1274 try {
1275 ActivityManagerService m = mSelf;
1276
Dianne Hackborna573f6a2012-02-09 16:12:18 -08001277 ServiceManager.addService("activity", m, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001278 ServiceManager.addService("meminfo", new MemBinder(m));
Chet Haase9c1e23b2011-03-24 10:51:31 -07001279 ServiceManager.addService("gfxinfo", new GraphicsBinder(m));
Jeff Brown6754ba22011-12-14 20:20:01 -08001280 ServiceManager.addService("dbinfo", new DbBinder(m));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001281 if (MONITOR_CPU_USAGE) {
1282 ServiceManager.addService("cpuinfo", new CpuBinder(m));
1283 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001284 ServiceManager.addService("permission", new PermissionController(m));
1285
1286 ApplicationInfo info =
1287 mSelf.mContext.getPackageManager().getApplicationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -07001288 "android", STOCK_PM_FLAGS);
Mike Cleron432b7132009-09-24 15:28:29 -07001289 mSystemThread.installSystemApplicationInfo(info);
1290
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001291 synchronized (mSelf) {
1292 ProcessRecord app = mSelf.newProcessRecordLocked(
1293 mSystemThread.getApplicationThread(), info,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001294 info.processName, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001295 app.persistent = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08001296 app.pid = MY_PID;
Dianne Hackborn7d608422011-08-07 16:24:18 -07001297 app.maxAdj = ProcessList.SYSTEM_ADJ;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001298 mSelf.mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001299 synchronized (mSelf.mPidsSelfLocked) {
1300 mSelf.mPidsSelfLocked.put(app.pid, app);
1301 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001302 mSelf.updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001303 }
1304 } catch (PackageManager.NameNotFoundException e) {
1305 throw new RuntimeException(
1306 "Unable to find android system package", e);
1307 }
1308 }
1309
1310 public void setWindowManager(WindowManagerService wm) {
1311 mWindowManager = wm;
1312 }
1313
1314 public static final Context main(int factoryTest) {
1315 AThread thr = new AThread();
1316 thr.start();
1317
1318 synchronized (thr) {
1319 while (thr.mService == null) {
1320 try {
1321 thr.wait();
1322 } catch (InterruptedException e) {
1323 }
1324 }
1325 }
1326
1327 ActivityManagerService m = thr.mService;
1328 mSelf = m;
1329 ActivityThread at = ActivityThread.systemMain();
1330 mSystemThread = at;
1331 Context context = at.getSystemContext();
Dianne Hackborn247fe742011-01-08 17:25:57 -08001332 context.setTheme(android.R.style.Theme_Holo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001333 m.mContext = context;
1334 m.mFactoryTest = factoryTest;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001335 m.mMainStack = new ActivityStack(m, context, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001336
1337 m.mBatteryStatsService.publish(context);
1338 m.mUsageStatsService.publish(context);
1339
1340 synchronized (thr) {
1341 thr.mReady = true;
1342 thr.notifyAll();
1343 }
1344
1345 m.startRunning(null, null, null, null);
1346
1347 return context;
1348 }
1349
1350 public static ActivityManagerService self() {
1351 return mSelf;
1352 }
1353
1354 static class AThread extends Thread {
1355 ActivityManagerService mService;
1356 boolean mReady = false;
1357
1358 public AThread() {
1359 super("ActivityManager");
1360 }
1361
1362 public void run() {
1363 Looper.prepare();
1364
1365 android.os.Process.setThreadPriority(
1366 android.os.Process.THREAD_PRIORITY_FOREGROUND);
Christopher Tate160edb32010-06-30 17:46:30 -07001367 android.os.Process.setCanSelfBackground(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001368
1369 ActivityManagerService m = new ActivityManagerService();
1370
1371 synchronized (this) {
1372 mService = m;
1373 notifyAll();
1374 }
1375
1376 synchronized (this) {
1377 while (!mReady) {
1378 try {
1379 wait();
1380 } catch (InterruptedException e) {
1381 }
1382 }
1383 }
1384
Brad Fitzpatrickec062f62010-11-03 09:56:54 -07001385 // For debug builds, log event loop stalls to dropbox for analysis.
1386 if (StrictMode.conditionallyEnableDebugLogging()) {
1387 Slog.i(TAG, "Enabled StrictMode logging for AThread's Looper");
1388 }
1389
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001390 Looper.loop();
1391 }
1392 }
1393
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001394 static class MemBinder extends Binder {
1395 ActivityManagerService mActivityManagerService;
1396 MemBinder(ActivityManagerService activityManagerService) {
1397 mActivityManagerService = activityManagerService;
1398 }
1399
1400 @Override
1401 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001402 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1403 != PackageManager.PERMISSION_GRANTED) {
1404 pw.println("Permission Denial: can't dump meminfo from from pid="
1405 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1406 + " without permission " + android.Manifest.permission.DUMP);
1407 return;
1408 }
1409
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001410 mActivityManagerService.dumpApplicationMemoryUsage(fd, pw, " ", args,
Dianne Hackborn672342c2011-11-29 11:29:02 -08001411 false, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001412 }
1413 }
1414
Chet Haase9c1e23b2011-03-24 10:51:31 -07001415 static class GraphicsBinder extends Binder {
1416 ActivityManagerService mActivityManagerService;
1417 GraphicsBinder(ActivityManagerService activityManagerService) {
1418 mActivityManagerService = activityManagerService;
1419 }
1420
1421 @Override
1422 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001423 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1424 != PackageManager.PERMISSION_GRANTED) {
1425 pw.println("Permission Denial: can't dump gfxinfo from from pid="
1426 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1427 + " without permission " + android.Manifest.permission.DUMP);
1428 return;
1429 }
1430
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001431 mActivityManagerService.dumpGraphicsHardwareUsage(fd, pw, args);
Chet Haase9c1e23b2011-03-24 10:51:31 -07001432 }
1433 }
1434
Jeff Brown6754ba22011-12-14 20:20:01 -08001435 static class DbBinder extends Binder {
1436 ActivityManagerService mActivityManagerService;
1437 DbBinder(ActivityManagerService activityManagerService) {
1438 mActivityManagerService = activityManagerService;
1439 }
1440
1441 @Override
1442 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1443 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1444 != PackageManager.PERMISSION_GRANTED) {
1445 pw.println("Permission Denial: can't dump dbinfo from from pid="
1446 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1447 + " without permission " + android.Manifest.permission.DUMP);
1448 return;
1449 }
1450
1451 mActivityManagerService.dumpDbInfo(fd, pw, args);
1452 }
1453 }
1454
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001455 static class CpuBinder extends Binder {
1456 ActivityManagerService mActivityManagerService;
1457 CpuBinder(ActivityManagerService activityManagerService) {
1458 mActivityManagerService = activityManagerService;
1459 }
1460
1461 @Override
1462 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001463 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1464 != PackageManager.PERMISSION_GRANTED) {
1465 pw.println("Permission Denial: can't dump cpuinfo from from pid="
1466 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1467 + " without permission " + android.Manifest.permission.DUMP);
1468 return;
1469 }
1470
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001471 synchronized (mActivityManagerService.mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07001472 pw.print(mActivityManagerService.mProcessStats.printCurrentLoad());
1473 pw.print(mActivityManagerService.mProcessStats.printCurrentState(
1474 SystemClock.uptimeMillis()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001475 }
1476 }
1477 }
1478
1479 private ActivityManagerService() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001480 Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
Dianne Hackborn2c6c5e62009-10-08 17:55:49 -07001481
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001482 mFgBroadcastQueue = new BroadcastQueue(this, "foreground", BROADCAST_FG_TIMEOUT);
1483 mBgBroadcastQueue = new BroadcastQueue(this, "background", BROADCAST_BG_TIMEOUT);
1484 mBroadcastQueues[0] = mFgBroadcastQueue;
1485 mBroadcastQueues[1] = mBgBroadcastQueue;
1486
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001487 File dataDir = Environment.getDataDirectory();
1488 File systemDir = new File(dataDir, "system");
1489 systemDir.mkdirs();
1490 mBatteryStatsService = new BatteryStatsService(new File(
1491 systemDir, "batterystats.bin").toString());
1492 mBatteryStatsService.getActiveStatistics().readLocked();
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001493 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
Dianne Hackborn287952c2010-09-22 22:34:31 -07001494 mOnBattery = DEBUG_POWER ? true
1495 : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001496 mBatteryStatsService.getActiveStatistics().setCallback(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001497
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001498 mUsageStatsService = new UsageStatsService(new File(
Dianne Hackborn6447ca32009-04-07 19:50:08 -07001499 systemDir, "usagestats").toString());
Mike Lockwood3a74bd32011-08-12 13:55:22 -07001500 mHeadless = "1".equals(SystemProperties.get("ro.config.headless", "0"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001501
Jack Palevichb90d28c2009-07-22 15:35:24 -07001502 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",
1503 ConfigurationInfo.GL_ES_VERSION_UNDEFINED);
1504
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001505 mConfiguration.setToDefaults();
1506 mConfiguration.locale = Locale.getDefault();
Dianne Hackborn813075a62011-11-14 17:45:19 -08001507 mConfigurationSeq = mConfiguration.seq = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001508 mProcessStats.init();
1509
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07001510 mCompatModePackages = new CompatModePackages(this, systemDir);
1511
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001512 // Add ourself to the Watchdog monitors.
1513 Watchdog.getInstance().addMonitor(this);
1514
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001515 mProcessStatsThread = new Thread("ProcessStats") {
1516 public void run() {
1517 while (true) {
1518 try {
1519 try {
1520 synchronized(this) {
1521 final long now = SystemClock.uptimeMillis();
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001522 long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001523 long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001524 //Slog.i(TAG, "Cpu delay=" + nextCpuDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001525 // + ", write delay=" + nextWriteDelay);
1526 if (nextWriteDelay < nextCpuDelay) {
1527 nextCpuDelay = nextWriteDelay;
1528 }
1529 if (nextCpuDelay > 0) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001530 mProcessStatsMutexFree.set(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001531 this.wait(nextCpuDelay);
1532 }
1533 }
1534 } catch (InterruptedException e) {
1535 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001536 updateCpuStatsNow();
1537 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001538 Slog.e(TAG, "Unexpected exception collecting process stats", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001539 }
1540 }
1541 }
1542 };
1543 mProcessStatsThread.start();
1544 }
1545
1546 @Override
1547 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1548 throws RemoteException {
1549 try {
1550 return super.onTransact(code, data, reply, flags);
1551 } catch (RuntimeException e) {
1552 // The activity manager only throws security exceptions, so let's
1553 // log all others.
1554 if (!(e instanceof SecurityException)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001555 Slog.e(TAG, "Activity Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001556 }
1557 throw e;
1558 }
1559 }
1560
1561 void updateCpuStats() {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001562 final long now = SystemClock.uptimeMillis();
1563 if (mLastCpuTime.get() >= now - MONITOR_CPU_MIN_TIME) {
1564 return;
1565 }
1566 if (mProcessStatsMutexFree.compareAndSet(true, false)) {
1567 synchronized (mProcessStatsThread) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001568 mProcessStatsThread.notify();
1569 }
1570 }
1571 }
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001572
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001573 void updateCpuStatsNow() {
1574 synchronized (mProcessStatsThread) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001575 mProcessStatsMutexFree.set(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001576 final long now = SystemClock.uptimeMillis();
1577 boolean haveNewCpuStats = false;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07001578
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001579 if (MONITOR_CPU_USAGE &&
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001580 mLastCpuTime.get() < (now-MONITOR_CPU_MIN_TIME)) {
1581 mLastCpuTime.set(now);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001582 haveNewCpuStats = true;
1583 mProcessStats.update();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001584 //Slog.i(TAG, mProcessStats.printCurrentState());
1585 //Slog.i(TAG, "Total CPU usage: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001586 // + mProcessStats.getTotalCpuPercent() + "%");
1587
Joe Onorato8a9b2202010-02-26 18:56:32 -08001588 // Slog the cpu usage if the property is set.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001589 if ("true".equals(SystemProperties.get("events.cpu"))) {
1590 int user = mProcessStats.getLastUserTime();
1591 int system = mProcessStats.getLastSystemTime();
1592 int iowait = mProcessStats.getLastIoWaitTime();
1593 int irq = mProcessStats.getLastIrqTime();
1594 int softIrq = mProcessStats.getLastSoftIrqTime();
1595 int idle = mProcessStats.getLastIdleTime();
1596
1597 int total = user + system + iowait + irq + softIrq + idle;
1598 if (total == 0) total = 1;
1599
Doug Zongker2bec3d42009-12-04 12:52:44 -08001600 EventLog.writeEvent(EventLogTags.CPU,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001601 ((user+system+iowait+irq+softIrq) * 100) / total,
1602 (user * 100) / total,
1603 (system * 100) / total,
1604 (iowait * 100) / total,
1605 (irq * 100) / total,
1606 (softIrq * 100) / total);
1607 }
1608 }
1609
Amith Yamasanie43530a2009-08-21 13:11:37 -07001610 long[] cpuSpeedTimes = mProcessStats.getLastCpuSpeedTimes();
Amith Yamasani819f9282009-06-24 23:18:15 -07001611 final BatteryStatsImpl bstats = mBatteryStatsService.getActiveStatistics();
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001612 synchronized(bstats) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001613 synchronized(mPidsSelfLocked) {
1614 if (haveNewCpuStats) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001615 if (mOnBattery) {
1616 int perc = bstats.startAddingCpuLocked();
1617 int totalUTime = 0;
1618 int totalSTime = 0;
Dianne Hackborn287952c2010-09-22 22:34:31 -07001619 final int N = mProcessStats.countStats();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001620 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001621 ProcessStats.Stats st = mProcessStats.getStats(i);
1622 if (!st.working) {
1623 continue;
1624 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001625 ProcessRecord pr = mPidsSelfLocked.get(st.pid);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001626 int otherUTime = (st.rel_utime*perc)/100;
1627 int otherSTime = (st.rel_stime*perc)/100;
1628 totalUTime += otherUTime;
1629 totalSTime += otherSTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001630 if (pr != null) {
1631 BatteryStatsImpl.Uid.Proc ps = pr.batteryStats;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001632 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1633 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001634 ps.addSpeedStepTimes(cpuSpeedTimes);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001635 pr.curCpuTime += (st.rel_utime+st.rel_stime) * 10;
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001636 } else {
1637 BatteryStatsImpl.Uid.Proc ps =
Amith Yamasani819f9282009-06-24 23:18:15 -07001638 bstats.getProcessStatsLocked(st.name, st.pid);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001639 if (ps != null) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001640 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1641 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001642 ps.addSpeedStepTimes(cpuSpeedTimes);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001643 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001644 }
1645 }
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001646 bstats.finishAddingCpuLocked(perc, totalUTime,
1647 totalSTime, cpuSpeedTimes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001648 }
1649 }
1650 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001651
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001652 if (mLastWriteTime < (now-BATTERY_STATS_TIME)) {
1653 mLastWriteTime = now;
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001654 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001655 }
1656 }
1657 }
1658 }
1659
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001660 @Override
1661 public void batteryNeedsCpuUpdate() {
1662 updateCpuStatsNow();
1663 }
1664
1665 @Override
1666 public void batteryPowerChanged(boolean onBattery) {
1667 // When plugging in, update the CPU stats first before changing
1668 // the plug state.
1669 updateCpuStatsNow();
1670 synchronized (this) {
1671 synchronized(mPidsSelfLocked) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001672 mOnBattery = DEBUG_POWER ? true : onBattery;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001673 }
1674 }
1675 }
1676
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001677 /**
1678 * Initialize the application bind args. These are passed to each
1679 * process when the bindApplication() IPC is sent to the process. They're
1680 * lazily setup to make sure the services are running when they're asked for.
1681 */
1682 private HashMap<String, IBinder> getCommonServicesLocked() {
1683 if (mAppBindArgs == null) {
1684 mAppBindArgs = new HashMap<String, IBinder>();
1685
1686 // Setup the application init args
1687 mAppBindArgs.put("package", ServiceManager.getService("package"));
1688 mAppBindArgs.put("window", ServiceManager.getService("window"));
1689 mAppBindArgs.put(Context.ALARM_SERVICE,
1690 ServiceManager.getService(Context.ALARM_SERVICE));
1691 }
1692 return mAppBindArgs;
1693 }
1694
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001695 final void setFocusedActivityLocked(ActivityRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001696 if (mFocusedActivity != r) {
1697 mFocusedActivity = r;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001698 if (r != null) {
1699 mWindowManager.setFocusedApp(r.appToken, true);
1700 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001701 }
1702 }
1703
Dianne Hackborn906497c2010-05-10 15:57:38 -07001704 private final void updateLruProcessInternalLocked(ProcessRecord app,
1705 boolean oomAdj, boolean updateActivityTime, int bestPos) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001706 // put it on the LRU to keep track of when it should be exited.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001707 int lrui = mLruProcesses.indexOf(app);
1708 if (lrui >= 0) mLruProcesses.remove(lrui);
1709
1710 int i = mLruProcesses.size()-1;
1711 int skipTop = 0;
1712
Dianne Hackborn906497c2010-05-10 15:57:38 -07001713 app.lruSeq = mLruSeq;
1714
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001715 // compute the new weight for this process.
1716 if (updateActivityTime) {
1717 app.lastActivityTime = SystemClock.uptimeMillis();
1718 }
1719 if (app.activities.size() > 0) {
1720 // If this process has activities, we more strongly want to keep
1721 // it around.
1722 app.lruWeight = app.lastActivityTime;
1723 } else if (app.pubProviders.size() > 0) {
1724 // If this process contains content providers, we want to keep
1725 // it a little more strongly.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001726 app.lruWeight = app.lastActivityTime - ProcessList.CONTENT_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001727 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001728 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001729 } else {
1730 // If this process doesn't have activities, we less strongly
1731 // want to keep it around, and generally want to avoid getting
1732 // in front of any very recently used activities.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001733 app.lruWeight = app.lastActivityTime - ProcessList.EMPTY_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001734 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001735 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001736 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001737
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001738 while (i >= 0) {
1739 ProcessRecord p = mLruProcesses.get(i);
1740 // If this app shouldn't be in front of the first N background
1741 // apps, then skip over that many that are currently hidden.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001742 if (skipTop > 0 && p.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001743 skipTop--;
1744 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001745 if (p.lruWeight <= app.lruWeight || i < bestPos) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001746 mLruProcesses.add(i+1, app);
1747 break;
1748 }
1749 i--;
1750 }
1751 if (i < 0) {
1752 mLruProcesses.add(0, app);
1753 }
1754
Dianne Hackborn906497c2010-05-10 15:57:38 -07001755 // If the app is currently using a content provider or service,
1756 // bump those processes as well.
1757 if (app.connections.size() > 0) {
1758 for (ConnectionRecord cr : app.connections) {
1759 if (cr.binding != null && cr.binding.service != null
1760 && cr.binding.service.app != null
1761 && cr.binding.service.app.lruSeq != mLruSeq) {
1762 updateLruProcessInternalLocked(cr.binding.service.app, oomAdj,
1763 updateActivityTime, i+1);
1764 }
1765 }
1766 }
1767 if (app.conProviders.size() > 0) {
1768 for (ContentProviderRecord cpr : app.conProviders.keySet()) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07001769 if (cpr.proc != null && cpr.proc.lruSeq != mLruSeq) {
1770 updateLruProcessInternalLocked(cpr.proc, oomAdj,
Dianne Hackborn906497c2010-05-10 15:57:38 -07001771 updateActivityTime, i+1);
1772 }
1773 }
1774 }
1775
Joe Onorato8a9b2202010-02-26 18:56:32 -08001776 //Slog.i(TAG, "Putting proc to front: " + app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001777 if (oomAdj) {
1778 updateOomAdjLocked();
1779 }
1780 }
1781
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001782 final void updateLruProcessLocked(ProcessRecord app,
Dianne Hackborn906497c2010-05-10 15:57:38 -07001783 boolean oomAdj, boolean updateActivityTime) {
1784 mLruSeq++;
1785 updateLruProcessInternalLocked(app, oomAdj, updateActivityTime, 0);
1786 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001787
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001788 final ProcessRecord getProcessRecordLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001789 String processName, int uid) {
1790 if (uid == Process.SYSTEM_UID) {
1791 // The system gets to run in any process. If there are multiple
1792 // processes with the same uid, just pick the first (this
1793 // should never happen).
1794 SparseArray<ProcessRecord> procs = mProcessNames.getMap().get(
1795 processName);
1796 return procs != null ? procs.valueAt(0) : null;
1797 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001798 // uid = applyUserId(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001799 ProcessRecord proc = mProcessNames.get(processName, uid);
1800 return proc;
1801 }
1802
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001803 void ensurePackageDexOpt(String packageName) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001804 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001805 try {
1806 if (pm.performDexOpt(packageName)) {
1807 mDidDexOpt = true;
1808 }
1809 } catch (RemoteException e) {
1810 }
1811 }
1812
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001813 boolean isNextTransitionForward() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001814 int transit = mWindowManager.getPendingAppTransition();
1815 return transit == WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
1816 || transit == WindowManagerPolicy.TRANSIT_TASK_OPEN
1817 || transit == WindowManagerPolicy.TRANSIT_TASK_TO_FRONT;
1818 }
1819
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001820 final ProcessRecord startProcessLocked(String processName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001821 ApplicationInfo info, boolean knownToBeDead, int intentFlags,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001822 String hostingType, ComponentName hostingName, boolean allowWhileBooting,
1823 boolean isolated) {
1824 ProcessRecord app;
1825 if (!isolated) {
1826 app = getProcessRecordLocked(processName, info.uid);
1827 } else {
1828 // If this is an isolated process, it can't re-use an existing process.
1829 app = null;
1830 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001831 // We don't have to do anything more if:
1832 // (1) There is an existing application record; and
1833 // (2) The caller doesn't think it is dead, OR there is no thread
1834 // object attached to it so we know it couldn't have crashed; and
1835 // (3) There is a pid assigned to it, so it is either starting or
1836 // already running.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001837 if (DEBUG_PROCESSES) Slog.v(TAG, "startProcess: name=" + processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001838 + " app=" + app + " knownToBeDead=" + knownToBeDead
1839 + " thread=" + (app != null ? app.thread : null)
1840 + " pid=" + (app != null ? app.pid : -1));
Magnus Edlund7bb25812010-02-24 15:45:06 +01001841 if (app != null && app.pid > 0) {
1842 if (!knownToBeDead || app.thread == null) {
Dianne Hackborn20cb56e2010-03-04 00:58:29 -08001843 // We already have the app running, or are waiting for it to
1844 // come up (we have a pid but not yet its thread), so keep it.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001845 if (DEBUG_PROCESSES) Slog.v(TAG, "App already running: " + app);
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001846 // If this is a new package in the process, add the package to the list
1847 app.addPackage(info.packageName);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001848 return app;
1849 } else {
1850 // An application record is attached to a previous process,
1851 // clean it up now.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001852 if (DEBUG_PROCESSES) Slog.v(TAG, "App died: " + app);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07001853 handleAppDiedLocked(app, true, true);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001854 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001855 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01001856
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001857 String hostingNameStr = hostingName != null
1858 ? hostingName.flattenToShortString() : null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001859
1860 if (!isolated) {
1861 if ((intentFlags&Intent.FLAG_FROM_BACKGROUND) != 0) {
1862 // If we are in the background, then check to see if this process
1863 // is bad. If so, we will just silently fail.
1864 if (mBadProcesses.get(info.processName, info.uid) != null) {
1865 if (DEBUG_PROCESSES) Slog.v(TAG, "Bad process: " + info.uid
1866 + "/" + info.processName);
1867 return null;
1868 }
1869 } else {
1870 // When the user is explicitly starting a process, then clear its
1871 // crash count so that we won't make it bad until they see at
1872 // least one crash dialog again, and make the process good again
1873 // if it had been bad.
1874 if (DEBUG_PROCESSES) Slog.v(TAG, "Clearing bad process: " + info.uid
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001875 + "/" + info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001876 mProcessCrashTimes.remove(info.processName, info.uid);
1877 if (mBadProcesses.get(info.processName, info.uid) != null) {
1878 EventLog.writeEvent(EventLogTags.AM_PROC_GOOD, info.uid,
1879 info.processName);
1880 mBadProcesses.remove(info.processName, info.uid);
1881 if (app != null) {
1882 app.bad = false;
1883 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001884 }
1885 }
1886 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001887
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001888 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001889 app = newProcessRecordLocked(null, info, processName, isolated);
1890 if (app == null) {
1891 Slog.w(TAG, "Failed making new process record for "
1892 + processName + "/" + info.uid + " isolated=" + isolated);
1893 return null;
1894 }
1895 mProcessNames.put(processName, app.uid, app);
1896 if (isolated) {
1897 mIsolatedProcesses.put(app.uid, app);
1898 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001899 } else {
1900 // If this is a new package in the process, add the package to the list
1901 app.addPackage(info.packageName);
1902 }
1903
1904 // If the system is not ready yet, then hold off on starting this
1905 // process until it is.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001906 if (!mProcessesReady
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001907 && !isAllowedWhileBooting(info)
1908 && !allowWhileBooting) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001909 if (!mProcessesOnHold.contains(app)) {
1910 mProcessesOnHold.add(app);
1911 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001912 if (DEBUG_PROCESSES) Slog.v(TAG, "System not ready, putting on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001913 return app;
1914 }
1915
1916 startProcessLocked(app, hostingType, hostingNameStr);
1917 return (app.pid != 0) ? app : null;
1918 }
1919
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001920 boolean isAllowedWhileBooting(ApplicationInfo ai) {
1921 return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0;
1922 }
1923
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001924 private final void startProcessLocked(ProcessRecord app,
1925 String hostingType, String hostingNameStr) {
1926 if (app.pid > 0 && app.pid != MY_PID) {
1927 synchronized (mPidsSelfLocked) {
1928 mPidsSelfLocked.remove(app.pid);
1929 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
1930 }
1931 app.pid = 0;
1932 }
1933
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001934 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
1935 "startProcessLocked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001936 mProcessesOnHold.remove(app);
1937
1938 updateCpuStats();
1939
1940 System.arraycopy(mProcDeaths, 0, mProcDeaths, 1, mProcDeaths.length-1);
1941 mProcDeaths[0] = 0;
1942
1943 try {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001944 int uid = app.uid;
Amith Yamasani742a6712011-05-04 14:49:28 -07001945
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001946 int[] gids = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001947 if (!app.isolated) {
1948 try {
1949 gids = mContext.getPackageManager().getPackageGids(
1950 app.info.packageName);
1951 } catch (PackageManager.NameNotFoundException e) {
1952 Slog.w(TAG, "Unable to retrieve gids", e);
1953 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001954 }
1955 if (mFactoryTest != SystemServer.FACTORY_TEST_OFF) {
1956 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
1957 && mTopComponent != null
1958 && app.processName.equals(mTopComponent.getPackageName())) {
1959 uid = 0;
1960 }
1961 if (mFactoryTest == SystemServer.FACTORY_TEST_HIGH_LEVEL
1962 && (app.info.flags&ApplicationInfo.FLAG_FACTORY_TEST) != 0) {
1963 uid = 0;
1964 }
1965 }
1966 int debugFlags = 0;
1967 if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
1968 debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;
Elliott Hughesfa36aee2011-06-17 14:39:41 -07001969 // Also turn on CheckJNI for debuggable apps. It's quite
1970 // awkward to turn on otherwise.
1971 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001972 }
Ben Cheng6c0afff2010-02-14 16:18:56 -08001973 // Run the app in safe mode if its manifest requests so or the
1974 // system is booted in safe mode.
1975 if ((app.info.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0 ||
1976 Zygote.systemInSafeMode == true) {
Ben Cheng23085b72010-02-08 16:06:32 -08001977 debugFlags |= Zygote.DEBUG_ENABLE_SAFEMODE;
1978 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001979 if ("1".equals(SystemProperties.get("debug.checkjni"))) {
1980 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
1981 }
Elliott Hughesae07ecf2011-07-06 17:33:27 -07001982 if ("1".equals(SystemProperties.get("debug.jni.logging"))) {
1983 debugFlags |= Zygote.DEBUG_ENABLE_JNI_LOGGING;
1984 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001985 if ("1".equals(SystemProperties.get("debug.assert"))) {
1986 debugFlags |= Zygote.DEBUG_ENABLE_ASSERT;
1987 }
Jeff Brown3f9dd282011-07-08 20:02:19 -07001988
1989 // Start the process. It will either succeed and return a result containing
1990 // the PID of the new process, or else throw a RuntimeException.
1991 Process.ProcessStartResult startResult = Process.start("android.app.ActivityThread",
Elliott Hughese1dfcb72011-07-08 11:08:07 -07001992 app.processName, uid, uid, gids, debugFlags,
1993 app.info.targetSdkVersion, null);
Jeff Brown3f9dd282011-07-08 20:02:19 -07001994
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001995 BatteryStatsImpl bs = app.batteryStats.getBatteryStats();
1996 synchronized (bs) {
1997 if (bs.isOnBattery()) {
1998 app.batteryStats.incStartsLocked();
1999 }
2000 }
2001
Jeff Brown3f9dd282011-07-08 20:02:19 -07002002 EventLog.writeEvent(EventLogTags.AM_PROC_START, startResult.pid, uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002003 app.processName, hostingType,
2004 hostingNameStr != null ? hostingNameStr : "");
2005
2006 if (app.persistent) {
Jeff Brown3f9dd282011-07-08 20:02:19 -07002007 Watchdog.getInstance().processStarted(app.processName, startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002008 }
2009
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07002010 StringBuilder buf = mStringBuilder;
2011 buf.setLength(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002012 buf.append("Start proc ");
2013 buf.append(app.processName);
2014 buf.append(" for ");
2015 buf.append(hostingType);
2016 if (hostingNameStr != null) {
2017 buf.append(" ");
2018 buf.append(hostingNameStr);
2019 }
2020 buf.append(": pid=");
Jeff Brown3f9dd282011-07-08 20:02:19 -07002021 buf.append(startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002022 buf.append(" uid=");
2023 buf.append(uid);
2024 buf.append(" gids={");
2025 if (gids != null) {
2026 for (int gi=0; gi<gids.length; gi++) {
2027 if (gi != 0) buf.append(", ");
2028 buf.append(gids[gi]);
2029
2030 }
2031 }
2032 buf.append("}");
Joe Onorato8a9b2202010-02-26 18:56:32 -08002033 Slog.i(TAG, buf.toString());
Jeff Brown3f9dd282011-07-08 20:02:19 -07002034 app.pid = startResult.pid;
2035 app.usingWrapper = startResult.usingWrapper;
2036 app.removed = false;
2037 synchronized (mPidsSelfLocked) {
2038 this.mPidsSelfLocked.put(startResult.pid, app);
2039 Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
2040 msg.obj = app;
2041 mHandler.sendMessageDelayed(msg, startResult.usingWrapper
2042 ? PROC_START_TIMEOUT_WITH_WRAPPER : PROC_START_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002043 }
2044 } catch (RuntimeException e) {
2045 // XXX do better error recovery.
2046 app.pid = 0;
Joe Onorato8a9b2202010-02-26 18:56:32 -08002047 Slog.e(TAG, "Failure starting process " + app.processName, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002048 }
2049 }
2050
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002051 void updateUsageStats(ActivityRecord resumedComponent, boolean resumed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002052 if (resumed) {
2053 mUsageStatsService.noteResumeComponent(resumedComponent.realActivity);
2054 } else {
2055 mUsageStatsService.notePauseComponent(resumedComponent.realActivity);
2056 }
2057 }
2058
Amith Yamasani742a6712011-05-04 14:49:28 -07002059 boolean startHomeActivityLocked(int userId) {
Mike Lockwooda8f767a2011-08-31 14:32:37 -04002060 if (mHeadless) {
2061 // Added because none of the other calls to ensureBootCompleted seem to fire
2062 // when running headless.
2063 ensureBootCompleted();
2064 return false;
2065 }
2066
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002067 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2068 && mTopAction == null) {
2069 // We are running in factory test mode, but unable to find
2070 // the factory test app, so just sit around displaying the
2071 // error message and don't try to start anything.
2072 return false;
2073 }
2074 Intent intent = new Intent(
2075 mTopAction,
2076 mTopData != null ? Uri.parse(mTopData) : null);
2077 intent.setComponent(mTopComponent);
2078 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
2079 intent.addCategory(Intent.CATEGORY_HOME);
2080 }
2081 ActivityInfo aInfo =
2082 intent.resolveActivityInfo(mContext.getPackageManager(),
2083 STOCK_PM_FLAGS);
2084 if (aInfo != null) {
2085 intent.setComponent(new ComponentName(
2086 aInfo.applicationInfo.packageName, aInfo.name));
2087 // Don't do this if the home app is currently being
2088 // instrumented.
Amith Yamasani742a6712011-05-04 14:49:28 -07002089 aInfo = new ActivityInfo(aInfo);
2090 aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002091 ProcessRecord app = getProcessRecordLocked(aInfo.processName,
2092 aInfo.applicationInfo.uid);
2093 if (app == null || app.instrumentationClass == null) {
2094 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002095 mMainStack.startActivityLocked(null, intent, null, null, 0, aInfo,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002096 null, null, 0, 0, 0, false, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002097 }
2098 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002099
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002100 return true;
2101 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002102
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002103 /**
2104 * Starts the "new version setup screen" if appropriate.
2105 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002106 void startSetupActivityLocked() {
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002107 // Only do this once per boot.
2108 if (mCheckedForSetup) {
2109 return;
2110 }
2111
2112 // We will show this screen if the current one is a different
2113 // version than the last one shown, and we are not running in
2114 // low-level factory test mode.
2115 final ContentResolver resolver = mContext.getContentResolver();
2116 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL &&
2117 Settings.Secure.getInt(resolver,
2118 Settings.Secure.DEVICE_PROVISIONED, 0) != 0) {
2119 mCheckedForSetup = true;
2120
2121 // See if we should be showing the platform update setup UI.
2122 Intent intent = new Intent(Intent.ACTION_UPGRADE_SETUP);
2123 List<ResolveInfo> ris = mSelf.mContext.getPackageManager()
2124 .queryIntentActivities(intent, PackageManager.GET_META_DATA);
2125
2126 // We don't allow third party apps to replace this.
2127 ResolveInfo ri = null;
2128 for (int i=0; ris != null && i<ris.size(); i++) {
2129 if ((ris.get(i).activityInfo.applicationInfo.flags
2130 & ApplicationInfo.FLAG_SYSTEM) != 0) {
2131 ri = ris.get(i);
2132 break;
2133 }
2134 }
2135
2136 if (ri != null) {
2137 String vers = ri.activityInfo.metaData != null
2138 ? ri.activityInfo.metaData.getString(Intent.METADATA_SETUP_VERSION)
2139 : null;
2140 if (vers == null && ri.activityInfo.applicationInfo.metaData != null) {
2141 vers = ri.activityInfo.applicationInfo.metaData.getString(
2142 Intent.METADATA_SETUP_VERSION);
2143 }
2144 String lastVers = Settings.Secure.getString(
2145 resolver, Settings.Secure.LAST_SETUP_SHOWN);
2146 if (vers != null && !vers.equals(lastVers)) {
2147 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2148 intent.setComponent(new ComponentName(
2149 ri.activityInfo.packageName, ri.activityInfo.name));
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002150 mMainStack.startActivityLocked(null, intent, null, null, 0, ri.activityInfo,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002151 null, null, 0, 0, 0, false, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002152 }
2153 }
2154 }
2155 }
2156
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002157 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002158 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002159 }
2160
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002161 void enforceNotIsolatedCaller(String caller) {
2162 if (UserId.isIsolated(Binder.getCallingUid())) {
2163 throw new SecurityException("Isolated process not allowed to call " + caller);
2164 }
2165 }
2166
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002167 public int getFrontActivityScreenCompatMode() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002168 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002169 synchronized (this) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002170 return mCompatModePackages.getFrontActivityScreenCompatModeLocked();
2171 }
2172 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002173
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002174 public void setFrontActivityScreenCompatMode(int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002175 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2176 "setFrontActivityScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002177 synchronized (this) {
2178 mCompatModePackages.setFrontActivityScreenCompatModeLocked(mode);
2179 }
2180 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002181
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002182 public int getPackageScreenCompatMode(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002183 enforceNotIsolatedCaller("getPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002184 synchronized (this) {
2185 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
2186 }
2187 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002188
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002189 public void setPackageScreenCompatMode(String packageName, int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002190 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2191 "setPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002192 synchronized (this) {
2193 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002194 }
2195 }
2196
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002197 public boolean getPackageAskScreenCompat(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002198 enforceNotIsolatedCaller("getPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002199 synchronized (this) {
2200 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
2201 }
2202 }
2203
2204 public void setPackageAskScreenCompat(String packageName, boolean ask) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002205 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2206 "setPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002207 synchronized (this) {
2208 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
2209 }
2210 }
2211
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002212 void reportResumedActivityLocked(ActivityRecord r) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002213 //Slog.i(TAG, "**** REPORT RESUME: " + r);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002214
2215 final int identHash = System.identityHashCode(r);
2216 updateUsageStats(r, true);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002217 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002218
Jeff Sharkeya4620792011-05-20 15:29:23 -07002219 private void dispatchForegroundActivitiesChanged(int pid, int uid, boolean foregroundActivities) {
2220 int i = mProcessObservers.beginBroadcast();
2221 while (i > 0) {
2222 i--;
2223 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2224 if (observer != null) {
2225 try {
2226 observer.onForegroundActivitiesChanged(pid, uid, foregroundActivities);
2227 } catch (RemoteException e) {
2228 }
2229 }
2230 }
2231 mProcessObservers.finishBroadcast();
2232 }
2233
2234 private void dispatchProcessDied(int pid, int uid) {
2235 int i = mProcessObservers.beginBroadcast();
2236 while (i > 0) {
2237 i--;
2238 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2239 if (observer != null) {
2240 try {
2241 observer.onProcessDied(pid, uid);
2242 } catch (RemoteException e) {
2243 }
2244 }
2245 }
2246 mProcessObservers.finishBroadcast();
2247 }
2248
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002249 final void doPendingActivityLaunchesLocked(boolean doResume) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002250 final int N = mPendingActivityLaunches.size();
2251 if (N <= 0) {
2252 return;
2253 }
2254 for (int i=0; i<N; i++) {
2255 PendingActivityLaunch pal = mPendingActivityLaunches.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002256 mMainStack.startActivityUncheckedLocked(pal.r, pal.sourceRecord,
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002257 pal.grantedUriPermissions, pal.grantedMode, pal.onlyIfNeeded,
2258 doResume && i == (N-1));
2259 }
2260 mPendingActivityLaunches.clear();
2261 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002262
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002263 public final int startActivity(IApplicationThread caller,
2264 Intent intent, String resolvedType, Uri[] grantedUriPermissions,
2265 int grantedMode, IBinder resultTo,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002266 String resultWho, int requestCode, boolean onlyIfNeeded, boolean debug,
2267 String profileFile, ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002268 enforceNotIsolatedCaller("startActivity");
Amith Yamasani742a6712011-05-04 14:49:28 -07002269 int userId = 0;
2270 if (intent.getCategories() != null && intent.getCategories().contains(Intent.CATEGORY_HOME)) {
2271 // Requesting home, set the identity to the current user
2272 // HACK!
2273 userId = mCurrentUserId;
2274 } else {
2275 // TODO: Fix this in a better way - calls coming from SystemUI should probably carry
2276 // the current user's userId
2277 if (Binder.getCallingUid() < Process.FIRST_APPLICATION_UID) {
2278 userId = 0;
2279 } else {
2280 userId = Binder.getOrigCallingUser();
2281 }
2282 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002283 return mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Amith Yamasani742a6712011-05-04 14:49:28 -07002284 grantedUriPermissions, grantedMode, resultTo, resultWho, requestCode, onlyIfNeeded,
2285 debug, profileFile, profileFd, autoStopProfiler, null, null, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002286 }
2287
2288 public final WaitResult startActivityAndWait(IApplicationThread caller,
2289 Intent intent, String resolvedType, Uri[] grantedUriPermissions,
2290 int grantedMode, IBinder resultTo,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002291 String resultWho, int requestCode, boolean onlyIfNeeded, boolean debug,
2292 String profileFile, ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002293 enforceNotIsolatedCaller("startActivityAndWait");
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002294 WaitResult res = new WaitResult();
Amith Yamasani742a6712011-05-04 14:49:28 -07002295 int userId = Binder.getOrigCallingUser();
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002296 mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002297 grantedUriPermissions, grantedMode, resultTo, resultWho,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002298 requestCode, onlyIfNeeded, debug, profileFile, profileFd, autoStopProfiler,
Amith Yamasani742a6712011-05-04 14:49:28 -07002299 res, null, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002300 return res;
2301 }
2302
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002303 public final int startActivityWithConfig(IApplicationThread caller,
2304 Intent intent, String resolvedType, Uri[] grantedUriPermissions,
2305 int grantedMode, IBinder resultTo,
2306 String resultWho, int requestCode, boolean onlyIfNeeded,
2307 boolean debug, Configuration config) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002308 enforceNotIsolatedCaller("startActivityWithConfig");
Amith Yamasani742a6712011-05-04 14:49:28 -07002309 int ret = mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002310 grantedUriPermissions, grantedMode, resultTo, resultWho,
Amith Yamasani742a6712011-05-04 14:49:28 -07002311 requestCode, onlyIfNeeded,
2312 debug, null, null, false, null, config, Binder.getOrigCallingUser());
2313 return ret;
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002314 }
2315
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002316 public int startActivityIntentSender(IApplicationThread caller,
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002317 IntentSender intent, Intent fillInIntent, String resolvedType,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002318 IBinder resultTo, String resultWho, int requestCode,
2319 int flagsMask, int flagsValues) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002320 enforceNotIsolatedCaller("startActivityIntentSender");
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002321 // Refuse possible leaked file descriptors
2322 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
2323 throw new IllegalArgumentException("File descriptors passed in Intent");
2324 }
2325
2326 IIntentSender sender = intent.getTarget();
2327 if (!(sender instanceof PendingIntentRecord)) {
2328 throw new IllegalArgumentException("Bad PendingIntent object");
2329 }
2330
2331 PendingIntentRecord pir = (PendingIntentRecord)sender;
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002332
2333 synchronized (this) {
2334 // If this is coming from the currently resumed activity, it is
2335 // effectively saying that app switches are allowed at this point.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002336 if (mMainStack.mResumedActivity != null
2337 && mMainStack.mResumedActivity.info.applicationInfo.uid ==
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002338 Binder.getCallingUid()) {
2339 mAppSwitchesAllowedTime = 0;
2340 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002341 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002342 int ret = pir.sendInner(0, fillInIntent, resolvedType, null,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002343 null, resultTo, resultWho, requestCode, flagsMask, flagsValues);
Amith Yamasani742a6712011-05-04 14:49:28 -07002344 return ret;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002345 }
2346
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002347 public boolean startNextMatchingActivity(IBinder callingActivity,
2348 Intent intent) {
2349 // Refuse possible leaked file descriptors
2350 if (intent != null && intent.hasFileDescriptors() == true) {
2351 throw new IllegalArgumentException("File descriptors passed in Intent");
2352 }
2353
2354 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002355 ActivityRecord r = mMainStack.isInStackLocked(callingActivity);
2356 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002357 return false;
2358 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002359 if (r.app == null || r.app.thread == null) {
2360 // The caller is not running... d'oh!
2361 return false;
2362 }
2363 intent = new Intent(intent);
2364 // The caller is not allowed to change the data.
2365 intent.setDataAndType(r.intent.getData(), r.intent.getType());
2366 // And we are resetting to find the next component...
2367 intent.setComponent(null);
2368
2369 ActivityInfo aInfo = null;
2370 try {
2371 List<ResolveInfo> resolves =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002372 AppGlobals.getPackageManager().queryIntentActivities(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002373 intent, r.resolvedType,
Dianne Hackborn1655be42009-05-08 14:29:01 -07002374 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002375
2376 // Look for the original activity in the list...
2377 final int N = resolves != null ? resolves.size() : 0;
2378 for (int i=0; i<N; i++) {
2379 ResolveInfo rInfo = resolves.get(i);
2380 if (rInfo.activityInfo.packageName.equals(r.packageName)
2381 && rInfo.activityInfo.name.equals(r.info.name)) {
2382 // We found the current one... the next matching is
2383 // after it.
2384 i++;
2385 if (i<N) {
2386 aInfo = resolves.get(i).activityInfo;
2387 }
2388 break;
2389 }
2390 }
2391 } catch (RemoteException e) {
2392 }
2393
2394 if (aInfo == null) {
2395 // Nobody who is next!
2396 return false;
2397 }
2398
2399 intent.setComponent(new ComponentName(
2400 aInfo.applicationInfo.packageName, aInfo.name));
2401 intent.setFlags(intent.getFlags()&~(
2402 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
2403 Intent.FLAG_ACTIVITY_CLEAR_TOP|
2404 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
2405 Intent.FLAG_ACTIVITY_NEW_TASK));
2406
2407 // Okay now we need to start the new activity, replacing the
2408 // currently running activity. This is a little tricky because
2409 // we want to start the new one as if the current one is finished,
2410 // but not finish the current one first so that there is no flicker.
2411 // And thus...
2412 final boolean wasFinishing = r.finishing;
2413 r.finishing = true;
2414
2415 // Propagate reply information over to the new activity.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002416 final ActivityRecord resultTo = r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002417 final String resultWho = r.resultWho;
2418 final int requestCode = r.requestCode;
2419 r.resultTo = null;
2420 if (resultTo != null) {
2421 resultTo.removeResultsLocked(r, resultWho, requestCode);
2422 }
2423
2424 final long origId = Binder.clearCallingIdentity();
2425 // XXX we are not dealing with propagating grantedUriPermissions...
2426 // those are not yet exposed to user code, so there is no need.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002427 int res = mMainStack.startActivityLocked(r.app.thread, intent,
Dianne Hackbornbe707852011-11-11 14:32:10 -08002428 r.resolvedType, null, 0, aInfo,
2429 resultTo != null ? resultTo.appToken : null, resultWho,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002430 requestCode, -1, r.launchedFromUid, false, false, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002431 Binder.restoreCallingIdentity(origId);
2432
2433 r.finishing = wasFinishing;
2434 if (res != START_SUCCESS) {
2435 return false;
2436 }
2437 return true;
2438 }
2439 }
2440
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002441 public final int startActivityInPackage(int uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002442 Intent intent, String resolvedType, IBinder resultTo,
2443 String resultWho, int requestCode, boolean onlyIfNeeded) {
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002444
2445 // This is so super not safe, that only the system (or okay root)
2446 // can do it.
Amith Yamasani742a6712011-05-04 14:49:28 -07002447 int userId = Binder.getOrigCallingUser();
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002448 final int callingUid = Binder.getCallingUid();
2449 if (callingUid != 0 && callingUid != Process.myUid()) {
2450 throw new SecurityException(
2451 "startActivityInPackage only available to the system");
2452 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002453
Amith Yamasani742a6712011-05-04 14:49:28 -07002454 int ret = mMainStack.startActivityMayWait(null, uid, intent, resolvedType,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002455 null, 0, resultTo, resultWho, requestCode, onlyIfNeeded, false,
Amith Yamasani742a6712011-05-04 14:49:28 -07002456 null, null, false, null, null, userId);
2457 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002458 }
2459
2460 public final int startActivities(IApplicationThread caller,
2461 Intent[] intents, String[] resolvedTypes, IBinder resultTo) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002462 enforceNotIsolatedCaller("startActivities");
Amith Yamasani742a6712011-05-04 14:49:28 -07002463 int ret = mMainStack.startActivities(caller, -1, intents, resolvedTypes, resultTo,
2464 Binder.getOrigCallingUser());
2465 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002466 }
2467
2468 public final int startActivitiesInPackage(int uid,
2469 Intent[] intents, String[] resolvedTypes, IBinder resultTo) {
2470
2471 // This is so super not safe, that only the system (or okay root)
2472 // can do it.
2473 final int callingUid = Binder.getCallingUid();
2474 if (callingUid != 0 && callingUid != Process.myUid()) {
2475 throw new SecurityException(
2476 "startActivityInPackage only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002477 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002478 int ret = mMainStack.startActivities(null, uid, intents, resolvedTypes, resultTo,
2479 UserId.getUserId(uid));
2480 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002481 }
2482
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002483 final void addRecentTaskLocked(TaskRecord task) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002484 int N = mRecentTasks.size();
Dianne Hackborn7c0e75e2010-12-21 19:15:40 -08002485 // Quick case: check if the top-most recent task is the same.
2486 if (N > 0 && mRecentTasks.get(0) == task) {
2487 return;
2488 }
2489 // Remove any existing entries that are the same kind of task.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002490 for (int i=0; i<N; i++) {
2491 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07002492 if (task.userId == tr.userId
2493 && ((task.affinity != null && task.affinity.equals(tr.affinity))
2494 || (task.intent != null && task.intent.filterEquals(tr.intent)))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002495 mRecentTasks.remove(i);
2496 i--;
2497 N--;
2498 if (task.intent == null) {
2499 // If the new recent task we are adding is not fully
2500 // specified, then replace it with the existing recent task.
2501 task = tr;
2502 }
2503 }
2504 }
2505 if (N >= MAX_RECENT_TASKS) {
2506 mRecentTasks.remove(N-1);
2507 }
2508 mRecentTasks.add(0, task);
2509 }
2510
2511 public void setRequestedOrientation(IBinder token,
2512 int requestedOrientation) {
2513 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002514 ActivityRecord r = mMainStack.isInStackLocked(token);
2515 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002516 return;
2517 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002518 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornbe707852011-11-11 14:32:10 -08002519 mWindowManager.setAppOrientation(r.appToken, requestedOrientation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002520 Configuration config = mWindowManager.updateOrientationFromAppTokens(
The Android Open Source Project10592532009-03-18 17:39:46 -07002521 mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -08002522 r.mayFreezeScreenLocked(r.app) ? r.appToken : null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002523 if (config != null) {
2524 r.frozenBeforeDestroy = true;
Dianne Hackborn813075a62011-11-14 17:45:19 -08002525 if (!updateConfigurationLocked(config, r, false, false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002526 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002527 }
2528 }
2529 Binder.restoreCallingIdentity(origId);
2530 }
2531 }
2532
2533 public int getRequestedOrientation(IBinder token) {
2534 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002535 ActivityRecord r = mMainStack.isInStackLocked(token);
2536 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002537 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
2538 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08002539 return mWindowManager.getAppOrientation(r.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002540 }
2541 }
2542
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002543 /**
2544 * This is the internal entry point for handling Activity.finish().
2545 *
2546 * @param token The Binder token referencing the Activity we want to finish.
2547 * @param resultCode Result code, if any, from this Activity.
2548 * @param resultData Result data (Intent), if any, from this Activity.
2549 *
Alexey Tarasov83bad3d2009-08-12 15:05:43 +11002550 * @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 -08002551 */
2552 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData) {
2553 // Refuse possible leaked file descriptors
2554 if (resultData != null && resultData.hasFileDescriptors() == true) {
2555 throw new IllegalArgumentException("File descriptors passed in Intent");
2556 }
2557
2558 synchronized(this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002559 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002560 // Find the first activity that is not finishing.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002561 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002562 if (next != null) {
2563 // ask watcher if this is allowed
2564 boolean resumeOK = true;
2565 try {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002566 resumeOK = mController.activityResuming(next.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002567 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002568 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002569 }
2570
2571 if (!resumeOK) {
2572 return false;
2573 }
2574 }
2575 }
2576 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002577 boolean res = mMainStack.requestFinishActivityLocked(token, resultCode,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002578 resultData, "app-request");
2579 Binder.restoreCallingIdentity(origId);
2580 return res;
2581 }
2582 }
2583
Dianne Hackborn860755f2010-06-03 18:47:52 -07002584 public final void finishHeavyWeightApp() {
2585 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2586 != PackageManager.PERMISSION_GRANTED) {
2587 String msg = "Permission Denial: finishHeavyWeightApp() from pid="
2588 + Binder.getCallingPid()
2589 + ", uid=" + Binder.getCallingUid()
2590 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2591 Slog.w(TAG, msg);
2592 throw new SecurityException(msg);
2593 }
2594
2595 synchronized(this) {
2596 if (mHeavyWeightProcess == null) {
2597 return;
2598 }
2599
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002600 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>(
Dianne Hackborn860755f2010-06-03 18:47:52 -07002601 mHeavyWeightProcess.activities);
2602 for (int i=0; i<activities.size(); i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002603 ActivityRecord r = activities.get(i);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002604 if (!r.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002605 int index = mMainStack.indexOfTokenLocked(r.appToken);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002606 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002607 mMainStack.finishActivityLocked(r, index, Activity.RESULT_CANCELED,
Dianne Hackborn860755f2010-06-03 18:47:52 -07002608 null, "finish-heavy");
2609 }
2610 }
2611 }
2612
2613 mHeavyWeightProcess = null;
2614 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
2615 }
2616 }
2617
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002618 public void crashApplication(int uid, int initialPid, String packageName,
2619 String message) {
2620 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2621 != PackageManager.PERMISSION_GRANTED) {
2622 String msg = "Permission Denial: crashApplication() from pid="
2623 + Binder.getCallingPid()
2624 + ", uid=" + Binder.getCallingUid()
2625 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2626 Slog.w(TAG, msg);
2627 throw new SecurityException(msg);
2628 }
2629
2630 synchronized(this) {
2631 ProcessRecord proc = null;
2632
2633 // Figure out which process to kill. We don't trust that initialPid
2634 // still has any relation to current pids, so must scan through the
2635 // list.
2636 synchronized (mPidsSelfLocked) {
2637 for (int i=0; i<mPidsSelfLocked.size(); i++) {
2638 ProcessRecord p = mPidsSelfLocked.valueAt(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002639 if (p.uid != uid) {
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002640 continue;
2641 }
2642 if (p.pid == initialPid) {
2643 proc = p;
2644 break;
2645 }
2646 for (String str : p.pkgList) {
2647 if (str.equals(packageName)) {
2648 proc = p;
2649 }
2650 }
2651 }
2652 }
2653
2654 if (proc == null) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07002655 Slog.w(TAG, "crashApplication: nothing for uid=" + uid
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002656 + " initialPid=" + initialPid
2657 + " packageName=" + packageName);
2658 return;
2659 }
2660
2661 if (proc.thread != null) {
Dianne Hackborn9f531192010-08-04 17:48:03 -07002662 if (proc.pid == Process.myPid()) {
2663 Log.w(TAG, "crashApplication: trying to crash self!");
2664 return;
2665 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002666 long ident = Binder.clearCallingIdentity();
2667 try {
2668 proc.thread.scheduleCrash(message);
2669 } catch (RemoteException e) {
2670 }
2671 Binder.restoreCallingIdentity(ident);
2672 }
2673 }
2674 }
2675
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002676 public final void finishSubActivity(IBinder token, String resultWho,
2677 int requestCode) {
2678 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002679 ActivityRecord self = mMainStack.isInStackLocked(token);
2680 if (self == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002681 return;
2682 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002683
2684 final long origId = Binder.clearCallingIdentity();
2685
2686 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002687 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2688 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002689 if (r.resultTo == self && r.requestCode == requestCode) {
2690 if ((r.resultWho == null && resultWho == null) ||
2691 (r.resultWho != null && r.resultWho.equals(resultWho))) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002692 mMainStack.finishActivityLocked(r, i,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002693 Activity.RESULT_CANCELED, null, "request-sub");
2694 }
2695 }
2696 }
2697
2698 Binder.restoreCallingIdentity(origId);
2699 }
2700 }
2701
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002702 public boolean willActivityBeVisible(IBinder token) {
2703 synchronized(this) {
2704 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002705 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2706 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08002707 if (r.appToken == token) {
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002708 return true;
2709 }
2710 if (r.fullscreen && !r.finishing) {
2711 return false;
2712 }
2713 }
2714 return true;
2715 }
2716 }
2717
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002718 public void overridePendingTransition(IBinder token, String packageName,
2719 int enterAnim, int exitAnim) {
2720 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002721 ActivityRecord self = mMainStack.isInStackLocked(token);
2722 if (self == null) {
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002723 return;
2724 }
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002725
2726 final long origId = Binder.clearCallingIdentity();
2727
2728 if (self.state == ActivityState.RESUMED
2729 || self.state == ActivityState.PAUSING) {
2730 mWindowManager.overridePendingAppTransition(packageName,
2731 enterAnim, exitAnim);
2732 }
2733
2734 Binder.restoreCallingIdentity(origId);
2735 }
2736 }
2737
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002738 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002739 * Main function for removing an existing process from the activity manager
2740 * as a result of that process going away. Clears out all connections
2741 * to the process.
2742 */
2743 private final void handleAppDiedLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002744 boolean restarting, boolean allowRestart) {
2745 cleanUpApplicationRecordLocked(app, restarting, allowRestart, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002746 if (!restarting) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002747 mLruProcesses.remove(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002748 }
2749
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002750 if (mProfileProc == app) {
2751 clearProfilerLocked();
2752 }
2753
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002754 // Just in case...
Dianne Hackborncbb722e2012-02-07 18:33:49 -08002755 mMainStack.appDiedLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002756
2757 // Remove this application's activities from active lists.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002758 mMainStack.removeHistoryRecordsForAppLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002759
2760 boolean atTop = true;
2761 boolean hasVisibleActivities = false;
2762
2763 // Clean out the history list.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002764 int i = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08002765 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002766 TAG, "Removing app " + app + " from history with " + i + " entries");
2767 while (i > 0) {
2768 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002769 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002770 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002771 TAG, "Record #" + i + " " + r + ": app=" + r.app);
2772 if (r.app == app) {
2773 if ((!r.haveState && !r.stateNotNeeded) || r.finishing) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002774 if (ActivityStack.DEBUG_ADD_REMOVE) {
2775 RuntimeException here = new RuntimeException("here");
2776 here.fillInStackTrace();
2777 Slog.i(TAG, "Removing activity " + r + " from stack at " + i
2778 + ": haveState=" + r.haveState
2779 + " stateNotNeeded=" + r.stateNotNeeded
2780 + " finishing=" + r.finishing
2781 + " state=" + r.state, here);
2782 }
2783 if (!r.finishing) {
2784 Slog.w(TAG, "Force removing " + r + ": app died, no saved state");
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -08002785 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
2786 System.identityHashCode(r),
2787 r.task.taskId, r.shortComponentName,
2788 "proc died without state saved");
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002789 }
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08002790 r.makeFinishing();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002791 mMainStack.mHistory.remove(i);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002792 r.takeFromHistory();
Dianne Hackbornbe707852011-11-11 14:32:10 -08002793 mWindowManager.removeAppToken(r.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002794 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002795 mMainStack.validateAppTokensLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002796 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002797 r.removeUriPermissionsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002798
2799 } else {
2800 // We have the current state for this activity, so
2801 // it can be restarted later when needed.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002802 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002803 TAG, "Keeping entry, setting app to null");
2804 if (r.visible) {
2805 hasVisibleActivities = true;
2806 }
2807 r.app = null;
2808 r.nowVisible = false;
2809 if (!r.haveState) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002810 if (ActivityStack.DEBUG_SAVED_STATE) Slog.i(TAG,
2811 "App died, clearing saved state of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002812 r.icicle = null;
2813 }
2814 }
2815
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002816 r.stack.cleanUpActivityLocked(r, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002817 }
2818 atTop = false;
2819 }
2820
2821 app.activities.clear();
2822
2823 if (app.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002824 Slog.w(TAG, "Crash of app " + app.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002825 + " running instrumentation " + app.instrumentationClass);
2826 Bundle info = new Bundle();
2827 info.putString("shortMsg", "Process crashed.");
2828 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
2829 }
2830
2831 if (!restarting) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002832 if (!mMainStack.resumeTopActivityLocked(null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002833 // If there was nothing to resume, and we are not already
2834 // restarting this process, but there is a visible activity that
2835 // is hosted by the process... then make sure all visible
2836 // activities are running, taking care of restarting this
2837 // process.
2838 if (hasVisibleActivities) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002839 mMainStack.ensureActivitiesVisibleLocked(null, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002840 }
2841 }
2842 }
2843 }
2844
2845 private final int getLRURecordIndexForAppLocked(IApplicationThread thread) {
2846 IBinder threadBinder = thread.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002847 // Find the application record.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002848 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2849 ProcessRecord rec = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002850 if (rec.thread != null && rec.thread.asBinder() == threadBinder) {
2851 return i;
2852 }
2853 }
2854 return -1;
2855 }
2856
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002857 final ProcessRecord getRecordForAppLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002858 IApplicationThread thread) {
2859 if (thread == null) {
2860 return null;
2861 }
2862
2863 int appIndex = getLRURecordIndexForAppLocked(thread);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002864 return appIndex >= 0 ? mLruProcesses.get(appIndex) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002865 }
2866
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002867 final void appDiedLocked(ProcessRecord app, int pid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002868 IApplicationThread thread) {
2869
2870 mProcDeaths[0]++;
2871
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002872 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
2873 synchronized (stats) {
2874 stats.noteProcessDiedLocked(app.info.uid, pid);
2875 }
2876
Magnus Edlund7bb25812010-02-24 15:45:06 +01002877 // Clean up already done if the process has been re-started.
2878 if (app.pid == pid && app.thread != null &&
2879 app.thread.asBinder() == thread.asBinder()) {
Dianne Hackborn906497c2010-05-10 15:57:38 -07002880 if (!app.killedBackground) {
2881 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
2882 + ") has died.");
2883 }
Doug Zongker2bec3d42009-12-04 12:52:44 -08002884 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002885 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002886 TAG, "Dying app: " + app + ", pid: " + pid
2887 + ", thread: " + thread.asBinder());
2888 boolean doLowMem = app.instrumentationClass == null;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002889 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002890
2891 if (doLowMem) {
2892 // If there are no longer any background processes running,
2893 // and the app that died was not running instrumentation,
2894 // then tell everyone we are now low on memory.
2895 boolean haveBg = false;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002896 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2897 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -07002898 if (rec.thread != null && rec.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002899 haveBg = true;
2900 break;
2901 }
2902 }
2903
2904 if (!haveBg) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002905 EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mLruProcesses.size());
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002906 long now = SystemClock.uptimeMillis();
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002907 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2908 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn36124872009-10-08 16:22:03 -07002909 if (rec != app && rec.thread != null &&
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002910 (rec.lastLowMemory+GC_MIN_INTERVAL) <= now) {
2911 // The low memory report is overriding any current
2912 // state for a GC request. Make sure to do
Dianne Hackborn32907cf2010-06-10 17:50:20 -07002913 // heavy/important/visible/foreground processes first.
Dianne Hackborn7d608422011-08-07 16:24:18 -07002914 if (rec.setAdj <= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002915 rec.lastRequestedGc = 0;
2916 } else {
2917 rec.lastRequestedGc = rec.lastLowMemory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002918 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002919 rec.reportLowMemory = true;
2920 rec.lastLowMemory = now;
2921 mProcessesToGc.remove(rec);
2922 addProcessToGcListLocked(rec);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002923 }
2924 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07002925 mHandler.sendEmptyMessage(REPORT_MEM_USAGE);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002926 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002927 }
2928 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01002929 } else if (app.pid != pid) {
2930 // A new process has already been started.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002931 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
Magnus Edlund7bb25812010-02-24 15:45:06 +01002932 + ") has died and restarted (pid " + app.pid + ").");
Dianne Hackborn28a8c2b2010-03-01 11:30:02 -08002933 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08002934 } else if (DEBUG_PROCESSES) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002935 Slog.d(TAG, "Received spurious death notification for thread "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002936 + thread.asBinder());
2937 }
2938 }
2939
Dan Egnor42471dd2010-01-07 17:25:22 -08002940 /**
2941 * If a stack trace dump file is configured, dump process stack traces.
Christopher Tate6ee412d2010-05-28 12:01:56 -07002942 * @param clearTraces causes the dump file to be erased prior to the new
2943 * traces being written, if true; when false, the new traces will be
2944 * appended to any existing file content.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002945 * @param firstPids of dalvik VM processes to dump stack traces for first
2946 * @param lastPids of dalvik VM processes to dump stack traces for last
Dan Egnor42471dd2010-01-07 17:25:22 -08002947 * @return file containing stack traces, or null if no dump file is configured
2948 */
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002949 public static File dumpStackTraces(boolean clearTraces, ArrayList<Integer> firstPids,
2950 ProcessStats processStats, SparseArray<Boolean> lastPids) {
Dan Egnor42471dd2010-01-07 17:25:22 -08002951 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
2952 if (tracesPath == null || tracesPath.length() == 0) {
2953 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002954 }
Dan Egnor42471dd2010-01-07 17:25:22 -08002955
2956 File tracesFile = new File(tracesPath);
2957 try {
2958 File tracesDir = tracesFile.getParentFile();
2959 if (!tracesDir.exists()) tracesFile.mkdirs();
2960 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
2961
Christopher Tate6ee412d2010-05-28 12:01:56 -07002962 if (clearTraces && tracesFile.exists()) tracesFile.delete();
Dan Egnor42471dd2010-01-07 17:25:22 -08002963 tracesFile.createNewFile();
2964 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
2965 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002966 Slog.w(TAG, "Unable to prepare ANR traces file: " + tracesPath, e);
Dan Egnor42471dd2010-01-07 17:25:22 -08002967 return null;
2968 }
2969
2970 // Use a FileObserver to detect when traces finish writing.
2971 // The order of traces is considered important to maintain for legibility.
2972 FileObserver observer = new FileObserver(tracesPath, FileObserver.CLOSE_WRITE) {
2973 public synchronized void onEvent(int event, String path) { notify(); }
2974 };
2975
2976 try {
2977 observer.startWatching();
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002978
2979 // First collect all of the stacks of the most important pids.
2980 try {
2981 int num = firstPids.size();
2982 for (int i = 0; i < num; i++) {
2983 synchronized (observer) {
2984 Process.sendSignal(firstPids.get(i), Process.SIGNAL_QUIT);
2985 observer.wait(200); // Wait for write-close, give up after 200msec
2986 }
2987 }
2988 } catch (InterruptedException e) {
2989 Log.wtf(TAG, e);
2990 }
2991
2992 // Next measure CPU usage.
2993 if (processStats != null) {
2994 processStats.init();
2995 System.gc();
2996 processStats.update();
2997 try {
2998 synchronized (processStats) {
2999 processStats.wait(500); // measure over 1/2 second.
3000 }
3001 } catch (InterruptedException e) {
3002 }
3003 processStats.update();
3004
3005 // We'll take the stack crawls of just the top apps using CPU.
3006 final int N = processStats.countWorkingStats();
3007 int numProcs = 0;
3008 for (int i=0; i<N && numProcs<5; i++) {
3009 ProcessStats.Stats stats = processStats.getWorkingStats(i);
3010 if (lastPids.indexOfKey(stats.pid) >= 0) {
3011 numProcs++;
3012 try {
3013 synchronized (observer) {
3014 Process.sendSignal(stats.pid, Process.SIGNAL_QUIT);
3015 observer.wait(200); // Wait for write-close, give up after 200msec
3016 }
3017 } catch (InterruptedException e) {
3018 Log.wtf(TAG, e);
3019 }
3020
3021 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003022 }
3023 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003024
3025 return tracesFile;
3026
Dan Egnor42471dd2010-01-07 17:25:22 -08003027 } finally {
3028 observer.stopWatching();
3029 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003030 }
3031
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003032 final void appNotResponding(ProcessRecord app, ActivityRecord activity,
3033 ActivityRecord parent, final String annotation) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003034 ArrayList<Integer> firstPids = new ArrayList<Integer>(5);
3035 SparseArray<Boolean> lastPids = new SparseArray<Boolean>(20);
3036
Dianne Hackborn287952c2010-09-22 22:34:31 -07003037 if (mController != null) {
3038 try {
3039 // 0 == continue, -1 = kill process immediately
3040 int res = mController.appEarlyNotResponding(app.processName, app.pid, annotation);
3041 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3042 } catch (RemoteException e) {
3043 mController = null;
3044 }
3045 }
3046
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003047 long anrTime = SystemClock.uptimeMillis();
3048 if (MONITOR_CPU_USAGE) {
3049 updateCpuStatsNow();
3050 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003051
3052 synchronized (this) {
3053 // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down.
3054 if (mShuttingDown) {
3055 Slog.i(TAG, "During shutdown skipping ANR: " + app + " " + annotation);
3056 return;
3057 } else if (app.notResponding) {
3058 Slog.i(TAG, "Skipping duplicate ANR: " + app + " " + annotation);
3059 return;
3060 } else if (app.crashing) {
3061 Slog.i(TAG, "Crashing app skipping ANR: " + app + " " + annotation);
3062 return;
3063 }
3064
3065 // In case we come through here for the same app before completing
3066 // this one, mark as anring now so we will bail out.
3067 app.notResponding = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08003068
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003069 // Log the ANR to the event log.
3070 EventLog.writeEvent(EventLogTags.AM_ANR, app.pid, app.processName, app.info.flags,
3071 annotation);
Dan Egnor42471dd2010-01-07 17:25:22 -08003072
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003073 // Dump thread traces as quickly as we can, starting with "interesting" processes.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003074 firstPids.add(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003075
3076 int parentPid = app.pid;
3077 if (parent != null && parent.app != null && parent.app.pid > 0) parentPid = parent.app.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003078 if (parentPid != app.pid) firstPids.add(parentPid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003079
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003080 if (MY_PID != app.pid && MY_PID != parentPid) firstPids.add(MY_PID);
Dan Egnor42471dd2010-01-07 17:25:22 -08003081
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003082 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
3083 ProcessRecord r = mLruProcesses.get(i);
3084 if (r != null && r.thread != null) {
3085 int pid = r.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003086 if (pid > 0 && pid != app.pid && pid != parentPid && pid != MY_PID) {
3087 if (r.persistent) {
3088 firstPids.add(pid);
3089 } else {
3090 lastPids.put(pid, Boolean.TRUE);
3091 }
3092 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003093 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003094 }
3095 }
3096
Dan Egnor42471dd2010-01-07 17:25:22 -08003097 // Log the ANR to the main log.
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07003098 StringBuilder info = mStringBuilder;
3099 info.setLength(0);
Dan Egnor42471dd2010-01-07 17:25:22 -08003100 info.append("ANR in ").append(app.processName);
3101 if (activity != null && activity.shortComponentName != null) {
3102 info.append(" (").append(activity.shortComponentName).append(")");
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07003103 }
Eric Rowe6f4f6192010-02-17 18:29:04 -08003104 info.append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003105 if (annotation != null) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003106 info.append("Reason: ").append(annotation).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003107 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003108 if (parent != null && parent != activity) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003109 info.append("Parent: ").append(parent.shortComponentName).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003110 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003111
Dianne Hackborn287952c2010-09-22 22:34:31 -07003112 final ProcessStats processStats = new ProcessStats(true);
3113
3114 File tracesFile = dumpStackTraces(true, firstPids, processStats, lastPids);
3115
Dan Egnor42471dd2010-01-07 17:25:22 -08003116 String cpuInfo = null;
3117 if (MONITOR_CPU_USAGE) {
3118 updateCpuStatsNow();
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003119 synchronized (mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003120 cpuInfo = mProcessStats.printCurrentState(anrTime);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003121 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003122 info.append(processStats.printCurrentLoad());
Dan Egnor42471dd2010-01-07 17:25:22 -08003123 info.append(cpuInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003124 }
3125
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003126 info.append(processStats.printCurrentState(anrTime));
3127
Joe Onorato8a9b2202010-02-26 18:56:32 -08003128 Slog.e(TAG, info.toString());
Dan Egnor42471dd2010-01-07 17:25:22 -08003129 if (tracesFile == null) {
3130 // There is no trace file, so dump (only) the alleged culprit's threads to the log
3131 Process.sendSignal(app.pid, Process.SIGNAL_QUIT);
3132 }
3133
Jeff Sharkeya353d262011-10-28 11:12:06 -07003134 addErrorToDropBox("anr", app, app.processName, activity, parent, annotation,
3135 cpuInfo, tracesFile, null);
Dan Egnor42471dd2010-01-07 17:25:22 -08003136
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003137 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003138 try {
Dan Egnor42471dd2010-01-07 17:25:22 -08003139 // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately
3140 int res = mController.appNotResponding(app.processName, app.pid, info.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003141 if (res != 0) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003142 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3143 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003144 }
3145 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003146 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003147 }
3148 }
3149
Dan Egnor42471dd2010-01-07 17:25:22 -08003150 // Unless configured otherwise, swallow ANRs in background processes & kill the process.
3151 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
3152 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003153
3154 synchronized (this) {
3155 if (!showBackground && !app.isInterestingToUserLocked() && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003156 Slog.w(TAG, "Killing " + app + ": background ANR");
3157 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
3158 app.processName, app.setAdj, "background ANR");
3159 Process.killProcessQuiet(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003160 return;
3161 }
3162
3163 // Set the app's notResponding state, and look up the errorReportReceiver
3164 makeAppNotRespondingLocked(app,
3165 activity != null ? activity.shortComponentName : null,
3166 annotation != null ? "ANR " + annotation : "ANR",
3167 info.toString());
3168
3169 // Bring up the infamous App Not Responding dialog
3170 Message msg = Message.obtain();
3171 HashMap map = new HashMap();
3172 msg.what = SHOW_NOT_RESPONDING_MSG;
3173 msg.obj = map;
3174 map.put("app", app);
3175 if (activity != null) {
3176 map.put("activity", activity);
3177 }
3178
3179 mHandler.sendMessage(msg);
Dan Egnor42471dd2010-01-07 17:25:22 -08003180 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003181 }
3182
Dianne Hackborn0dad3642010-09-09 21:25:35 -07003183 final void showLaunchWarningLocked(final ActivityRecord cur, final ActivityRecord next) {
3184 if (!mLaunchWarningShown) {
3185 mLaunchWarningShown = true;
3186 mHandler.post(new Runnable() {
3187 @Override
3188 public void run() {
3189 synchronized (ActivityManagerService.this) {
3190 final Dialog d = new LaunchWarningWindow(mContext, cur, next);
3191 d.show();
3192 mHandler.postDelayed(new Runnable() {
3193 @Override
3194 public void run() {
3195 synchronized (ActivityManagerService.this) {
3196 d.dismiss();
3197 mLaunchWarningShown = false;
3198 }
3199 }
3200 }, 4000);
3201 }
3202 }
3203 });
3204 }
3205 }
3206
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003207 public boolean clearApplicationUserData(final String packageName,
Amith Yamasani742a6712011-05-04 14:49:28 -07003208 final IPackageDataObserver observer, final int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003209 enforceNotIsolatedCaller("clearApplicationUserData");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003210 int uid = Binder.getCallingUid();
3211 int pid = Binder.getCallingPid();
3212 long callingId = Binder.clearCallingIdentity();
3213 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003214 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003215 int pkgUid = -1;
3216 synchronized(this) {
3217 try {
3218 pkgUid = pm.getPackageUid(packageName);
3219 } catch (RemoteException e) {
3220 }
3221 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003222 Slog.w(TAG, "Invalid packageName:" + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003223 return false;
3224 }
3225 if (uid == pkgUid || checkComponentPermission(
3226 android.Manifest.permission.CLEAR_APP_USER_DATA,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08003227 pid, uid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003228 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003229 forceStopPackageLocked(packageName, pkgUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003230 } else {
3231 throw new SecurityException(pid+" does not have permission:"+
3232 android.Manifest.permission.CLEAR_APP_USER_DATA+" to clear data" +
3233 "for process:"+packageName);
3234 }
3235 }
3236
3237 try {
3238 //clear application user data
3239 pm.clearApplicationUserData(packageName, observer);
3240 Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED,
3241 Uri.fromParts("package", packageName, null));
3242 intent.putExtra(Intent.EXTRA_UID, pkgUid);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003243 broadcastIntentInPackage("android", Process.SYSTEM_UID, intent,
Amith Yamasani742a6712011-05-04 14:49:28 -07003244 null, null, 0, null, null, null, false, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003245 } catch (RemoteException e) {
3246 }
3247 } finally {
3248 Binder.restoreCallingIdentity(callingId);
3249 }
3250 return true;
3251 }
3252
Dianne Hackborn03abb812010-01-04 18:43:19 -08003253 public void killBackgroundProcesses(final String packageName) {
3254 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3255 != PackageManager.PERMISSION_GRANTED &&
3256 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES)
3257 != PackageManager.PERMISSION_GRANTED) {
3258 String msg = "Permission Denial: killBackgroundProcesses() from pid="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003259 + Binder.getCallingPid()
3260 + ", uid=" + Binder.getCallingUid()
Dianne Hackborn03abb812010-01-04 18:43:19 -08003261 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003262 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003263 throw new SecurityException(msg);
3264 }
3265
3266 long callingId = Binder.clearCallingIdentity();
3267 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003268 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003269 int pkgUid = -1;
3270 synchronized(this) {
3271 try {
3272 pkgUid = pm.getPackageUid(packageName);
3273 } catch (RemoteException e) {
3274 }
3275 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003276 Slog.w(TAG, "Invalid packageName: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003277 return;
3278 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003279 killPackageProcessesLocked(packageName, pkgUid,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003280 ProcessList.SERVICE_ADJ, false, true, true, false, "kill background");
3281 }
3282 } finally {
3283 Binder.restoreCallingIdentity(callingId);
3284 }
3285 }
3286
3287 public void killAllBackgroundProcesses() {
3288 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3289 != PackageManager.PERMISSION_GRANTED) {
3290 String msg = "Permission Denial: killAllBackgroundProcesses() from pid="
3291 + Binder.getCallingPid()
3292 + ", uid=" + Binder.getCallingUid()
3293 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
3294 Slog.w(TAG, msg);
3295 throw new SecurityException(msg);
3296 }
3297
3298 long callingId = Binder.clearCallingIdentity();
3299 try {
3300 synchronized(this) {
3301 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
3302 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3303 final int NA = apps.size();
3304 for (int ia=0; ia<NA; ia++) {
3305 ProcessRecord app = apps.valueAt(ia);
3306 if (app.persistent) {
3307 // we don't kill persistent processes
3308 continue;
3309 }
3310 if (app.removed) {
3311 procs.add(app);
3312 } else if (app.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
3313 app.removed = true;
3314 procs.add(app);
3315 }
3316 }
3317 }
3318
3319 int N = procs.size();
3320 for (int i=0; i<N; i++) {
3321 removeProcessLocked(procs.get(i), false, true, "kill all background");
3322 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003323 }
3324 } finally {
3325 Binder.restoreCallingIdentity(callingId);
3326 }
3327 }
3328
3329 public void forceStopPackage(final String packageName) {
3330 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3331 != PackageManager.PERMISSION_GRANTED) {
3332 String msg = "Permission Denial: forceStopPackage() from pid="
3333 + Binder.getCallingPid()
3334 + ", uid=" + Binder.getCallingUid()
3335 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003336 Slog.w(TAG, msg);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003337 throw new SecurityException(msg);
3338 }
Amith Yamasani742a6712011-05-04 14:49:28 -07003339 final int userId = Binder.getOrigCallingUser();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003340 long callingId = Binder.clearCallingIdentity();
3341 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003342 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003343 int pkgUid = -1;
3344 synchronized(this) {
3345 try {
3346 pkgUid = pm.getPackageUid(packageName);
Amith Yamasani742a6712011-05-04 14:49:28 -07003347 // Convert the uid to the one for the calling user
3348 pkgUid = UserId.getUid(userId, pkgUid);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003349 } catch (RemoteException e) {
3350 }
3351 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003352 Slog.w(TAG, "Invalid packageName: " + packageName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003353 return;
3354 }
3355 forceStopPackageLocked(packageName, pkgUid);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003356 try {
3357 pm.setPackageStoppedState(packageName, true);
3358 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08003359 } catch (IllegalArgumentException e) {
3360 Slog.w(TAG, "Failed trying to unstop package "
3361 + packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003362 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003363 }
3364 } finally {
3365 Binder.restoreCallingIdentity(callingId);
3366 }
3367 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003368
3369 /*
3370 * The pkg name and uid have to be specified.
3371 * @see android.app.IActivityManager#killApplicationWithUid(java.lang.String, int)
3372 */
3373 public void killApplicationWithUid(String pkg, int uid) {
3374 if (pkg == null) {
3375 return;
3376 }
3377 // Make sure the uid is valid.
3378 if (uid < 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003379 Slog.w(TAG, "Invalid uid specified for pkg : " + pkg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003380 return;
3381 }
3382 int callerUid = Binder.getCallingUid();
3383 // Only the system server can kill an application
3384 if (callerUid == Process.SYSTEM_UID) {
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07003385 // Post an aysnc message to kill the application
3386 Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG);
3387 msg.arg1 = uid;
3388 msg.arg2 = 0;
3389 msg.obj = pkg;
Suchi Amalapurapud50066f2009-08-18 16:57:41 -07003390 mHandler.sendMessage(msg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003391 } else {
3392 throw new SecurityException(callerUid + " cannot kill pkg: " +
3393 pkg);
3394 }
3395 }
3396
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003397 public void closeSystemDialogs(String reason) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003398 enforceNotIsolatedCaller("closeSystemDialogs");
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003399 Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003400 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003401 if (reason != null) {
3402 intent.putExtra("reason", reason);
3403 }
3404
3405 final int uid = Binder.getCallingUid();
3406 final long origId = Binder.clearCallingIdentity();
3407 synchronized (this) {
Dianne Hackbornffa42482009-09-23 22:20:11 -07003408 mWindowManager.closeSystemDialogs(reason);
3409
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08003410 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003411 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornffa42482009-09-23 22:20:11 -07003412 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003413 r.stack.finishActivityLocked(r, i,
Dianne Hackbornffa42482009-09-23 22:20:11 -07003414 Activity.RESULT_CANCELED, null, "close-sys");
3415 }
3416 }
3417
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003418 broadcastIntentLocked(null, null, intent, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07003419 null, 0, null, null, null, false, false, -1, uid, 0 /* TODO: Verify */);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003420 }
3421 Binder.restoreCallingIdentity(origId);
3422 }
3423
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003424 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids)
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003425 throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003426 enforceNotIsolatedCaller("getProcessMemoryInfo");
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003427 Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length];
3428 for (int i=pids.length-1; i>=0; i--) {
3429 infos[i] = new Debug.MemoryInfo();
3430 Debug.getMemoryInfo(pids[i], infos[i]);
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003431 }
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003432 return infos;
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003433 }
Christopher Tate5e1ab332009-09-01 20:32:49 -07003434
Dianne Hackbornb437e092011-08-05 17:50:29 -07003435 public long[] getProcessPss(int[] pids) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003436 enforceNotIsolatedCaller("getProcessPss");
Dianne Hackbornb437e092011-08-05 17:50:29 -07003437 long[] pss = new long[pids.length];
3438 for (int i=pids.length-1; i>=0; i--) {
3439 pss[i] = Debug.getPss(pids[i]);
3440 }
3441 return pss;
3442 }
3443
Christopher Tate5e1ab332009-09-01 20:32:49 -07003444 public void killApplicationProcess(String processName, int uid) {
3445 if (processName == null) {
3446 return;
3447 }
3448
3449 int callerUid = Binder.getCallingUid();
3450 // Only the system server can kill an application
3451 if (callerUid == Process.SYSTEM_UID) {
3452 synchronized (this) {
3453 ProcessRecord app = getProcessRecordLocked(processName, uid);
Christopher Tate4a627c72011-04-01 14:43:32 -07003454 if (app != null && app.thread != null) {
Christopher Tate5e1ab332009-09-01 20:32:49 -07003455 try {
3456 app.thread.scheduleSuicide();
3457 } catch (RemoteException e) {
3458 // If the other end already died, then our work here is done.
3459 }
3460 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003461 Slog.w(TAG, "Process/uid not found attempting kill of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07003462 + processName + " / " + uid);
3463 }
3464 }
3465 } else {
3466 throw new SecurityException(callerUid + " cannot kill app process: " +
3467 processName);
3468 }
3469 }
3470
Dianne Hackborn03abb812010-01-04 18:43:19 -08003471 private void forceStopPackageLocked(final String packageName, int uid) {
Christopher Tate3dacd842011-08-19 14:56:15 -07003472 forceStopPackageLocked(packageName, uid, false, false, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003473 Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED,
3474 Uri.fromParts("package", packageName, null));
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003475 if (!mProcessesReady) {
3476 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3477 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003478 intent.putExtra(Intent.EXTRA_UID, uid);
3479 broadcastIntentLocked(null, null, intent,
3480 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07003481 false, false,
3482 MY_PID, Process.SYSTEM_UID, UserId.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003483 }
3484
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003485 private final boolean killPackageProcessesLocked(String packageName, int uid,
Christopher Tate3dacd842011-08-19 14:56:15 -07003486 int minOomAdj, boolean callerWillRestart, boolean allowRestart, boolean doit,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003487 boolean evenPersistent, String reason) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003488 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003489
Dianne Hackborn03abb812010-01-04 18:43:19 -08003490 // Remove all processes this package may have touched: all with the
3491 // same UID (except for the system or root user), and all whose name
3492 // matches the package name.
3493 final String procNamePrefix = packageName + ":";
3494 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3495 final int NA = apps.size();
3496 for (int ia=0; ia<NA; ia++) {
3497 ProcessRecord app = apps.valueAt(ia);
Christopher Tate3dacd842011-08-19 14:56:15 -07003498 if (app.persistent && !evenPersistent) {
Christopher Tate064d8422011-07-26 15:38:07 -07003499 // we don't kill persistent processes
3500 continue;
3501 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003502 if (app.removed) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003503 if (doit) {
3504 procs.add(app);
3505 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003506 } else if ((uid > 0 && uid != Process.SYSTEM_UID && app.info.uid == uid)
3507 || app.processName.equals(packageName)
3508 || app.processName.startsWith(procNamePrefix)) {
3509 if (app.setAdj >= minOomAdj) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003510 if (!doit) {
3511 return true;
3512 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003513 app.removed = true;
3514 procs.add(app);
3515 }
3516 }
3517 }
3518 }
3519
3520 int N = procs.size();
3521 for (int i=0; i<N; i++) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003522 removeProcessLocked(procs.get(i), callerWillRestart, allowRestart, reason);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003523 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003524 return N > 0;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003525 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003526
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003527 private final boolean forceStopPackageLocked(String name, int uid,
Christopher Tate3dacd842011-08-19 14:56:15 -07003528 boolean callerWillRestart, boolean purgeCache, boolean doit,
3529 boolean evenPersistent) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003530 int i;
3531 int N;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003532
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003533 if (uid < 0) {
3534 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003535 uid = AppGlobals.getPackageManager().getPackageUid(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003536 } catch (RemoteException e) {
3537 }
3538 }
3539
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003540 if (doit) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003541 Slog.i(TAG, "Force stopping package " + name + " uid=" + uid);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003542
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003543 Iterator<SparseArray<Long>> badApps = mProcessCrashTimes.getMap().values().iterator();
3544 while (badApps.hasNext()) {
3545 SparseArray<Long> ba = badApps.next();
3546 if (ba.get(uid) != null) {
3547 badApps.remove();
3548 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003549 }
3550 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003551
3552 boolean didSomething = killPackageProcessesLocked(name, uid, -100,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003553 callerWillRestart, false, doit, evenPersistent, "force stop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003554
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003555 TaskRecord lastTask = null;
3556 for (i=0; i<mMainStack.mHistory.size(); i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003557 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003558 final boolean samePackage = r.packageName.equals(name);
3559 if ((samePackage || r.task == lastTask)
Christopher Tate3dacd842011-08-19 14:56:15 -07003560 && (r.app == null || evenPersistent || !r.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003561 if (!doit) {
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003562 if (r.finishing) {
3563 // If this activity is just finishing, then it is not
3564 // interesting as far as something to stop.
3565 continue;
3566 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003567 return true;
3568 }
3569 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003570 Slog.i(TAG, " Force finishing activity " + r);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003571 if (samePackage) {
3572 if (r.app != null) {
3573 r.app.removed = true;
3574 }
3575 r.app = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003576 }
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003577 lastTask = r.task;
3578 if (r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
3579 null, "force-stop")) {
3580 i--;
3581 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003582 }
3583 }
3584
3585 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
Amith Yamasani742a6712011-05-04 14:49:28 -07003586 int userId = UserId.getUserId(uid);
3587 for (ServiceRecord service : mServiceMap.getAllServices(userId)) {
Christopher Tate064d8422011-07-26 15:38:07 -07003588 if (service.packageName.equals(name)
Christopher Tate3dacd842011-08-19 14:56:15 -07003589 && (service.app == null || evenPersistent || !service.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003590 if (!doit) {
3591 return true;
3592 }
3593 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003594 Slog.i(TAG, " Force stopping service " + service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003595 if (service.app != null) {
3596 service.app.removed = true;
3597 }
3598 service.app = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003599 service.isolatedProc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003600 services.add(service);
3601 }
3602 }
3603
3604 N = services.size();
3605 for (i=0; i<N; i++) {
3606 bringDownServiceLocked(services.get(i), true);
3607 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003608
3609 ArrayList<ContentProviderRecord> providers = new ArrayList<ContentProviderRecord>();
Amith Yamasani37ce3a82012-02-06 12:04:42 -08003610 for (ContentProviderRecord provider : mProviderMap.getProvidersByClass(-1).values()) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003611 if (provider.info.packageName.equals(name)
3612 && (provider.proc == null || evenPersistent || !provider.proc.persistent)) {
3613 if (!doit) {
3614 return true;
3615 }
3616 didSomething = true;
3617 providers.add(provider);
3618 }
3619 }
3620
3621 N = providers.size();
3622 for (i=0; i<N; i++) {
3623 removeDyingProviderLocked(null, providers.get(i));
3624 }
3625
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003626 if (doit) {
3627 if (purgeCache) {
3628 AttributeCache ac = AttributeCache.instance();
3629 if (ac != null) {
3630 ac.removePackage(name);
3631 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003632 }
Dianne Hackborn38cc8962011-10-13 11:33:55 -07003633 if (mBooted) {
3634 mMainStack.resumeTopActivityLocked(null);
3635 mMainStack.scheduleIdleLocked();
3636 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003637 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003638
3639 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003640 }
3641
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003642 private final boolean removeProcessLocked(ProcessRecord app,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003643 boolean callerWillRestart, boolean allowRestart, String reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003644 final String name = app.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003645 final int uid = app.uid;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003646 if (DEBUG_PROCESSES) Slog.d(
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003647 TAG, "Force removing proc " + app.toShortString() + " (" + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003648 + "/" + uid + ")");
3649
3650 mProcessNames.remove(name, uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003651 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003652 if (mHeavyWeightProcess == app) {
3653 mHeavyWeightProcess = null;
3654 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3655 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003656 boolean needRestart = false;
3657 if (app.pid > 0 && app.pid != MY_PID) {
3658 int pid = app.pid;
3659 synchronized (mPidsSelfLocked) {
3660 mPidsSelfLocked.remove(pid);
3661 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3662 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003663 Slog.i(TAG, "Killing proc " + app.toShortString() + ": " + reason);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003664 handleAppDiedLocked(app, true, allowRestart);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003665 mLruProcesses.remove(app);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003666 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003667
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003668 if (app.persistent && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003669 if (!callerWillRestart) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003670 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003671 } else {
3672 needRestart = true;
3673 }
3674 }
3675 } else {
3676 mRemovedProcesses.add(app);
3677 }
3678
3679 return needRestart;
3680 }
3681
3682 private final void processStartTimedOutLocked(ProcessRecord app) {
3683 final int pid = app.pid;
3684 boolean gone = false;
3685 synchronized (mPidsSelfLocked) {
3686 ProcessRecord knownApp = mPidsSelfLocked.get(pid);
3687 if (knownApp != null && knownApp.thread == null) {
3688 mPidsSelfLocked.remove(pid);
3689 gone = true;
3690 }
3691 }
3692
3693 if (gone) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003694 Slog.w(TAG, "Process " + app + " failed to attach");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003695 EventLog.writeEvent(EventLogTags.AM_PROCESS_START_TIMEOUT, pid, app.uid,
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003696 app.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003697 mProcessNames.remove(app.processName, app.uid);
3698 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003699 if (mHeavyWeightProcess == app) {
3700 mHeavyWeightProcess = null;
3701 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3702 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003703 // Take care of any launching providers waiting for this process.
3704 checkAppInLaunchingProvidersLocked(app, true);
3705 // Take care of any services that are waiting for the process.
3706 for (int i=0; i<mPendingServices.size(); i++) {
3707 ServiceRecord sr = mPendingServices.get(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003708 if ((app.uid == sr.appInfo.uid
3709 && app.processName.equals(sr.processName))
3710 || sr.isolatedProc == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003711 Slog.w(TAG, "Forcing bringing down service: " + sr);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003712 sr.isolatedProc = null;
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003713 mPendingServices.remove(i);
3714 i--;
3715 bringDownServiceLocked(sr, true);
3716 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003717 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003718 EventLog.writeEvent(EventLogTags.AM_KILL, pid,
3719 app.processName, app.setAdj, "start timeout");
3720 Process.killProcessQuiet(pid);
Christopher Tate181fafa2009-05-14 11:12:14 -07003721 if (mBackupTarget != null && mBackupTarget.app.pid == pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003722 Slog.w(TAG, "Unattached app died before backup, skipping");
Christopher Tate181fafa2009-05-14 11:12:14 -07003723 try {
3724 IBackupManager bm = IBackupManager.Stub.asInterface(
3725 ServiceManager.getService(Context.BACKUP_SERVICE));
3726 bm.agentDisconnected(app.info.packageName);
3727 } catch (RemoteException e) {
3728 // Can't happen; the backup manager is local
3729 }
3730 }
Christopher Tatef46723b2012-01-26 14:19:24 -08003731 if (isPendingBroadcastProcessLocked(pid)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003732 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
Christopher Tatef46723b2012-01-26 14:19:24 -08003733 skipPendingBroadcastLocked(pid);
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003734 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003735 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003736 Slog.w(TAG, "Spurious process start timeout - pid not known for " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003737 }
3738 }
3739
3740 private final boolean attachApplicationLocked(IApplicationThread thread,
3741 int pid) {
3742
3743 // Find the application record that is being attached... either via
3744 // the pid if we are running in multiple processes, or just pull the
3745 // next app record if we are emulating process with anonymous threads.
3746 ProcessRecord app;
3747 if (pid != MY_PID && pid >= 0) {
3748 synchronized (mPidsSelfLocked) {
3749 app = mPidsSelfLocked.get(pid);
3750 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003751 } else {
3752 app = null;
3753 }
3754
3755 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003756 Slog.w(TAG, "No pending application record for pid " + pid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003757 + " (IApplicationThread " + thread + "); dropping process");
Doug Zongker2bec3d42009-12-04 12:52:44 -08003758 EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003759 if (pid > 0 && pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003760 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003761 } else {
3762 try {
3763 thread.scheduleExit();
3764 } catch (Exception e) {
3765 // Ignore exceptions.
3766 }
3767 }
3768 return false;
3769 }
3770
3771 // If this application record is still attached to a previous
3772 // process, clean it up now.
3773 if (app.thread != null) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003774 handleAppDiedLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003775 }
3776
3777 // Tell the process all about itself.
3778
Joe Onorato8a9b2202010-02-26 18:56:32 -08003779 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003780 TAG, "Binding process pid " + pid + " to record " + app);
3781
3782 String processName = app.processName;
3783 try {
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07003784 AppDeathRecipient adr = new AppDeathRecipient(
3785 app, pid, thread);
3786 thread.asBinder().linkToDeath(adr, 0);
3787 app.deathRecipient = adr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003788 } catch (RemoteException e) {
3789 app.resetPackageList();
3790 startProcessLocked(app, "link fail", processName);
3791 return false;
3792 }
3793
Doug Zongker2bec3d42009-12-04 12:52:44 -08003794 EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.pid, app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003795
3796 app.thread = thread;
3797 app.curAdj = app.setAdj = -100;
Dianne Hackborn09c916b2009-12-08 14:50:51 -08003798 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
3799 app.setSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003800 app.forcingToForeground = null;
3801 app.foregroundServices = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07003802 app.hasShownUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003803 app.debugging = false;
3804
3805 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3806
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003807 boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003808 List providers = normalMode ? generateApplicationProvidersLocked(app) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003809
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003810 if (!normalMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003811 Slog.i(TAG, "Launching preboot mode app: " + app);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003812 }
3813
Joe Onorato8a9b2202010-02-26 18:56:32 -08003814 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003815 TAG, "New app record " + app
3816 + " thread=" + thread.asBinder() + " pid=" + pid);
3817 try {
3818 int testMode = IApplicationThread.DEBUG_OFF;
3819 if (mDebugApp != null && mDebugApp.equals(processName)) {
3820 testMode = mWaitForDebugger
3821 ? IApplicationThread.DEBUG_WAIT
3822 : IApplicationThread.DEBUG_ON;
3823 app.debugging = true;
3824 if (mDebugTransient) {
3825 mDebugApp = mOrigDebugApp;
3826 mWaitForDebugger = mOrigWaitForDebugger;
3827 }
3828 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003829 String profileFile = app.instrumentationProfileFile;
3830 ParcelFileDescriptor profileFd = null;
3831 boolean profileAutoStop = false;
3832 if (mProfileApp != null && mProfileApp.equals(processName)) {
3833 mProfileProc = app;
3834 profileFile = mProfileFile;
3835 profileFd = mProfileFd;
3836 profileAutoStop = mAutoStopProfiler;
3837 }
3838
Christopher Tate181fafa2009-05-14 11:12:14 -07003839 // If the app is being launched for restore or full backup, set it up specially
3840 boolean isRestrictedBackupMode = false;
3841 if (mBackupTarget != null && mBackupAppName.equals(processName)) {
3842 isRestrictedBackupMode = (mBackupTarget.backupMode == BackupRecord.RESTORE)
Christopher Tate75a99702011-05-18 16:28:19 -07003843 || (mBackupTarget.backupMode == BackupRecord.RESTORE_FULL)
Christopher Tate181fafa2009-05-14 11:12:14 -07003844 || (mBackupTarget.backupMode == BackupRecord.BACKUP_FULL);
3845 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003846
Dianne Hackbornd7f6daa2009-06-22 17:06:35 -07003847 ensurePackageDexOpt(app.instrumentationInfo != null
3848 ? app.instrumentationInfo.packageName
3849 : app.info.packageName);
3850 if (app.instrumentationClass != null) {
3851 ensurePackageDexOpt(app.instrumentationClass.getPackageName());
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003852 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08003853 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Binding proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003854 + processName + " with config " + mConfiguration);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003855 ApplicationInfo appInfo = app.instrumentationInfo != null
3856 ? app.instrumentationInfo : app.info;
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -07003857 app.compat = compatibilityInfoForPackageLocked(appInfo);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003858 if (profileFd != null) {
3859 profileFd = profileFd.dup();
3860 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003861 thread.bindApplication(processName, appInfo, providers,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003862 app.instrumentationClass, profileFile, profileFd, profileAutoStop,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003863 app.instrumentationArguments, app.instrumentationWatcher, testMode,
Dianne Hackborn5d927c22011-09-02 12:22:18 -07003864 isRestrictedBackupMode || !normalMode, app.persistent,
Dianne Hackborn813075a62011-11-14 17:45:19 -08003865 new Configuration(mConfiguration), app.compat, getCommonServicesLocked(),
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08003866 mCoreSettingsObserver.getCoreSettingsLocked());
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003867 updateLruProcessLocked(app, false, true);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003868 app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003869 } catch (Exception e) {
3870 // todo: Yikes! What should we do? For now we will try to
3871 // start another process, but that could easily get us in
3872 // an infinite loop of restarting processes...
Joe Onorato8a9b2202010-02-26 18:56:32 -08003873 Slog.w(TAG, "Exception thrown during bind!", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003874
3875 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07003876 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003877 startProcessLocked(app, "bind fail", processName);
3878 return false;
3879 }
3880
3881 // Remove this record from the list of starting applications.
3882 mPersistentStartingProcesses.remove(app);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003883 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
3884 "Attach application locked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003885 mProcessesOnHold.remove(app);
3886
3887 boolean badApp = false;
3888 boolean didSomething = false;
3889
3890 // See if the top visible activity is waiting to run in this process...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003891 ActivityRecord hr = mMainStack.topRunningActivityLocked(null);
Christopher Tate04c0af82010-06-07 18:35:20 -07003892 if (hr != null && normalMode) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003893 if (hr.app == null && app.uid == hr.info.applicationInfo.uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003894 && processName.equals(hr.processName)) {
3895 try {
Mike Lockwood3a74bd32011-08-12 13:55:22 -07003896 if (mHeadless) {
3897 Slog.e(TAG, "Starting activities not supported on headless device: " + hr);
3898 } else if (mMainStack.realStartActivityLocked(hr, app, true, true)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003899 didSomething = true;
3900 }
3901 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003902 Slog.w(TAG, "Exception in new application when starting activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003903 + hr.intent.getComponent().flattenToShortString(), e);
3904 badApp = true;
3905 }
3906 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003907 mMainStack.ensureActivitiesVisibleLocked(hr, null, processName, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003908 }
3909 }
3910
3911 // Find any services that should be running in this process...
3912 if (!badApp && mPendingServices.size() > 0) {
3913 ServiceRecord sr = null;
3914 try {
3915 for (int i=0; i<mPendingServices.size(); i++) {
3916 sr = mPendingServices.get(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003917 if (app != sr.isolatedProc && (app.uid != sr.appInfo.uid
3918 || !processName.equals(sr.processName))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003919 continue;
3920 }
3921
3922 mPendingServices.remove(i);
3923 i--;
3924 realStartServiceLocked(sr, app);
3925 didSomething = true;
3926 }
3927 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003928 Slog.w(TAG, "Exception in new application when starting service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003929 + sr.shortName, e);
3930 badApp = true;
3931 }
3932 }
3933
Christopher Tatef46723b2012-01-26 14:19:24 -08003934 // Check if a next-broadcast receiver is in this process...
3935 if (!badApp && isPendingBroadcastProcessLocked(pid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003936 try {
Christopher Tatef46723b2012-01-26 14:19:24 -08003937 didSomething = sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003938 } catch (Exception e) {
Christopher Tatef46723b2012-01-26 14:19:24 -08003939 // If the app died trying to launch the receiver we declare it 'bad'
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003940 badApp = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003941 }
3942 }
3943
Christopher Tate181fafa2009-05-14 11:12:14 -07003944 // Check whether the next backup agent is in this process...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003945 if (!badApp && mBackupTarget != null && mBackupTarget.appInfo.uid == app.uid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003946 if (DEBUG_BACKUP) Slog.v(TAG, "New app is backup target, launching agent for " + app);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003947 ensurePackageDexOpt(mBackupTarget.appInfo.packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07003948 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003949 thread.scheduleCreateBackupAgent(mBackupTarget.appInfo,
3950 compatibilityInfoForPackageLocked(mBackupTarget.appInfo),
3951 mBackupTarget.backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -07003952 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003953 Slog.w(TAG, "Exception scheduling backup agent creation: ");
Christopher Tate181fafa2009-05-14 11:12:14 -07003954 e.printStackTrace();
3955 }
3956 }
3957
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003958 if (badApp) {
3959 // todo: Also need to kill application to deal with all
3960 // kinds of exceptions.
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003961 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003962 return false;
3963 }
3964
3965 if (!didSomething) {
3966 updateOomAdjLocked();
3967 }
3968
3969 return true;
3970 }
3971
3972 public final void attachApplication(IApplicationThread thread) {
3973 synchronized (this) {
3974 int callingPid = Binder.getCallingPid();
3975 final long origId = Binder.clearCallingIdentity();
3976 attachApplicationLocked(thread, callingPid);
3977 Binder.restoreCallingIdentity(origId);
3978 }
3979 }
3980
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003981 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003982 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003983 ActivityRecord r = mMainStack.activityIdleInternal(token, false, config);
3984 if (stopProfiling) {
3985 synchronized (this) {
3986 if (mProfileProc == r.app) {
3987 if (mProfileFd != null) {
3988 try {
3989 mProfileFd.close();
3990 } catch (IOException e) {
3991 }
3992 clearProfilerLocked();
3993 }
3994 }
3995 }
3996 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003997 Binder.restoreCallingIdentity(origId);
3998 }
3999
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004000 void enableScreenAfterBoot() {
Doug Zongker2bec3d42009-12-04 12:52:44 -08004001 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004002 SystemClock.uptimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004003 mWindowManager.enableScreenAfterBoot();
4004 }
4005
Dianne Hackborn661cd522011-08-22 00:26:20 -07004006 public void showBootMessage(final CharSequence msg, final boolean always) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004007 enforceNotIsolatedCaller("showBootMessage");
Dianne Hackborn661cd522011-08-22 00:26:20 -07004008 mWindowManager.showBootMessage(msg, always);
4009 }
4010
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004011 public void dismissKeyguardOnNextActivity() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004012 enforceNotIsolatedCaller("dismissKeyguardOnNextActivity");
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004013 synchronized (this) {
4014 mMainStack.dismissKeyguardOnNextActivityLocked();
4015 }
4016 }
4017
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004018 final void finishBooting() {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004019 IntentFilter pkgFilter = new IntentFilter();
4020 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
4021 pkgFilter.addDataScheme("package");
4022 mContext.registerReceiver(new BroadcastReceiver() {
4023 @Override
4024 public void onReceive(Context context, Intent intent) {
4025 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
4026 if (pkgs != null) {
4027 for (String pkg : pkgs) {
Vairavan Srinivasan61f07652010-07-22 13:36:40 -07004028 synchronized (ActivityManagerService.this) {
Christopher Tate3dacd842011-08-19 14:56:15 -07004029 if (forceStopPackageLocked(pkg, -1, false, false, false, false)) {
Vairavan Srinivasan61f07652010-07-22 13:36:40 -07004030 setResultCode(Activity.RESULT_OK);
4031 return;
4032 }
4033 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004034 }
4035 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004036 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004037 }, pkgFilter);
4038
4039 synchronized (this) {
4040 // Ensure that any processes we had put on hold are now started
4041 // up.
4042 final int NP = mProcessesOnHold.size();
4043 if (NP > 0) {
4044 ArrayList<ProcessRecord> procs =
4045 new ArrayList<ProcessRecord>(mProcessesOnHold);
4046 for (int ip=0; ip<NP; ip++) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004047 if (DEBUG_PROCESSES) Slog.v(TAG, "Starting process on hold: "
4048 + procs.get(ip));
4049 startProcessLocked(procs.get(ip), "on-hold", null);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004050 }
4051 }
4052
4053 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004054 // Start looking for apps that are abusing wake locks.
4055 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07004056 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004057 // Tell anyone interested that we are done booting!
Dianne Hackbornf4c454b2010-08-11 12:47:41 -07004058 SystemProperties.set("sys.boot_completed", "1");
Guang Zhu191713a2012-01-12 12:02:22 -08004059 SystemProperties.set("dev.bootcomplete", "1");
Amith Yamasani742a6712011-05-04 14:49:28 -07004060 /* TODO: Send this to all users that are to be logged in on startup */
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004061 broadcastIntentLocked(null, null,
4062 new Intent(Intent.ACTION_BOOT_COMPLETED, null),
4063 null, null, 0, null, null,
4064 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
Amith Yamasani742a6712011-05-04 14:49:28 -07004065 false, false, MY_PID, Process.SYSTEM_UID, Binder.getOrigCallingUser());
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004066 }
4067 }
4068 }
4069
4070 final void ensureBootCompleted() {
4071 boolean booting;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004072 boolean enableScreen;
4073 synchronized (this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004074 booting = mBooting;
4075 mBooting = false;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004076 enableScreen = !mBooted;
4077 mBooted = true;
4078 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004079
4080 if (booting) {
4081 finishBooting();
4082 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004083
4084 if (enableScreen) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004085 enableScreenAfterBoot();
4086 }
4087 }
4088
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004089 public final void activityPaused(IBinder token) {
4090 final long origId = Binder.clearCallingIdentity();
4091 mMainStack.activityPaused(token, false);
4092 Binder.restoreCallingIdentity(origId);
4093 }
4094
4095 public final void activityStopped(IBinder token, Bundle icicle, Bitmap thumbnail,
4096 CharSequence description) {
4097 if (localLOGV) Slog.v(
4098 TAG, "Activity stopped: token=" + token);
4099
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004100 // Refuse possible leaked file descriptors
4101 if (icicle != null && icicle.hasFileDescriptors()) {
4102 throw new IllegalArgumentException("File descriptors passed in Bundle");
4103 }
4104
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004105 ActivityRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004106
4107 final long origId = Binder.clearCallingIdentity();
4108
4109 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004110 r = mMainStack.isInStackLocked(token);
4111 if (r != null) {
4112 r.stack.activityStoppedLocked(r, icicle, thumbnail, description);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004113 }
4114 }
4115
4116 if (r != null) {
4117 sendPendingThumbnail(r, null, null, null, false);
4118 }
4119
4120 trimApplications();
4121
4122 Binder.restoreCallingIdentity(origId);
4123 }
4124
4125 public final void activityDestroyed(IBinder token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004126 if (DEBUG_SWITCH) Slog.v(TAG, "ACTIVITY DESTROYED: " + token);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004127 mMainStack.activityDestroyed(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004128 }
4129
4130 public String getCallingPackage(IBinder token) {
4131 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004132 ActivityRecord r = getCallingRecordLocked(token);
Dianne Hackborn9bbcb912009-10-20 15:42:38 -07004133 return r != null && r.app != null ? r.info.packageName : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004134 }
4135 }
4136
4137 public ComponentName getCallingActivity(IBinder token) {
4138 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004139 ActivityRecord r = getCallingRecordLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004140 return r != null ? r.intent.getComponent() : null;
4141 }
4142 }
4143
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004144 private ActivityRecord getCallingRecordLocked(IBinder token) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004145 ActivityRecord r = mMainStack.isInStackLocked(token);
4146 if (r == null) {
4147 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004148 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004149 return r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004150 }
4151
4152 public ComponentName getActivityClassForToken(IBinder token) {
4153 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004154 ActivityRecord r = mMainStack.isInStackLocked(token);
4155 if (r == null) {
4156 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004157 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004158 return r.intent.getComponent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004159 }
4160 }
4161
4162 public String getPackageForToken(IBinder token) {
4163 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004164 ActivityRecord r = mMainStack.isInStackLocked(token);
4165 if (r == null) {
4166 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004167 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004168 return r.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004169 }
4170 }
4171
4172 public IIntentSender getIntentSender(int type,
4173 String packageName, IBinder token, String resultWho,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004174 int requestCode, Intent[] intents, String[] resolvedTypes, int flags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004175 enforceNotIsolatedCaller("getIntentSender");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004176 // Refuse possible leaked file descriptors
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004177 if (intents != null) {
4178 if (intents.length < 1) {
4179 throw new IllegalArgumentException("Intents array length must be >= 1");
4180 }
4181 for (int i=0; i<intents.length; i++) {
4182 Intent intent = intents[i];
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004183 if (intent != null) {
4184 if (intent.hasFileDescriptors()) {
4185 throw new IllegalArgumentException("File descriptors passed in Intent");
4186 }
4187 if (type == INTENT_SENDER_BROADCAST &&
4188 (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
4189 throw new IllegalArgumentException(
4190 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
4191 }
4192 intents[i] = new Intent(intent);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004193 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004194 }
4195 if (resolvedTypes != null && resolvedTypes.length != intents.length) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004196 throw new IllegalArgumentException(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004197 "Intent array length does not match resolvedTypes length");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004198 }
4199 }
4200
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004201 synchronized(this) {
4202 int callingUid = Binder.getCallingUid();
4203 try {
Jeff Brown10e89712011-07-08 18:52:57 -07004204 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004205 int uid = AppGlobals.getPackageManager()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004206 .getPackageUid(packageName);
Amith Yamasani742a6712011-05-04 14:49:28 -07004207 if (UserId.getAppId(callingUid) != uid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004208 String msg = "Permission Denial: getIntentSender() from pid="
4209 + Binder.getCallingPid()
4210 + ", uid=" + Binder.getCallingUid()
4211 + ", (need uid=" + uid + ")"
4212 + " is not allowed to send as package " + packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004213 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004214 throw new SecurityException(msg);
4215 }
4216 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004217
Amith Yamasani742a6712011-05-04 14:49:28 -07004218 if (DEBUG_MU)
4219 Slog.i(TAG_MU, "Getting intent sender for origCallingUid="
4220 + Binder.getOrigCallingUid());
4221 return getIntentSenderLocked(type, packageName, Binder.getOrigCallingUid(),
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004222 token, resultWho, requestCode, intents, resolvedTypes, flags);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004223
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004224 } catch (RemoteException e) {
4225 throw new SecurityException(e);
4226 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004227 }
4228 }
4229
4230 IIntentSender getIntentSenderLocked(int type,
4231 String packageName, int callingUid, IBinder token, String resultWho,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004232 int requestCode, Intent[] intents, String[] resolvedTypes, int flags) {
Amith Yamasani742a6712011-05-04 14:49:28 -07004233 if (DEBUG_MU)
4234 Slog.v(TAG_MU, "getIntentSenderLocked(): uid=" + callingUid);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004235 ActivityRecord activity = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07004236 if (type == INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004237 activity = mMainStack.isInStackLocked(token);
4238 if (activity == null) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004239 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004240 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004241 if (activity.finishing) {
4242 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004243 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004244 }
4245
4246 final boolean noCreate = (flags&PendingIntent.FLAG_NO_CREATE) != 0;
4247 final boolean cancelCurrent = (flags&PendingIntent.FLAG_CANCEL_CURRENT) != 0;
4248 final boolean updateCurrent = (flags&PendingIntent.FLAG_UPDATE_CURRENT) != 0;
4249 flags &= ~(PendingIntent.FLAG_NO_CREATE|PendingIntent.FLAG_CANCEL_CURRENT
4250 |PendingIntent.FLAG_UPDATE_CURRENT);
4251
4252 PendingIntentRecord.Key key = new PendingIntentRecord.Key(
4253 type, packageName, activity, resultWho,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004254 requestCode, intents, resolvedTypes, flags);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004255 WeakReference<PendingIntentRecord> ref;
4256 ref = mIntentSenderRecords.get(key);
4257 PendingIntentRecord rec = ref != null ? ref.get() : null;
4258 if (rec != null) {
4259 if (!cancelCurrent) {
4260 if (updateCurrent) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004261 if (rec.key.requestIntent != null) {
4262 rec.key.requestIntent.replaceExtras(intents != null ? intents[0] : null);
4263 }
4264 if (intents != null) {
4265 intents[intents.length-1] = rec.key.requestIntent;
4266 rec.key.allIntents = intents;
4267 rec.key.allResolvedTypes = resolvedTypes;
4268 } else {
4269 rec.key.allIntents = null;
4270 rec.key.allResolvedTypes = null;
4271 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004272 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004273 return rec;
4274 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004275 rec.canceled = true;
4276 mIntentSenderRecords.remove(key);
4277 }
4278 if (noCreate) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004279 return rec;
4280 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004281 rec = new PendingIntentRecord(this, key, callingUid);
4282 mIntentSenderRecords.put(key, rec.ref);
4283 if (type == INTENT_SENDER_ACTIVITY_RESULT) {
4284 if (activity.pendingResults == null) {
4285 activity.pendingResults
4286 = new HashSet<WeakReference<PendingIntentRecord>>();
4287 }
4288 activity.pendingResults.add(rec.ref);
4289 }
4290 return rec;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004291 }
4292
4293 public void cancelIntentSender(IIntentSender sender) {
4294 if (!(sender instanceof PendingIntentRecord)) {
4295 return;
4296 }
4297 synchronized(this) {
4298 PendingIntentRecord rec = (PendingIntentRecord)sender;
4299 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004300 int uid = AppGlobals.getPackageManager()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004301 .getPackageUid(rec.key.packageName);
4302 if (uid != Binder.getCallingUid()) {
4303 String msg = "Permission Denial: cancelIntentSender() from pid="
4304 + Binder.getCallingPid()
4305 + ", uid=" + Binder.getCallingUid()
4306 + " is not allowed to cancel packges "
4307 + rec.key.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004308 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004309 throw new SecurityException(msg);
4310 }
4311 } catch (RemoteException e) {
4312 throw new SecurityException(e);
4313 }
4314 cancelIntentSenderLocked(rec, true);
4315 }
4316 }
4317
4318 void cancelIntentSenderLocked(PendingIntentRecord rec, boolean cleanActivity) {
4319 rec.canceled = true;
4320 mIntentSenderRecords.remove(rec.key);
4321 if (cleanActivity && rec.key.activity != null) {
4322 rec.key.activity.pendingResults.remove(rec.ref);
4323 }
4324 }
4325
4326 public String getPackageForIntentSender(IIntentSender pendingResult) {
4327 if (!(pendingResult instanceof PendingIntentRecord)) {
4328 return null;
4329 }
Brad Fitzpatrickb213d102010-04-19 11:58:52 -07004330 try {
4331 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4332 return res.key.packageName;
4333 } catch (ClassCastException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004334 }
4335 return null;
4336 }
4337
Dianne Hackborn6c418d52011-06-29 14:05:33 -07004338 public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) {
4339 if (!(pendingResult instanceof PendingIntentRecord)) {
4340 return false;
4341 }
4342 try {
4343 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4344 if (res.key.allIntents == null) {
4345 return false;
4346 }
4347 for (int i=0; i<res.key.allIntents.length; i++) {
4348 Intent intent = res.key.allIntents[i];
4349 if (intent.getPackage() != null && intent.getComponent() != null) {
4350 return false;
4351 }
4352 }
4353 return true;
4354 } catch (ClassCastException e) {
4355 }
4356 return false;
4357 }
4358
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004359 public void setProcessLimit(int max) {
4360 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4361 "setProcessLimit()");
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004362 synchronized (this) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07004363 mProcessLimit = max < 0 ? ProcessList.MAX_HIDDEN_APPS : max;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004364 mProcessLimitOverride = max;
4365 }
4366 trimApplications();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004367 }
4368
4369 public int getProcessLimit() {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004370 synchronized (this) {
4371 return mProcessLimitOverride;
4372 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004373 }
4374
4375 void foregroundTokenDied(ForegroundToken token) {
4376 synchronized (ActivityManagerService.this) {
4377 synchronized (mPidsSelfLocked) {
4378 ForegroundToken cur
4379 = mForegroundProcesses.get(token.pid);
4380 if (cur != token) {
4381 return;
4382 }
4383 mForegroundProcesses.remove(token.pid);
4384 ProcessRecord pr = mPidsSelfLocked.get(token.pid);
4385 if (pr == null) {
4386 return;
4387 }
4388 pr.forcingToForeground = null;
4389 pr.foregroundServices = false;
4390 }
4391 updateOomAdjLocked();
4392 }
4393 }
4394
4395 public void setProcessForeground(IBinder token, int pid, boolean isForeground) {
4396 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4397 "setProcessForeground()");
4398 synchronized(this) {
4399 boolean changed = false;
4400
4401 synchronized (mPidsSelfLocked) {
4402 ProcessRecord pr = mPidsSelfLocked.get(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004403 if (pr == null && isForeground) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004404 Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004405 return;
4406 }
4407 ForegroundToken oldToken = mForegroundProcesses.get(pid);
4408 if (oldToken != null) {
4409 oldToken.token.unlinkToDeath(oldToken, 0);
4410 mForegroundProcesses.remove(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004411 if (pr != null) {
4412 pr.forcingToForeground = null;
4413 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004414 changed = true;
4415 }
4416 if (isForeground && token != null) {
4417 ForegroundToken newToken = new ForegroundToken() {
4418 public void binderDied() {
4419 foregroundTokenDied(this);
4420 }
4421 };
4422 newToken.pid = pid;
4423 newToken.token = token;
4424 try {
4425 token.linkToDeath(newToken, 0);
4426 mForegroundProcesses.put(pid, newToken);
4427 pr.forcingToForeground = token;
4428 changed = true;
4429 } catch (RemoteException e) {
4430 // If the process died while doing this, we will later
4431 // do the cleanup with the process death link.
4432 }
4433 }
4434 }
4435
4436 if (changed) {
4437 updateOomAdjLocked();
4438 }
4439 }
4440 }
4441
4442 // =========================================================
4443 // PERMISSIONS
4444 // =========================================================
4445
4446 static class PermissionController extends IPermissionController.Stub {
4447 ActivityManagerService mActivityManagerService;
4448 PermissionController(ActivityManagerService activityManagerService) {
4449 mActivityManagerService = activityManagerService;
4450 }
4451
4452 public boolean checkPermission(String permission, int pid, int uid) {
4453 return mActivityManagerService.checkPermission(permission, pid,
4454 uid) == PackageManager.PERMISSION_GRANTED;
4455 }
4456 }
4457
4458 /**
4459 * This can be called with or without the global lock held.
4460 */
4461 int checkComponentPermission(String permission, int pid, int uid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004462 int owningUid, boolean exported) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004463 // We might be performing an operation on behalf of an indirect binder
4464 // invocation, e.g. via {@link #openContentUri}. Check and adjust the
4465 // client identity accordingly before proceeding.
4466 Identity tlsIdentity = sCallerIdentity.get();
4467 if (tlsIdentity != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004468 Slog.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004469 + tlsIdentity.pid + "," + tlsIdentity.uid + "}");
4470 uid = tlsIdentity.uid;
4471 pid = tlsIdentity.pid;
4472 }
4473
4474 // Root, system server and our own process get to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07004475 if (uid == 0 || uid == Process.SYSTEM_UID || pid == MY_PID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004476 return PackageManager.PERMISSION_GRANTED;
4477 }
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004478 // Isolated processes don't get any permissions.
4479 if (UserId.isIsolated(uid)) {
4480 return PackageManager.PERMISSION_DENIED;
4481 }
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004482 // If there is a uid that owns whatever is being accessed, it has
4483 // blanket access to it regardless of the permissions it requires.
Amith Yamasani742a6712011-05-04 14:49:28 -07004484 if (owningUid >= 0 && UserId.isSameApp(uid, owningUid)) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004485 return PackageManager.PERMISSION_GRANTED;
4486 }
4487 // If the target is not exported, then nobody else can get to it.
4488 if (!exported) {
4489 Slog.w(TAG, "Permission denied: checkComponentPermission() owningUid=" + owningUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004490 return PackageManager.PERMISSION_DENIED;
4491 }
4492 if (permission == null) {
4493 return PackageManager.PERMISSION_GRANTED;
4494 }
4495 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004496 return AppGlobals.getPackageManager()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004497 .checkUidPermission(permission, uid);
4498 } catch (RemoteException e) {
4499 // Should never happen, but if it does... deny!
Joe Onorato8a9b2202010-02-26 18:56:32 -08004500 Slog.e(TAG, "PackageManager is dead?!?", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004501 }
4502 return PackageManager.PERMISSION_DENIED;
4503 }
4504
4505 /**
4506 * As the only public entry point for permissions checking, this method
4507 * can enforce the semantic that requesting a check on a null global
4508 * permission is automatically denied. (Internally a null permission
4509 * string is used when calling {@link #checkComponentPermission} in cases
4510 * when only uid-based security is needed.)
4511 *
4512 * This can be called with or without the global lock held.
4513 */
4514 public int checkPermission(String permission, int pid, int uid) {
4515 if (permission == null) {
4516 return PackageManager.PERMISSION_DENIED;
4517 }
Amith Yamasani742a6712011-05-04 14:49:28 -07004518 return checkComponentPermission(permission, pid, UserId.getAppId(uid), -1, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004519 }
4520
4521 /**
4522 * Binder IPC calls go through the public entry point.
4523 * This can be called with or without the global lock held.
4524 */
4525 int checkCallingPermission(String permission) {
4526 return checkPermission(permission,
4527 Binder.getCallingPid(),
Amith Yamasani742a6712011-05-04 14:49:28 -07004528 UserId.getAppId(Binder.getCallingUid()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004529 }
4530
4531 /**
4532 * This can be called with or without the global lock held.
4533 */
4534 void enforceCallingPermission(String permission, String func) {
4535 if (checkCallingPermission(permission)
4536 == PackageManager.PERMISSION_GRANTED) {
4537 return;
4538 }
4539
4540 String msg = "Permission Denial: " + func + " from pid="
4541 + Binder.getCallingPid()
4542 + ", uid=" + Binder.getCallingUid()
4543 + " requires " + permission;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004544 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004545 throw new SecurityException(msg);
4546 }
4547
4548 private final boolean checkHoldingPermissionsLocked(IPackageManager pm,
Dianne Hackborn48058e82010-09-27 16:53:23 -07004549 ProviderInfo pi, Uri uri, int uid, int modeFlags) {
4550 boolean readPerm = (modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) == 0;
4551 boolean writePerm = (modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) == 0;
4552 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4553 "checkHoldingPermissionsLocked: uri=" + uri + " uid=" + uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004554 try {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004555 // Is the component private from the target uid?
4556 final boolean prv = !pi.exported && pi.applicationInfo.uid != uid;
4557
4558 // Acceptable if the there is no read permission needed from the
4559 // target or the target is holding the read permission.
4560 if (!readPerm) {
4561 if ((!prv && pi.readPermission == null) ||
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004562 (pm.checkUidPermission(pi.readPermission, uid)
Dianne Hackborn48058e82010-09-27 16:53:23 -07004563 == PackageManager.PERMISSION_GRANTED)) {
4564 readPerm = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004565 }
4566 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004567
4568 // Acceptable if the there is no write permission needed from the
4569 // target or the target is holding the read permission.
4570 if (!writePerm) {
4571 if (!prv && (pi.writePermission == null) ||
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004572 (pm.checkUidPermission(pi.writePermission, uid)
Dianne Hackborn48058e82010-09-27 16:53:23 -07004573 == PackageManager.PERMISSION_GRANTED)) {
4574 writePerm = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004575 }
4576 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004577
4578 // Acceptable if there is a path permission matching the URI that
4579 // the target holds the permission on.
4580 PathPermission[] pps = pi.pathPermissions;
4581 if (pps != null && (!readPerm || !writePerm)) {
4582 final String path = uri.getPath();
4583 int i = pps.length;
4584 while (i > 0 && (!readPerm || !writePerm)) {
4585 i--;
4586 PathPermission pp = pps[i];
4587 if (!readPerm) {
4588 final String pprperm = pp.getReadPermission();
4589 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking read perm for "
4590 + pprperm + " for " + pp.getPath()
4591 + ": match=" + pp.match(path)
4592 + " check=" + pm.checkUidPermission(pprperm, uid));
4593 if (pprperm != null && pp.match(path) &&
4594 (pm.checkUidPermission(pprperm, uid)
4595 == PackageManager.PERMISSION_GRANTED)) {
4596 readPerm = true;
4597 }
4598 }
4599 if (!writePerm) {
4600 final String ppwperm = pp.getWritePermission();
4601 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking write perm "
4602 + ppwperm + " for " + pp.getPath()
4603 + ": match=" + pp.match(path)
4604 + " check=" + pm.checkUidPermission(ppwperm, uid));
4605 if (ppwperm != null && pp.match(path) &&
4606 (pm.checkUidPermission(ppwperm, uid)
4607 == PackageManager.PERMISSION_GRANTED)) {
4608 writePerm = true;
4609 }
4610 }
4611 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07004612 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004613 } catch (RemoteException e) {
4614 return false;
4615 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004616
4617 return readPerm && writePerm;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004618 }
4619
4620 private final boolean checkUriPermissionLocked(Uri uri, int uid,
4621 int modeFlags) {
4622 // Root gets to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07004623 if (uid == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004624 return true;
4625 }
4626 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(uid);
4627 if (perms == null) return false;
4628 UriPermission perm = perms.get(uri);
4629 if (perm == null) return false;
4630 return (modeFlags&perm.modeFlags) == modeFlags;
4631 }
4632
4633 public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004634 enforceNotIsolatedCaller("checkUriPermission");
4635
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004636 // Another redirected-binder-call permissions check as in
4637 // {@link checkComponentPermission}.
4638 Identity tlsIdentity = sCallerIdentity.get();
4639 if (tlsIdentity != null) {
4640 uid = tlsIdentity.uid;
4641 pid = tlsIdentity.pid;
4642 }
4643
Amith Yamasani742a6712011-05-04 14:49:28 -07004644 uid = UserId.getAppId(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004645 // Our own process gets to do everything.
4646 if (pid == MY_PID) {
4647 return PackageManager.PERMISSION_GRANTED;
4648 }
4649 synchronized(this) {
4650 return checkUriPermissionLocked(uri, uid, modeFlags)
4651 ? PackageManager.PERMISSION_GRANTED
4652 : PackageManager.PERMISSION_DENIED;
4653 }
4654 }
4655
Dianne Hackborn39792d22010-08-19 18:01:52 -07004656 /**
4657 * Check if the targetPkg can be granted permission to access uri by
4658 * the callingUid using the given modeFlags. Throws a security exception
4659 * if callingUid is not allowed to do this. Returns the uid of the target
4660 * if the URI permission grant should be performed; returns -1 if it is not
4661 * needed (for example targetPkg already has permission to access the URI).
4662 */
4663 int checkGrantUriPermissionLocked(int callingUid, String targetPkg,
4664 Uri uri, int modeFlags) {
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
4703 int targetUid;
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004704 if (targetPkg != null) {
4705 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 }
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004715 } else {
4716 targetUid = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004717 }
4718
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004719 if (targetUid >= 0) {
4720 // First... does the target actually need this permission?
4721 if (checkHoldingPermissionsLocked(pm, pi, uri, targetUid, modeFlags)) {
4722 // No need to grant the target this permission.
4723 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4724 "Target " + targetPkg + " already has full permission to " + uri);
4725 return -1;
4726 }
4727 } else {
4728 // First... there is no target package, so can anyone access it?
4729 boolean allowed = pi.exported;
4730 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
4731 if (pi.readPermission != null) {
4732 allowed = false;
4733 }
4734 }
4735 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
4736 if (pi.writePermission != null) {
4737 allowed = false;
4738 }
4739 }
4740 if (allowed) {
4741 return -1;
4742 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004743 }
4744
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004745 // Second... is the provider allowing granting of URI permissions?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004746 if (!pi.grantUriPermissions) {
4747 throw new SecurityException("Provider " + pi.packageName
4748 + "/" + pi.name
4749 + " does not allow granting of Uri permissions (uri "
4750 + uri + ")");
4751 }
4752 if (pi.uriPermissionPatterns != null) {
4753 final int N = pi.uriPermissionPatterns.length;
4754 boolean allowed = false;
4755 for (int i=0; i<N; i++) {
4756 if (pi.uriPermissionPatterns[i] != null
4757 && pi.uriPermissionPatterns[i].match(uri.getPath())) {
4758 allowed = true;
4759 break;
4760 }
4761 }
4762 if (!allowed) {
4763 throw new SecurityException("Provider " + pi.packageName
4764 + "/" + pi.name
4765 + " does not allow granting of permission to path of Uri "
4766 + uri);
4767 }
4768 }
4769
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004770 // Third... does the caller itself have permission to access
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004771 // this uri?
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004772 if (callingUid != Process.myUid()) {
4773 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
4774 if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
4775 throw new SecurityException("Uid " + callingUid
4776 + " does not have permission to uri " + uri);
4777 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004778 }
4779 }
4780
Dianne Hackborn39792d22010-08-19 18:01:52 -07004781 return targetUid;
4782 }
4783
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004784 public int checkGrantUriPermission(int callingUid, String targetPkg,
4785 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004786 enforceNotIsolatedCaller("checkGrantUriPermission");
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004787 synchronized(this) {
4788 return checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags);
4789 }
4790 }
4791
Dianne Hackborn39792d22010-08-19 18:01:52 -07004792 void grantUriPermissionUncheckedLocked(int targetUid, String targetPkg,
4793 Uri uri, int modeFlags, UriPermissionOwner owner) {
4794 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4795 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4796 if (modeFlags == 0) {
4797 return;
4798 }
4799
4800 // So here we are: the caller has the assumed permission
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004801 // to the uri, and the target doesn't. Let's now give this to
4802 // the target.
4803
Joe Onorato8a9b2202010-02-26 18:56:32 -08004804 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn39792d22010-08-19 18:01:52 -07004805 "Granting " + targetPkg + "/" + targetUid + " permission to " + uri);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004806
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004807 HashMap<Uri, UriPermission> targetUris
4808 = mGrantedUriPermissions.get(targetUid);
4809 if (targetUris == null) {
4810 targetUris = new HashMap<Uri, UriPermission>();
4811 mGrantedUriPermissions.put(targetUid, targetUris);
4812 }
4813
4814 UriPermission perm = targetUris.get(uri);
4815 if (perm == null) {
4816 perm = new UriPermission(targetUid, uri);
4817 targetUris.put(uri, perm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004818 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07004819
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004820 perm.modeFlags |= modeFlags;
Dianne Hackborn39792d22010-08-19 18:01:52 -07004821 if (owner == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004822 perm.globalModeFlags |= modeFlags;
Vairavan Srinivasan91c12c22011-01-21 18:26:06 -08004823 } else {
4824 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
4825 perm.readOwners.add(owner);
4826 owner.addReadPermission(perm);
4827 }
4828 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
4829 perm.writeOwners.add(owner);
4830 owner.addWritePermission(perm);
4831 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004832 }
4833 }
4834
Dianne Hackborn39792d22010-08-19 18:01:52 -07004835 void grantUriPermissionLocked(int callingUid,
4836 String targetPkg, Uri uri, int modeFlags, UriPermissionOwner owner) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004837 if (targetPkg == null) {
4838 throw new NullPointerException("targetPkg");
4839 }
4840
Dianne Hackborn39792d22010-08-19 18:01:52 -07004841 int targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags);
4842 if (targetUid < 0) {
4843 return;
4844 }
4845
4846 grantUriPermissionUncheckedLocked(targetUid, targetPkg, uri, modeFlags, owner);
4847 }
4848
4849 /**
4850 * Like checkGrantUriPermissionLocked, but takes an Intent.
4851 */
4852 int checkGrantUriPermissionFromIntentLocked(int callingUid,
4853 String targetPkg, Intent intent) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07004854 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn39792d22010-08-19 18:01:52 -07004855 "Checking URI perm to " + (intent != null ? intent.getData() : null)
Dianne Hackbornb424b632010-08-18 15:59:05 -07004856 + " from " + intent + "; flags=0x"
4857 + Integer.toHexString(intent != null ? intent.getFlags() : 0));
4858
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004859 if (targetPkg == null) {
4860 throw new NullPointerException("targetPkg");
4861 }
4862
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004863 if (intent == null) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004864 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004865 }
4866 Uri data = intent.getData();
4867 if (data == null) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004868 return -1;
4869 }
4870 return checkGrantUriPermissionLocked(callingUid, targetPkg, data,
4871 intent.getFlags());
4872 }
4873
4874 /**
4875 * Like grantUriPermissionUncheckedLocked, but takes an Intent.
4876 */
4877 void grantUriPermissionUncheckedFromIntentLocked(int targetUid,
4878 String targetPkg, Intent intent, UriPermissionOwner owner) {
4879 grantUriPermissionUncheckedLocked(targetUid, targetPkg, intent.getData(),
4880 intent.getFlags(), owner);
4881 }
4882
4883 void grantUriPermissionFromIntentLocked(int callingUid,
4884 String targetPkg, Intent intent, UriPermissionOwner owner) {
4885 int targetUid = checkGrantUriPermissionFromIntentLocked(callingUid, targetPkg, intent);
4886 if (targetUid < 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004887 return;
4888 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07004889
4890 grantUriPermissionUncheckedFromIntentLocked(targetUid, targetPkg, intent, owner);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004891 }
4892
4893 public void grantUriPermission(IApplicationThread caller, String targetPkg,
4894 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004895 enforceNotIsolatedCaller("grantUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004896 synchronized(this) {
4897 final ProcessRecord r = getRecordForAppLocked(caller);
4898 if (r == null) {
4899 throw new SecurityException("Unable to find app for caller "
4900 + caller
4901 + " when granting permission to uri " + uri);
4902 }
4903 if (targetPkg == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07004904 throw new IllegalArgumentException("null target");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004905 }
4906 if (uri == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07004907 throw new IllegalArgumentException("null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004908 }
4909
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004910 grantUriPermissionLocked(r.uid, targetPkg, uri, modeFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004911 null);
4912 }
4913 }
4914
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004915 void removeUriPermissionIfNeededLocked(UriPermission perm) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004916 if ((perm.modeFlags&(Intent.FLAG_GRANT_READ_URI_PERMISSION
4917 |Intent.FLAG_GRANT_WRITE_URI_PERMISSION)) == 0) {
4918 HashMap<Uri, UriPermission> perms
4919 = mGrantedUriPermissions.get(perm.uid);
4920 if (perms != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004921 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004922 "Removing " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004923 perms.remove(perm.uri);
4924 if (perms.size() == 0) {
4925 mGrantedUriPermissions.remove(perm.uid);
4926 }
4927 }
4928 }
4929 }
4930
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004931 private void revokeUriPermissionLocked(int callingUid, Uri uri,
4932 int modeFlags) {
4933 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4934 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4935 if (modeFlags == 0) {
4936 return;
4937 }
4938
Joe Onorato8a9b2202010-02-26 18:56:32 -08004939 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004940 "Revoking all granted permissions to " + uri);
4941
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004942 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004943
4944 final String authority = uri.getAuthority();
4945 ProviderInfo pi = null;
Amith Yamasani742a6712011-05-04 14:49:28 -07004946 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority,
4947 UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004948 if (cpr != null) {
4949 pi = cpr.info;
4950 } else {
4951 try {
4952 pi = pm.resolveContentProvider(authority,
4953 PackageManager.GET_URI_PERMISSION_PATTERNS);
4954 } catch (RemoteException ex) {
4955 }
4956 }
4957 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07004958 Slog.w(TAG, "No content provider found for permission revoke: " + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004959 return;
4960 }
4961
4962 // Does the caller have this permission on the URI?
Dianne Hackborn48058e82010-09-27 16:53:23 -07004963 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004964 // Right now, if you are not the original owner of the permission,
4965 // you are not allowed to revoke it.
4966 //if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
4967 throw new SecurityException("Uid " + callingUid
4968 + " does not have permission to uri " + uri);
4969 //}
4970 }
4971
4972 // Go through all of the permissions and remove any that match.
4973 final List<String> SEGMENTS = uri.getPathSegments();
4974 if (SEGMENTS != null) {
4975 final int NS = SEGMENTS.size();
4976 int N = mGrantedUriPermissions.size();
4977 for (int i=0; i<N; i++) {
4978 HashMap<Uri, UriPermission> perms
4979 = mGrantedUriPermissions.valueAt(i);
4980 Iterator<UriPermission> it = perms.values().iterator();
4981 toploop:
4982 while (it.hasNext()) {
4983 UriPermission perm = it.next();
4984 Uri targetUri = perm.uri;
4985 if (!authority.equals(targetUri.getAuthority())) {
4986 continue;
4987 }
4988 List<String> targetSegments = targetUri.getPathSegments();
4989 if (targetSegments == null) {
4990 continue;
4991 }
4992 if (targetSegments.size() < NS) {
4993 continue;
4994 }
4995 for (int j=0; j<NS; j++) {
4996 if (!SEGMENTS.get(j).equals(targetSegments.get(j))) {
4997 continue toploop;
4998 }
4999 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08005000 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005001 "Revoking " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005002 perm.clearModes(modeFlags);
5003 if (perm.modeFlags == 0) {
5004 it.remove();
5005 }
5006 }
5007 if (perms.size() == 0) {
5008 mGrantedUriPermissions.remove(
5009 mGrantedUriPermissions.keyAt(i));
5010 N--;
5011 i--;
5012 }
5013 }
5014 }
5015 }
5016
5017 public void revokeUriPermission(IApplicationThread caller, Uri uri,
5018 int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005019 enforceNotIsolatedCaller("revokeUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005020 synchronized(this) {
5021 final ProcessRecord r = getRecordForAppLocked(caller);
5022 if (r == null) {
5023 throw new SecurityException("Unable to find app for caller "
5024 + caller
5025 + " when revoking permission to uri " + uri);
5026 }
5027 if (uri == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005028 Slog.w(TAG, "revokeUriPermission: null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005029 return;
5030 }
5031
5032 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5033 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5034 if (modeFlags == 0) {
5035 return;
5036 }
5037
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005038 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005039
5040 final String authority = uri.getAuthority();
5041 ProviderInfo pi = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005042 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005043 if (cpr != null) {
5044 pi = cpr.info;
5045 } else {
5046 try {
5047 pi = pm.resolveContentProvider(authority,
5048 PackageManager.GET_URI_PERMISSION_PATTERNS);
5049 } catch (RemoteException ex) {
5050 }
5051 }
5052 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005053 Slog.w(TAG, "No content provider found for permission revoke: "
5054 + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005055 return;
5056 }
5057
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005058 revokeUriPermissionLocked(r.uid, uri, modeFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005059 }
5060 }
5061
Dianne Hackborn7e269642010-08-25 19:50:20 -07005062 @Override
5063 public IBinder newUriPermissionOwner(String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005064 enforceNotIsolatedCaller("newUriPermissionOwner");
Dianne Hackborn7e269642010-08-25 19:50:20 -07005065 synchronized(this) {
5066 UriPermissionOwner owner = new UriPermissionOwner(this, name);
5067 return owner.getExternalTokenLocked();
5068 }
5069 }
5070
5071 @Override
5072 public void grantUriPermissionFromOwner(IBinder token, int fromUid, String targetPkg,
5073 Uri uri, int modeFlags) {
5074 synchronized(this) {
5075 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5076 if (owner == null) {
5077 throw new IllegalArgumentException("Unknown owner: " + token);
5078 }
5079 if (fromUid != Binder.getCallingUid()) {
5080 if (Binder.getCallingUid() != Process.myUid()) {
5081 // Only system code can grant URI permissions on behalf
5082 // of other users.
5083 throw new SecurityException("nice try");
5084 }
5085 }
5086 if (targetPkg == null) {
5087 throw new IllegalArgumentException("null target");
5088 }
5089 if (uri == null) {
5090 throw new IllegalArgumentException("null uri");
5091 }
5092
5093 grantUriPermissionLocked(fromUid, targetPkg, uri, modeFlags, owner);
5094 }
5095 }
5096
5097 @Override
5098 public void revokeUriPermissionFromOwner(IBinder token, Uri uri, int mode) {
5099 synchronized(this) {
5100 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5101 if (owner == null) {
5102 throw new IllegalArgumentException("Unknown owner: " + token);
5103 }
5104
5105 if (uri == null) {
5106 owner.removeUriPermissionsLocked(mode);
5107 } else {
5108 owner.removeUriPermissionLocked(uri, mode);
5109 }
5110 }
5111 }
5112
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005113 public void showWaitingForDebugger(IApplicationThread who, boolean waiting) {
5114 synchronized (this) {
5115 ProcessRecord app =
5116 who != null ? getRecordForAppLocked(who) : null;
5117 if (app == null) return;
5118
5119 Message msg = Message.obtain();
5120 msg.what = WAIT_FOR_DEBUGGER_MSG;
5121 msg.obj = app;
5122 msg.arg1 = waiting ? 1 : 0;
5123 mHandler.sendMessage(msg);
5124 }
5125 }
5126
5127 public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07005128 final long homeAppMem = mProcessList.getMemLevel(ProcessList.HOME_APP_ADJ);
5129 final long hiddenAppMem = mProcessList.getMemLevel(ProcessList.HIDDEN_APP_MIN_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005130 outInfo.availMem = Process.getFreeMemory();
Dianne Hackborn7d608422011-08-07 16:24:18 -07005131 outInfo.threshold = homeAppMem;
5132 outInfo.lowMemory = outInfo.availMem < (homeAppMem + ((hiddenAppMem-homeAppMem)/2));
5133 outInfo.hiddenAppThreshold = hiddenAppMem;
5134 outInfo.secondaryServerThreshold = mProcessList.getMemLevel(
Dianne Hackborne02c88a2011-10-28 13:58:15 -07005135 ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07005136 outInfo.visibleAppThreshold = mProcessList.getMemLevel(
5137 ProcessList.VISIBLE_APP_ADJ);
5138 outInfo.foregroundAppThreshold = mProcessList.getMemLevel(
5139 ProcessList.FOREGROUND_APP_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005140 }
5141
5142 // =========================================================
5143 // TASK MANAGEMENT
5144 // =========================================================
5145
5146 public List getTasks(int maxNum, int flags,
5147 IThumbnailReceiver receiver) {
5148 ArrayList list = new ArrayList();
5149
5150 PendingThumbnailsRecord pending = null;
5151 IApplicationThread topThumbnail = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005152 ActivityRecord topRecord = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005153
5154 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005155 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005156 TAG, "getTasks: max=" + maxNum + ", flags=" + flags
5157 + ", receiver=" + receiver);
5158
5159 if (checkCallingPermission(android.Manifest.permission.GET_TASKS)
5160 != PackageManager.PERMISSION_GRANTED) {
5161 if (receiver != null) {
5162 // If the caller wants to wait for pending thumbnails,
5163 // it ain't gonna get them.
5164 try {
5165 receiver.finished();
5166 } catch (RemoteException ex) {
5167 }
5168 }
5169 String msg = "Permission Denial: getTasks() from pid="
5170 + Binder.getCallingPid()
5171 + ", uid=" + Binder.getCallingUid()
5172 + " requires " + android.Manifest.permission.GET_TASKS;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005173 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005174 throw new SecurityException(msg);
5175 }
5176
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005177 int pos = mMainStack.mHistory.size()-1;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005178 ActivityRecord next =
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005179 pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005180 ActivityRecord top = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005181 TaskRecord curTask = null;
5182 int numActivities = 0;
5183 int numRunning = 0;
5184 while (pos >= 0 && maxNum > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005185 final ActivityRecord r = next;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005186 pos--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005187 next = pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005188
5189 // Initialize state for next task if needed.
5190 if (top == null ||
5191 (top.state == ActivityState.INITIALIZING
5192 && top.task == r.task)) {
5193 top = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005194 curTask = r.task;
5195 numActivities = numRunning = 0;
5196 }
5197
5198 // Add 'r' into the current task.
5199 numActivities++;
5200 if (r.app != null && r.app.thread != null) {
5201 numRunning++;
5202 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005203
Joe Onorato8a9b2202010-02-26 18:56:32 -08005204 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005205 TAG, r.intent.getComponent().flattenToShortString()
5206 + ": task=" + r.task);
5207
5208 // If the next one is a different task, generate a new
5209 // TaskInfo entry for what we have.
5210 if (next == null || next.task != curTask) {
5211 ActivityManager.RunningTaskInfo ci
5212 = new ActivityManager.RunningTaskInfo();
5213 ci.id = curTask.taskId;
5214 ci.baseActivity = r.intent.getComponent();
5215 ci.topActivity = top.intent.getComponent();
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005216 if (top.thumbHolder != null) {
5217 ci.description = top.thumbHolder.lastDescription;
5218 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005219 ci.numActivities = numActivities;
5220 ci.numRunning = numRunning;
5221 //System.out.println(
5222 // "#" + maxNum + ": " + " descr=" + ci.description);
5223 if (ci.thumbnail == null && receiver != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005224 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005225 TAG, "State=" + top.state + "Idle=" + top.idle
5226 + " app=" + top.app
5227 + " thr=" + (top.app != null ? top.app.thread : null));
5228 if (top.state == ActivityState.RESUMED
5229 || top.state == ActivityState.PAUSING) {
5230 if (top.idle && top.app != null
5231 && top.app.thread != null) {
5232 topRecord = top;
5233 topThumbnail = top.app.thread;
5234 } else {
5235 top.thumbnailNeeded = true;
5236 }
5237 }
5238 if (pending == null) {
5239 pending = new PendingThumbnailsRecord(receiver);
5240 }
5241 pending.pendingRecords.add(top);
5242 }
5243 list.add(ci);
5244 maxNum--;
5245 top = null;
5246 }
5247 }
5248
5249 if (pending != null) {
5250 mPendingThumbnails.add(pending);
5251 }
5252 }
5253
Joe Onorato8a9b2202010-02-26 18:56:32 -08005254 if (localLOGV) Slog.v(TAG, "We have pending thumbnails: " + pending);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005255
5256 if (topThumbnail != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005257 if (localLOGV) Slog.v(TAG, "Requesting top thumbnail");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005258 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08005259 topThumbnail.requestThumbnail(topRecord.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005260 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005261 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005262 sendPendingThumbnail(null, topRecord.appToken, null, null, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005263 }
5264 }
5265
5266 if (pending == null && receiver != null) {
5267 // In this case all thumbnails were available and the client
5268 // is being asked to be told when the remaining ones come in...
5269 // which is unusually, since the top-most currently running
5270 // activity should never have a canned thumbnail! Oh well.
5271 try {
5272 receiver.finished();
5273 } catch (RemoteException ex) {
5274 }
5275 }
5276
5277 return list;
5278 }
5279
5280 public List<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum,
5281 int flags) {
Amith Yamasani742a6712011-05-04 14:49:28 -07005282 final int callingUid = Binder.getCallingUid();
5283 // If it's the system uid asking, then use the current user id.
5284 // TODO: Make sure that there aren't any other legitimate calls from the system uid that
5285 // require the entire list.
5286 final int callingUserId = callingUid == Process.SYSTEM_UID
5287 ? mCurrentUserId : UserId.getUserId(callingUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005288 synchronized (this) {
5289 enforceCallingPermission(android.Manifest.permission.GET_TASKS,
5290 "getRecentTasks()");
5291
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005292 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005293
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005294 final int N = mRecentTasks.size();
5295 ArrayList<ActivityManager.RecentTaskInfo> res
5296 = new ArrayList<ActivityManager.RecentTaskInfo>(
5297 maxNum < N ? maxNum : N);
5298 for (int i=0; i<N && maxNum > 0; i++) {
5299 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005300 // Only add calling user's recent tasks
5301 if (tr.userId != callingUserId) continue;
Dianne Hackborn905577f2011-09-07 18:31:28 -07005302 // Return the entry if desired by the caller. We always return
5303 // the first entry, because callers always expect this to be the
Amith Yamasani742a6712011-05-04 14:49:28 -07005304 // foreground app. We may filter others if the caller has
Dianne Hackborn905577f2011-09-07 18:31:28 -07005305 // not supplied RECENT_WITH_EXCLUDED and there is some reason
5306 // we should exclude the entry.
Amith Yamasani742a6712011-05-04 14:49:28 -07005307
Dianne Hackborn905577f2011-09-07 18:31:28 -07005308 if (i == 0
5309 || ((flags&ActivityManager.RECENT_WITH_EXCLUDED) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005310 || (tr.intent == null)
5311 || ((tr.intent.getFlags()
5312 &Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) == 0)) {
5313 ActivityManager.RecentTaskInfo rti
5314 = new ActivityManager.RecentTaskInfo();
5315 rti.id = tr.numActivities > 0 ? tr.taskId : -1;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005316 rti.persistentId = tr.taskId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005317 rti.baseIntent = new Intent(
5318 tr.intent != null ? tr.intent : tr.affinityIntent);
5319 rti.origActivity = tr.origActivity;
Dianne Hackbornd2835932010-12-13 16:28:46 -08005320 rti.description = tr.lastDescription;
5321
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005322 if ((flags&ActivityManager.RECENT_IGNORE_UNAVAILABLE) != 0) {
5323 // Check whether this activity is currently available.
5324 try {
5325 if (rti.origActivity != null) {
5326 if (pm.getActivityInfo(rti.origActivity, 0) == null) {
5327 continue;
5328 }
5329 } else if (rti.baseIntent != null) {
5330 if (pm.queryIntentActivities(rti.baseIntent,
5331 null, 0) == null) {
5332 continue;
5333 }
5334 }
5335 } catch (RemoteException e) {
5336 // Will never happen.
5337 }
5338 }
5339
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005340 res.add(rti);
5341 maxNum--;
5342 }
5343 }
5344 return res;
5345 }
5346 }
5347
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005348 private TaskRecord taskForIdLocked(int id) {
5349 final int N = mRecentTasks.size();
5350 for (int i=0; i<N; i++) {
5351 TaskRecord tr = mRecentTasks.get(i);
5352 if (tr.taskId == id) {
5353 return tr;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005354 }
5355 }
5356 return null;
5357 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005358
5359 public ActivityManager.TaskThumbnails getTaskThumbnails(int id) {
5360 synchronized (this) {
5361 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
5362 "getTaskThumbnails()");
5363 TaskRecord tr = taskForIdLocked(id);
5364 if (tr != null) {
5365 return mMainStack.getTaskThumbnailsLocked(tr);
5366 }
5367 }
5368 return null;
5369 }
5370
5371 public boolean removeSubTask(int taskId, int subTaskIndex) {
5372 synchronized (this) {
5373 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5374 "removeSubTask()");
5375 long ident = Binder.clearCallingIdentity();
5376 try {
5377 return mMainStack.removeTaskActivitiesLocked(taskId, subTaskIndex) != null;
5378 } finally {
5379 Binder.restoreCallingIdentity(ident);
5380 }
5381 }
5382 }
5383
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005384 private void cleanUpRemovedTaskLocked(ActivityRecord root, boolean killProcesses) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005385 TaskRecord tr = root.task;
5386 Intent baseIntent = new Intent(
5387 tr.intent != null ? tr.intent : tr.affinityIntent);
5388 ComponentName component = baseIntent.getComponent();
5389 if (component == null) {
5390 Slog.w(TAG, "Now component for base intent of task: " + tr);
5391 return;
5392 }
5393
5394 // Find any running services associated with this app.
5395 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
Amith Yamasani742a6712011-05-04 14:49:28 -07005396 for (ServiceRecord sr : mServiceMap.getAllServices(root.userId)) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005397 if (sr.packageName.equals(component.getPackageName())) {
5398 services.add(sr);
5399 }
5400 }
5401
5402 // Take care of any running services associated with the app.
5403 for (int i=0; i<services.size(); i++) {
5404 ServiceRecord sr = services.get(i);
5405 if (sr.startRequested) {
5406 if ((sr.serviceInfo.flags&ServiceInfo.FLAG_STOP_WITH_TASK) != 0) {
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005407 Slog.i(TAG, "Stopping service " + sr.shortName + ": remove task");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005408 stopServiceLocked(sr);
5409 } else {
5410 sr.pendingStarts.add(new ServiceRecord.StartItem(sr, true,
5411 sr.makeNextStartId(), baseIntent, -1));
5412 if (sr.app != null && sr.app.thread != null) {
5413 sendServiceArgsLocked(sr, false);
5414 }
5415 }
5416 }
5417 }
5418
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005419 if (killProcesses) {
5420 // Find any running processes associated with this app.
5421 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
5422 SparseArray<ProcessRecord> appProcs
5423 = mProcessNames.getMap().get(component.getPackageName());
5424 if (appProcs != null) {
5425 for (int i=0; i<appProcs.size(); i++) {
5426 procs.add(appProcs.valueAt(i));
5427 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005428 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005429
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005430 // Kill the running processes.
5431 for (int i=0; i<procs.size(); i++) {
5432 ProcessRecord pr = procs.get(i);
5433 if (pr.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
5434 Slog.i(TAG, "Killing " + pr.toShortString() + ": remove task");
5435 EventLog.writeEvent(EventLogTags.AM_KILL, pr.pid,
5436 pr.processName, pr.setAdj, "remove task");
5437 Process.killProcessQuiet(pr.pid);
5438 } else {
5439 pr.waitingToKill = "remove task";
5440 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005441 }
5442 }
5443 }
5444
5445 public boolean removeTask(int taskId, int flags) {
5446 synchronized (this) {
5447 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5448 "removeTask()");
5449 long ident = Binder.clearCallingIdentity();
5450 try {
5451 ActivityRecord r = mMainStack.removeTaskActivitiesLocked(taskId, -1);
5452 if (r != null) {
5453 mRecentTasks.remove(r.task);
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005454 cleanUpRemovedTaskLocked(r,
5455 (flags&ActivityManager.REMOVE_TASK_KILL_PROCESS) != 0);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005456 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005457 } else {
5458 TaskRecord tr = null;
5459 int i=0;
5460 while (i < mRecentTasks.size()) {
5461 TaskRecord t = mRecentTasks.get(i);
5462 if (t.taskId == taskId) {
5463 tr = t;
5464 break;
5465 }
5466 i++;
5467 }
5468 if (tr != null) {
5469 if (tr.numActivities <= 0) {
5470 // Caller is just removing a recent task that is
5471 // not actively running. That is easy!
5472 mRecentTasks.remove(i);
5473 } else {
5474 Slog.w(TAG, "removeTask: task " + taskId
5475 + " does not have activities to remove, "
5476 + " but numActivities=" + tr.numActivities
5477 + ": " + tr);
5478 }
5479 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005480 }
5481 } finally {
5482 Binder.restoreCallingIdentity(ident);
5483 }
5484 }
5485 return false;
5486 }
Dianne Hackbornd94df452011-02-16 18:53:31 -08005487
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005488 private final int findAffinityTaskTopLocked(int startIndex, String affinity) {
5489 int j;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005490 TaskRecord startTask = ((ActivityRecord)mMainStack.mHistory.get(startIndex)).task;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005491 TaskRecord jt = startTask;
5492
5493 // First look backwards
5494 for (j=startIndex-1; j>=0; j--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005495 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005496 if (r.task != jt) {
5497 jt = r.task;
5498 if (affinity.equals(jt.affinity)) {
5499 return j;
5500 }
5501 }
5502 }
5503
5504 // Now look forwards
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005505 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005506 jt = startTask;
5507 for (j=startIndex+1; j<N; j++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005508 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005509 if (r.task != jt) {
5510 if (affinity.equals(jt.affinity)) {
5511 return j;
5512 }
5513 jt = r.task;
5514 }
5515 }
5516
5517 // Might it be at the top?
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005518 if (affinity.equals(((ActivityRecord)mMainStack.mHistory.get(N-1)).task.affinity)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005519 return N-1;
5520 }
5521
5522 return -1;
5523 }
5524
5525 /**
Dianne Hackbornb06ea702009-07-13 13:07:51 -07005526 * TODO: Add mController hook
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005527 */
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005528 public void moveTaskToFront(int task, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005529 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5530 "moveTaskToFront()");
5531
5532 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005533 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5534 Binder.getCallingUid(), "Task to front")) {
5535 return;
5536 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005537 final long origId = Binder.clearCallingIdentity();
5538 try {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005539 TaskRecord tr = taskForIdLocked(task);
5540 if (tr != null) {
5541 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5542 mMainStack.mUserLeaving = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005543 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005544 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5545 // Caller wants the home activity moved with it. To accomplish this,
5546 // we'll just move the home task to the top first.
5547 mMainStack.moveHomeToFrontLocked();
5548 }
5549 mMainStack.moveTaskToFrontLocked(tr, null);
5550 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005551 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005552 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
5553 ActivityRecord hr = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005554 if (hr.task.taskId == task) {
Dianne Hackbornd94df452011-02-16 18:53:31 -08005555 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5556 mMainStack.mUserLeaving = true;
5557 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005558 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5559 // Caller wants the home activity moved with it. To accomplish this,
5560 // we'll just move the home task to the top first.
5561 mMainStack.moveHomeToFrontLocked();
5562 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005563 mMainStack.moveTaskToFrontLocked(hr.task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005564 return;
5565 }
5566 }
5567 } finally {
5568 Binder.restoreCallingIdentity(origId);
5569 }
5570 }
5571 }
5572
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005573 public void moveTaskToBack(int task) {
5574 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5575 "moveTaskToBack()");
5576
5577 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005578 if (mMainStack.mResumedActivity != null
5579 && mMainStack.mResumedActivity.task.taskId == task) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005580 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5581 Binder.getCallingUid(), "Task to back")) {
5582 return;
5583 }
5584 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005585 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005586 mMainStack.moveTaskToBackLocked(task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005587 Binder.restoreCallingIdentity(origId);
5588 }
5589 }
5590
5591 /**
5592 * Moves an activity, and all of the other activities within the same task, to the bottom
5593 * of the history stack. The activity's order within the task is unchanged.
5594 *
5595 * @param token A reference to the activity we wish to move
5596 * @param nonRoot If false then this only works if the activity is the root
5597 * of a task; if true it will work for any activity in a task.
5598 * @return Returns true if the move completed, false if not.
5599 */
5600 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005601 enforceNotIsolatedCaller("moveActivityTaskToBack");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005602 synchronized(this) {
5603 final long origId = Binder.clearCallingIdentity();
5604 int taskId = getTaskForActivityLocked(token, !nonRoot);
5605 if (taskId >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005606 return mMainStack.moveTaskToBackLocked(taskId, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005607 }
5608 Binder.restoreCallingIdentity(origId);
5609 }
5610 return false;
5611 }
5612
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005613 public void moveTaskBackwards(int task) {
5614 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5615 "moveTaskBackwards()");
5616
5617 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005618 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5619 Binder.getCallingUid(), "Task backwards")) {
5620 return;
5621 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005622 final long origId = Binder.clearCallingIdentity();
5623 moveTaskBackwardsLocked(task);
5624 Binder.restoreCallingIdentity(origId);
5625 }
5626 }
5627
5628 private final void moveTaskBackwardsLocked(int task) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005629 Slog.e(TAG, "moveTaskBackwards not yet implemented!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005630 }
5631
5632 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
5633 synchronized(this) {
5634 return getTaskForActivityLocked(token, onlyRoot);
5635 }
5636 }
5637
5638 int getTaskForActivityLocked(IBinder token, boolean onlyRoot) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005639 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005640 TaskRecord lastTask = null;
5641 for (int i=0; i<N; i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005642 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005643 if (r.appToken == token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005644 if (!onlyRoot || lastTask != r.task) {
5645 return r.task.taskId;
5646 }
5647 return -1;
5648 }
5649 lastTask = r.task;
5650 }
5651
5652 return -1;
5653 }
5654
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005655 // =========================================================
5656 // THUMBNAILS
5657 // =========================================================
5658
5659 public void reportThumbnail(IBinder token,
5660 Bitmap thumbnail, CharSequence description) {
5661 //System.out.println("Report thumbnail for " + token + ": " + thumbnail);
5662 final long origId = Binder.clearCallingIdentity();
5663 sendPendingThumbnail(null, token, thumbnail, description, true);
5664 Binder.restoreCallingIdentity(origId);
5665 }
5666
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005667 final void sendPendingThumbnail(ActivityRecord r, IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005668 Bitmap thumbnail, CharSequence description, boolean always) {
5669 TaskRecord task = null;
5670 ArrayList receivers = null;
5671
5672 //System.out.println("Send pending thumbnail: " + r);
5673
5674 synchronized(this) {
5675 if (r == null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07005676 r = mMainStack.isInStackLocked(token);
5677 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005678 return;
5679 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005680 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005681 if (thumbnail == null && r.thumbHolder != null) {
5682 thumbnail = r.thumbHolder.lastThumbnail;
5683 description = r.thumbHolder.lastDescription;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005684 }
5685 if (thumbnail == null && !always) {
5686 // If there is no thumbnail, and this entry is not actually
5687 // going away, then abort for now and pick up the next
5688 // thumbnail we get.
5689 return;
5690 }
5691 task = r.task;
5692
5693 int N = mPendingThumbnails.size();
5694 int i=0;
5695 while (i<N) {
5696 PendingThumbnailsRecord pr =
5697 (PendingThumbnailsRecord)mPendingThumbnails.get(i);
5698 //System.out.println("Looking in " + pr.pendingRecords);
5699 if (pr.pendingRecords.remove(r)) {
5700 if (receivers == null) {
5701 receivers = new ArrayList();
5702 }
5703 receivers.add(pr);
5704 if (pr.pendingRecords.size() == 0) {
5705 pr.finished = true;
5706 mPendingThumbnails.remove(i);
5707 N--;
5708 continue;
5709 }
5710 }
5711 i++;
5712 }
5713 }
5714
5715 if (receivers != null) {
5716 final int N = receivers.size();
5717 for (int i=0; i<N; i++) {
5718 try {
5719 PendingThumbnailsRecord pr =
5720 (PendingThumbnailsRecord)receivers.get(i);
5721 pr.receiver.newThumbnail(
5722 task != null ? task.taskId : -1, thumbnail, description);
5723 if (pr.finished) {
5724 pr.receiver.finished();
5725 }
5726 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005727 Slog.w(TAG, "Exception thrown when sending thumbnail", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005728 }
5729 }
5730 }
5731 }
5732
5733 // =========================================================
5734 // CONTENT PROVIDERS
5735 // =========================================================
5736
Jeff Brown10e89712011-07-08 18:52:57 -07005737 private final List<ProviderInfo> generateApplicationProvidersLocked(ProcessRecord app) {
5738 List<ProviderInfo> providers = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005739 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005740 providers = AppGlobals.getPackageManager().
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005741 queryContentProviders(app.processName, app.uid,
Dianne Hackborn1655be42009-05-08 14:29:01 -07005742 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005743 } catch (RemoteException ex) {
5744 }
Amith Yamasani742a6712011-05-04 14:49:28 -07005745 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005746 Slog.v(TAG_MU, "generateApplicationProvidersLocked, app.info.uid = " + app.uid);
5747 int userId = app.userId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005748 if (providers != null) {
5749 final int N = providers.size();
5750 for (int i=0; i<N; i++) {
5751 ProviderInfo cpi =
5752 (ProviderInfo)providers.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005753
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07005754 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07005755 ContentProviderRecord cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005756 if (cpr == null) {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08005757 cpr = new ContentProviderRecord(this, cpi, app.info, comp);
Amith Yamasani742a6712011-05-04 14:49:28 -07005758 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005759 }
Amith Yamasani742a6712011-05-04 14:49:28 -07005760 if (DEBUG_MU)
5761 Slog.v(TAG_MU, "generateApplicationProvidersLocked, cpi.uid = " + cpr.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005762 app.pubProviders.put(cpi.name, cpr);
5763 app.addPackage(cpi.applicationInfo.packageName);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07005764 ensurePackageDexOpt(cpi.applicationInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005765 }
5766 }
5767 return providers;
5768 }
5769
5770 private final String checkContentProviderPermissionLocked(
Dianne Hackbornb424b632010-08-18 15:59:05 -07005771 ProviderInfo cpi, ProcessRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005772 final int callingPid = (r != null) ? r.pid : Binder.getCallingPid();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005773 final int callingUid = (r != null) ? r.uid : Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005774 if (checkComponentPermission(cpi.readPermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005775 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005776 == PackageManager.PERMISSION_GRANTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005777 return null;
5778 }
5779 if (checkComponentPermission(cpi.writePermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005780 cpi.applicationInfo.uid, cpi.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005781 == PackageManager.PERMISSION_GRANTED) {
5782 return null;
5783 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07005784
5785 PathPermission[] pps = cpi.pathPermissions;
5786 if (pps != null) {
5787 int i = pps.length;
5788 while (i > 0) {
5789 i--;
5790 PathPermission pp = pps[i];
5791 if (checkComponentPermission(pp.getReadPermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005792 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005793 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07005794 return null;
5795 }
5796 if (checkComponentPermission(pp.getWritePermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005797 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackborn2af632f2009-07-08 14:56:37 -07005798 == PackageManager.PERMISSION_GRANTED) {
5799 return null;
5800 }
5801 }
5802 }
5803
Dianne Hackbornb424b632010-08-18 15:59:05 -07005804 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(callingUid);
5805 if (perms != null) {
5806 for (Map.Entry<Uri, UriPermission> uri : perms.entrySet()) {
5807 if (uri.getKey().getAuthority().equals(cpi.authority)) {
5808 return null;
5809 }
5810 }
5811 }
5812
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005813 String msg;
5814 if (!cpi.exported) {
5815 msg = "Permission Denial: opening provider " + cpi.name
5816 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
5817 + ", uid=" + callingUid + ") that is not exported from uid "
5818 + cpi.applicationInfo.uid;
5819 } else {
5820 msg = "Permission Denial: opening provider " + cpi.name
5821 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
5822 + ", uid=" + callingUid + ") requires "
5823 + cpi.readPermission + " or " + cpi.writePermission;
5824 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08005825 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005826 return msg;
5827 }
5828
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08005829 boolean incProviderCount(ProcessRecord r, final ContentProviderRecord cpr,
5830 IBinder externalProcessToken) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005831 if (r != null) {
5832 Integer cnt = r.conProviders.get(cpr);
5833 if (DEBUG_PROVIDER) Slog.v(TAG,
5834 "Adding provider requested by "
5835 + r.processName + " from process "
5836 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
5837 + " cnt=" + (cnt == null ? 1 : cnt));
5838 if (cnt == null) {
5839 cpr.clients.add(r);
5840 r.conProviders.put(cpr, new Integer(1));
5841 return true;
5842 } else {
5843 r.conProviders.put(cpr, new Integer(cnt.intValue()+1));
5844 }
5845 } else {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08005846 cpr.addExternalProcessHandleLocked(externalProcessToken);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005847 }
5848 return false;
5849 }
5850
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08005851 boolean decProviderCount(ProcessRecord r, final ContentProviderRecord cpr,
5852 IBinder externalProcessToken) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005853 if (r != null) {
5854 Integer cnt = r.conProviders.get(cpr);
5855 if (DEBUG_PROVIDER) Slog.v(TAG,
5856 "Removing provider requested by "
5857 + r.processName + " from process "
5858 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
5859 + " cnt=" + cnt);
5860 if (cnt == null || cnt.intValue() <= 1) {
5861 cpr.clients.remove(r);
5862 r.conProviders.remove(cpr);
5863 return true;
5864 } else {
5865 r.conProviders.put(cpr, new Integer(cnt.intValue()-1));
5866 }
5867 } else {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08005868 cpr.removeExternalProcessHandleLocked(externalProcessToken);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005869 }
5870 return false;
5871 }
5872
Amith Yamasani742a6712011-05-04 14:49:28 -07005873 private final ContentProviderHolder getContentProviderImpl(IApplicationThread caller,
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08005874 String name, IBinder token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005875 ContentProviderRecord cpr;
5876 ProviderInfo cpi = null;
5877
5878 synchronized(this) {
5879 ProcessRecord r = null;
5880 if (caller != null) {
5881 r = getRecordForAppLocked(caller);
5882 if (r == null) {
5883 throw new SecurityException(
5884 "Unable to find app for caller " + caller
5885 + " (pid=" + Binder.getCallingPid()
5886 + ") when getting content provider " + name);
5887 }
5888 }
5889
5890 // First check if this content provider has been published...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005891 int userId = UserId.getUserId(r != null ? r.uid : Binder.getCallingUid());
Amith Yamasani742a6712011-05-04 14:49:28 -07005892 cpr = mProviderMap.getProviderByName(name, userId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005893 boolean providerRunning = cpr != null;
5894 if (providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005895 cpi = cpr.info;
Dianne Hackbornb424b632010-08-18 15:59:05 -07005896 String msg;
5897 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
5898 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005899 }
5900
5901 if (r != null && cpr.canRunHere(r)) {
5902 // This provider has been published or is in the process
5903 // of being published... but it is also allowed to run
5904 // in the caller's process, so don't make a connection
5905 // and just let the caller instantiate its own instance.
5906 if (cpr.provider != null) {
5907 // don't give caller the provider object, it needs
5908 // to make its own.
5909 cpr = new ContentProviderRecord(cpr);
5910 }
5911 return cpr;
5912 }
5913
5914 final long origId = Binder.clearCallingIdentity();
5915
Dianne Hackborna1e989b2009-09-01 19:54:29 -07005916 // In this case the provider instance already exists, so we can
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005917 // return it right away.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08005918 final boolean countChanged = incProviderCount(r, cpr, token);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005919 if (countChanged) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07005920 if (cpr.proc != null && r.setAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005921 // If this is a perceptible app accessing the provider,
Dianne Hackborn906497c2010-05-10 15:57:38 -07005922 // make sure to count it as being accessed and thus
5923 // back up on the LRU list. This is good because
5924 // content providers are often expensive to start.
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07005925 updateLruProcessLocked(cpr.proc, false, true);
Dianne Hackborn906497c2010-05-10 15:57:38 -07005926 }
Dianne Hackborn6f86c0e2010-05-11 14:20:52 -07005927 }
5928
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07005929 if (cpr.proc != null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005930 if (false) {
5931 if (cpr.name.flattenToShortString().equals(
5932 "com.android.providers.calendar/.CalendarProvider2")) {
5933 Slog.v(TAG, "****************** KILLING "
5934 + cpr.name.flattenToShortString());
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07005935 Process.killProcess(cpr.proc.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005936 }
5937 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07005938 boolean success = updateOomAdjLocked(cpr.proc);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005939 if (DEBUG_PROVIDER) Slog.i(TAG, "Adjust success: " + success);
5940 // NOTE: there is still a race here where a signal could be
5941 // pending on the process even though we managed to update its
5942 // adj level. Not sure what to do about this, but at least
5943 // the race is now smaller.
5944 if (!success) {
5945 // Uh oh... it looks like the provider's process
5946 // has been killed on us. We need to wait for a new
5947 // process to be started, and make sure its death
5948 // doesn't kill our process.
5949 Slog.i(TAG,
5950 "Existing provider " + cpr.name.flattenToShortString()
5951 + " is crashing; detaching " + r);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08005952 boolean lastRef = decProviderCount(r, cpr, token);
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07005953 appDiedLocked(cpr.proc, cpr.proc.pid, cpr.proc.thread);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005954 if (!lastRef) {
5955 // This wasn't the last ref our process had on
5956 // the provider... we have now been killed, bail.
5957 return null;
5958 }
5959 providerRunning = false;
5960 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005961 }
5962
5963 Binder.restoreCallingIdentity(origId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005964 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005965
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005966 if (!providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005967 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005968 cpi = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07005969 resolveContentProvider(name,
5970 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005971 } catch (RemoteException ex) {
5972 }
5973 if (cpi == null) {
5974 return null;
5975 }
5976
Amith Yamasani742a6712011-05-04 14:49:28 -07005977 cpi.applicationInfo = getAppInfoForUser(cpi.applicationInfo,
5978 Binder.getOrigCallingUser());
5979
Dianne Hackbornb424b632010-08-18 15:59:05 -07005980 String msg;
5981 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
5982 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005983 }
5984
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07005985 if (!mProcessesReady && !mDidUpdate && !mWaitingUpdate
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08005986 && !cpi.processName.equals("system")) {
5987 // If this content provider does not run in the system
5988 // process, and the system is not yet ready to run other
5989 // processes, then fail fast instead of hanging.
5990 throw new IllegalArgumentException(
5991 "Attempt to launch content provider before system ready");
5992 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07005993
5994 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07005995 cpr = mProviderMap.getProviderByClass(comp, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005996 final boolean firstClass = cpr == null;
5997 if (firstClass) {
5998 try {
5999 ApplicationInfo ai =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006000 AppGlobals.getPackageManager().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006001 getApplicationInfo(
6002 cpi.applicationInfo.packageName,
Dianne Hackborn1655be42009-05-08 14:29:01 -07006003 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006004 if (ai == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006005 Slog.w(TAG, "No package info for content provider "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006006 + cpi.name);
6007 return null;
6008 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006009 ai = getAppInfoForUser(ai, Binder.getOrigCallingUser());
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006010 cpr = new ContentProviderRecord(this, cpi, ai, comp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006011 } catch (RemoteException ex) {
6012 // pm is in same process, this will never happen.
6013 }
6014 }
6015
6016 if (r != null && cpr.canRunHere(r)) {
6017 // If this is a multiprocess provider, then just return its
6018 // info and allow the caller to instantiate it. Only do
6019 // this if the provider is the same user as the caller's
6020 // process, or can run as root (so can be in any process).
6021 return cpr;
6022 }
6023
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006024 if (DEBUG_PROVIDER) {
6025 RuntimeException e = new RuntimeException("here");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006026 Slog.w(TAG, "LAUNCHING REMOTE PROVIDER (myuid " + r.uid
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006027 + " pruid " + cpr.appInfo.uid + "): " + cpr.info.name, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006028 }
6029
6030 // This is single process, and our app is now connecting to it.
6031 // See if we are already in the process of launching this
6032 // provider.
6033 final int N = mLaunchingProviders.size();
6034 int i;
6035 for (i=0; i<N; i++) {
6036 if (mLaunchingProviders.get(i) == cpr) {
6037 break;
6038 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006039 }
6040
6041 // If the provider is not already being launched, then get it
6042 // started.
6043 if (i >= N) {
6044 final long origId = Binder.clearCallingIdentity();
Dianne Hackborne7f97212011-02-24 14:40:20 -08006045
6046 try {
6047 // Content provider is now in use, its package can't be stopped.
6048 try {
6049 AppGlobals.getPackageManager().setPackageStoppedState(
6050 cpr.appInfo.packageName, false);
6051 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006052 } catch (IllegalArgumentException e) {
6053 Slog.w(TAG, "Failed trying to unstop package "
6054 + cpr.appInfo.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006055 }
6056
6057 ProcessRecord proc = startProcessLocked(cpi.processName,
6058 cpr.appInfo, false, 0, "content provider",
6059 new ComponentName(cpi.applicationInfo.packageName,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006060 cpi.name), false, false);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006061 if (proc == null) {
6062 Slog.w(TAG, "Unable to launch app "
6063 + cpi.applicationInfo.packageName + "/"
6064 + cpi.applicationInfo.uid + " for provider "
6065 + name + ": process is bad");
6066 return null;
6067 }
6068 cpr.launchingApp = proc;
6069 mLaunchingProviders.add(cpr);
6070 } finally {
6071 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006072 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006073 }
6074
6075 // Make sure the provider is published (the same provider class
6076 // may be published under multiple names).
6077 if (firstClass) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006078 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006079 }
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006080
Amith Yamasani742a6712011-05-04 14:49:28 -07006081 mProviderMap.putProviderByName(name, cpr);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006082 incProviderCount(r, cpr, token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006083 }
6084 }
6085
6086 // Wait for the provider to be published...
6087 synchronized (cpr) {
6088 while (cpr.provider == null) {
6089 if (cpr.launchingApp == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006090 Slog.w(TAG, "Unable to launch app "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006091 + cpi.applicationInfo.packageName + "/"
6092 + cpi.applicationInfo.uid + " for provider "
6093 + name + ": launching app became null");
Doug Zongker2bec3d42009-12-04 12:52:44 -08006094 EventLog.writeEvent(EventLogTags.AM_PROVIDER_LOST_PROCESS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006095 cpi.applicationInfo.packageName,
6096 cpi.applicationInfo.uid, name);
6097 return null;
6098 }
6099 try {
Amith Yamasani742a6712011-05-04 14:49:28 -07006100 if (DEBUG_MU) {
6101 Slog.v(TAG_MU, "Waiting to start provider " + cpr + " launchingApp="
6102 + cpr.launchingApp);
6103 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006104 cpr.wait();
6105 } catch (InterruptedException ex) {
6106 }
6107 }
6108 }
6109 return cpr;
6110 }
6111
6112 public final ContentProviderHolder getContentProvider(
6113 IApplicationThread caller, String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006114 enforceNotIsolatedCaller("getContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006115 if (caller == null) {
6116 String msg = "null IApplicationThread when getting content provider "
6117 + name;
Joe Onorato8a9b2202010-02-26 18:56:32 -08006118 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006119 throw new SecurityException(msg);
6120 }
6121
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006122 return getContentProviderImpl(caller, name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006123 }
6124
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006125 public ContentProviderHolder getContentProviderExternal(String name, IBinder token) {
6126 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6127 "Do not have permission in call getContentProviderExternal()");
6128 return getContentProviderExternalUnchecked(name, token);
6129 }
6130
6131 private ContentProviderHolder getContentProviderExternalUnchecked(String name,IBinder token) {
6132 return getContentProviderImpl(null, name, token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006133 }
6134
6135 /**
6136 * Drop a content provider from a ProcessRecord's bookkeeping
6137 * @param cpr
6138 */
6139 public void removeContentProvider(IApplicationThread caller, String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006140 enforceNotIsolatedCaller("removeContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006141 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006142 int userId = UserId.getUserId(Binder.getCallingUid());
6143 ContentProviderRecord cpr = mProviderMap.getProviderByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006144 if(cpr == null) {
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006145 // remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006146 if (DEBUG_PROVIDER) Slog.v(TAG, name +
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006147 " provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006148 return;
6149 }
6150 final ProcessRecord r = getRecordForAppLocked(caller);
6151 if (r == null) {
6152 throw new SecurityException(
6153 "Unable to find app for caller " + caller +
6154 " when removing content provider " + name);
6155 }
6156 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006157 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006158 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp, userId);
6159 if (DEBUG_PROVIDER) Slog.v(TAG, "Removing provider requested by "
6160 + r.info.processName + " from process "
6161 + localCpr.appInfo.processName);
6162 if (localCpr.launchingApp == r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006163 //should not happen. taken care of as a local provider
Joe Onorato8a9b2202010-02-26 18:56:32 -08006164 Slog.w(TAG, "removeContentProvider called on local provider: "
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006165 + cpr.info.name + " in process " + r.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006166 return;
6167 } else {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006168 if (decProviderCount(r, localCpr, null)) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006169 updateOomAdjLocked();
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07006170 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006171 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006172 }
6173 }
6174
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006175 public void removeContentProviderExternal(String name, IBinder token) {
6176 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6177 "Do not have permission in call removeContentProviderExternal()");
6178 removeContentProviderExternalUnchecked(name, token);
6179 }
6180
6181 private void removeContentProviderExternalUnchecked(String name, IBinder token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006182 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006183 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
6184 Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006185 if(cpr == null) {
6186 //remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006187 if(localLOGV) Slog.v(TAG, name+" content provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006188 return;
6189 }
6190
6191 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006192 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006193 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp,
6194 Binder.getOrigCallingUser());
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006195 if (localCpr.hasExternalProcessHandles()) {
6196 if (localCpr.removeExternalProcessHandleLocked(token)) {
6197 updateOomAdjLocked();
6198 } else {
6199 Slog.e(TAG, "Attmpt to remove content provider " + localCpr
6200 + " with no external reference for token: "
6201 + token + ".");
6202 }
6203 } else {
6204 Slog.e(TAG, "Attmpt to remove content provider: " + localCpr
6205 + " with no external references.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006206 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006207 }
6208 }
6209
6210 public final void publishContentProviders(IApplicationThread caller,
6211 List<ContentProviderHolder> providers) {
6212 if (providers == null) {
6213 return;
6214 }
6215
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006216 enforceNotIsolatedCaller("publishContentProviders");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006217 synchronized(this) {
6218 final ProcessRecord r = getRecordForAppLocked(caller);
Amith Yamasani742a6712011-05-04 14:49:28 -07006219 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006220 Slog.v(TAG_MU, "ProcessRecord uid = " + r.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006221 if (r == null) {
6222 throw new SecurityException(
6223 "Unable to find app for caller " + caller
6224 + " (pid=" + Binder.getCallingPid()
6225 + ") when publishing content providers");
6226 }
6227
6228 final long origId = Binder.clearCallingIdentity();
6229
6230 final int N = providers.size();
6231 for (int i=0; i<N; i++) {
6232 ContentProviderHolder src = providers.get(i);
6233 if (src == null || src.info == null || src.provider == null) {
6234 continue;
6235 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07006236 ContentProviderRecord dst = r.pubProviders.get(src.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006237 if (DEBUG_MU)
6238 Slog.v(TAG_MU, "ContentProviderRecord uid = " + dst.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006239 if (dst != null) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006240 ComponentName comp = new ComponentName(dst.info.packageName, dst.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006241 mProviderMap.putProviderByClass(comp, dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006242 String names[] = dst.info.authority.split(";");
6243 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006244 mProviderMap.putProviderByName(names[j], dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006245 }
6246
6247 int NL = mLaunchingProviders.size();
6248 int j;
6249 for (j=0; j<NL; j++) {
6250 if (mLaunchingProviders.get(j) == dst) {
6251 mLaunchingProviders.remove(j);
6252 j--;
6253 NL--;
6254 }
6255 }
6256 synchronized (dst) {
6257 dst.provider = src.provider;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006258 dst.proc = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006259 dst.notifyAll();
6260 }
6261 updateOomAdjLocked(r);
6262 }
6263 }
6264
6265 Binder.restoreCallingIdentity(origId);
6266 }
6267 }
6268
6269 public static final void installSystemProviders() {
Jeff Brown10e89712011-07-08 18:52:57 -07006270 List<ProviderInfo> providers;
Josh Bartel2ecce342010-02-25 10:55:48 -06006271 synchronized (mSelf) {
6272 ProcessRecord app = mSelf.mProcessNames.get("system", Process.SYSTEM_UID);
6273 providers = mSelf.generateApplicationProvidersLocked(app);
Dianne Hackborn5c83a5f2010-03-12 16:46:46 -08006274 if (providers != null) {
6275 for (int i=providers.size()-1; i>=0; i--) {
6276 ProviderInfo pi = (ProviderInfo)providers.get(i);
6277 if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6278 Slog.w(TAG, "Not installing system proc provider " + pi.name
6279 + ": not system .apk");
6280 providers.remove(i);
6281 }
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006282 }
6283 }
6284 }
Josh Bartel2ecce342010-02-25 10:55:48 -06006285 if (providers != null) {
6286 mSystemThread.installSystemProviders(providers);
6287 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08006288
6289 mSelf.mCoreSettingsObserver = new CoreSettingsObserver(mSelf);
Mark Brophyc6350272011-08-05 16:16:39 +01006290
6291 mSelf.mUsageStatsService.monitorPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006292 }
6293
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006294 /**
6295 * Allows app to retrieve the MIME type of a URI without having permission
6296 * to access its content provider.
6297 *
6298 * CTS tests for this functionality can be run with "runtest cts-appsecurity".
6299 *
6300 * Test cases are at cts/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/
6301 * src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java
6302 */
6303 public String getProviderMimeType(Uri uri) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006304 enforceNotIsolatedCaller("getProviderMimeType");
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006305 final String name = uri.getAuthority();
6306 final long ident = Binder.clearCallingIdentity();
6307 ContentProviderHolder holder = null;
6308
6309 try {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006310 holder = getContentProviderExternalUnchecked(name, null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006311 if (holder != null) {
6312 return holder.provider.getType(uri);
6313 }
6314 } catch (RemoteException e) {
6315 Log.w(TAG, "Content provider dead retrieving " + uri, e);
6316 return null;
6317 } finally {
6318 if (holder != null) {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006319 removeContentProviderExternalUnchecked(name, null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006320 }
6321 Binder.restoreCallingIdentity(ident);
6322 }
6323
6324 return null;
6325 }
6326
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006327 // =========================================================
6328 // GLOBAL MANAGEMENT
6329 // =========================================================
6330
6331 final ProcessRecord newProcessRecordLocked(IApplicationThread thread,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006332 ApplicationInfo info, String customProcess, boolean isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006333 String proc = customProcess != null ? customProcess : info.processName;
6334 BatteryStatsImpl.Uid.Proc ps = null;
6335 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006336 int uid = info.uid;
6337 if (isolated) {
6338 int userId = UserId.getUserId(uid);
6339 int stepsLeft = Process.LAST_ISOLATED_UID - Process.FIRST_ISOLATED_UID + 1;
6340 uid = 0;
6341 while (true) {
6342 if (mNextIsolatedProcessUid < Process.FIRST_ISOLATED_UID
6343 || mNextIsolatedProcessUid > Process.LAST_ISOLATED_UID) {
6344 mNextIsolatedProcessUid = Process.FIRST_ISOLATED_UID;
6345 }
6346 uid = UserId.getUid(userId, mNextIsolatedProcessUid);
6347 mNextIsolatedProcessUid++;
6348 if (mIsolatedProcesses.indexOfKey(uid) < 0) {
6349 // No process for this uid, use it.
6350 break;
6351 }
6352 stepsLeft--;
6353 if (stepsLeft <= 0) {
6354 return null;
6355 }
6356 }
6357 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006358 synchronized (stats) {
6359 ps = stats.getProcessStatsLocked(info.uid, proc);
6360 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006361 return new ProcessRecord(ps, thread, info, proc, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006362 }
6363
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006364 final ProcessRecord addAppLocked(ApplicationInfo info, boolean isolated) {
6365 ProcessRecord app;
6366 if (!isolated) {
6367 app = getProcessRecordLocked(info.processName, info.uid);
6368 } else {
6369 app = null;
6370 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006371
6372 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006373 app = newProcessRecordLocked(null, info, null, isolated);
6374 mProcessNames.put(info.processName, app.uid, app);
6375 if (isolated) {
6376 mIsolatedProcesses.put(app.uid, app);
6377 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08006378 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006379 }
6380
Dianne Hackborne7f97212011-02-24 14:40:20 -08006381 // This package really, really can not be stopped.
6382 try {
6383 AppGlobals.getPackageManager().setPackageStoppedState(
6384 info.packageName, false);
6385 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006386 } catch (IllegalArgumentException e) {
6387 Slog.w(TAG, "Failed trying to unstop package "
6388 + info.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006389 }
6390
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006391 if ((info.flags&(ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT))
6392 == (ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT)) {
6393 app.persistent = true;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07006394 app.maxAdj = ProcessList.PERSISTENT_PROC_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006395 }
6396 if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) {
6397 mPersistentStartingProcesses.add(app);
6398 startProcessLocked(app, "added application", app.processName);
6399 }
6400
6401 return app;
6402 }
6403
6404 public void unhandledBack() {
6405 enforceCallingPermission(android.Manifest.permission.FORCE_BACK,
6406 "unhandledBack()");
6407
6408 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006409 int count = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08006410 if (DEBUG_SWITCH) Slog.d(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006411 TAG, "Performing unhandledBack(): stack size = " + count);
6412 if (count > 1) {
6413 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006414 mMainStack.finishActivityLocked((ActivityRecord)mMainStack.mHistory.get(count-1),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006415 count-1, Activity.RESULT_CANCELED, null, "unhandled-back");
6416 Binder.restoreCallingIdentity(origId);
6417 }
6418 }
6419 }
6420
6421 public ParcelFileDescriptor openContentUri(Uri uri) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006422 enforceNotIsolatedCaller("openContentUri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006423 String name = uri.getAuthority();
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006424 ContentProviderHolder cph = getContentProviderExternalUnchecked(name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006425 ParcelFileDescriptor pfd = null;
6426 if (cph != null) {
6427 // We record the binder invoker's uid in thread-local storage before
6428 // going to the content provider to open the file. Later, in the code
6429 // that handles all permissions checks, we look for this uid and use
6430 // that rather than the Activity Manager's own uid. The effect is that
6431 // we do the check against the caller's permissions even though it looks
6432 // to the content provider like the Activity Manager itself is making
6433 // the request.
6434 sCallerIdentity.set(new Identity(
6435 Binder.getCallingPid(), Binder.getCallingUid()));
6436 try {
6437 pfd = cph.provider.openFile(uri, "r");
6438 } catch (FileNotFoundException e) {
6439 // do nothing; pfd will be returned null
6440 } finally {
6441 // Ensure that whatever happens, we clean up the identity state
6442 sCallerIdentity.remove();
6443 }
6444
6445 // We've got the fd now, so we're done with the provider.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006446 removeContentProviderExternalUnchecked(name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006447 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006448 Slog.d(TAG, "Failed to get provider for authority '" + name + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006449 }
6450 return pfd;
6451 }
6452
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006453 // Actually is sleeping or shutting down or whatever else in the future
6454 // is an inactive state.
6455 public boolean isSleeping() {
6456 return mSleeping || mShuttingDown;
6457 }
6458
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006459 public void goingToSleep() {
6460 synchronized(this) {
6461 mSleeping = true;
6462 mWindowManager.setEventDispatching(false);
6463
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006464 mMainStack.stopIfSleepingLocked();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006465
6466 // Initialize the wake times of all processes.
Dianne Hackborn287952c2010-09-22 22:34:31 -07006467 checkExcessivePowerUsageLocked(false);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006468 mHandler.removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
6469 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07006470 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006471 }
6472 }
6473
Dianne Hackborn55280a92009-05-07 15:53:46 -07006474 public boolean shutdown(int timeout) {
6475 if (checkCallingPermission(android.Manifest.permission.SHUTDOWN)
6476 != PackageManager.PERMISSION_GRANTED) {
6477 throw new SecurityException("Requires permission "
6478 + android.Manifest.permission.SHUTDOWN);
6479 }
6480
6481 boolean timedout = false;
6482
6483 synchronized(this) {
6484 mShuttingDown = true;
6485 mWindowManager.setEventDispatching(false);
6486
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006487 if (mMainStack.mResumedActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006488 mMainStack.stopIfSleepingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07006489 final long endTime = System.currentTimeMillis() + timeout;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006490 while (mMainStack.mResumedActivity != null
Dianne Hackborncbb722e2012-02-07 18:33:49 -08006491 || mMainStack.mPausingActivities.size() > 0) {
Dianne Hackborn55280a92009-05-07 15:53:46 -07006492 long delay = endTime - System.currentTimeMillis();
6493 if (delay <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006494 Slog.w(TAG, "Activity manager shutdown timed out");
Dianne Hackborn55280a92009-05-07 15:53:46 -07006495 timedout = true;
6496 break;
6497 }
6498 try {
6499 this.wait();
6500 } catch (InterruptedException e) {
6501 }
6502 }
6503 }
6504 }
6505
6506 mUsageStatsService.shutdown();
6507 mBatteryStatsService.shutdown();
6508
6509 return timedout;
6510 }
6511
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006512 public final void activitySlept(IBinder token) {
6513 if (localLOGV) Slog.v(
6514 TAG, "Activity slept: token=" + token);
6515
6516 ActivityRecord r = null;
6517
6518 final long origId = Binder.clearCallingIdentity();
6519
6520 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006521 r = mMainStack.isInStackLocked(token);
6522 if (r != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006523 mMainStack.activitySleptLocked(r);
6524 }
6525 }
6526
6527 Binder.restoreCallingIdentity(origId);
6528 }
6529
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006530 public void wakingUp() {
6531 synchronized(this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006532 mWindowManager.setEventDispatching(true);
6533 mSleeping = false;
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006534 mMainStack.awakeFromSleepingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006535 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006536 }
6537 }
6538
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006539 public void stopAppSwitches() {
6540 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
6541 != PackageManager.PERMISSION_GRANTED) {
6542 throw new SecurityException("Requires permission "
6543 + android.Manifest.permission.STOP_APP_SWITCHES);
6544 }
6545
6546 synchronized(this) {
6547 mAppSwitchesAllowedTime = SystemClock.uptimeMillis()
6548 + APP_SWITCH_DELAY_TIME;
6549 mDidAppSwitch = false;
6550 mHandler.removeMessages(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
6551 Message msg = mHandler.obtainMessage(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
6552 mHandler.sendMessageDelayed(msg, APP_SWITCH_DELAY_TIME);
6553 }
6554 }
6555
6556 public void resumeAppSwitches() {
6557 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
6558 != PackageManager.PERMISSION_GRANTED) {
6559 throw new SecurityException("Requires permission "
6560 + android.Manifest.permission.STOP_APP_SWITCHES);
6561 }
6562
6563 synchronized(this) {
6564 // Note that we don't execute any pending app switches... we will
6565 // let those wait until either the timeout, or the next start
6566 // activity request.
6567 mAppSwitchesAllowedTime = 0;
6568 }
6569 }
6570
6571 boolean checkAppSwitchAllowedLocked(int callingPid, int callingUid,
6572 String name) {
6573 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
6574 return true;
6575 }
6576
6577 final int perm = checkComponentPermission(
6578 android.Manifest.permission.STOP_APP_SWITCHES, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006579 callingUid, -1, true);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006580 if (perm == PackageManager.PERMISSION_GRANTED) {
6581 return true;
6582 }
6583
Joe Onorato8a9b2202010-02-26 18:56:32 -08006584 Slog.w(TAG, name + " request from " + callingUid + " stopped");
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006585 return false;
6586 }
6587
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006588 public void setDebugApp(String packageName, boolean waitForDebugger,
6589 boolean persistent) {
6590 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
6591 "setDebugApp()");
6592
6593 // Note that this is not really thread safe if there are multiple
6594 // callers into it at the same time, but that's not a situation we
6595 // care about.
6596 if (persistent) {
6597 final ContentResolver resolver = mContext.getContentResolver();
6598 Settings.System.putString(
6599 resolver, Settings.System.DEBUG_APP,
6600 packageName);
6601 Settings.System.putInt(
6602 resolver, Settings.System.WAIT_FOR_DEBUGGER,
6603 waitForDebugger ? 1 : 0);
6604 }
6605
6606 synchronized (this) {
6607 if (!persistent) {
6608 mOrigDebugApp = mDebugApp;
6609 mOrigWaitForDebugger = mWaitForDebugger;
6610 }
6611 mDebugApp = packageName;
6612 mWaitForDebugger = waitForDebugger;
6613 mDebugTransient = !persistent;
6614 if (packageName != null) {
6615 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -07006616 forceStopPackageLocked(packageName, -1, false, false, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006617 Binder.restoreCallingIdentity(origId);
6618 }
6619 }
6620 }
6621
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07006622 void setProfileApp(ApplicationInfo app, String processName, String profileFile,
6623 ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
6624 synchronized (this) {
6625 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
6626 if (!isDebuggable) {
6627 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
6628 throw new SecurityException("Process not debuggable: " + app.packageName);
6629 }
6630 }
6631 mProfileApp = processName;
6632 mProfileFile = profileFile;
6633 if (mProfileFd != null) {
6634 try {
6635 mProfileFd.close();
6636 } catch (IOException e) {
6637 }
6638 mProfileFd = null;
6639 }
6640 mProfileFd = profileFd;
6641 mProfileType = 0;
6642 mAutoStopProfiler = autoStopProfiler;
6643 }
6644 }
6645
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006646 public void setAlwaysFinish(boolean enabled) {
6647 enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH,
6648 "setAlwaysFinish()");
6649
6650 Settings.System.putInt(
6651 mContext.getContentResolver(),
6652 Settings.System.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0);
6653
6654 synchronized (this) {
6655 mAlwaysFinishActivities = enabled;
6656 }
6657 }
6658
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006659 public void setActivityController(IActivityController controller) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006660 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006661 "setActivityController()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006662 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006663 mController = controller;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006664 }
6665 }
6666
Dianne Hackborn9327f4f2010-01-29 10:38:29 -08006667 public boolean isUserAMonkey() {
6668 // For now the fact that there is a controller implies
6669 // we have a monkey.
6670 synchronized (this) {
6671 return mController != null;
6672 }
6673 }
6674
Jeff Sharkeya4620792011-05-20 15:29:23 -07006675 public void registerProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08006676 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
6677 "registerProcessObserver()");
6678 synchronized (this) {
6679 mProcessObservers.register(observer);
6680 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07006681 }
6682
6683 public void unregisterProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08006684 synchronized (this) {
6685 mProcessObservers.unregister(observer);
6686 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07006687 }
6688
Daniel Sandler69a48172010-06-23 16:29:36 -04006689 public void setImmersive(IBinder token, boolean immersive) {
6690 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006691 ActivityRecord r = mMainStack.isInStackLocked(token);
6692 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04006693 throw new IllegalArgumentException();
6694 }
Daniel Sandler69a48172010-06-23 16:29:36 -04006695 r.immersive = immersive;
6696 }
6697 }
6698
6699 public boolean isImmersive(IBinder token) {
6700 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006701 ActivityRecord r = mMainStack.isInStackLocked(token);
6702 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04006703 throw new IllegalArgumentException();
6704 }
Daniel Sandler69a48172010-06-23 16:29:36 -04006705 return r.immersive;
6706 }
6707 }
6708
6709 public boolean isTopActivityImmersive() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006710 enforceNotIsolatedCaller("startActivity");
Daniel Sandler69a48172010-06-23 16:29:36 -04006711 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006712 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Daniel Sandler69a48172010-06-23 16:29:36 -04006713 return (r != null) ? r.immersive : false;
6714 }
6715 }
6716
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006717 public final void enterSafeMode() {
6718 synchronized(this) {
6719 // It only makes sense to do this before the system is ready
6720 // and started launching other packages.
6721 if (!mSystemReady) {
6722 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006723 AppGlobals.getPackageManager().enterSafeMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006724 } catch (RemoteException e) {
6725 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006726 }
6727 }
6728 }
6729
Jeff Brownb09abc12011-01-13 21:08:27 -08006730 public final void showSafeModeOverlay() {
6731 View v = LayoutInflater.from(mContext).inflate(
6732 com.android.internal.R.layout.safe_mode, null);
6733 WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
6734 lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
6735 lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
6736 lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
6737 lp.gravity = Gravity.BOTTOM | Gravity.LEFT;
6738 lp.format = v.getBackground().getOpacity();
6739 lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
6740 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
6741 ((WindowManager)mContext.getSystemService(
6742 Context.WINDOW_SERVICE)).addView(v, lp);
6743 }
6744
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006745 public void noteWakeupAlarm(IIntentSender sender) {
6746 if (!(sender instanceof PendingIntentRecord)) {
6747 return;
6748 }
6749 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
6750 synchronized (stats) {
6751 if (mBatteryStatsService.isOnBattery()) {
6752 mBatteryStatsService.enforceCallingPermission();
6753 PendingIntentRecord rec = (PendingIntentRecord)sender;
6754 int MY_UID = Binder.getCallingUid();
6755 int uid = rec.uid == MY_UID ? Process.SYSTEM_UID : rec.uid;
6756 BatteryStatsImpl.Uid.Pkg pkg =
6757 stats.getPackageStatsLocked(uid, rec.key.packageName);
6758 pkg.incWakeupsLocked();
6759 }
6760 }
6761 }
6762
Dianne Hackborn64825172011-03-02 21:32:58 -08006763 public boolean killPids(int[] pids, String pReason, boolean secure) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006764 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006765 throw new SecurityException("killPids only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006766 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006767 String reason = (pReason == null) ? "Unknown" : pReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006768 // XXX Note: don't acquire main activity lock here, because the window
6769 // manager calls in with its locks held.
6770
6771 boolean killed = false;
6772 synchronized (mPidsSelfLocked) {
6773 int[] types = new int[pids.length];
6774 int worstType = 0;
6775 for (int i=0; i<pids.length; i++) {
6776 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
6777 if (proc != null) {
6778 int type = proc.setAdj;
6779 types[i] = type;
6780 if (type > worstType) {
6781 worstType = type;
6782 }
6783 }
6784 }
6785
Dianne Hackborn64825172011-03-02 21:32:58 -08006786 // If the worst oom_adj is somewhere in the hidden proc LRU range,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006787 // then constrain it so we will kill all hidden procs.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07006788 if (worstType < ProcessList.HIDDEN_APP_MAX_ADJ
6789 && worstType > ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07006790 worstType = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006791 }
Dianne Hackborn64825172011-03-02 21:32:58 -08006792
6793 // If this is not a secure call, don't let it kill processes that
6794 // are important.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07006795 if (!secure && worstType < ProcessList.SERVICE_ADJ) {
6796 worstType = ProcessList.SERVICE_ADJ;
Dianne Hackborn64825172011-03-02 21:32:58 -08006797 }
6798
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006799 Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006800 for (int i=0; i<pids.length; i++) {
6801 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
6802 if (proc == null) {
6803 continue;
6804 }
6805 int adj = proc.setAdj;
Dianne Hackborn906497c2010-05-10 15:57:38 -07006806 if (adj >= worstType && !proc.killedBackground) {
Dianne Hackborn8633e682010-04-22 16:03:41 -07006807 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006808 EventLog.writeEvent(EventLogTags.AM_KILL, proc.pid,
6809 proc.processName, adj, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006810 killed = true;
Dianne Hackborn906497c2010-05-10 15:57:38 -07006811 proc.killedBackground = true;
6812 Process.killProcessQuiet(pids[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006813 }
6814 }
6815 }
6816 return killed;
6817 }
6818
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006819 public final void startRunning(String pkg, String cls, String action,
6820 String data) {
6821 synchronized(this) {
6822 if (mStartRunning) {
6823 return;
6824 }
6825 mStartRunning = true;
6826 mTopComponent = pkg != null && cls != null
6827 ? new ComponentName(pkg, cls) : null;
6828 mTopAction = action != null ? action : Intent.ACTION_MAIN;
6829 mTopData = data;
6830 if (!mSystemReady) {
6831 return;
6832 }
6833 }
6834
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07006835 systemReady(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006836 }
6837
6838 private void retrieveSettings() {
6839 final ContentResolver resolver = mContext.getContentResolver();
6840 String debugApp = Settings.System.getString(
6841 resolver, Settings.System.DEBUG_APP);
6842 boolean waitForDebugger = Settings.System.getInt(
6843 resolver, Settings.System.WAIT_FOR_DEBUGGER, 0) != 0;
6844 boolean alwaysFinishActivities = Settings.System.getInt(
6845 resolver, Settings.System.ALWAYS_FINISH_ACTIVITIES, 0) != 0;
6846
6847 Configuration configuration = new Configuration();
6848 Settings.System.getConfiguration(resolver, configuration);
6849
6850 synchronized (this) {
6851 mDebugApp = mOrigDebugApp = debugApp;
6852 mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger;
6853 mAlwaysFinishActivities = alwaysFinishActivities;
6854 // This happens before any activities are started, so we can
6855 // change mConfiguration in-place.
Dianne Hackborn813075a62011-11-14 17:45:19 -08006856 updateConfigurationLocked(configuration, null, false, true);
Joe Onorato8a9b2202010-02-26 18:56:32 -08006857 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Initial config: " + mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006858 }
6859 }
6860
6861 public boolean testIsSystemReady() {
6862 // no need to synchronize(this) just to read & return the value
6863 return mSystemReady;
6864 }
6865
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006866 private static File getCalledPreBootReceiversFile() {
6867 File dataDir = Environment.getDataDirectory();
6868 File systemDir = new File(dataDir, "system");
6869 File fname = new File(systemDir, "called_pre_boots.dat");
6870 return fname;
6871 }
Dianne Hackborn661cd522011-08-22 00:26:20 -07006872
6873 static final int LAST_DONE_VERSION = 10000;
6874
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006875 private static ArrayList<ComponentName> readLastDonePreBootReceivers() {
6876 ArrayList<ComponentName> lastDoneReceivers = new ArrayList<ComponentName>();
6877 File file = getCalledPreBootReceiversFile();
6878 FileInputStream fis = null;
6879 try {
6880 fis = new FileInputStream(file);
6881 DataInputStream dis = new DataInputStream(new BufferedInputStream(fis, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07006882 int fvers = dis.readInt();
6883 if (fvers == LAST_DONE_VERSION) {
6884 String vers = dis.readUTF();
6885 String codename = dis.readUTF();
6886 String build = dis.readUTF();
6887 if (android.os.Build.VERSION.RELEASE.equals(vers)
6888 && android.os.Build.VERSION.CODENAME.equals(codename)
6889 && android.os.Build.VERSION.INCREMENTAL.equals(build)) {
6890 int num = dis.readInt();
6891 while (num > 0) {
6892 num--;
6893 String pkg = dis.readUTF();
6894 String cls = dis.readUTF();
6895 lastDoneReceivers.add(new ComponentName(pkg, cls));
6896 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006897 }
6898 }
6899 } catch (FileNotFoundException e) {
6900 } catch (IOException e) {
6901 Slog.w(TAG, "Failure reading last done pre-boot receivers", e);
6902 } finally {
6903 if (fis != null) {
6904 try {
6905 fis.close();
6906 } catch (IOException e) {
6907 }
6908 }
6909 }
6910 return lastDoneReceivers;
6911 }
6912
6913 private static void writeLastDonePreBootReceivers(ArrayList<ComponentName> list) {
6914 File file = getCalledPreBootReceiversFile();
6915 FileOutputStream fos = null;
6916 DataOutputStream dos = null;
6917 try {
6918 Slog.i(TAG, "Writing new set of last done pre-boot receivers...");
6919 fos = new FileOutputStream(file);
6920 dos = new DataOutputStream(new BufferedOutputStream(fos, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07006921 dos.writeInt(LAST_DONE_VERSION);
6922 dos.writeUTF(android.os.Build.VERSION.RELEASE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006923 dos.writeUTF(android.os.Build.VERSION.CODENAME);
Dianne Hackborn661cd522011-08-22 00:26:20 -07006924 dos.writeUTF(android.os.Build.VERSION.INCREMENTAL);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006925 dos.writeInt(list.size());
6926 for (int i=0; i<list.size(); i++) {
6927 dos.writeUTF(list.get(i).getPackageName());
6928 dos.writeUTF(list.get(i).getClassName());
6929 }
6930 } catch (IOException e) {
6931 Slog.w(TAG, "Failure writing last done pre-boot receivers", e);
6932 file.delete();
6933 } finally {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07006934 FileUtils.sync(fos);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006935 if (dos != null) {
6936 try {
6937 dos.close();
6938 } catch (IOException e) {
6939 // TODO Auto-generated catch block
6940 e.printStackTrace();
6941 }
6942 }
6943 }
6944 }
6945
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07006946 public void systemReady(final Runnable goingCallback) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006947 synchronized(this) {
6948 if (mSystemReady) {
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07006949 if (goingCallback != null) goingCallback.run();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006950 return;
6951 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006952
6953 // Check to see if there are any update receivers to run.
6954 if (!mDidUpdate) {
6955 if (mWaitingUpdate) {
6956 return;
6957 }
6958 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
6959 List<ResolveInfo> ris = null;
6960 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006961 ris = AppGlobals.getPackageManager().queryIntentReceivers(
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006962 intent, null, 0);
6963 } catch (RemoteException e) {
6964 }
6965 if (ris != null) {
6966 for (int i=ris.size()-1; i>=0; i--) {
6967 if ((ris.get(i).activityInfo.applicationInfo.flags
6968 &ApplicationInfo.FLAG_SYSTEM) == 0) {
6969 ris.remove(i);
6970 }
6971 }
6972 intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006973
6974 ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers();
6975
6976 final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006977 for (int i=0; i<ris.size(); i++) {
6978 ActivityInfo ai = ris.get(i).activityInfo;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006979 ComponentName comp = new ComponentName(ai.packageName, ai.name);
6980 if (lastDoneReceivers.contains(comp)) {
6981 ris.remove(i);
6982 i--;
6983 }
6984 }
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07006985
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006986 for (int i=0; i<ris.size(); i++) {
6987 ActivityInfo ai = ris.get(i).activityInfo;
6988 ComponentName comp = new ComponentName(ai.packageName, ai.name);
6989 doneReceivers.add(comp);
6990 intent.setComponent(comp);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006991 IIntentReceiver finisher = null;
Dianne Hackbornd6847842010-01-12 18:14:19 -08006992 if (i == ris.size()-1) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006993 finisher = new IIntentReceiver.Stub() {
6994 public void performReceive(Intent intent, int resultCode,
Dianne Hackborn68d881c2009-10-05 13:58:17 -07006995 String data, Bundle extras, boolean ordered,
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006996 boolean sticky) {
6997 // The raw IIntentReceiver interface is called
6998 // with the AM lock held, so redispatch to
6999 // execute our code without the lock.
7000 mHandler.post(new Runnable() {
7001 public void run() {
7002 synchronized (ActivityManagerService.this) {
7003 mDidUpdate = true;
7004 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007005 writeLastDonePreBootReceivers(doneReceivers);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007006 showBootMessage(mContext.getText(
7007 R.string.android_upgrading_complete),
7008 false);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007009 systemReady(goingCallback);
7010 }
7011 });
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007012 }
7013 };
7014 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08007015 Slog.i(TAG, "Sending system update to: " + intent.getComponent());
Amith Yamasani742a6712011-05-04 14:49:28 -07007016 /* TODO: Send this to all users */
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007017 broadcastIntentLocked(null, null, intent, null, finisher,
Amith Yamasani742a6712011-05-04 14:49:28 -07007018 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID,
Amith Yamasanic600e21f2012-02-14 16:08:07 -08007019 0 /* UserId zero */);
Dianne Hackbornd6847842010-01-12 18:14:19 -08007020 if (finisher != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007021 mWaitingUpdate = true;
7022 }
7023 }
7024 }
7025 if (mWaitingUpdate) {
7026 return;
7027 }
7028 mDidUpdate = true;
7029 }
7030
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007031 mSystemReady = true;
7032 if (!mStartRunning) {
7033 return;
7034 }
7035 }
7036
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007037 ArrayList<ProcessRecord> procsToKill = null;
7038 synchronized(mPidsSelfLocked) {
7039 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
7040 ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7041 if (!isAllowedWhileBooting(proc.info)){
7042 if (procsToKill == null) {
7043 procsToKill = new ArrayList<ProcessRecord>();
7044 }
7045 procsToKill.add(proc);
7046 }
7047 }
7048 }
7049
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007050 synchronized(this) {
7051 if (procsToKill != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007052 for (int i=procsToKill.size()-1; i>=0; i--) {
7053 ProcessRecord proc = procsToKill.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007054 Slog.i(TAG, "Removing system update proc: " + proc);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007055 removeProcessLocked(proc, true, false, "system update done");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007056 }
7057 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007058
7059 // Now that we have cleaned up any update processes, we
7060 // are ready to start launching real processes and know that
7061 // we won't trample on them any more.
7062 mProcessesReady = true;
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007063 }
7064
Joe Onorato8a9b2202010-02-26 18:56:32 -08007065 Slog.i(TAG, "System now ready");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007066 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007067 SystemClock.uptimeMillis());
7068
7069 synchronized(this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007070 // Make sure we have no pre-ready processes sitting around.
7071
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007072 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
7073 ResolveInfo ri = mContext.getPackageManager()
7074 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST),
Dianne Hackborn1655be42009-05-08 14:29:01 -07007075 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007076 CharSequence errorMsg = null;
7077 if (ri != null) {
7078 ActivityInfo ai = ri.activityInfo;
7079 ApplicationInfo app = ai.applicationInfo;
7080 if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7081 mTopAction = Intent.ACTION_FACTORY_TEST;
7082 mTopData = null;
7083 mTopComponent = new ComponentName(app.packageName,
7084 ai.name);
7085 } else {
7086 errorMsg = mContext.getResources().getText(
7087 com.android.internal.R.string.factorytest_not_system);
7088 }
7089 } else {
7090 errorMsg = mContext.getResources().getText(
7091 com.android.internal.R.string.factorytest_no_action);
7092 }
7093 if (errorMsg != null) {
7094 mTopAction = null;
7095 mTopData = null;
7096 mTopComponent = null;
7097 Message msg = Message.obtain();
7098 msg.what = SHOW_FACTORY_ERROR_MSG;
7099 msg.getData().putCharSequence("msg", errorMsg);
7100 mHandler.sendMessage(msg);
7101 }
7102 }
7103 }
7104
7105 retrieveSettings();
7106
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007107 if (goingCallback != null) goingCallback.run();
7108
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007109 synchronized (this) {
7110 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
7111 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007112 List apps = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07007113 getPersistentApplications(STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007114 if (apps != null) {
7115 int N = apps.size();
7116 int i;
7117 for (i=0; i<N; i++) {
7118 ApplicationInfo info
7119 = (ApplicationInfo)apps.get(i);
7120 if (info != null &&
7121 !info.packageName.equals("android")) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007122 addAppLocked(info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007123 }
7124 }
7125 }
7126 } catch (RemoteException ex) {
7127 // pm is in same process, this will never happen.
7128 }
7129 }
7130
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007131 // Start up initial activity.
7132 mBooting = true;
7133
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007134 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007135 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007136 Message msg = Message.obtain();
7137 msg.what = SHOW_UID_ERROR_MSG;
7138 mHandler.sendMessage(msg);
7139 }
7140 } catch (RemoteException e) {
7141 }
7142
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007143 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007144 }
7145 }
7146
Dan Egnorb7f03672009-12-09 16:22:32 -08007147 private boolean makeAppCrashingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007148 String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007149 app.crashing = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007150 app.crashingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007151 ActivityManager.ProcessErrorStateInfo.CRASHED, null, shortMsg, longMsg, stackTrace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007152 startAppProblemLocked(app);
7153 app.stopFreezingAllLocked();
7154 return handleAppCrashLocked(app);
7155 }
7156
Dan Egnorb7f03672009-12-09 16:22:32 -08007157 private void makeAppNotRespondingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007158 String activity, String shortMsg, String longMsg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007159 app.notResponding = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007160 app.notRespondingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007161 ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING,
7162 activity, shortMsg, longMsg, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007163 startAppProblemLocked(app);
7164 app.stopFreezingAllLocked();
7165 }
7166
7167 /**
7168 * Generate a process error record, suitable for attachment to a ProcessRecord.
7169 *
7170 * @param app The ProcessRecord in which the error occurred.
7171 * @param condition Crashing, Application Not Responding, etc. Values are defined in
7172 * ActivityManager.AppErrorStateInfo
Dan Egnor60d87622009-12-16 16:32:58 -08007173 * @param activity The activity associated with the crash, if known.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007174 * @param shortMsg Short message describing the crash.
7175 * @param longMsg Long message describing the crash.
Dan Egnorb7f03672009-12-09 16:22:32 -08007176 * @param stackTrace Full crash stack trace, may be null.
7177 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007178 * @return Returns a fully-formed AppErrorStateInfo record.
7179 */
7180 private ActivityManager.ProcessErrorStateInfo generateProcessError(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007181 int condition, String activity, String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007182 ActivityManager.ProcessErrorStateInfo report = new ActivityManager.ProcessErrorStateInfo();
Dan Egnorb7f03672009-12-09 16:22:32 -08007183
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007184 report.condition = condition;
7185 report.processName = app.processName;
7186 report.pid = app.pid;
7187 report.uid = app.info.uid;
Dan Egnor60d87622009-12-16 16:32:58 -08007188 report.tag = activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007189 report.shortMsg = shortMsg;
7190 report.longMsg = longMsg;
Dan Egnorb7f03672009-12-09 16:22:32 -08007191 report.stackTrace = stackTrace;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007192
7193 return report;
7194 }
7195
Dan Egnor42471dd2010-01-07 17:25:22 -08007196 void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007197 synchronized (this) {
7198 app.crashing = false;
7199 app.crashingReport = null;
7200 app.notResponding = false;
7201 app.notRespondingReport = null;
7202 if (app.anrDialog == fromDialog) {
7203 app.anrDialog = null;
7204 }
7205 if (app.waitDialog == fromDialog) {
7206 app.waitDialog = null;
7207 }
7208 if (app.pid > 0 && app.pid != MY_PID) {
Dan Egnor42471dd2010-01-07 17:25:22 -08007209 handleAppCrashLocked(app);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007210 Slog.i(ActivityManagerService.TAG, "Killing " + app + ": user's request");
Dianne Hackborn8633e682010-04-22 16:03:41 -07007211 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
7212 app.processName, app.setAdj, "user's request after error");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007213 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007214 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007215 }
7216 }
Dan Egnor42471dd2010-01-07 17:25:22 -08007217
Dan Egnorb7f03672009-12-09 16:22:32 -08007218 private boolean handleAppCrashLocked(ProcessRecord app) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007219 long now = SystemClock.uptimeMillis();
7220
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007221 Long crashTime;
7222 if (!app.isolated) {
7223 crashTime = mProcessCrashTimes.get(app.info.processName, app.uid);
7224 } else {
7225 crashTime = null;
7226 }
Dianne Hackborn7d608422011-08-07 16:24:18 -07007227 if (crashTime != null && now < crashTime+ProcessList.MIN_CRASH_INTERVAL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007228 // This process loses!
Joe Onorato8a9b2202010-02-26 18:56:32 -08007229 Slog.w(TAG, "Process " + app.info.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007230 + " has crashed too many times: killing!");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007231 EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007232 app.info.processName, app.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007233 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
7234 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007235 if (r.app == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007236 Slog.w(TAG, " Force finishing activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007237 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007238 r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED, null, "crashed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007239 }
7240 }
7241 if (!app.persistent) {
7242 // We don't want to start this process again until the user
7243 // explicitly does so... but for persistent process, we really
7244 // need to keep it running. If a persistent process is actually
7245 // repeatedly crashing, then badness for everyone.
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007246 EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007247 app.info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007248 if (!app.isolated) {
7249 // XXX We don't have a way to mark isolated processes
7250 // as bad, since they don't have a peristent identity.
7251 mBadProcesses.put(app.info.processName, app.uid, now);
7252 mProcessCrashTimes.remove(app.info.processName, app.uid);
7253 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007254 app.bad = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007255 app.removed = true;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07007256 // Don't let services in this process be restarted and potentially
7257 // annoy the user repeatedly. Unless it is persistent, since those
7258 // processes run critical code.
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007259 removeProcessLocked(app, false, false, "crash");
Dianne Hackborncb44d962011-03-10 17:02:27 -08007260 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007261 return false;
7262 }
Dianne Hackborncb44d962011-03-10 17:02:27 -08007263 mMainStack.resumeTopActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007264 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007265 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007266 if (r.app == app) {
7267 // If the top running activity is from this crashing
7268 // process, then terminate it to avoid getting in a loop.
7269 Slog.w(TAG, " Force finishing activity "
7270 + r.intent.getComponent().flattenToShortString());
Dianne Hackbornbe707852011-11-11 14:32:10 -08007271 int index = mMainStack.indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007272 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007273 Activity.RESULT_CANCELED, null, "crashed");
Dianne Hackborn070783f2010-12-29 16:46:28 -08007274 // Also terminate any activities below it that aren't yet
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007275 // stopped, to avoid a situation where one will get
7276 // re-start our crashing activity once it gets resumed again.
7277 index--;
7278 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007279 r = (ActivityRecord)mMainStack.mHistory.get(index);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007280 if (r.state == ActivityState.RESUMED
7281 || r.state == ActivityState.PAUSING
7282 || r.state == ActivityState.PAUSED) {
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08007283 if (!r.isHomeActivity || mHomeProcess != r.app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007284 Slog.w(TAG, " Force finishing activity "
7285 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007286 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007287 Activity.RESULT_CANCELED, null, "crashed");
7288 }
7289 }
7290 }
7291 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007292 }
7293
7294 // Bump up the crash count of any services currently running in the proc.
7295 if (app.services.size() != 0) {
7296 // Any services running in the application need to be placed
7297 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -07007298 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007299 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07007300 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007301 sr.crashCount++;
7302 }
7303 }
Mattias Larssona4fd0072010-06-22 22:37:03 +02007304
7305 // If the crashing process is what we consider to be the "home process" and it has been
7306 // replaced by a third-party app, clear the package preferred activities from packages
7307 // with a home activity running in the process to prevent a repeatedly crashing app
7308 // from blocking the user to manually clear the list.
7309 if (app == mHomeProcess && mHomeProcess.activities.size() > 0
7310 && (mHomeProcess.info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
7311 Iterator it = mHomeProcess.activities.iterator();
7312 while (it.hasNext()) {
Jean-Baptiste Queru5ea89f72010-07-30 09:30:31 -07007313 ActivityRecord r = (ActivityRecord)it.next();
Mattias Larssona4fd0072010-06-22 22:37:03 +02007314 if (r.isHomeActivity) {
7315 Log.i(TAG, "Clearing package preferred activities from " + r.packageName);
7316 try {
7317 ActivityThread.getPackageManager()
7318 .clearPackagePreferredActivities(r.packageName);
7319 } catch (RemoteException c) {
7320 // pm is in same process, this will never happen.
7321 }
7322 }
7323 }
7324 }
7325
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007326 if (!app.isolated) {
7327 // XXX Can't keep track of crash times for isolated processes,
7328 // because they don't have a perisistent identity.
7329 mProcessCrashTimes.put(app.info.processName, app.uid, now);
7330 }
7331
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007332 return true;
7333 }
7334
7335 void startAppProblemLocked(ProcessRecord app) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08007336 app.errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver(
7337 mContext, app.info.packageName, app.info.flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007338 skipCurrentReceiverLocked(app);
7339 }
7340
7341 void skipCurrentReceiverLocked(ProcessRecord app) {
Christopher Tatef46723b2012-01-26 14:19:24 -08007342 for (BroadcastQueue queue : mBroadcastQueues) {
7343 queue.skipCurrentReceiverLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007344 }
7345 }
7346
Dan Egnor60d87622009-12-16 16:32:58 -08007347 /**
7348 * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes.
7349 * The application process will exit immediately after this call returns.
7350 * @param app object of the crashing app, null for the system server
7351 * @param crashInfo describing the exception
7352 */
7353 public void handleApplicationCrash(IBinder app, ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007354 ProcessRecord r = findAppProcess(app, "Crash");
Jeff Sharkeya353d262011-10-28 11:12:06 -07007355 final String processName = app == null ? "system_server"
7356 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08007357
7358 EventLog.writeEvent(EventLogTags.AM_CRASH, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07007359 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08007360 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08007361 crashInfo.exceptionClassName,
7362 crashInfo.exceptionMessage,
7363 crashInfo.throwFileName,
7364 crashInfo.throwLineNumber);
7365
Jeff Sharkeya353d262011-10-28 11:12:06 -07007366 addErrorToDropBox("crash", r, processName, null, null, null, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08007367
7368 crashApplication(r, crashInfo);
7369 }
7370
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007371 public void handleApplicationStrictModeViolation(
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007372 IBinder app,
7373 int violationMask,
7374 StrictMode.ViolationInfo info) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007375 ProcessRecord r = findAppProcess(app, "StrictMode");
7376 if (r == null) {
7377 return;
7378 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007379
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007380 if ((violationMask & StrictMode.PENALTY_DROPBOX) != 0) {
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08007381 Integer stackFingerprint = info.hashCode();
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007382 boolean logIt = true;
7383 synchronized (mAlreadyLoggedViolatedStacks) {
7384 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) {
7385 logIt = false;
7386 // TODO: sub-sample into EventLog for these, with
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007387 // the info.durationMillis? Then we'd get
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007388 // the relative pain numbers, without logging all
7389 // the stack traces repeatedly. We'd want to do
7390 // likewise in the client code, which also does
7391 // dup suppression, before the Binder call.
7392 } else {
7393 if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) {
7394 mAlreadyLoggedViolatedStacks.clear();
7395 }
7396 mAlreadyLoggedViolatedStacks.add(stackFingerprint);
7397 }
7398 }
7399 if (logIt) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007400 logStrictModeViolationToDropBox(r, info);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007401 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007402 }
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007403
7404 if ((violationMask & StrictMode.PENALTY_DIALOG) != 0) {
7405 AppErrorResult result = new AppErrorResult();
7406 synchronized (this) {
7407 final long origId = Binder.clearCallingIdentity();
7408
7409 Message msg = Message.obtain();
7410 msg.what = SHOW_STRICT_MODE_VIOLATION_MSG;
7411 HashMap<String, Object> data = new HashMap<String, Object>();
7412 data.put("result", result);
7413 data.put("app", r);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007414 data.put("violationMask", violationMask);
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007415 data.put("info", info);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007416 msg.obj = data;
7417 mHandler.sendMessage(msg);
7418
7419 Binder.restoreCallingIdentity(origId);
7420 }
7421 int res = result.get();
Dianne Hackbornb424b632010-08-18 15:59:05 -07007422 Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007423 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007424 }
7425
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007426 // Depending on the policy in effect, there could be a bunch of
7427 // these in quick succession so we try to batch these together to
7428 // minimize disk writes, number of dropbox entries, and maximize
7429 // compression, by having more fewer, larger records.
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007430 private void logStrictModeViolationToDropBox(
7431 ProcessRecord process,
7432 StrictMode.ViolationInfo info) {
7433 if (info == null) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007434 return;
7435 }
7436 final boolean isSystemApp = process == null ||
7437 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM |
7438 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07007439 final String processName = process == null ? "unknown" : process.processName;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007440 final String dropboxTag = isSystemApp ? "system_app_strictmode" : "data_app_strictmode";
7441 final DropBoxManager dbox = (DropBoxManager)
7442 mContext.getSystemService(Context.DROPBOX_SERVICE);
7443
7444 // Exit early if the dropbox isn't configured to accept this report type.
7445 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
7446
7447 boolean bufferWasEmpty;
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007448 boolean needsFlush;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007449 final StringBuilder sb = isSystemApp ? mStrictModeBuffer : new StringBuilder(1024);
7450 synchronized (sb) {
7451 bufferWasEmpty = sb.length() == 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07007452 appendDropBoxProcessHeaders(process, processName, sb);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007453 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
7454 sb.append("System-App: ").append(isSystemApp).append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007455 sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n");
7456 if (info.violationNumThisLoop != 0) {
7457 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n");
7458 }
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07007459 if (info.numAnimationsRunning != 0) {
7460 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n");
7461 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07007462 if (info.broadcastIntentAction != null) {
7463 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n");
7464 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08007465 if (info.durationMillis != -1) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007466 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n");
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007467 }
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08007468 if (info.numInstances != -1) {
7469 sb.append("Instance-Count: ").append(info.numInstances).append("\n");
7470 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08007471 if (info.tags != null) {
7472 for (String tag : info.tags) {
7473 sb.append("Span-Tag: ").append(tag).append("\n");
7474 }
7475 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007476 sb.append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007477 if (info.crashInfo != null && info.crashInfo.stackTrace != null) {
7478 sb.append(info.crashInfo.stackTrace);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007479 }
7480 sb.append("\n");
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007481
7482 // Only buffer up to ~64k. Various logging bits truncate
7483 // things at 128k.
7484 needsFlush = (sb.length() > 64 * 1024);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007485 }
7486
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007487 // Flush immediately if the buffer's grown too large, or this
7488 // is a non-system app. Non-system apps are isolated with a
7489 // different tag & policy and not batched.
7490 //
7491 // Batching is useful during internal testing with
7492 // StrictMode settings turned up high. Without batching,
7493 // thousands of separate files could be created on boot.
7494 if (!isSystemApp || needsFlush) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007495 new Thread("Error dump: " + dropboxTag) {
7496 @Override
7497 public void run() {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007498 String report;
7499 synchronized (sb) {
7500 report = sb.toString();
7501 sb.delete(0, sb.length());
7502 sb.trimToSize();
7503 }
7504 if (report.length() != 0) {
7505 dbox.addText(dropboxTag, report);
7506 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007507 }
7508 }.start();
7509 return;
7510 }
7511
7512 // System app batching:
7513 if (!bufferWasEmpty) {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007514 // An existing dropbox-writing thread is outstanding, so
7515 // we don't need to start it up. The existing thread will
7516 // catch the buffer appends we just did.
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007517 return;
7518 }
7519
7520 // Worker thread to both batch writes and to avoid blocking the caller on I/O.
7521 // (After this point, we shouldn't access AMS internal data structures.)
7522 new Thread("Error dump: " + dropboxTag) {
7523 @Override
7524 public void run() {
7525 // 5 second sleep to let stacks arrive and be batched together
7526 try {
7527 Thread.sleep(5000); // 5 seconds
7528 } catch (InterruptedException e) {}
7529
7530 String errorReport;
7531 synchronized (mStrictModeBuffer) {
7532 errorReport = mStrictModeBuffer.toString();
7533 if (errorReport.length() == 0) {
7534 return;
7535 }
7536 mStrictModeBuffer.delete(0, mStrictModeBuffer.length());
7537 mStrictModeBuffer.trimToSize();
7538 }
7539 dbox.addText(dropboxTag, errorReport);
7540 }
7541 }.start();
7542 }
7543
Dan Egnor60d87622009-12-16 16:32:58 -08007544 /**
7545 * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors.
7546 * @param app object of the crashing app, null for the system server
7547 * @param tag reported by the caller
7548 * @param crashInfo describing the context of the error
7549 * @return true if the process should exit immediately (WTF is fatal)
7550 */
7551 public boolean handleApplicationWtf(IBinder app, String tag,
Dan Egnorb7f03672009-12-09 16:22:32 -08007552 ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007553 ProcessRecord r = findAppProcess(app, "WTF");
Jeff Sharkeya353d262011-10-28 11:12:06 -07007554 final String processName = app == null ? "system_server"
7555 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08007556
7557 EventLog.writeEvent(EventLogTags.AM_WTF, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07007558 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08007559 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08007560 tag, crashInfo.exceptionMessage);
7561
Jeff Sharkeya353d262011-10-28 11:12:06 -07007562 addErrorToDropBox("wtf", r, processName, null, null, tag, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08007563
Dianne Hackborn1ab43772011-03-15 14:38:02 -07007564 if (r != null && r.pid != Process.myPid() &&
7565 Settings.Secure.getInt(mContext.getContentResolver(),
7566 Settings.Secure.WTF_IS_FATAL, 0) != 0) {
Dan Egnor60d87622009-12-16 16:32:58 -08007567 crashApplication(r, crashInfo);
7568 return true;
7569 } else {
7570 return false;
7571 }
7572 }
7573
7574 /**
7575 * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit})
7576 * @return the corresponding {@link ProcessRecord} object, or null if none could be found
7577 */
Dianne Hackborncb44d962011-03-10 17:02:27 -08007578 private ProcessRecord findAppProcess(IBinder app, String reason) {
Dan Egnor60d87622009-12-16 16:32:58 -08007579 if (app == null) {
7580 return null;
7581 }
7582
7583 synchronized (this) {
7584 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
7585 final int NA = apps.size();
7586 for (int ia=0; ia<NA; ia++) {
7587 ProcessRecord p = apps.valueAt(ia);
7588 if (p.thread != null && p.thread.asBinder() == app) {
7589 return p;
7590 }
7591 }
7592 }
7593
Dianne Hackborncb44d962011-03-10 17:02:27 -08007594 Slog.w(TAG, "Can't find mystery application for " + reason
7595 + " from pid=" + Binder.getCallingPid()
7596 + " uid=" + Binder.getCallingUid() + ": " + app);
Dan Egnor60d87622009-12-16 16:32:58 -08007597 return null;
7598 }
7599 }
7600
7601 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007602 * Utility function for addErrorToDropBox and handleStrictModeViolation's logging
7603 * to append various headers to the dropbox log text.
Dan Egnor60d87622009-12-16 16:32:58 -08007604 */
Jeff Sharkeya353d262011-10-28 11:12:06 -07007605 private void appendDropBoxProcessHeaders(ProcessRecord process, String processName,
7606 StringBuilder sb) {
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08007607 // Watchdog thread ends up invoking this function (with
7608 // a null ProcessRecord) to add the stack file to dropbox.
7609 // Do not acquire a lock on this (am) in such cases, as it
7610 // could cause a potential deadlock, if and when watchdog
7611 // is invoked due to unavailability of lock on am and it
7612 // would prevent watchdog from killing system_server.
7613 if (process == null) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07007614 sb.append("Process: ").append(processName).append("\n");
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08007615 return;
7616 }
Brad Fitzpatrick1e02d362010-09-10 09:19:50 -07007617 // Note: ProcessRecord 'process' is guarded by the service
7618 // instance. (notably process.pkgList, which could otherwise change
7619 // concurrently during execution of this method)
7620 synchronized (this) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07007621 sb.append("Process: ").append(processName).append("\n");
Dan Egnora455d192010-03-12 08:52:28 -08007622 int flags = process.info.flags;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007623 IPackageManager pm = AppGlobals.getPackageManager();
Dan Egnora455d192010-03-12 08:52:28 -08007624 sb.append("Flags: 0x").append(Integer.toString(flags, 16)).append("\n");
7625 for (String pkg : process.pkgList) {
7626 sb.append("Package: ").append(pkg);
Dan Egnor42471dd2010-01-07 17:25:22 -08007627 try {
Dan Egnora455d192010-03-12 08:52:28 -08007628 PackageInfo pi = pm.getPackageInfo(pkg, 0);
7629 if (pi != null) {
7630 sb.append(" v").append(pi.versionCode);
7631 if (pi.versionName != null) {
7632 sb.append(" (").append(pi.versionName).append(")");
7633 }
7634 }
7635 } catch (RemoteException e) {
7636 Slog.e(TAG, "Error getting package info: " + pkg, e);
Dan Egnor60d87622009-12-16 16:32:58 -08007637 }
Dan Egnora455d192010-03-12 08:52:28 -08007638 sb.append("\n");
Dan Egnor60d87622009-12-16 16:32:58 -08007639 }
Dan Egnora455d192010-03-12 08:52:28 -08007640 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007641 }
7642
7643 private static String processClass(ProcessRecord process) {
7644 if (process == null || process.pid == MY_PID) {
7645 return "system_server";
7646 } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
7647 return "system_app";
7648 } else {
7649 return "data_app";
7650 }
7651 }
7652
7653 /**
7654 * Write a description of an error (crash, WTF, ANR) to the drop box.
7655 * @param eventType to include in the drop box tag ("crash", "wtf", etc.)
7656 * @param process which caused the error, null means the system server
7657 * @param activity which triggered the error, null if unknown
7658 * @param parent activity related to the error, null if unknown
7659 * @param subject line related to the error, null if absent
7660 * @param report in long form describing the error, null if absent
7661 * @param logFile to include in the report, null if none
7662 * @param crashInfo giving an application stack trace, null if absent
7663 */
7664 public void addErrorToDropBox(String eventType,
Jeff Sharkeya353d262011-10-28 11:12:06 -07007665 ProcessRecord process, String processName, ActivityRecord activity,
7666 ActivityRecord parent, String subject,
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007667 final String report, final File logFile,
7668 final ApplicationErrorReport.CrashInfo crashInfo) {
7669 // NOTE -- this must never acquire the ActivityManagerService lock,
7670 // otherwise the watchdog may be prevented from resetting the system.
7671
7672 final String dropboxTag = processClass(process) + "_" + eventType;
7673 final DropBoxManager dbox = (DropBoxManager)
7674 mContext.getSystemService(Context.DROPBOX_SERVICE);
7675
7676 // Exit early if the dropbox isn't configured to accept this report type.
7677 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
7678
7679 final StringBuilder sb = new StringBuilder(1024);
Jeff Sharkeya353d262011-10-28 11:12:06 -07007680 appendDropBoxProcessHeaders(process, processName, sb);
Dan Egnora455d192010-03-12 08:52:28 -08007681 if (activity != null) {
7682 sb.append("Activity: ").append(activity.shortComponentName).append("\n");
7683 }
7684 if (parent != null && parent.app != null && parent.app.pid != process.pid) {
7685 sb.append("Parent-Process: ").append(parent.app.processName).append("\n");
7686 }
7687 if (parent != null && parent != activity) {
7688 sb.append("Parent-Activity: ").append(parent.shortComponentName).append("\n");
7689 }
7690 if (subject != null) {
7691 sb.append("Subject: ").append(subject).append("\n");
7692 }
7693 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
Christian Lindeberg03d2ca62010-09-28 14:52:20 +02007694 if (Debug.isDebuggerConnected()) {
7695 sb.append("Debugger: Connected\n");
7696 }
Dan Egnora455d192010-03-12 08:52:28 -08007697 sb.append("\n");
7698
7699 // Do the rest in a worker thread to avoid blocking the caller on I/O
7700 // (After this point, we shouldn't access AMS internal data structures.)
7701 Thread worker = new Thread("Error dump: " + dropboxTag) {
7702 @Override
7703 public void run() {
7704 if (report != null) {
7705 sb.append(report);
7706 }
7707 if (logFile != null) {
7708 try {
7709 sb.append(FileUtils.readTextFile(logFile, 128 * 1024, "\n\n[[TRUNCATED]]"));
7710 } catch (IOException e) {
7711 Slog.e(TAG, "Error reading " + logFile, e);
7712 }
7713 }
7714 if (crashInfo != null && crashInfo.stackTrace != null) {
7715 sb.append(crashInfo.stackTrace);
7716 }
7717
7718 String setting = Settings.Secure.ERROR_LOGCAT_PREFIX + dropboxTag;
7719 int lines = Settings.Secure.getInt(mContext.getContentResolver(), setting, 0);
7720 if (lines > 0) {
7721 sb.append("\n");
7722
7723 // Merge several logcat streams, and take the last N lines
7724 InputStreamReader input = null;
7725 try {
7726 java.lang.Process logcat = new ProcessBuilder("/system/bin/logcat",
7727 "-v", "time", "-b", "events", "-b", "system", "-b", "main",
7728 "-t", String.valueOf(lines)).redirectErrorStream(true).start();
7729
7730 try { logcat.getOutputStream().close(); } catch (IOException e) {}
7731 try { logcat.getErrorStream().close(); } catch (IOException e) {}
7732 input = new InputStreamReader(logcat.getInputStream());
7733
7734 int num;
7735 char[] buf = new char[8192];
7736 while ((num = input.read(buf)) > 0) sb.append(buf, 0, num);
7737 } catch (IOException e) {
7738 Slog.e(TAG, "Error running logcat", e);
7739 } finally {
7740 if (input != null) try { input.close(); } catch (IOException e) {}
7741 }
7742 }
7743
7744 dbox.addText(dropboxTag, sb.toString());
Dan Egnor60d87622009-12-16 16:32:58 -08007745 }
Dan Egnora455d192010-03-12 08:52:28 -08007746 };
7747
7748 if (process == null || process.pid == MY_PID) {
7749 worker.run(); // We may be about to die -- need to run this synchronously
7750 } else {
7751 worker.start();
Dan Egnor60d87622009-12-16 16:32:58 -08007752 }
7753 }
7754
7755 /**
7756 * Bring up the "unexpected error" dialog box for a crashing app.
7757 * Deal with edge cases (intercepts from instrumented applications,
7758 * ActivityController, error intent receivers, that sort of thing).
7759 * @param r the application crashing
7760 * @param crashInfo describing the failure
7761 */
7762 private void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) {
Dan Egnorb7f03672009-12-09 16:22:32 -08007763 long timeMillis = System.currentTimeMillis();
7764 String shortMsg = crashInfo.exceptionClassName;
7765 String longMsg = crashInfo.exceptionMessage;
7766 String stackTrace = crashInfo.stackTrace;
7767 if (shortMsg != null && longMsg != null) {
7768 longMsg = shortMsg + ": " + longMsg;
7769 } else if (shortMsg != null) {
7770 longMsg = shortMsg;
7771 }
7772
Dan Egnor60d87622009-12-16 16:32:58 -08007773 AppErrorResult result = new AppErrorResult();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007774 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007775 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007776 try {
7777 String name = r != null ? r.processName : null;
7778 int pid = r != null ? r.pid : Binder.getCallingPid();
Dan Egnor60d87622009-12-16 16:32:58 -08007779 if (!mController.appCrashed(name, pid,
Dan Egnorb7f03672009-12-09 16:22:32 -08007780 shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007781 Slog.w(TAG, "Force-killing crashed app " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007782 + " at watcher's request");
7783 Process.killProcess(pid);
Dan Egnorb7f03672009-12-09 16:22:32 -08007784 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007785 }
7786 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007787 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007788 }
7789 }
7790
7791 final long origId = Binder.clearCallingIdentity();
7792
7793 // If this process is running instrumentation, finish it.
7794 if (r != null && r.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007795 Slog.w(TAG, "Error in app " + r.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007796 + " running instrumentation " + r.instrumentationClass + ":");
Joe Onorato8a9b2202010-02-26 18:56:32 -08007797 if (shortMsg != null) Slog.w(TAG, " " + shortMsg);
7798 if (longMsg != null) Slog.w(TAG, " " + longMsg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007799 Bundle info = new Bundle();
7800 info.putString("shortMsg", shortMsg);
7801 info.putString("longMsg", longMsg);
7802 finishInstrumentationLocked(r, Activity.RESULT_CANCELED, info);
7803 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08007804 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007805 }
7806
Dan Egnor60d87622009-12-16 16:32:58 -08007807 // If we can't identify the process or it's already exceeded its crash quota,
7808 // quit right away without showing a crash dialog.
7809 if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007810 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08007811 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007812 }
7813
7814 Message msg = Message.obtain();
7815 msg.what = SHOW_ERROR_MSG;
7816 HashMap data = new HashMap();
7817 data.put("result", result);
7818 data.put("app", r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007819 msg.obj = data;
7820 mHandler.sendMessage(msg);
7821
7822 Binder.restoreCallingIdentity(origId);
7823 }
7824
7825 int res = result.get();
7826
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007827 Intent appErrorIntent = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007828 synchronized (this) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007829 if (r != null && !r.isolated) {
7830 // XXX Can't keep track of crash time for isolated processes,
7831 // since they don't have a persistent identity.
7832 mProcessCrashTimes.put(r.info.processName, r.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007833 SystemClock.uptimeMillis());
7834 }
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007835 if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) {
Dan Egnorb7f03672009-12-09 16:22:32 -08007836 appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007837 }
7838 }
7839
7840 if (appErrorIntent != null) {
7841 try {
7842 mContext.startActivity(appErrorIntent);
7843 } catch (ActivityNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007844 Slog.w(TAG, "bug report receiver dissappeared", e);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007845 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007846 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007847 }
Dan Egnorb7f03672009-12-09 16:22:32 -08007848
7849 Intent createAppErrorIntentLocked(ProcessRecord r,
7850 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
7851 ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007852 if (report == null) {
7853 return null;
7854 }
7855 Intent result = new Intent(Intent.ACTION_APP_ERROR);
7856 result.setComponent(r.errorReportReceiver);
7857 result.putExtra(Intent.EXTRA_BUG_REPORT, report);
7858 result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
7859 return result;
7860 }
7861
Dan Egnorb7f03672009-12-09 16:22:32 -08007862 private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r,
7863 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007864 if (r.errorReportReceiver == null) {
7865 return null;
7866 }
7867
7868 if (!r.crashing && !r.notResponding) {
7869 return null;
7870 }
7871
Dan Egnorb7f03672009-12-09 16:22:32 -08007872 ApplicationErrorReport report = new ApplicationErrorReport();
7873 report.packageName = r.info.packageName;
7874 report.installerPackageName = r.errorReportReceiver.getPackageName();
7875 report.processName = r.processName;
7876 report.time = timeMillis;
Jacek Surazskie0ee6ef2010-01-07 16:23:03 +01007877 report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007878
Dan Egnorb7f03672009-12-09 16:22:32 -08007879 if (r.crashing) {
7880 report.type = ApplicationErrorReport.TYPE_CRASH;
7881 report.crashInfo = crashInfo;
7882 } else if (r.notResponding) {
7883 report.type = ApplicationErrorReport.TYPE_ANR;
7884 report.anrInfo = new ApplicationErrorReport.AnrInfo();
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007885
Dan Egnorb7f03672009-12-09 16:22:32 -08007886 report.anrInfo.activity = r.notRespondingReport.tag;
7887 report.anrInfo.cause = r.notRespondingReport.shortMsg;
7888 report.anrInfo.info = r.notRespondingReport.longMsg;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007889 }
7890
Dan Egnorb7f03672009-12-09 16:22:32 -08007891 return report;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007892 }
7893
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007894 public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08007895 enforceNotIsolatedCaller("getProcessesInErrorState");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007896 // assume our apps are happy - lazy create the list
7897 List<ActivityManager.ProcessErrorStateInfo> errList = null;
7898
7899 synchronized (this) {
7900
7901 // iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08007902 for (int i=mLruProcesses.size()-1; i>=0; i--) {
7903 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007904 if ((app.thread != null) && (app.crashing || app.notResponding)) {
7905 // This one's in trouble, so we'll generate a report for it
7906 // crashes are higher priority (in case there's a crash *and* an anr)
7907 ActivityManager.ProcessErrorStateInfo report = null;
7908 if (app.crashing) {
7909 report = app.crashingReport;
7910 } else if (app.notResponding) {
7911 report = app.notRespondingReport;
7912 }
7913
7914 if (report != null) {
7915 if (errList == null) {
7916 errList = new ArrayList<ActivityManager.ProcessErrorStateInfo>(1);
7917 }
7918 errList.add(report);
7919 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007920 Slog.w(TAG, "Missing app error report, app = " + app.processName +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007921 " crashing = " + app.crashing +
7922 " notResponding = " + app.notResponding);
7923 }
7924 }
7925 }
7926 }
7927
7928 return errList;
7929 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07007930
7931 static int oomAdjToImportance(int adj, ActivityManager.RunningAppProcessInfo currApp) {
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007932 if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07007933 if (currApp != null) {
7934 currApp.lru = adj - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
7935 }
7936 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007937 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
7938 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
Dianne Hackborn905577f2011-09-07 18:31:28 -07007939 } else if (adj >= ProcessList.HOME_APP_ADJ) {
7940 if (currApp != null) {
7941 currApp.lru = 0;
7942 }
7943 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007944 } else if (adj >= ProcessList.SERVICE_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07007945 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
7946 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
7947 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
7948 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
7949 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
7950 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
7951 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
7952 } else {
7953 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
7954 }
7955 }
7956
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007957 public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08007958 enforceNotIsolatedCaller("getRunningAppProcesses");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007959 // Lazy instantiation of list
7960 List<ActivityManager.RunningAppProcessInfo> runList = null;
7961 synchronized (this) {
7962 // Iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08007963 for (int i=mLruProcesses.size()-1; i>=0; i--) {
7964 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007965 if ((app.thread != null) && (!app.crashing && !app.notResponding)) {
7966 // Generate process state info for running application
7967 ActivityManager.RunningAppProcessInfo currApp =
7968 new ActivityManager.RunningAppProcessInfo(app.processName,
7969 app.pid, app.getPackageList());
Dianne Hackborneb034652009-09-07 00:49:58 -07007970 currApp.uid = app.info.uid;
Dianne Hackbornbaf42c62010-06-24 11:23:39 -07007971 if (mHeavyWeightProcess == app) {
Dianne Hackborn482566e2010-09-03 12:51:28 -07007972 currApp.flags |= ActivityManager.RunningAppProcessInfo.FLAG_CANT_SAVE_STATE;
Dianne Hackbornbaf42c62010-06-24 11:23:39 -07007973 }
Dianne Hackborn42499172010-10-15 18:45:07 -07007974 if (app.persistent) {
7975 currApp.flags |= ActivityManager.RunningAppProcessInfo.FLAG_PERSISTENT;
7976 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007977 int adj = app.curAdj;
Dianne Hackborn905577f2011-09-07 18:31:28 -07007978 currApp.importance = oomAdjToImportance(adj, currApp);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07007979 currApp.importanceReasonCode = app.adjTypeCode;
7980 if (app.adjSource instanceof ProcessRecord) {
7981 currApp.importanceReasonPid = ((ProcessRecord)app.adjSource).pid;
Dianne Hackborn905577f2011-09-07 18:31:28 -07007982 currApp.importanceReasonImportance = oomAdjToImportance(
7983 app.adjSourceOom, null);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007984 } else if (app.adjSource instanceof ActivityRecord) {
7985 ActivityRecord r = (ActivityRecord)app.adjSource;
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07007986 if (r.app != null) currApp.importanceReasonPid = r.app.pid;
7987 }
7988 if (app.adjTarget instanceof ComponentName) {
7989 currApp.importanceReasonComponent = (ComponentName)app.adjTarget;
7990 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08007991 //Slog.v(TAG, "Proc " + app.processName + ": imp=" + currApp.importance
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007992 // + " lru=" + currApp.lru);
7993 if (runList == null) {
7994 runList = new ArrayList<ActivityManager.RunningAppProcessInfo>();
7995 }
7996 runList.add(currApp);
7997 }
7998 }
7999 }
8000 return runList;
8001 }
8002
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008003 public List<ApplicationInfo> getRunningExternalApplications() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008004 enforceNotIsolatedCaller("getRunningExternalApplications");
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008005 List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses();
8006 List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>();
8007 if (runningApps != null && runningApps.size() > 0) {
8008 Set<String> extList = new HashSet<String>();
8009 for (ActivityManager.RunningAppProcessInfo app : runningApps) {
8010 if (app.pkgList != null) {
8011 for (String pkg : app.pkgList) {
8012 extList.add(pkg);
8013 }
8014 }
8015 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008016 IPackageManager pm = AppGlobals.getPackageManager();
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008017 for (String pkg : extList) {
8018 try {
8019 ApplicationInfo info = pm.getApplicationInfo(pkg, 0);
8020 if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
8021 retList.add(info);
8022 }
8023 } catch (RemoteException e) {
8024 }
8025 }
8026 }
8027 return retList;
8028 }
8029
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008030 @Override
8031 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008032 if (checkCallingPermission(android.Manifest.permission.DUMP)
8033 != PackageManager.PERMISSION_GRANTED) {
8034 pw.println("Permission Denial: can't dump ActivityManager from from pid="
8035 + Binder.getCallingPid()
8036 + ", uid=" + Binder.getCallingUid()
8037 + " without permission "
8038 + android.Manifest.permission.DUMP);
8039 return;
8040 }
8041
8042 boolean dumpAll = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008043 boolean dumpClient = false;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008044 String dumpPackage = null;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008045
8046 int opti = 0;
8047 while (opti < args.length) {
8048 String opt = args[opti];
8049 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
8050 break;
8051 }
8052 opti++;
8053 if ("-a".equals(opt)) {
8054 dumpAll = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008055 } else if ("-c".equals(opt)) {
8056 dumpClient = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008057 } else if ("-h".equals(opt)) {
8058 pw.println("Activity manager dump options:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008059 pw.println(" [-a] [-c] [-h] [cmd] ...");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008060 pw.println(" cmd may be one of:");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008061 pw.println(" a[ctivities]: activity stack state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008062 pw.println(" b[roadcasts] [PACKAGE_NAME]: broadcast state");
8063 pw.println(" i[ntents] [PACKAGE_NAME]: pending intent state");
8064 pw.println(" p[rocesses] [PACKAGE_NAME]: process state");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008065 pw.println(" o[om]: out of memory management");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008066 pw.println(" prov[iders] [COMP_SPEC ...]: content provider state");
Marco Nelissen18cb2872011-11-15 11:19:53 -08008067 pw.println(" provider [COMP_SPEC]: provider client-side state");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008068 pw.println(" s[ervices] [COMP_SPEC ...]: service state");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008069 pw.println(" service [COMP_SPEC]: service client-side state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008070 pw.println(" package [PACKAGE_NAME]: all state related to given package");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008071 pw.println(" all: dump all activities");
8072 pw.println(" top: dump the top activity");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008073 pw.println(" cmd may also be a COMP_SPEC to dump activities.");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008074 pw.println(" COMP_SPEC may be a component name (com.foo/.myApp),");
8075 pw.println(" a partial substring in a component name, a");
8076 pw.println(" hex object identifier.");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008077 pw.println(" -a: include all available server state.");
8078 pw.println(" -c: include client state.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008079 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008080 } else {
8081 pw.println("Unknown argument: " + opt + "; use -h for help");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008082 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008083 }
8084
8085 // Is the caller requesting to dump a particular piece of data?
8086 if (opti < args.length) {
8087 String cmd = args[opti];
8088 opti++;
8089 if ("activities".equals(cmd) || "a".equals(cmd)) {
8090 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008091 dumpActivitiesLocked(fd, pw, args, opti, true, dumpClient, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008092 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008093 return;
8094 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008095 String[] newArgs;
8096 String name;
8097 if (opti >= args.length) {
8098 name = null;
8099 newArgs = EMPTY_STRING_ARRAY;
8100 } else {
8101 name = args[opti];
8102 opti++;
8103 newArgs = new String[args.length - opti];
8104 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8105 args.length - opti);
8106 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008107 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008108 dumpBroadcastsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008109 }
8110 return;
8111 } else if ("intents".equals(cmd) || "i".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008112 String[] newArgs;
8113 String name;
8114 if (opti >= args.length) {
8115 name = null;
8116 newArgs = EMPTY_STRING_ARRAY;
8117 } else {
8118 name = args[opti];
8119 opti++;
8120 newArgs = new String[args.length - opti];
8121 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8122 args.length - opti);
8123 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008124 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008125 dumpPendingIntentsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008126 }
8127 return;
8128 } else if ("processes".equals(cmd) || "p".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008129 String[] newArgs;
8130 String name;
8131 if (opti >= args.length) {
8132 name = null;
8133 newArgs = EMPTY_STRING_ARRAY;
8134 } else {
8135 name = args[opti];
8136 opti++;
8137 newArgs = new String[args.length - opti];
8138 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8139 args.length - opti);
8140 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008141 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008142 dumpProcessesLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008143 }
8144 return;
Dianne Hackborn287952c2010-09-22 22:34:31 -07008145 } else if ("oom".equals(cmd) || "o".equals(cmd)) {
8146 synchronized (this) {
8147 dumpOomLocked(fd, pw, args, opti, true);
8148 }
8149 return;
Marco Nelissen18cb2872011-11-15 11:19:53 -08008150 } else if ("provider".equals(cmd)) {
8151 String[] newArgs;
8152 String name;
8153 if (opti >= args.length) {
8154 name = null;
8155 newArgs = EMPTY_STRING_ARRAY;
8156 } else {
8157 name = args[opti];
8158 opti++;
8159 newArgs = new String[args.length - opti];
8160 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
8161 }
8162 if (!dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) {
8163 pw.println("No providers match: " + name);
8164 pw.println("Use -h for help.");
8165 }
8166 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008167 } else if ("providers".equals(cmd) || "prov".equals(cmd)) {
8168 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008169 dumpProvidersLocked(fd, pw, args, opti, true, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008170 }
8171 return;
8172 } else if ("service".equals(cmd)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008173 String[] newArgs;
8174 String name;
8175 if (opti >= args.length) {
8176 name = null;
8177 newArgs = EMPTY_STRING_ARRAY;
8178 } else {
8179 name = args[opti];
8180 opti++;
8181 newArgs = new String[args.length - opti];
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008182 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8183 args.length - opti);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008184 }
8185 if (!dumpService(fd, pw, name, newArgs, 0, dumpAll)) {
8186 pw.println("No services match: " + name);
8187 pw.println("Use -h for help.");
8188 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008189 return;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008190 } else if ("package".equals(cmd)) {
8191 String[] newArgs;
8192 if (opti >= args.length) {
8193 pw.println("package: no package name specified");
8194 pw.println("Use -h for help.");
8195 return;
8196 } else {
8197 dumpPackage = args[opti];
8198 opti++;
8199 newArgs = new String[args.length - opti];
8200 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8201 args.length - opti);
8202 args = newArgs;
8203 opti = 0;
8204 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008205 } else if ("services".equals(cmd) || "s".equals(cmd)) {
8206 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008207 dumpServicesLocked(fd, pw, args, opti, true, dumpClient, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008208 }
8209 return;
Dianne Hackborn625ac272010-09-17 18:29:22 -07008210 } else {
8211 // Dumping a single activity?
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008212 if (!dumpActivity(fd, pw, cmd, args, opti, dumpAll)) {
8213 pw.println("Bad activity command, or no activities match: " + cmd);
8214 pw.println("Use -h for help.");
Dianne Hackborn625ac272010-09-17 18:29:22 -07008215 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08008216 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008217 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008218 }
8219
8220 // No piece of data specified, dump everything.
8221 synchronized (this) {
8222 boolean needSep;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008223 needSep = dumpPendingIntentsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008224 if (needSep) {
8225 pw.println(" ");
8226 }
8227 if (dumpAll) {
8228 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008229 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008230 needSep = dumpBroadcastsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008231 if (needSep) {
8232 pw.println(" ");
8233 }
8234 if (dumpAll) {
8235 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008236 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008237 needSep = dumpProvidersLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008238 if (needSep) {
8239 pw.println(" ");
8240 }
8241 if (dumpAll) {
8242 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008243 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008244 needSep = dumpServicesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008245 if (needSep) {
8246 pw.println(" ");
8247 }
8248 if (dumpAll) {
8249 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008250 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008251 needSep = dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008252 if (needSep) {
8253 pw.println(" ");
8254 }
8255 if (dumpAll) {
8256 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008257 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008258 dumpProcessesLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008259 }
8260 }
8261
8262 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008263 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008264 pw.println("ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
8265 pw.println(" Main stack:");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008266 dumpHistoryList(fd, pw, mMainStack.mHistory, " ", "Hist", true, !dumpAll, dumpClient,
8267 dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008268 pw.println(" ");
8269 pw.println(" Running activities (most recent first):");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008270 dumpHistoryList(fd, pw, mMainStack.mLRUActivities, " ", "Run", false, !dumpAll, false,
8271 dumpPackage);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008272 if (mMainStack.mWaitingVisibleActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008273 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008274 pw.println(" Activities waiting for another to become visible:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008275 dumpHistoryList(fd, pw, mMainStack.mWaitingVisibleActivities, " ", "Wait", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008276 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008277 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008278 if (mMainStack.mStoppingActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008279 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008280 pw.println(" Activities waiting to stop:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008281 dumpHistoryList(fd, pw, mMainStack.mStoppingActivities, " ", "Stop", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008282 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008283 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008284 if (mMainStack.mGoingToSleepActivities.size() > 0) {
8285 pw.println(" ");
8286 pw.println(" Activities waiting to sleep:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008287 dumpHistoryList(fd, pw, mMainStack.mGoingToSleepActivities, " ", "Sleep", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008288 !dumpAll, false, dumpPackage);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008289 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008290 if (mMainStack.mFinishingActivities.size() > 0) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008291 pw.println(" ");
8292 pw.println(" Activities waiting to finish:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008293 dumpHistoryList(fd, pw, mMainStack.mFinishingActivities, " ", "Fin", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008294 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008295 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008296
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008297 pw.println(" ");
Dianne Hackborncbb722e2012-02-07 18:33:49 -08008298 if (mMainStack.mPausingActivities.size() > 0) {
8299 pw.println(" mPausingActivities: " + Arrays.toString(
8300 mMainStack.mPausingActivities.toArray()));
8301 }
8302 if (mMainStack.mInputPausedActivities.size() > 0) {
8303 pw.println(" mInputPausedActivities: " + Arrays.toString(
8304 mMainStack.mInputPausedActivities.toArray()));
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008305 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008306 pw.println(" mResumedActivity: " + mMainStack.mResumedActivity);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008307 pw.println(" mFocusedActivity: " + mFocusedActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008308 if (dumpAll) {
8309 pw.println(" mLastPausedActivity: " + mMainStack.mLastPausedActivity);
8310 pw.println(" mSleepTimeout: " + mMainStack.mSleepTimeout);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07008311 pw.println(" mDismissKeyguardOnNextActivity: "
8312 + mMainStack.mDismissKeyguardOnNextActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008313 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008314
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008315 if (mRecentTasks.size() > 0) {
8316 pw.println();
8317 pw.println(" Recent tasks:");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008318
8319 final int N = mRecentTasks.size();
8320 for (int i=0; i<N; i++) {
8321 TaskRecord tr = mRecentTasks.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008322 if (dumpPackage != null) {
8323 if (tr.realActivity == null ||
8324 !dumpPackage.equals(tr.realActivity)) {
8325 continue;
8326 }
8327 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008328 pw.print(" * Recent #"); pw.print(i); pw.print(": ");
8329 pw.println(tr);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008330 if (dumpAll) {
8331 mRecentTasks.get(i).dump(pw, " ");
8332 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008333 }
8334 }
8335
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008336 if (dumpAll) {
8337 pw.println(" ");
8338 pw.println(" mCurTask: " + mCurTask);
8339 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008340
8341 return true;
8342 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008343
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008344 boolean dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008345 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008346 boolean needSep = false;
8347 int numPers = 0;
8348
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008349 pw.println("ACTIVITY MANAGER RUNNING PROCESSES (dumpsys activity processes)");
8350
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008351 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008352 for (SparseArray<ProcessRecord> procs : mProcessNames.getMap().values()) {
8353 final int NA = procs.size();
8354 for (int ia=0; ia<NA; ia++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008355 ProcessRecord r = procs.valueAt(ia);
8356 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8357 continue;
8358 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008359 if (!needSep) {
8360 pw.println(" All known processes:");
8361 needSep = true;
8362 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008363 pw.print(r.persistent ? " *PERS*" : " *APP*");
8364 pw.print(" UID "); pw.print(procs.keyAt(ia));
8365 pw.print(" "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008366 r.dump(pw, " ");
8367 if (r.persistent) {
8368 numPers++;
8369 }
8370 }
8371 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008372 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008373
8374 if (mIsolatedProcesses.size() > 0) {
8375 if (needSep) pw.println(" ");
8376 needSep = true;
8377 pw.println(" Isolated process list (sorted by uid):");
8378 for (int i=0; i<mIsolatedProcesses.size(); i++) {
8379 ProcessRecord r = mIsolatedProcesses.valueAt(i);
8380 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8381 continue;
8382 }
8383 pw.println(String.format("%sIsolated #%2d: %s",
8384 " ", i, r.toString()));
8385 }
8386 }
8387
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008388 if (mLruProcesses.size() > 0) {
8389 if (needSep) pw.println(" ");
8390 needSep = true;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008391 pw.println(" Process LRU list (sorted by oom_adj):");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008392 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008393 "Proc", "PERS", false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008394 needSep = true;
8395 }
8396
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008397 if (dumpAll) {
8398 synchronized (mPidsSelfLocked) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008399 boolean printed = false;
8400 for (int i=0; i<mPidsSelfLocked.size(); i++) {
8401 ProcessRecord r = mPidsSelfLocked.valueAt(i);
8402 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8403 continue;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008404 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008405 if (!printed) {
8406 if (needSep) pw.println(" ");
8407 needSep = true;
8408 pw.println(" PID mappings:");
8409 printed = true;
8410 }
8411 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i));
8412 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008413 }
8414 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008415 }
8416
8417 if (mForegroundProcesses.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008418 synchronized (mPidsSelfLocked) {
8419 boolean printed = false;
8420 for (int i=0; i<mForegroundProcesses.size(); i++) {
8421 ProcessRecord r = mPidsSelfLocked.get(
8422 mForegroundProcesses.valueAt(i).pid);
8423 if (dumpPackage != null && (r == null
8424 || !dumpPackage.equals(r.info.packageName))) {
8425 continue;
8426 }
8427 if (!printed) {
8428 if (needSep) pw.println(" ");
8429 needSep = true;
8430 pw.println(" Foreground Processes:");
8431 printed = true;
8432 }
8433 pw.print(" PID #"); pw.print(mForegroundProcesses.keyAt(i));
8434 pw.print(": "); pw.println(mForegroundProcesses.valueAt(i));
8435 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008436 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008437 }
8438
8439 if (mPersistentStartingProcesses.size() > 0) {
8440 if (needSep) pw.println(" ");
8441 needSep = true;
8442 pw.println(" Persisent processes that are starting:");
8443 dumpProcessList(pw, this, mPersistentStartingProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008444 "Starting Norm", "Restarting PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008445 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008446
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008447 if (mRemovedProcesses.size() > 0) {
8448 if (needSep) pw.println(" ");
8449 needSep = true;
8450 pw.println(" Processes that are being removed:");
8451 dumpProcessList(pw, this, mRemovedProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008452 "Removed Norm", "Removed PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008453 }
8454
8455 if (mProcessesOnHold.size() > 0) {
8456 if (needSep) pw.println(" ");
8457 needSep = true;
8458 pw.println(" Processes that are on old until the system is ready:");
8459 dumpProcessList(pw, this, mProcessesOnHold, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008460 "OnHold Norm", "OnHold PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008461 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008462
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008463 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008464
8465 if (mProcessCrashTimes.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008466 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008467 long now = SystemClock.uptimeMillis();
8468 for (Map.Entry<String, SparseArray<Long>> procs
8469 : mProcessCrashTimes.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008470 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008471 SparseArray<Long> uids = procs.getValue();
8472 final int N = uids.size();
8473 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008474 int puid = uids.keyAt(i);
8475 ProcessRecord r = mProcessNames.get(pname, puid);
8476 if (dumpPackage != null && (r == null
8477 || !dumpPackage.equals(r.info.packageName))) {
8478 continue;
8479 }
8480 if (!printed) {
8481 if (needSep) pw.println(" ");
8482 needSep = true;
8483 pw.println(" Time since processes crashed:");
8484 printed = true;
8485 }
8486 pw.print(" Process "); pw.print(pname);
8487 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008488 pw.print(": last crashed ");
8489 pw.print((now-uids.valueAt(i)));
Dianne Hackbornfd12af42009-08-27 00:44:33 -07008490 pw.println(" ms ago");
Dianne Hackbornfd12af42009-08-27 00:44:33 -07008491 }
8492 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008493 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008494
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008495 if (mBadProcesses.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008496 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008497 for (Map.Entry<String, SparseArray<Long>> procs
8498 : mBadProcesses.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008499 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008500 SparseArray<Long> uids = procs.getValue();
8501 final int N = uids.size();
8502 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008503 int puid = uids.keyAt(i);
8504 ProcessRecord r = mProcessNames.get(pname, puid);
8505 if (dumpPackage != null && (r == null
8506 || !dumpPackage.equals(r.info.packageName))) {
8507 continue;
8508 }
8509 if (!printed) {
8510 if (needSep) pw.println(" ");
8511 needSep = true;
8512 pw.println(" Bad processes:");
8513 }
8514 pw.print(" Bad process "); pw.print(pname);
8515 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008516 pw.print(": crashed at time ");
8517 pw.println(uids.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008518 }
8519 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008520 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008521
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008522 pw.println();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008523 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07008524 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn50685602011-12-01 12:23:37 -08008525 if (dumpAll) {
8526 StringBuilder sb = new StringBuilder(128);
8527 sb.append(" mPreviousProcessVisibleTime: ");
8528 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
8529 pw.println(sb);
8530 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07008531 if (mHeavyWeightProcess != null) {
8532 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
8533 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008534 pw.println(" mConfiguration: " + mConfiguration);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008535 if (dumpAll) {
8536 pw.println(" mConfigWillChange: " + mMainStack.mConfigWillChange);
Dianne Hackborn3d0724d2011-05-12 15:39:41 -07008537 if (mCompatModePackages.getPackages().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008538 boolean printed = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07008539 for (Map.Entry<String, Integer> entry
8540 : mCompatModePackages.getPackages().entrySet()) {
8541 String pkg = entry.getKey();
8542 int mode = entry.getValue();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008543 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
8544 continue;
8545 }
8546 if (!printed) {
8547 pw.println(" mScreenCompatPackages:");
8548 printed = true;
8549 }
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07008550 pw.print(" "); pw.print(pkg); pw.print(": ");
8551 pw.print(mode); pw.println();
8552 }
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07008553 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008554 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008555 pw.println(" mSleeping=" + mSleeping + " mShuttingDown=" + mShuttingDown);
8556 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
8557 || mOrigWaitForDebugger) {
8558 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp
8559 + " mDebugTransient=" + mDebugTransient
8560 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger);
8561 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07008562 if (mProfileApp != null || mProfileProc != null || mProfileFile != null
8563 || mProfileFd != null) {
8564 pw.println(" mProfileApp=" + mProfileApp + " mProfileProc=" + mProfileProc);
8565 pw.println(" mProfileFile=" + mProfileFile + " mProfileFd=" + mProfileFd);
8566 pw.println(" mProfileType=" + mProfileType + " mAutoStopProfiler="
8567 + mAutoStopProfiler);
8568 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008569 if (mAlwaysFinishActivities || mController != null) {
8570 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities
8571 + " mController=" + mController);
8572 }
8573 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008574 pw.println(" Total persistent processes: " + numPers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008575 pw.println(" mStartRunning=" + mStartRunning
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07008576 + " mProcessesReady=" + mProcessesReady
8577 + " mSystemReady=" + mSystemReady);
8578 pw.println(" mBooting=" + mBooting
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008579 + " mBooted=" + mBooted
8580 + " mFactoryTest=" + mFactoryTest);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008581 pw.print(" mLastPowerCheckRealtime=");
8582 TimeUtils.formatDuration(mLastPowerCheckRealtime, pw);
8583 pw.println("");
8584 pw.print(" mLastPowerCheckUptime=");
8585 TimeUtils.formatDuration(mLastPowerCheckUptime, pw);
8586 pw.println("");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008587 pw.println(" mGoingToSleep=" + mMainStack.mGoingToSleep);
8588 pw.println(" mLaunchingActivity=" + mMainStack.mLaunchingActivity);
Dianne Hackborn906497c2010-05-10 15:57:38 -07008589 pw.println(" mAdjSeq=" + mAdjSeq + " mLruSeq=" + mLruSeq);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008590 pw.println(" mNumServiceProcs=" + mNumServiceProcs
8591 + " mNewNumServiceProcs=" + mNewNumServiceProcs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008592 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008593
8594 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008595 }
8596
Dianne Hackborn287952c2010-09-22 22:34:31 -07008597 boolean dumpProcessesToGc(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008598 int opti, boolean needSep, boolean dumpAll, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07008599 if (mProcessesToGc.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008600 boolean printed = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -07008601 long now = SystemClock.uptimeMillis();
8602 for (int i=0; i<mProcessesToGc.size(); i++) {
8603 ProcessRecord proc = mProcessesToGc.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008604 if (dumpPackage != null && !dumpPackage.equals(proc.info.packageName)) {
8605 continue;
8606 }
8607 if (!printed) {
8608 if (needSep) pw.println(" ");
8609 needSep = true;
8610 pw.println(" Processes that are waiting to GC:");
8611 printed = true;
8612 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008613 pw.print(" Process "); pw.println(proc);
8614 pw.print(" lowMem="); pw.print(proc.reportLowMemory);
8615 pw.print(", last gced=");
8616 pw.print(now-proc.lastRequestedGc);
8617 pw.print(" ms ago, last lowMem=");
8618 pw.print(now-proc.lastLowMemory);
8619 pw.println(" ms ago");
8620
8621 }
8622 }
8623 return needSep;
8624 }
8625
8626 boolean dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args,
8627 int opti, boolean dumpAll) {
8628 boolean needSep = false;
8629
8630 if (mLruProcesses.size() > 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07008631 if (needSep) pw.println(" ");
8632 needSep = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -07008633 pw.println(" OOM levels:");
Dianne Hackborn7d608422011-08-07 16:24:18 -07008634 pw.print(" SYSTEM_ADJ: "); pw.println(ProcessList.SYSTEM_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008635 pw.print(" PERSISTENT_PROC_ADJ: "); pw.println(ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07008636 pw.print(" FOREGROUND_APP_ADJ: "); pw.println(ProcessList.FOREGROUND_APP_ADJ);
8637 pw.print(" VISIBLE_APP_ADJ: "); pw.println(ProcessList.VISIBLE_APP_ADJ);
8638 pw.print(" PERCEPTIBLE_APP_ADJ: "); pw.println(ProcessList.PERCEPTIBLE_APP_ADJ);
8639 pw.print(" HEAVY_WEIGHT_APP_ADJ: "); pw.println(ProcessList.HEAVY_WEIGHT_APP_ADJ);
8640 pw.print(" BACKUP_APP_ADJ: "); pw.println(ProcessList.BACKUP_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008641 pw.print(" SERVICE_ADJ: "); pw.println(ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07008642 pw.print(" HOME_APP_ADJ: "); pw.println(ProcessList.HOME_APP_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07008643 pw.print(" PREVIOUS_APP_ADJ: "); pw.println(ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008644 pw.print(" SERVICE_B_ADJ: "); pw.println(ProcessList.SERVICE_B_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07008645 pw.print(" HIDDEN_APP_MIN_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008646 pw.print(" HIDDEN_APP_MAX_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MAX_ADJ);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07008647
8648 if (needSep) pw.println(" ");
8649 needSep = true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07008650 pw.println(" Process OOM control:");
Dianne Hackborn905577f2011-09-07 18:31:28 -07008651 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008652 "Proc", "PERS", true, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008653 needSep = true;
8654 }
8655
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008656 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008657
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008658 pw.println();
Dianne Hackborn287952c2010-09-22 22:34:31 -07008659 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07008660 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008661 if (mHeavyWeightProcess != null) {
8662 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
8663 }
8664
8665 return true;
8666 }
8667
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008668 /**
8669 * There are three ways to call this:
8670 * - no service specified: dump all the services
8671 * - a flattened component name that matched an existing service was specified as the
8672 * first arg: dump that one service
8673 * - the first arg isn't the flattened component name of an existing service:
8674 * dump all services whose component contains the first arg as a substring
8675 */
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008676 protected boolean dumpService(FileDescriptor fd, PrintWriter pw, String name, String[] args,
8677 int opti, boolean dumpAll) {
8678 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008679
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008680 if ("all".equals(name)) {
Dianne Hackborn14bfa392010-07-24 19:58:06 -07008681 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07008682 try {
8683 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
8684 for (UserInfo user : users) {
8685 for (ServiceRecord r1 : mServiceMap.getAllServices(user.id)) {
8686 services.add(r1);
8687 }
8688 }
8689 } catch (RemoteException re) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008690 }
8691 }
8692 } else {
8693 ComponentName componentName = name != null
8694 ? ComponentName.unflattenFromString(name) : null;
8695 int objectId = 0;
8696 if (componentName == null) {
8697 // Not a '/' separated full component name; maybe an object ID?
8698 try {
8699 objectId = Integer.parseInt(name, 16);
8700 name = null;
8701 componentName = null;
8702 } catch (RuntimeException e) {
8703 }
8704 }
8705
8706 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07008707 try {
8708 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
8709 for (UserInfo user : users) {
8710 for (ServiceRecord r1 : mServiceMap.getAllServices(user.id)) {
8711 if (componentName != null) {
8712 if (r1.name.equals(componentName)) {
8713 services.add(r1);
8714 }
8715 } else if (name != null) {
8716 if (r1.name.flattenToString().contains(name)) {
8717 services.add(r1);
8718 }
8719 } else if (System.identityHashCode(r1) == objectId) {
8720 services.add(r1);
8721 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008722 }
Dianne Hackborn14bfa392010-07-24 19:58:06 -07008723 }
Amith Yamasani742a6712011-05-04 14:49:28 -07008724 } catch (RemoteException re) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008725 }
8726 }
8727 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008728
8729 if (services.size() <= 0) {
8730 return false;
8731 }
8732
8733 boolean needSep = false;
8734 for (int i=0; i<services.size(); i++) {
8735 if (needSep) {
8736 pw.println();
8737 }
8738 needSep = true;
8739 dumpService("", fd, pw, services.get(i), args, dumpAll);
8740 }
8741 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008742 }
8743
8744 /**
8745 * Invokes IApplicationThread.dumpService() on the thread of the specified service if
8746 * there is a thread associated with the service.
8747 */
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008748 private void dumpService(String prefix, FileDescriptor fd, PrintWriter pw,
8749 final ServiceRecord r, String[] args, boolean dumpAll) {
8750 String innerPrefix = prefix + " ";
8751 synchronized (this) {
8752 pw.print(prefix); pw.print("SERVICE ");
8753 pw.print(r.shortName); pw.print(" ");
8754 pw.print(Integer.toHexString(System.identityHashCode(r)));
8755 pw.print(" pid=");
8756 if (r.app != null) pw.println(r.app.pid);
8757 else pw.println("(not running)");
8758 if (dumpAll) {
8759 r.dump(pw, innerPrefix);
8760 }
8761 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008762 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008763 pw.print(prefix); pw.println(" Client:");
8764 pw.flush();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008765 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008766 TransferPipe tp = new TransferPipe();
8767 try {
8768 r.app.thread.dumpService(tp.getWriteFd().getFileDescriptor(), r, args);
8769 tp.setBufferPrefix(prefix + " ");
8770 tp.go(fd);
8771 } finally {
8772 tp.kill();
8773 }
8774 } catch (IOException e) {
8775 pw.println(prefix + " Failure while dumping the service: " + e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008776 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008777 pw.println(prefix + " Got a RemoteException while dumping the service");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008778 }
8779 }
8780 }
8781
Marco Nelissen18cb2872011-11-15 11:19:53 -08008782 /**
8783 * There are three ways to call this:
8784 * - no provider specified: dump all the providers
8785 * - a flattened component name that matched an existing provider was specified as the
8786 * first arg: dump that one provider
8787 * - the first arg isn't the flattened component name of an existing provider:
8788 * dump all providers whose component contains the first arg as a substring
8789 */
8790 protected boolean dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args,
8791 int opti, boolean dumpAll) {
Marco Nelissende7408c2012-02-08 14:57:38 -08008792 return mProviderMap.dumpProvider(fd, pw, name, args, opti, dumpAll);
Marco Nelissen18cb2872011-11-15 11:19:53 -08008793 }
8794
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008795 static class ItemMatcher {
8796 ArrayList<ComponentName> components;
8797 ArrayList<String> strings;
8798 ArrayList<Integer> objects;
8799 boolean all;
8800
8801 ItemMatcher() {
8802 all = true;
8803 }
8804
8805 void build(String name) {
8806 ComponentName componentName = ComponentName.unflattenFromString(name);
8807 if (componentName != null) {
8808 if (components == null) {
8809 components = new ArrayList<ComponentName>();
8810 }
8811 components.add(componentName);
8812 all = false;
8813 } else {
8814 int objectId = 0;
8815 // Not a '/' separated full component name; maybe an object ID?
8816 try {
8817 objectId = Integer.parseInt(name, 16);
8818 if (objects == null) {
8819 objects = new ArrayList<Integer>();
8820 }
8821 objects.add(objectId);
8822 all = false;
8823 } catch (RuntimeException e) {
8824 // Not an integer; just do string match.
8825 if (strings == null) {
8826 strings = new ArrayList<String>();
8827 }
8828 strings.add(name);
8829 all = false;
8830 }
8831 }
8832 }
8833
8834 int build(String[] args, int opti) {
8835 for (; opti<args.length; opti++) {
8836 String name = args[opti];
8837 if ("--".equals(name)) {
8838 return opti+1;
8839 }
8840 build(name);
8841 }
8842 return opti;
8843 }
8844
8845 boolean match(Object object, ComponentName comp) {
8846 if (all) {
8847 return true;
8848 }
8849 if (components != null) {
8850 for (int i=0; i<components.size(); i++) {
8851 if (components.get(i).equals(comp)) {
8852 return true;
8853 }
8854 }
8855 }
8856 if (objects != null) {
8857 for (int i=0; i<objects.size(); i++) {
8858 if (System.identityHashCode(object) == objects.get(i)) {
8859 return true;
8860 }
8861 }
8862 }
8863 if (strings != null) {
8864 String flat = comp.flattenToString();
8865 for (int i=0; i<strings.size(); i++) {
8866 if (flat.contains(strings.get(i))) {
8867 return true;
8868 }
8869 }
8870 }
8871 return false;
8872 }
8873 }
8874
Dianne Hackborn625ac272010-09-17 18:29:22 -07008875 /**
8876 * There are three things that cmd can be:
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008877 * - a flattened component name that matches an existing activity
Dianne Hackborn625ac272010-09-17 18:29:22 -07008878 * - the cmd arg isn't the flattened component name of an existing activity:
8879 * dump all activity whose component contains the cmd as a substring
8880 * - A hex number of the ActivityRecord object instance.
8881 */
8882 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
8883 int opti, boolean dumpAll) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07008884 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008885
8886 if ("all".equals(name)) {
8887 synchronized (this) {
8888 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07008889 activities.add(r1);
8890 }
8891 }
Dianne Hackbornf9302322011-06-14 18:36:14 -07008892 } else if ("top".equals(name)) {
8893 synchronized (this) {
8894 final int N = mMainStack.mHistory.size();
8895 if (N > 0) {
8896 activities.add((ActivityRecord)mMainStack.mHistory.get(N-1));
8897 }
8898 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008899 } else {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008900 ItemMatcher matcher = new ItemMatcher();
8901 matcher.build(name);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008902
8903 synchronized (this) {
8904 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008905 if (matcher.match(r1, r1.intent.getComponent())) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008906 activities.add(r1);
8907 }
8908 }
8909 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07008910 }
8911
8912 if (activities.size() <= 0) {
8913 return false;
8914 }
8915
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008916 String[] newArgs = new String[args.length - opti];
8917 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
8918
Dianne Hackborn30d71892010-12-11 10:37:55 -08008919 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008920 boolean needSep = false;
Dianne Hackborn30d71892010-12-11 10:37:55 -08008921 for (int i=activities.size()-1; i>=0; i--) {
8922 ActivityRecord r = (ActivityRecord)activities.get(i);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008923 if (needSep) {
8924 pw.println();
8925 }
8926 needSep = true;
8927 synchronized (this) {
8928 if (lastTask != r.task) {
8929 lastTask = r.task;
8930 pw.print("TASK "); pw.print(lastTask.affinity);
8931 pw.print(" id="); pw.println(lastTask.taskId);
8932 if (dumpAll) {
8933 lastTask.dump(pw, " ");
8934 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08008935 }
8936 }
8937 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
Dianne Hackborn625ac272010-09-17 18:29:22 -07008938 }
8939 return true;
8940 }
8941
8942 /**
8943 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
8944 * there is a thread associated with the activity.
8945 */
Dianne Hackborn30d71892010-12-11 10:37:55 -08008946 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008947 final ActivityRecord r, String[] args, boolean dumpAll) {
8948 String innerPrefix = prefix + " ";
Dianne Hackborn30d71892010-12-11 10:37:55 -08008949 synchronized (this) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008950 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
8951 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
8952 pw.print(" pid=");
Dianne Hackborn30d71892010-12-11 10:37:55 -08008953 if (r.app != null) pw.println(r.app.pid);
8954 else pw.println("(not running)");
8955 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008956 r.dump(pw, innerPrefix);
Dianne Hackborn625ac272010-09-17 18:29:22 -07008957 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07008958 }
8959 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008960 // flush anything that is already in the PrintWriter since the thread is going
8961 // to write to the file descriptor directly
8962 pw.flush();
Dianne Hackborn625ac272010-09-17 18:29:22 -07008963 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008964 TransferPipe tp = new TransferPipe();
8965 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08008966 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
8967 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008968 tp.go(fd);
8969 } finally {
8970 tp.kill();
8971 }
8972 } catch (IOException e) {
8973 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
Dianne Hackborn625ac272010-09-17 18:29:22 -07008974 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008975 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
Dianne Hackborn625ac272010-09-17 18:29:22 -07008976 }
8977 }
8978 }
8979
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008980 boolean dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008981 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008982 boolean needSep = false;
8983
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008984 pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008985 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008986 if (mRegisteredReceivers.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008987 boolean printed = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008988 Iterator it = mRegisteredReceivers.values().iterator();
8989 while (it.hasNext()) {
8990 ReceiverList r = (ReceiverList)it.next();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008991 if (dumpPackage != null && (r.app == null ||
8992 !dumpPackage.equals(r.app.info.packageName))) {
8993 continue;
8994 }
8995 if (!printed) {
8996 pw.println(" Registered Receivers:");
8997 needSep = true;
8998 printed = true;
8999 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009000 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009001 r.dump(pw, " ");
9002 }
9003 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009004
9005 if (mReceiverResolver.dump(pw, needSep ?
9006 "\n Receiver Resolver Table:" : " Receiver Resolver Table:",
9007 " ", dumpPackage, false)) {
9008 needSep = true;
9009 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009010 }
Christopher Tatef46723b2012-01-26 14:19:24 -08009011
9012 for (BroadcastQueue q : mBroadcastQueues) {
9013 needSep = q.dumpLocked(fd, pw, args, opti, dumpAll, dumpPackage, needSep);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009014 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009015
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009016 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009017
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009018 if (mStickyBroadcasts != null && dumpPackage == null) {
9019 if (needSep) {
9020 pw.println();
9021 }
9022 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009023 pw.println(" Sticky broadcasts:");
9024 StringBuilder sb = new StringBuilder(128);
9025 for (Map.Entry<String, ArrayList<Intent>> ent
9026 : mStickyBroadcasts.entrySet()) {
9027 pw.print(" * Sticky action "); pw.print(ent.getKey());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009028 if (dumpAll) {
9029 pw.println(":");
9030 ArrayList<Intent> intents = ent.getValue();
9031 final int N = intents.size();
9032 for (int i=0; i<N; i++) {
9033 sb.setLength(0);
9034 sb.append(" Intent: ");
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009035 intents.get(i).toShortString(sb, false, true, false);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009036 pw.println(sb.toString());
9037 Bundle bundle = intents.get(i).getExtras();
9038 if (bundle != null) {
9039 pw.print(" ");
9040 pw.println(bundle.toString());
9041 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009042 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009043 } else {
9044 pw.println("");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009045 }
9046 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009047 needSep = true;
9048 }
9049
9050 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009051 pw.println();
Christopher Tatef46723b2012-01-26 14:19:24 -08009052 for (BroadcastQueue queue : mBroadcastQueues) {
9053 pw.println(" mBroadcastsScheduled [" + queue.mQueueName + "]="
9054 + queue.mBroadcastsScheduled);
9055 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009056 pw.println(" mHandler:");
9057 mHandler.dump(new PrintWriterPrinter(pw), " ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009058 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009059 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009060
9061 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009062 }
9063
Marco Nelissen18cb2872011-11-15 11:19:53 -08009064 /**
9065 * Prints a list of ServiceRecords (dumpsys activity services)
9066 */
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009067 boolean dumpServicesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009068 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009069 boolean needSep = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009070
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009071 ItemMatcher matcher = new ItemMatcher();
9072 matcher.build(args, opti);
9073
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009074 pw.println("ACTIVITY MANAGER SERVICES (dumpsys activity services)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009075 try {
9076 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
9077 for (UserInfo user : users) {
9078 if (mServiceMap.getAllServices(user.id).size() > 0) {
9079 boolean printed = false;
9080 long nowReal = SystemClock.elapsedRealtime();
9081 Iterator<ServiceRecord> it = mServiceMap.getAllServices(
9082 user.id).iterator();
9083 needSep = false;
9084 while (it.hasNext()) {
9085 ServiceRecord r = it.next();
9086 if (!matcher.match(r, r.name)) {
9087 continue;
9088 }
9089 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9090 continue;
9091 }
9092 if (!printed) {
9093 pw.println(" Active services:");
9094 printed = true;
9095 }
9096 if (needSep) {
9097 pw.println();
9098 }
9099 pw.print(" * ");
9100 pw.println(r);
9101 if (dumpAll) {
9102 r.dump(pw, " ");
9103 needSep = true;
9104 } else {
9105 pw.print(" app=");
9106 pw.println(r.app);
9107 pw.print(" created=");
9108 TimeUtils.formatDuration(r.createTime, nowReal, pw);
9109 pw.print(" started=");
9110 pw.print(r.startRequested);
9111 pw.print(" connections=");
9112 pw.println(r.connections.size());
9113 if (r.connections.size() > 0) {
9114 pw.println(" Connections:");
9115 for (ArrayList<ConnectionRecord> clist : r.connections.values()) {
9116 for (int i = 0; i < clist.size(); i++) {
9117 ConnectionRecord conn = clist.get(i);
9118 pw.print(" ");
9119 pw.print(conn.binding.intent.intent.getIntent()
9120 .toShortString(false, false, false));
9121 pw.print(" -> ");
9122 ProcessRecord proc = conn.binding.client;
9123 pw.println(proc != null ? proc.toShortString() : "null");
9124 }
9125 }
Dianne Hackborn8ec8d412011-11-14 18:27:24 -08009126 }
9127 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009128 if (dumpClient && r.app != null && r.app.thread != null) {
9129 pw.println(" Client:");
9130 pw.flush();
9131 try {
9132 TransferPipe tp = new TransferPipe();
9133 try {
9134 r.app.thread.dumpService(tp.getWriteFd().getFileDescriptor(),
9135 r, args);
9136 tp.setBufferPrefix(" ");
9137 // Short timeout, since blocking here can
9138 // deadlock with the application.
9139 tp.go(fd, 2000);
9140 } finally {
9141 tp.kill();
9142 }
9143 } catch (IOException e) {
9144 pw.println(" Failure while dumping the service: " + e);
9145 } catch (RemoteException e) {
9146 pw.println(" Got a RemoteException while dumping the service");
9147 }
9148 needSep = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009149 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009150 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009151 needSep = printed;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009152 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009153 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009154 } catch (RemoteException re) {
9155
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009156 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009157
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009158 if (mPendingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009159 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009160 for (int i=0; i<mPendingServices.size(); i++) {
9161 ServiceRecord r = mPendingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009162 if (!matcher.match(r, r.name)) {
9163 continue;
9164 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009165 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9166 continue;
9167 }
9168 if (!printed) {
9169 if (needSep) pw.println(" ");
9170 needSep = true;
9171 pw.println(" Pending services:");
9172 printed = true;
9173 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009174 pw.print(" * Pending "); pw.println(r);
9175 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009176 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009177 needSep = true;
9178 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009179
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009180 if (mRestartingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009181 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009182 for (int i=0; i<mRestartingServices.size(); i++) {
9183 ServiceRecord r = mRestartingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009184 if (!matcher.match(r, r.name)) {
9185 continue;
9186 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009187 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9188 continue;
9189 }
9190 if (!printed) {
9191 if (needSep) pw.println(" ");
9192 needSep = true;
9193 pw.println(" Restarting services:");
9194 printed = true;
9195 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009196 pw.print(" * Restarting "); pw.println(r);
9197 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009198 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009199 needSep = true;
9200 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009201
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009202 if (mStoppingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009203 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009204 for (int i=0; i<mStoppingServices.size(); i++) {
9205 ServiceRecord r = mStoppingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009206 if (!matcher.match(r, r.name)) {
9207 continue;
9208 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009209 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9210 continue;
9211 }
9212 if (!printed) {
9213 if (needSep) pw.println(" ");
9214 needSep = true;
9215 pw.println(" Stopping services:");
9216 printed = true;
9217 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009218 pw.print(" * Stopping "); pw.println(r);
9219 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009220 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009221 needSep = true;
9222 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009223
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009224 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009225 if (mServiceConnections.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009226 boolean printed = false;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009227 Iterator<ArrayList<ConnectionRecord>> it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009228 = mServiceConnections.values().iterator();
9229 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009230 ArrayList<ConnectionRecord> r = it.next();
9231 for (int i=0; i<r.size(); i++) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009232 ConnectionRecord cr = r.get(i);
9233 if (!matcher.match(cr.binding.service, cr.binding.service.name)) {
9234 continue;
9235 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009236 if (dumpPackage != null && (cr.binding.client == null
9237 || !dumpPackage.equals(cr.binding.client.info.packageName))) {
9238 continue;
9239 }
9240 if (!printed) {
9241 if (needSep) pw.println(" ");
9242 needSep = true;
9243 pw.println(" Connection bindings to services:");
9244 printed = true;
9245 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009246 pw.print(" * "); pw.println(cr);
9247 cr.dump(pw, " ");
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009248 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009249 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009250 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009251 }
9252 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009253
9254 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009255 }
9256
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009257 boolean dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009258 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009259 boolean needSep = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009260
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009261 ItemMatcher matcher = new ItemMatcher();
9262 matcher.build(args, opti);
9263
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009264 pw.println("ACTIVITY MANAGER CONTENT PROVIDERS (dumpsys activity providers)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009265
9266 mProviderMap.dumpProvidersLocked(pw, dumpAll);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009267
9268 if (mLaunchingProviders.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009269 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009270 for (int i=mLaunchingProviders.size()-1; i>=0; i--) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009271 ContentProviderRecord r = mLaunchingProviders.get(i);
9272 if (dumpPackage != null && !dumpPackage.equals(r.name.getPackageName())) {
9273 continue;
9274 }
9275 if (!printed) {
9276 if (needSep) pw.println(" ");
9277 needSep = true;
9278 pw.println(" Launching content providers:");
9279 printed = true;
9280 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009281 pw.print(" Launching #"); pw.print(i); pw.print(": ");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009282 pw.println(r);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009283 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009284 }
9285
9286 if (mGrantedUriPermissions.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009287 if (needSep) pw.println();
9288 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009289 pw.println("Granted Uri Permissions:");
9290 for (int i=0; i<mGrantedUriPermissions.size(); i++) {
9291 int uid = mGrantedUriPermissions.keyAt(i);
9292 HashMap<Uri, UriPermission> perms
9293 = mGrantedUriPermissions.valueAt(i);
9294 pw.print(" * UID "); pw.print(uid);
9295 pw.println(" holds:");
9296 for (UriPermission perm : perms.values()) {
9297 pw.print(" "); pw.println(perm);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009298 if (dumpAll) {
9299 perm.dump(pw, " ");
9300 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009301 }
9302 }
9303 needSep = true;
9304 }
9305
9306 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009307 }
9308
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009309 boolean dumpPendingIntentsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009310 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009311 boolean needSep = false;
9312
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009313 if (mIntentSenderRecords.size() > 0) {
9314 boolean printed = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009315 Iterator<WeakReference<PendingIntentRecord>> it
9316 = mIntentSenderRecords.values().iterator();
9317 while (it.hasNext()) {
9318 WeakReference<PendingIntentRecord> ref = it.next();
9319 PendingIntentRecord rec = ref != null ? ref.get(): null;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009320 if (dumpPackage != null && (rec == null
9321 || !dumpPackage.equals(rec.key.packageName))) {
9322 continue;
9323 }
9324 if (!printed) {
9325 pw.println("ACTIVITY MANAGER PENDING INTENTS (dumpsys activity intents)");
9326 printed = true;
9327 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009328 needSep = true;
9329 if (rec != null) {
9330 pw.print(" * "); pw.println(rec);
9331 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009332 rec.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009333 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009334 } else {
9335 pw.print(" * "); pw.println(ref);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009336 }
9337 }
9338 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009339
9340 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009341 }
9342
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009343 private static final void dumpHistoryList(FileDescriptor fd, PrintWriter pw, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009344 String prefix, String label, boolean complete, boolean brief, boolean client,
9345 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009346 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009347 boolean needNL = false;
9348 final String innerPrefix = prefix + " ";
9349 final String[] args = new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009350 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009351 final ActivityRecord r = (ActivityRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009352 if (dumpPackage != null && !dumpPackage.equals(r.packageName)) {
9353 continue;
9354 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07009355 final boolean full = !brief && (complete || !r.isInHistory());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009356 if (needNL) {
9357 pw.println(" ");
9358 needNL = false;
9359 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009360 if (lastTask != r.task) {
9361 lastTask = r.task;
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009362 pw.print(prefix);
9363 pw.print(full ? "* " : " ");
9364 pw.println(lastTask);
9365 if (full) {
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009366 lastTask.dump(pw, prefix + " ");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009367 } else if (complete) {
9368 // Complete + brief == give a summary. Isn't that obvious?!?
9369 if (lastTask.intent != null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009370 pw.print(prefix); pw.print(" ");
9371 pw.println(lastTask.intent.toInsecureString());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009372 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009373 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009374 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009375 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label);
9376 pw.print(" #"); pw.print(i); pw.print(": ");
9377 pw.println(r);
9378 if (full) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009379 r.dump(pw, innerPrefix);
9380 } else if (complete) {
9381 // Complete + brief == give a summary. Isn't that obvious?!?
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009382 pw.print(innerPrefix); pw.println(r.intent.toInsecureString());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009383 if (r.app != null) {
9384 pw.print(innerPrefix); pw.println(r.app);
9385 }
9386 }
9387 if (client && r.app != null && r.app.thread != null) {
9388 // flush anything that is already in the PrintWriter since the thread is going
9389 // to write to the file descriptor directly
9390 pw.flush();
9391 try {
9392 TransferPipe tp = new TransferPipe();
9393 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009394 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9395 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009396 // Short timeout, since blocking here can
9397 // deadlock with the application.
9398 tp.go(fd, 2000);
9399 } finally {
9400 tp.kill();
9401 }
9402 } catch (IOException e) {
9403 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
9404 } catch (RemoteException e) {
9405 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
9406 }
9407 needNL = true;
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009408 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009409 }
9410 }
9411
Dianne Hackborn09c916b2009-12-08 14:50:51 -08009412 private static String buildOomTag(String prefix, String space, int val, int base) {
9413 if (val == base) {
9414 if (space == null) return prefix;
9415 return prefix + " ";
9416 }
9417 return prefix + "+" + Integer.toString(val-base);
9418 }
9419
9420 private static final int dumpProcessList(PrintWriter pw,
9421 ActivityManagerService service, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009422 String prefix, String normalLabel, String persistentLabel,
9423 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009424 int numPers = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07009425 final int N = list.size()-1;
9426 for (int i=N; i>=0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009427 ProcessRecord r = (ProcessRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009428 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9429 continue;
9430 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009431 pw.println(String.format("%s%s #%2d: %s",
9432 prefix, (r.persistent ? persistentLabel : normalLabel),
9433 i, r.toString()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009434 if (r.persistent) {
9435 numPers++;
9436 }
9437 }
9438 return numPers;
9439 }
9440
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009441 private static final boolean dumpProcessOomList(PrintWriter pw,
Dianne Hackborn905577f2011-09-07 18:31:28 -07009442 ActivityManagerService service, List<ProcessRecord> origList,
Dianne Hackborn287952c2010-09-22 22:34:31 -07009443 String prefix, String normalLabel, String persistentLabel,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009444 boolean inclDetails, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009445
Dianne Hackborn905577f2011-09-07 18:31:28 -07009446 ArrayList<Pair<ProcessRecord, Integer>> list
9447 = new ArrayList<Pair<ProcessRecord, Integer>>(origList.size());
9448 for (int i=0; i<origList.size(); i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009449 ProcessRecord r = origList.get(i);
9450 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9451 continue;
9452 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07009453 list.add(new Pair<ProcessRecord, Integer>(origList.get(i), i));
9454 }
9455
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009456 if (list.size() <= 0) {
9457 return false;
9458 }
9459
Dianne Hackborn905577f2011-09-07 18:31:28 -07009460 Comparator<Pair<ProcessRecord, Integer>> comparator
9461 = new Comparator<Pair<ProcessRecord, Integer>>() {
9462 @Override
9463 public int compare(Pair<ProcessRecord, Integer> object1,
9464 Pair<ProcessRecord, Integer> object2) {
9465 if (object1.first.setAdj != object2.first.setAdj) {
9466 return object1.first.setAdj > object2.first.setAdj ? -1 : 1;
9467 }
9468 if (object1.second.intValue() != object2.second.intValue()) {
9469 return object1.second.intValue() > object2.second.intValue() ? -1 : 1;
9470 }
9471 return 0;
9472 }
9473 };
9474
9475 Collections.sort(list, comparator);
9476
Dianne Hackborn287952c2010-09-22 22:34:31 -07009477 final long curRealtime = SystemClock.elapsedRealtime();
9478 final long realtimeSince = curRealtime - service.mLastPowerCheckRealtime;
9479 final long curUptime = SystemClock.uptimeMillis();
9480 final long uptimeSince = curUptime - service.mLastPowerCheckUptime;
9481
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009482 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07009483 ProcessRecord r = list.get(i).first;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009484 String oomAdj;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009485 if (r.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07009486 oomAdj = buildOomTag("bak", " ", r.setAdj, ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009487 } else if (r.setAdj >= ProcessList.SERVICE_B_ADJ) {
9488 oomAdj = buildOomTag("svcb ", null, r.setAdj, ProcessList.SERVICE_B_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009489 } else if (r.setAdj >= ProcessList.PREVIOUS_APP_ADJ) {
9490 oomAdj = buildOomTag("prev ", null, r.setAdj, ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009491 } else if (r.setAdj >= ProcessList.HOME_APP_ADJ) {
9492 oomAdj = buildOomTag("home ", null, r.setAdj, ProcessList.HOME_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009493 } else if (r.setAdj >= ProcessList.SERVICE_ADJ) {
9494 oomAdj = buildOomTag("svc ", null, r.setAdj, ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009495 } else if (r.setAdj >= ProcessList.BACKUP_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08009496 oomAdj = buildOomTag("bkup ", null, r.setAdj, ProcessList.BACKUP_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009497 } else if (r.setAdj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
9498 oomAdj = buildOomTag("hvy ", null, r.setAdj, ProcessList.HEAVY_WEIGHT_APP_ADJ);
9499 } else if (r.setAdj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
9500 oomAdj = buildOomTag("prcp ", null, r.setAdj, ProcessList.PERCEPTIBLE_APP_ADJ);
9501 } else if (r.setAdj >= ProcessList.VISIBLE_APP_ADJ) {
9502 oomAdj = buildOomTag("vis ", null, r.setAdj, ProcessList.VISIBLE_APP_ADJ);
9503 } else if (r.setAdj >= ProcessList.FOREGROUND_APP_ADJ) {
9504 oomAdj = buildOomTag("fore ", null, r.setAdj, ProcessList.FOREGROUND_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009505 } else if (r.setAdj >= ProcessList.PERSISTENT_PROC_ADJ) {
9506 oomAdj = buildOomTag("pers ", null, r.setAdj, ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009507 } else if (r.setAdj >= ProcessList.SYSTEM_ADJ) {
9508 oomAdj = buildOomTag("sys ", null, r.setAdj, ProcessList.SYSTEM_ADJ);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009509 } else {
9510 oomAdj = Integer.toString(r.setAdj);
9511 }
9512 String schedGroup;
9513 switch (r.setSchedGroup) {
9514 case Process.THREAD_GROUP_BG_NONINTERACTIVE:
9515 schedGroup = "B";
9516 break;
9517 case Process.THREAD_GROUP_DEFAULT:
9518 schedGroup = "F";
9519 break;
9520 default:
9521 schedGroup = Integer.toString(r.setSchedGroup);
9522 break;
9523 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07009524 String foreground;
9525 if (r.foregroundActivities) {
9526 foreground = "A";
9527 } else if (r.foregroundServices) {
9528 foreground = "S";
9529 } else {
9530 foreground = " ";
9531 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07009532 pw.println(String.format("%s%s #%2d: adj=%s/%s%s trm=%2d %s (%s)",
Dianne Hackborn287952c2010-09-22 22:34:31 -07009533 prefix, (r.persistent ? persistentLabel : normalLabel),
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009534 (origList.size()-1)-list.get(i).second, oomAdj, schedGroup,
9535 foreground, r.trimMemoryLevel, r.toShortString(), r.adjType));
Dianne Hackborn287952c2010-09-22 22:34:31 -07009536 if (r.adjSource != null || r.adjTarget != null) {
9537 pw.print(prefix);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009538 pw.print(" ");
Dianne Hackborn287952c2010-09-22 22:34:31 -07009539 if (r.adjTarget instanceof ComponentName) {
9540 pw.print(((ComponentName)r.adjTarget).flattenToShortString());
9541 } else if (r.adjTarget != null) {
9542 pw.print(r.adjTarget.toString());
9543 } else {
9544 pw.print("{null}");
9545 }
9546 pw.print("<=");
9547 if (r.adjSource instanceof ProcessRecord) {
9548 pw.print("Proc{");
9549 pw.print(((ProcessRecord)r.adjSource).toShortString());
9550 pw.println("}");
9551 } else if (r.adjSource != null) {
9552 pw.println(r.adjSource.toString());
9553 } else {
9554 pw.println("{null}");
9555 }
9556 }
9557 if (inclDetails) {
9558 pw.print(prefix);
9559 pw.print(" ");
9560 pw.print("oom: max="); pw.print(r.maxAdj);
9561 pw.print(" hidden="); pw.print(r.hiddenAdj);
9562 pw.print(" curRaw="); pw.print(r.curRawAdj);
9563 pw.print(" setRaw="); pw.print(r.setRawAdj);
9564 pw.print(" cur="); pw.print(r.curAdj);
9565 pw.print(" set="); pw.println(r.setAdj);
9566 pw.print(prefix);
9567 pw.print(" ");
9568 pw.print("keeping="); pw.print(r.keeping);
9569 pw.print(" hidden="); pw.print(r.hidden);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009570 pw.print(" empty="); pw.print(r.empty);
9571 pw.print(" hasAboveClient="); pw.println(r.hasAboveClient);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009572
9573 if (!r.keeping) {
9574 if (r.lastWakeTime != 0) {
9575 long wtime;
9576 BatteryStatsImpl stats = service.mBatteryStatsService.getActiveStatistics();
9577 synchronized (stats) {
9578 wtime = stats.getProcessWakeTime(r.info.uid,
9579 r.pid, curRealtime);
9580 }
9581 long timeUsed = wtime - r.lastWakeTime;
9582 pw.print(prefix);
9583 pw.print(" ");
9584 pw.print("keep awake over ");
9585 TimeUtils.formatDuration(realtimeSince, pw);
9586 pw.print(" used ");
9587 TimeUtils.formatDuration(timeUsed, pw);
9588 pw.print(" (");
9589 pw.print((timeUsed*100)/realtimeSince);
9590 pw.println("%)");
9591 }
9592 if (r.lastCpuTime != 0) {
9593 long timeUsed = r.curCpuTime - r.lastCpuTime;
9594 pw.print(prefix);
9595 pw.print(" ");
9596 pw.print("run cpu over ");
9597 TimeUtils.formatDuration(uptimeSince, pw);
9598 pw.print(" used ");
9599 TimeUtils.formatDuration(timeUsed, pw);
9600 pw.print(" (");
9601 pw.print((timeUsed*100)/uptimeSince);
9602 pw.println("%)");
9603 }
9604 }
9605 }
9606 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009607 return true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009608 }
9609
Dianne Hackbornb437e092011-08-05 17:50:29 -07009610 ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, String[] args) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009611 ArrayList<ProcessRecord> procs;
9612 synchronized (this) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009613 if (args != null && args.length > start
9614 && args[start].charAt(0) != '-') {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009615 procs = new ArrayList<ProcessRecord>();
9616 int pid = -1;
9617 try {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009618 pid = Integer.parseInt(args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009619 } catch (NumberFormatException e) {
9620
9621 }
9622 for (int i=mLruProcesses.size()-1; i>=0; i--) {
9623 ProcessRecord proc = mLruProcesses.get(i);
9624 if (proc.pid == pid) {
9625 procs.add(proc);
Dianne Hackbornb437e092011-08-05 17:50:29 -07009626 } else if (proc.processName.equals(args[start])) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009627 procs.add(proc);
9628 }
9629 }
9630 if (procs.size() <= 0) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009631 pw.println("No process found for: " + args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009632 return null;
9633 }
9634 } else {
9635 procs = new ArrayList<ProcessRecord>(mLruProcesses);
9636 }
9637 }
9638 return procs;
9639 }
9640
9641 final void dumpGraphicsHardwareUsage(FileDescriptor fd,
9642 PrintWriter pw, String[] args) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009643 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009644 if (procs == null) {
9645 return;
9646 }
9647
9648 long uptime = SystemClock.uptimeMillis();
9649 long realtime = SystemClock.elapsedRealtime();
9650 pw.println("Applications Graphics Acceleration Info:");
9651 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
9652
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009653 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
9654 ProcessRecord r = procs.get(i);
Chet Haase9c1e23b2011-03-24 10:51:31 -07009655 if (r.thread != null) {
9656 pw.println("\n** Graphics info for pid " + r.pid + " [" + r.processName + "] **");
9657 pw.flush();
9658 try {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009659 TransferPipe tp = new TransferPipe();
9660 try {
9661 r.thread.dumpGfxInfo(tp.getWriteFd().getFileDescriptor(), args);
9662 tp.go(fd);
9663 } finally {
9664 tp.kill();
9665 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009666 } catch (IOException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009667 pw.println("Failure while dumping the app: " + r);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009668 pw.flush();
Chet Haase9c1e23b2011-03-24 10:51:31 -07009669 } catch (RemoteException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009670 pw.println("Got a RemoteException while dumping the app " + r);
Chet Haase9c1e23b2011-03-24 10:51:31 -07009671 pw.flush();
9672 }
9673 }
9674 }
Chet Haase9c1e23b2011-03-24 10:51:31 -07009675 }
9676
Jeff Brown6754ba22011-12-14 20:20:01 -08009677 final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) {
9678 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
9679 if (procs == null) {
9680 return;
9681 }
9682
9683 pw.println("Applications Database Info:");
9684
9685 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
9686 ProcessRecord r = procs.get(i);
9687 if (r.thread != null) {
9688 pw.println("\n** Database info for pid " + r.pid + " [" + r.processName + "] **");
9689 pw.flush();
9690 try {
9691 TransferPipe tp = new TransferPipe();
9692 try {
9693 r.thread.dumpDbInfo(tp.getWriteFd().getFileDescriptor(), args);
9694 tp.go(fd);
9695 } finally {
9696 tp.kill();
9697 }
9698 } catch (IOException e) {
9699 pw.println("Failure while dumping the app: " + r);
9700 pw.flush();
9701 } catch (RemoteException e) {
9702 pw.println("Got a RemoteException while dumping the app " + r);
9703 pw.flush();
9704 }
9705 }
9706 }
9707 }
9708
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009709 final static class MemItem {
9710 final String label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009711 final String shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009712 final long pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009713 final int id;
Dianne Hackborna4bacb82011-08-24 15:12:38 -07009714 ArrayList<MemItem> subitems;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009715
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009716 public MemItem(String _label, String _shortLabel, long _pss, int _id) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009717 label = _label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009718 shortLabel = _shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009719 pss = _pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009720 id = _id;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009721 }
9722 }
9723
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009724 static final void dumpMemItems(PrintWriter pw, String prefix, ArrayList<MemItem> items,
Dianne Hackbornb437e092011-08-05 17:50:29 -07009725 boolean sort) {
9726 if (sort) {
9727 Collections.sort(items, new Comparator<MemItem>() {
9728 @Override
9729 public int compare(MemItem lhs, MemItem rhs) {
9730 if (lhs.pss < rhs.pss) {
9731 return 1;
9732 } else if (lhs.pss > rhs.pss) {
9733 return -1;
9734 }
9735 return 0;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009736 }
Dianne Hackbornb437e092011-08-05 17:50:29 -07009737 });
9738 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009739
9740 for (int i=0; i<items.size(); i++) {
9741 MemItem mi = items.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009742 pw.print(prefix); pw.printf("%7d kB: ", mi.pss); pw.println(mi.label);
Dianne Hackborna4bacb82011-08-24 15:12:38 -07009743 if (mi.subitems != null) {
9744 dumpMemItems(pw, prefix + " ", mi.subitems, true);
9745 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009746 }
9747 }
9748
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009749 // These are in KB.
9750 static final long[] DUMP_MEM_BUCKETS = new long[] {
9751 5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024,
9752 120*1024, 160*1024, 200*1024,
9753 250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024,
9754 1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024
9755 };
9756
Dianne Hackborn672342c2011-11-29 11:29:02 -08009757 static final void appendMemBucket(StringBuilder out, long memKB, String label,
9758 boolean stackLike) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009759 int start = label.lastIndexOf('.');
9760 if (start >= 0) start++;
9761 else start = 0;
9762 int end = label.length();
9763 for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) {
9764 if (DUMP_MEM_BUCKETS[i] >= memKB) {
9765 long bucket = DUMP_MEM_BUCKETS[i]/1024;
9766 out.append(bucket);
Dianne Hackborn672342c2011-11-29 11:29:02 -08009767 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009768 out.append(label, start, end);
9769 return;
9770 }
9771 }
9772 out.append(memKB/1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -08009773 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009774 out.append(label, start, end);
9775 }
9776
9777 static final int[] DUMP_MEM_OOM_ADJ = new int[] {
9778 ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ, ProcessList.FOREGROUND_APP_ADJ,
9779 ProcessList.VISIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ,
9780 ProcessList.BACKUP_APP_ADJ, ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ,
9781 ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.HIDDEN_APP_MAX_ADJ
9782 };
9783 static final String[] DUMP_MEM_OOM_LABEL = new String[] {
9784 "System", "Persistent", "Foreground",
9785 "Visible", "Perceptible", "Heavy Weight",
9786 "Backup", "A Services", "Home", "Previous",
9787 "B Services", "Background"
9788 };
9789
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009790 final void dumpApplicationMemoryUsage(FileDescriptor fd,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08009791 PrintWriter pw, String prefix, String[] args, boolean brief,
Dianne Hackborn672342c2011-11-29 11:29:02 -08009792 PrintWriter categoryPw, StringBuilder outTag, StringBuilder outStack) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009793 boolean dumpAll = false;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08009794 boolean oomOnly = false;
Dianne Hackbornb437e092011-08-05 17:50:29 -07009795
9796 int opti = 0;
9797 while (opti < args.length) {
9798 String opt = args[opti];
9799 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
9800 break;
9801 }
9802 opti++;
9803 if ("-a".equals(opt)) {
9804 dumpAll = true;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08009805 } else if ("--oom".equals(opt)) {
9806 oomOnly = true;
Dianne Hackbornb437e092011-08-05 17:50:29 -07009807 } else if ("-h".equals(opt)) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08009808 pw.println("meminfo dump options: [-a] [--oom] [process]");
Dianne Hackbornb437e092011-08-05 17:50:29 -07009809 pw.println(" -a: include all available information for each process.");
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08009810 pw.println(" --oom: only show processes organized by oom adj.");
Dianne Hackbornb437e092011-08-05 17:50:29 -07009811 pw.println("If [process] is specified it can be the name or ");
9812 pw.println("pid of a specific process to dump.");
9813 return;
9814 } else {
9815 pw.println("Unknown argument: " + opt + "; use -h for help");
9816 }
9817 }
9818
9819 ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009820 if (procs == null) {
9821 return;
9822 }
9823
Dianne Hackborn6447ca32009-04-07 19:50:08 -07009824 final boolean isCheckinRequest = scanArgs(args, "--checkin");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009825 long uptime = SystemClock.uptimeMillis();
9826 long realtime = SystemClock.elapsedRealtime();
Dianne Hackbornb437e092011-08-05 17:50:29 -07009827
9828 if (procs.size() == 1 || isCheckinRequest) {
9829 dumpAll = true;
9830 }
9831
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009832 if (isCheckinRequest) {
9833 // short checkin version
9834 pw.println(uptime + "," + realtime);
9835 pw.flush();
9836 } else {
9837 pw.println("Applications Memory Usage (kB):");
9838 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
9839 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009840
Dianne Hackbornb437e092011-08-05 17:50:29 -07009841 String[] innerArgs = new String[args.length-opti];
9842 System.arraycopy(args, opti, innerArgs, 0, args.length-opti);
9843
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009844 ArrayList<MemItem> procMems = new ArrayList<MemItem>();
9845 long nativePss=0, dalvikPss=0, otherPss=0;
9846 long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
9847
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009848 long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length];
9849 ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[])
9850 new ArrayList[DUMP_MEM_OOM_LABEL.length];
Dianne Hackbornb437e092011-08-05 17:50:29 -07009851
9852 long totalPss = 0;
9853
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009854 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
9855 ProcessRecord r = procs.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009856 if (r.thread != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009857 if (!isCheckinRequest && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009858 pw.println("\n** MEMINFO in pid " + r.pid + " [" + r.processName + "] **");
9859 pw.flush();
9860 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009861 Debug.MemoryInfo mi = null;
Dianne Hackbornb437e092011-08-05 17:50:29 -07009862 if (dumpAll) {
9863 try {
9864 mi = r.thread.dumpMemInfo(fd, isCheckinRequest, dumpAll, innerArgs);
9865 } catch (RemoteException e) {
9866 if (!isCheckinRequest) {
9867 pw.println("Got RemoteException!");
9868 pw.flush();
9869 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009870 }
Dianne Hackbornb437e092011-08-05 17:50:29 -07009871 } else {
9872 mi = new Debug.MemoryInfo();
9873 Debug.getMemoryInfo(r.pid, mi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009874 }
Dianne Hackbornb437e092011-08-05 17:50:29 -07009875
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009876 if (!isCheckinRequest && mi != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009877 long myTotalPss = mi.getTotalPss();
9878 totalPss += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -07009879 MemItem pssItem = new MemItem(r.processName + " (pid " + r.pid + ")",
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009880 r.processName, myTotalPss, 0);
Dianne Hackborna4bacb82011-08-24 15:12:38 -07009881 procMems.add(pssItem);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009882
9883 nativePss += mi.nativePss;
9884 dalvikPss += mi.dalvikPss;
9885 otherPss += mi.otherPss;
9886 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
9887 long mem = mi.getOtherPss(j);
9888 miscPss[j] += mem;
9889 otherPss -= mem;
9890 }
Dianne Hackbornb437e092011-08-05 17:50:29 -07009891
9892 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009893 if (r.setAdj <= DUMP_MEM_OOM_ADJ[oomIndex]
9894 || oomIndex == (oomPss.length-1)) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009895 oomPss[oomIndex] += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -07009896 if (oomProcs[oomIndex] == null) {
9897 oomProcs[oomIndex] = new ArrayList<MemItem>();
9898 }
9899 oomProcs[oomIndex].add(pssItem);
Dianne Hackbornb437e092011-08-05 17:50:29 -07009900 break;
9901 }
9902 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009903 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009904 }
9905 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009906
9907 if (!isCheckinRequest && procs.size() > 1) {
9908 ArrayList<MemItem> catMems = new ArrayList<MemItem>();
9909
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009910 catMems.add(new MemItem("Native", "Native", nativePss, -1));
9911 catMems.add(new MemItem("Dalvik", "Dalvik", dalvikPss, -2));
9912 catMems.add(new MemItem("Unknown", "Unknown", otherPss, -3));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009913 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009914 String label = Debug.MemoryInfo.getOtherLabel(j);
9915 catMems.add(new MemItem(label, label, miscPss[j], j));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009916 }
9917
Dianne Hackbornb437e092011-08-05 17:50:29 -07009918 ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
9919 for (int j=0; j<oomPss.length; j++) {
9920 if (oomPss[j] != 0) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009921 String label = DUMP_MEM_OOM_LABEL[j];
9922 MemItem item = new MemItem(label, label, oomPss[j],
9923 DUMP_MEM_OOM_ADJ[j]);
Dianne Hackborna4bacb82011-08-24 15:12:38 -07009924 item.subitems = oomProcs[j];
9925 oomMems.add(item);
Dianne Hackbornb437e092011-08-05 17:50:29 -07009926 }
9927 }
9928
Dianne Hackborn672342c2011-11-29 11:29:02 -08009929 if (outTag != null || outStack != null) {
9930 if (outTag != null) {
9931 appendMemBucket(outTag, totalPss, "total", false);
9932 }
9933 if (outStack != null) {
9934 appendMemBucket(outStack, totalPss, "total", true);
9935 }
9936 boolean firstLine = true;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009937 for (int i=0; i<oomMems.size(); i++) {
9938 MemItem miCat = oomMems.get(i);
9939 if (miCat.subitems == null || miCat.subitems.size() < 1) {
9940 continue;
9941 }
9942 if (miCat.id < ProcessList.SERVICE_ADJ
9943 || miCat.id == ProcessList.HOME_APP_ADJ
9944 || miCat.id == ProcessList.PREVIOUS_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08009945 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
9946 outTag.append(" / ");
9947 }
9948 if (outStack != null) {
9949 if (miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
9950 if (firstLine) {
9951 outStack.append(":");
9952 firstLine = false;
9953 }
9954 outStack.append("\n\t at ");
9955 } else {
9956 outStack.append("$");
9957 }
9958 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009959 for (int j=0; j<miCat.subitems.size(); j++) {
9960 MemItem mi = miCat.subitems.get(j);
9961 if (j > 0) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08009962 if (outTag != null) {
9963 outTag.append(" ");
9964 }
9965 if (outStack != null) {
9966 outStack.append("$");
9967 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009968 }
Dianne Hackborn672342c2011-11-29 11:29:02 -08009969 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
9970 appendMemBucket(outTag, mi.pss, mi.shortLabel, false);
9971 }
9972 if (outStack != null) {
9973 appendMemBucket(outStack, mi.pss, mi.shortLabel, true);
9974 }
9975 }
9976 if (outStack != null && miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
9977 outStack.append("(");
9978 for (int k=0; k<DUMP_MEM_OOM_ADJ.length; k++) {
9979 if (DUMP_MEM_OOM_ADJ[k] == miCat.id) {
9980 outStack.append(DUMP_MEM_OOM_LABEL[k]);
9981 outStack.append(":");
9982 outStack.append(DUMP_MEM_OOM_ADJ[k]);
9983 }
9984 }
9985 outStack.append(")");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009986 }
9987 }
9988 }
9989 }
9990
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08009991 if (!brief && !oomOnly) {
Dianne Hackborn04d6db32011-11-04 20:07:24 -07009992 pw.println();
9993 pw.println("Total PSS by process:");
9994 dumpMemItems(pw, " ", procMems, true);
9995 pw.println();
9996 }
Dianne Hackbornb437e092011-08-05 17:50:29 -07009997 pw.println("Total PSS by OOM adjustment:");
9998 dumpMemItems(pw, " ", oomMems, false);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08009999 if (!oomOnly) {
10000 PrintWriter out = categoryPw != null ? categoryPw : pw;
10001 out.println();
10002 out.println("Total PSS by category:");
10003 dumpMemItems(out, " ", catMems, true);
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010004 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010005 pw.println();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010006 pw.print("Total PSS: "); pw.print(totalPss); pw.println(" kB");
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010007 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010008 }
10009
10010 /**
10011 * Searches array of arguments for the specified string
10012 * @param args array of argument strings
10013 * @param value value to search for
10014 * @return true if the value is contained in the array
10015 */
10016 private static boolean scanArgs(String[] args, String value) {
10017 if (args != null) {
10018 for (String arg : args) {
10019 if (value.equals(arg)) {
10020 return true;
10021 }
10022 }
10023 }
10024 return false;
10025 }
10026
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010027 private final void killServicesLocked(ProcessRecord app,
10028 boolean allowRestart) {
10029 // Report disconnected services.
10030 if (false) {
10031 // XXX we are letting the client link to the service for
10032 // death notifications.
10033 if (app.services.size() > 0) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010034 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010035 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010036 ServiceRecord r = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010037 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010038 Iterator<ArrayList<ConnectionRecord>> jt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010039 = r.connections.values().iterator();
10040 while (jt.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010041 ArrayList<ConnectionRecord> cl = jt.next();
10042 for (int i=0; i<cl.size(); i++) {
10043 ConnectionRecord c = cl.get(i);
10044 if (c.binding.client != app) {
10045 try {
10046 //c.conn.connected(r.className, null);
10047 } catch (Exception e) {
10048 // todo: this should be asynchronous!
10049 Slog.w(TAG, "Exception thrown disconnected servce "
10050 + r.shortName
10051 + " from app " + app.processName, e);
10052 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010053 }
10054 }
10055 }
10056 }
10057 }
10058 }
10059 }
10060
10061 // Clean up any connections this application has to other services.
10062 if (app.connections.size() > 0) {
10063 Iterator<ConnectionRecord> it = app.connections.iterator();
10064 while (it.hasNext()) {
10065 ConnectionRecord r = it.next();
10066 removeConnectionLocked(r, app, null);
10067 }
10068 }
10069 app.connections.clear();
10070
10071 if (app.services.size() != 0) {
10072 // Any services running in the application need to be placed
10073 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -070010074 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010075 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010076 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010077 synchronized (sr.stats.getBatteryStats()) {
10078 sr.stats.stopLaunchedLocked();
10079 }
10080 sr.app = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010081 sr.isolatedProc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010082 sr.executeNesting = 0;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010083 if (mStoppingServices.remove(sr)) {
10084 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
10085 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010086
10087 boolean hasClients = sr.bindings.size() > 0;
10088 if (hasClients) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010089 Iterator<IntentBindRecord> bindings
10090 = sr.bindings.values().iterator();
10091 while (bindings.hasNext()) {
10092 IntentBindRecord b = bindings.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -080010093 if (DEBUG_SERVICE) Slog.v(TAG, "Killing binding " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010094 + ": shouldUnbind=" + b.hasBound);
10095 b.binder = null;
10096 b.requested = b.received = b.hasBound = false;
10097 }
10098 }
10099
Dianne Hackborn070783f2010-12-29 16:46:28 -080010100 if (sr.crashCount >= 2 && (sr.serviceInfo.applicationInfo.flags
10101 &ApplicationInfo.FLAG_PERSISTENT) == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010102 Slog.w(TAG, "Service crashed " + sr.crashCount
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010103 + " times, stopping: " + sr);
Doug Zongker2bec3d42009-12-04 12:52:44 -080010104 EventLog.writeEvent(EventLogTags.AM_SERVICE_CRASHED_TOO_MUCH,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010105 sr.crashCount, sr.shortName, app.pid);
10106 bringDownServiceLocked(sr, true);
10107 } else if (!allowRestart) {
10108 bringDownServiceLocked(sr, true);
10109 } else {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010110 boolean canceled = scheduleServiceRestartLocked(sr, true);
10111
10112 // Should the service remain running? Note that in the
10113 // extreme case of so many attempts to deliver a command
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010114 // that it failed we also will stop it here.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010115 if (sr.startRequested && (sr.stopIfKilled || canceled)) {
10116 if (sr.pendingStarts.size() == 0) {
10117 sr.startRequested = false;
10118 if (!hasClients) {
10119 // Whoops, no reason to restart!
10120 bringDownServiceLocked(sr, true);
10121 }
10122 }
10123 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010124 }
10125 }
10126
10127 if (!allowRestart) {
10128 app.services.clear();
10129 }
10130 }
10131
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010132 // Make sure we have no more records on the stopping list.
10133 int i = mStoppingServices.size();
10134 while (i > 0) {
10135 i--;
10136 ServiceRecord sr = mStoppingServices.get(i);
10137 if (sr.app == app) {
10138 mStoppingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010139 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010140 }
10141 }
10142
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010143 app.executingServices.clear();
10144 }
10145
10146 private final void removeDyingProviderLocked(ProcessRecord proc,
10147 ContentProviderRecord cpr) {
10148 synchronized (cpr) {
10149 cpr.launchingApp = null;
10150 cpr.notifyAll();
10151 }
10152
Amith Yamasani742a6712011-05-04 14:49:28 -070010153 mProviderMap.removeProviderByClass(cpr.name, UserId.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010154 String names[] = cpr.info.authority.split(";");
10155 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010156 mProviderMap.removeProviderByName(names[j], UserId.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010157 }
10158
10159 Iterator<ProcessRecord> cit = cpr.clients.iterator();
10160 while (cit.hasNext()) {
10161 ProcessRecord capp = cit.next();
10162 if (!capp.persistent && capp.thread != null
10163 && capp.pid != 0
10164 && capp.pid != MY_PID) {
Dianne Hackborn8633e682010-04-22 16:03:41 -070010165 Slog.i(TAG, "Kill " + capp.processName
10166 + " (pid " + capp.pid + "): provider " + cpr.info.name
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010167 + " in dying process " + (proc != null ? proc.processName : "??"));
Dianne Hackborn8633e682010-04-22 16:03:41 -070010168 EventLog.writeEvent(EventLogTags.AM_KILL, capp.pid,
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010169 capp.processName, capp.setAdj, "dying provider "
10170 + cpr.name.toShortString());
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070010171 Process.killProcessQuiet(capp.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010172 }
10173 }
10174
10175 mLaunchingProviders.remove(cpr);
10176 }
10177
10178 /**
10179 * Main code for cleaning up a process when it has gone away. This is
10180 * called both as a result of the process dying, or directly when stopping
10181 * a process when running in single process mode.
10182 */
10183 private final void cleanUpApplicationRecordLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010184 boolean restarting, boolean allowRestart, int index) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010185 if (index >= 0) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010186 mLruProcesses.remove(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010187 }
10188
Dianne Hackborn36124872009-10-08 16:22:03 -070010189 mProcessesToGc.remove(app);
10190
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010191 // Dismiss any open dialogs.
10192 if (app.crashDialog != null) {
10193 app.crashDialog.dismiss();
10194 app.crashDialog = null;
10195 }
10196 if (app.anrDialog != null) {
10197 app.anrDialog.dismiss();
10198 app.anrDialog = null;
10199 }
10200 if (app.waitDialog != null) {
10201 app.waitDialog.dismiss();
10202 app.waitDialog = null;
10203 }
10204
10205 app.crashing = false;
10206 app.notResponding = false;
10207
10208 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -070010209 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010210 app.thread = null;
10211 app.forcingToForeground = null;
10212 app.foregroundServices = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010213 app.foregroundActivities = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070010214 app.hasShownUi = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010215 app.hasAboveClient = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010216
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010217 killServicesLocked(app, allowRestart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010218
10219 boolean restart = false;
10220
10221 int NL = mLaunchingProviders.size();
10222
10223 // Remove published content providers.
10224 if (!app.pubProviders.isEmpty()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010225 Iterator<ContentProviderRecord> it = app.pubProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010226 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010227 ContentProviderRecord cpr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010228 cpr.provider = null;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010229 cpr.proc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010230
10231 // See if someone is waiting for this provider... in which
10232 // case we don't remove it, but just let it restart.
10233 int i = 0;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010234 if (!app.bad && allowRestart) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010235 for (; i<NL; i++) {
10236 if (mLaunchingProviders.get(i) == cpr) {
10237 restart = true;
10238 break;
10239 }
10240 }
10241 } else {
10242 i = NL;
10243 }
10244
10245 if (i >= NL) {
10246 removeDyingProviderLocked(app, cpr);
10247 NL = mLaunchingProviders.size();
10248 }
10249 }
10250 app.pubProviders.clear();
10251 }
10252
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010253 // Take care of any launching providers waiting for this process.
10254 if (checkAppInLaunchingProvidersLocked(app, false)) {
10255 restart = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010256 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010257
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010258 // Unregister from connected content providers.
10259 if (!app.conProviders.isEmpty()) {
Dianne Hackborn0c3154d2009-10-06 17:18:05 -070010260 Iterator it = app.conProviders.keySet().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010261 while (it.hasNext()) {
10262 ContentProviderRecord cpr = (ContentProviderRecord)it.next();
10263 cpr.clients.remove(app);
10264 }
10265 app.conProviders.clear();
10266 }
10267
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010268 // At this point there may be remaining entries in mLaunchingProviders
10269 // where we were the only one waiting, so they are no longer of use.
10270 // Look for these and clean up if found.
10271 // XXX Commented out for now. Trying to figure out a way to reproduce
10272 // the actual situation to identify what is actually going on.
10273 if (false) {
10274 for (int i=0; i<NL; i++) {
10275 ContentProviderRecord cpr = (ContentProviderRecord)
10276 mLaunchingProviders.get(i);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080010277 if (cpr.clients.size() <= 0 && !cpr.hasExternalProcessHandles()) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010278 synchronized (cpr) {
10279 cpr.launchingApp = null;
10280 cpr.notifyAll();
10281 }
10282 }
10283 }
10284 }
10285
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010286 skipCurrentReceiverLocked(app);
10287
10288 // Unregister any receivers.
10289 if (app.receivers.size() > 0) {
10290 Iterator<ReceiverList> it = app.receivers.iterator();
10291 while (it.hasNext()) {
10292 removeReceiverLocked(it.next());
10293 }
10294 app.receivers.clear();
10295 }
10296
Christopher Tate181fafa2009-05-14 11:12:14 -070010297 // If the app is undergoing backup, tell the backup manager about it
10298 if (mBackupTarget != null && app.pid == mBackupTarget.app.pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010299 if (DEBUG_BACKUP) Slog.d(TAG, "App " + mBackupTarget.appInfo + " died during backup");
Christopher Tate181fafa2009-05-14 11:12:14 -070010300 try {
10301 IBackupManager bm = IBackupManager.Stub.asInterface(
10302 ServiceManager.getService(Context.BACKUP_SERVICE));
10303 bm.agentDisconnected(app.info.packageName);
10304 } catch (RemoteException e) {
10305 // can't happen; backup manager is local
10306 }
10307 }
10308
Jeff Sharkey287bd832011-05-28 19:36:26 -070010309 mHandler.obtainMessage(DISPATCH_PROCESS_DIED, app.pid, app.info.uid, null).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010310
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010311 // If the caller is restarting this app, then leave it in its
10312 // current lists and let the caller take care of it.
10313 if (restarting) {
10314 return;
10315 }
10316
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010317 if (!app.persistent || app.isolated) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010318 if (DEBUG_PROCESSES) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010319 "Removing non-persistent process during cleanup: " + app);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010320 mProcessNames.remove(app.processName, app.uid);
10321 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -070010322 if (mHeavyWeightProcess == app) {
10323 mHeavyWeightProcess = null;
10324 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
10325 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010326 } else if (!app.removed) {
10327 // This app is persistent, so we need to keep its record around.
10328 // If it is not already on the pending app list, add it there
10329 // and start a new process for it.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010330 if (mPersistentStartingProcesses.indexOf(app) < 0) {
10331 mPersistentStartingProcesses.add(app);
10332 restart = true;
10333 }
10334 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070010335 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
10336 "Clean-up removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010337 mProcessesOnHold.remove(app);
10338
The Android Open Source Project4df24232009-03-05 14:34:35 -080010339 if (app == mHomeProcess) {
10340 mHomeProcess = null;
10341 }
Dianne Hackbornf35fe232011-11-01 19:25:20 -070010342 if (app == mPreviousProcess) {
10343 mPreviousProcess = null;
10344 }
10345
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010346 if (restart && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010347 // We have components that still need to be running in the
10348 // process, so re-launch it.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010349 mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010350 startProcessLocked(app, "restart", app.processName);
10351 } else if (app.pid > 0 && app.pid != MY_PID) {
10352 // Goodbye!
10353 synchronized (mPidsSelfLocked) {
10354 mPidsSelfLocked.remove(app.pid);
10355 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
10356 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010357 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010358 }
10359 }
10360
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010361 boolean checkAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) {
10362 // Look through the content providers we are waiting to have launched,
10363 // and if any run in this process then either schedule a restart of
10364 // the process or kill the client waiting for it if this process has
10365 // gone bad.
10366 int NL = mLaunchingProviders.size();
10367 boolean restart = false;
10368 for (int i=0; i<NL; i++) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010369 ContentProviderRecord cpr = mLaunchingProviders.get(i);
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010370 if (cpr.launchingApp == app) {
10371 if (!alwaysBad && !app.bad) {
10372 restart = true;
10373 } else {
10374 removeDyingProviderLocked(app, cpr);
10375 NL = mLaunchingProviders.size();
10376 }
10377 }
10378 }
10379 return restart;
10380 }
10381
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010382 // =========================================================
10383 // SERVICES
10384 // =========================================================
10385
10386 ActivityManager.RunningServiceInfo makeRunningServiceInfoLocked(ServiceRecord r) {
10387 ActivityManager.RunningServiceInfo info =
10388 new ActivityManager.RunningServiceInfo();
10389 info.service = r.name;
10390 if (r.app != null) {
10391 info.pid = r.app.pid;
10392 }
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010393 info.uid = r.appInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010394 info.process = r.processName;
10395 info.foreground = r.isForeground;
10396 info.activeSince = r.createTime;
10397 info.started = r.startRequested;
10398 info.clientCount = r.connections.size();
10399 info.crashCount = r.crashCount;
10400 info.lastActivityTime = r.lastActivity;
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010401 if (r.isForeground) {
10402 info.flags |= ActivityManager.RunningServiceInfo.FLAG_FOREGROUND;
10403 }
10404 if (r.startRequested) {
10405 info.flags |= ActivityManager.RunningServiceInfo.FLAG_STARTED;
10406 }
Dan Egnor42471dd2010-01-07 17:25:22 -080010407 if (r.app != null && r.app.pid == MY_PID) {
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010408 info.flags |= ActivityManager.RunningServiceInfo.FLAG_SYSTEM_PROCESS;
10409 }
10410 if (r.app != null && r.app.persistent) {
10411 info.flags |= ActivityManager.RunningServiceInfo.FLAG_PERSISTENT_PROCESS;
10412 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010413
10414 for (ArrayList<ConnectionRecord> connl : r.connections.values()) {
10415 for (int i=0; i<connl.size(); i++) {
10416 ConnectionRecord conn = connl.get(i);
10417 if (conn.clientLabel != 0) {
10418 info.clientPackage = conn.binding.client.info.packageName;
10419 info.clientLabel = conn.clientLabel;
10420 return info;
10421 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010422 }
10423 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010424 return info;
10425 }
10426
10427 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum,
10428 int flags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010429 enforceNotIsolatedCaller("getServices");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010430 synchronized (this) {
10431 ArrayList<ActivityManager.RunningServiceInfo> res
10432 = new ArrayList<ActivityManager.RunningServiceInfo>();
10433
Amith Yamasani742a6712011-05-04 14:49:28 -070010434 int userId = UserId.getUserId(Binder.getCallingUid());
10435 if (mServiceMap.getAllServices(userId).size() > 0) {
10436 Iterator<ServiceRecord> it
10437 = mServiceMap.getAllServices(userId).iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010438 while (it.hasNext() && res.size() < maxNum) {
10439 res.add(makeRunningServiceInfoLocked(it.next()));
10440 }
10441 }
10442
10443 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
10444 ServiceRecord r = mRestartingServices.get(i);
10445 ActivityManager.RunningServiceInfo info =
10446 makeRunningServiceInfoLocked(r);
10447 info.restarting = r.nextRestartTime;
10448 res.add(info);
10449 }
10450
10451 return res;
10452 }
10453 }
10454
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010455 public PendingIntent getRunningServiceControlPanel(ComponentName name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010456 enforceNotIsolatedCaller("getRunningServiceControlPanel");
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010457 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010458 int userId = UserId.getUserId(Binder.getCallingUid());
10459 ServiceRecord r = mServiceMap.getServiceByName(name, userId);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010460 if (r != null) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010461 for (ArrayList<ConnectionRecord> conn : r.connections.values()) {
10462 for (int i=0; i<conn.size(); i++) {
10463 if (conn.get(i).clientIntent != null) {
10464 return conn.get(i).clientIntent;
10465 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010466 }
10467 }
10468 }
10469 }
10470 return null;
10471 }
10472
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010473 private final ServiceRecord findServiceLocked(ComponentName name,
10474 IBinder token) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010475 ServiceRecord r = mServiceMap.getServiceByName(name, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010476 return r == token ? r : null;
10477 }
10478
10479 private final class ServiceLookupResult {
10480 final ServiceRecord record;
10481 final String permission;
10482
10483 ServiceLookupResult(ServiceRecord _record, String _permission) {
10484 record = _record;
10485 permission = _permission;
10486 }
10487 };
10488
10489 private ServiceLookupResult findServiceLocked(Intent service,
10490 String resolvedType) {
10491 ServiceRecord r = null;
10492 if (service.getComponent() != null) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010493 r = mServiceMap.getServiceByName(service.getComponent(), Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010494 }
10495 if (r == null) {
10496 Intent.FilterComparison filter = new Intent.FilterComparison(service);
Amith Yamasani742a6712011-05-04 14:49:28 -070010497 r = mServiceMap.getServiceByIntent(filter, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010498 }
10499
10500 if (r == null) {
10501 try {
10502 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070010503 AppGlobals.getPackageManager().resolveService(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010504 service, resolvedType, 0);
10505 ServiceInfo sInfo =
10506 rInfo != null ? rInfo.serviceInfo : null;
10507 if (sInfo == null) {
10508 return null;
10509 }
10510
10511 ComponentName name = new ComponentName(
10512 sInfo.applicationInfo.packageName, sInfo.name);
Amith Yamasani742a6712011-05-04 14:49:28 -070010513 r = mServiceMap.getServiceByName(name, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010514 } catch (RemoteException ex) {
10515 // pm is in same process, this will never happen.
10516 }
10517 }
10518 if (r != null) {
10519 int callingPid = Binder.getCallingPid();
10520 int callingUid = Binder.getCallingUid();
10521 if (checkComponentPermission(r.permission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010522 callingPid, callingUid, r.appInfo.uid, r.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010523 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010524 if (!r.exported) {
10525 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
10526 + " from pid=" + callingPid
10527 + ", uid=" + callingUid
10528 + " that is not exported from uid " + r.appInfo.uid);
10529 return new ServiceLookupResult(null, "not exported from uid "
10530 + r.appInfo.uid);
10531 }
Joe Onorato8a9b2202010-02-26 18:56:32 -080010532 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010533 + " from pid=" + callingPid
10534 + ", uid=" + callingUid
10535 + " requires " + r.permission);
10536 return new ServiceLookupResult(null, r.permission);
10537 }
10538 return new ServiceLookupResult(r, null);
10539 }
10540 return null;
10541 }
10542
10543 private class ServiceRestarter implements Runnable {
10544 private ServiceRecord mService;
10545
10546 void setService(ServiceRecord service) {
10547 mService = service;
10548 }
10549
10550 public void run() {
10551 synchronized(ActivityManagerService.this) {
10552 performServiceRestartLocked(mService);
10553 }
10554 }
10555 }
10556
10557 private ServiceLookupResult retrieveServiceLocked(Intent service,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010558 String resolvedType, int callingPid, int callingUid, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010559 ServiceRecord r = null;
Amith Yamasani742a6712011-05-04 14:49:28 -070010560 if (DEBUG_SERVICE)
10561 Slog.v(TAG, "retrieveServiceLocked: " + service + " type=" + resolvedType
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010562 + " callingUid=" + callingUid);
Amith Yamasani742a6712011-05-04 14:49:28 -070010563
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010564 if (service.getComponent() != null) {
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010565 r = mServiceMap.getServiceByName(service.getComponent(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010566 }
Amith Yamasani742a6712011-05-04 14:49:28 -070010567 if (r == null) {
10568 Intent.FilterComparison filter = new Intent.FilterComparison(service);
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010569 r = mServiceMap.getServiceByIntent(filter, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -070010570 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010571 if (r == null) {
10572 try {
10573 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070010574 AppGlobals.getPackageManager().resolveService(
Dianne Hackborn1655be42009-05-08 14:29:01 -070010575 service, resolvedType, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010576 ServiceInfo sInfo =
10577 rInfo != null ? rInfo.serviceInfo : null;
10578 if (sInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010579 Slog.w(TAG, "Unable to start service " + service +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010580 ": not found");
10581 return null;
10582 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010583 if (userId > 0) {
10584 sInfo.applicationInfo = getAppInfoForUser(sInfo.applicationInfo, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -070010585 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010586 ComponentName name = new ComponentName(
10587 sInfo.applicationInfo.packageName, sInfo.name);
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010588 r = mServiceMap.getServiceByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010589 if (r == null) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010590 Intent.FilterComparison filter = new Intent.FilterComparison(
10591 service.cloneFilter());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010592 ServiceRestarter res = new ServiceRestarter();
10593 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
10594 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
10595 synchronized (stats) {
10596 ss = stats.getServiceStatsLocked(
10597 sInfo.applicationInfo.uid, sInfo.packageName,
10598 sInfo.name);
10599 }
Dianne Hackbornb1c4a2a2010-01-19 15:36:42 -080010600 r = new ServiceRecord(this, ss, name, filter, sInfo, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010601 res.setService(r);
Amith Yamasani742a6712011-05-04 14:49:28 -070010602 mServiceMap.putServiceByName(name, UserId.getUserId(r.appInfo.uid), r);
10603 mServiceMap.putServiceByIntent(filter, UserId.getUserId(r.appInfo.uid), r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010604
10605 // Make sure this component isn't in the pending list.
10606 int N = mPendingServices.size();
10607 for (int i=0; i<N; i++) {
10608 ServiceRecord pr = mPendingServices.get(i);
10609 if (pr.name.equals(name)) {
10610 mPendingServices.remove(i);
10611 i--;
10612 N--;
10613 }
10614 }
10615 }
10616 } catch (RemoteException ex) {
10617 // pm is in same process, this will never happen.
10618 }
10619 }
10620 if (r != null) {
10621 if (checkComponentPermission(r.permission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010622 callingPid, callingUid, r.appInfo.uid, r.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010623 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010624 if (!r.exported) {
10625 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
10626 + " from pid=" + callingPid
10627 + ", uid=" + callingUid
10628 + " that is not exported from uid " + r.appInfo.uid);
10629 return new ServiceLookupResult(null, "not exported from uid "
10630 + r.appInfo.uid);
10631 }
Joe Onorato8a9b2202010-02-26 18:56:32 -080010632 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010633 + " from pid=" + callingPid
10634 + ", uid=" + callingUid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010635 + " requires " + r.permission);
10636 return new ServiceLookupResult(null, r.permission);
10637 }
10638 return new ServiceLookupResult(r, null);
10639 }
10640 return null;
10641 }
10642
Dianne Hackborn287952c2010-09-22 22:34:31 -070010643 private final void bumpServiceExecutingLocked(ServiceRecord r, String why) {
10644 if (DEBUG_SERVICE) Log.v(TAG, ">>> EXECUTING "
10645 + why + " of " + r + " in app " + r.app);
10646 else if (DEBUG_SERVICE_EXECUTING) Log.v(TAG, ">>> EXECUTING "
10647 + why + " of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010648 long now = SystemClock.uptimeMillis();
10649 if (r.executeNesting == 0 && r.app != null) {
10650 if (r.app.executingServices.size() == 0) {
10651 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
10652 msg.obj = r.app;
10653 mHandler.sendMessageAtTime(msg, now+SERVICE_TIMEOUT);
10654 }
10655 r.app.executingServices.add(r);
10656 }
10657 r.executeNesting++;
10658 r.executingStart = now;
10659 }
10660
10661 private final void sendServiceArgsLocked(ServiceRecord r,
10662 boolean oomAdjusted) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010663 final int N = r.pendingStarts.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010664 if (N == 0) {
10665 return;
10666 }
10667
Dianne Hackborn39792d22010-08-19 18:01:52 -070010668 while (r.pendingStarts.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010669 try {
Dianne Hackborn39792d22010-08-19 18:01:52 -070010670 ServiceRecord.StartItem si = r.pendingStarts.remove(0);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010671 if (DEBUG_SERVICE) Slog.v(TAG, "Sending arguments to: "
10672 + r + " " + r.intent + " args=" + si.intent);
Dianne Hackborn3a28f222011-03-01 12:25:54 -080010673 if (si.intent == null && N > 1) {
10674 // If somehow we got a dummy null intent in the middle,
10675 // then skip it. DO NOT skip a null intent when it is
10676 // the only one in the list -- this is to support the
10677 // onStartCommand(null) case.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010678 continue;
10679 }
Dianne Hackborn39792d22010-08-19 18:01:52 -070010680 si.deliveredTime = SystemClock.uptimeMillis();
10681 r.deliveredStarts.add(si);
10682 si.deliveryCount++;
Dianne Hackborn3a28f222011-03-01 12:25:54 -080010683 if (si.targetPermissionUid >= 0 && si.intent != null) {
Dianne Hackborn39792d22010-08-19 18:01:52 -070010684 grantUriPermissionUncheckedFromIntentLocked(si.targetPermissionUid,
Dianne Hackborn7e269642010-08-25 19:50:20 -070010685 r.packageName, si.intent, si.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -070010686 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070010687 bumpServiceExecutingLocked(r, "start");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010688 if (!oomAdjusted) {
10689 oomAdjusted = true;
10690 updateOomAdjLocked(r.app);
10691 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010692 int flags = 0;
10693 if (si.deliveryCount > 0) {
10694 flags |= Service.START_FLAG_RETRY;
10695 }
10696 if (si.doneExecutingCount > 0) {
10697 flags |= Service.START_FLAG_REDELIVERY;
10698 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070010699 r.app.thread.scheduleServiceArgs(r, si.taskRemoved, si.id, flags, si.intent);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010700 } catch (RemoteException e) {
10701 // Remote process gone... we'll let the normal cleanup take
10702 // care of this.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010703 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while scheduling start: " + r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010704 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010705 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010706 Slog.w(TAG, "Unexpected exception", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010707 break;
10708 }
10709 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010710 }
10711
10712 private final boolean requestServiceBindingLocked(ServiceRecord r,
10713 IntentBindRecord i, boolean rebind) {
10714 if (r.app == null || r.app.thread == null) {
10715 // If service is not currently running, can't yet bind.
10716 return false;
10717 }
10718 if ((!i.requested || rebind) && i.apps.size() > 0) {
10719 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070010720 bumpServiceExecutingLocked(r, "bind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010721 r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind);
10722 if (!rebind) {
10723 i.requested = true;
10724 }
10725 i.hasBound = true;
10726 i.doRebind = false;
10727 } catch (RemoteException e) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010728 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while binding " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010729 return false;
10730 }
10731 }
10732 return true;
10733 }
10734
10735 private final void requestServiceBindingsLocked(ServiceRecord r) {
10736 Iterator<IntentBindRecord> bindings = r.bindings.values().iterator();
10737 while (bindings.hasNext()) {
10738 IntentBindRecord i = bindings.next();
10739 if (!requestServiceBindingLocked(r, i, false)) {
10740 break;
10741 }
10742 }
10743 }
10744
10745 private final void realStartServiceLocked(ServiceRecord r,
10746 ProcessRecord app) throws RemoteException {
10747 if (app.thread == null) {
10748 throw new RemoteException();
10749 }
Amith Yamasani742a6712011-05-04 14:49:28 -070010750 if (DEBUG_MU)
10751 Slog.v(TAG_MU, "realStartServiceLocked, ServiceRecord.uid = " + r.appInfo.uid
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010752 + ", ProcessRecord.uid = " + app.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010753 r.app = app;
The Android Open Source Project10592532009-03-18 17:39:46 -070010754 r.restartTime = r.lastActivity = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010755
10756 app.services.add(r);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010757 bumpServiceExecutingLocked(r, "create");
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010758 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010759
10760 boolean created = false;
10761 try {
Dianne Hackborna33e3f72009-09-29 17:28:24 -070010762 mStringBuilder.setLength(0);
Dianne Hackborn90c52de2011-09-23 12:57:44 -070010763 r.intent.getIntent().toShortString(mStringBuilder, true, false, true);
Doug Zongker2bec3d42009-12-04 12:52:44 -080010764 EventLog.writeEvent(EventLogTags.AM_CREATE_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010765 System.identityHashCode(r), r.shortName,
Dianne Hackborna33e3f72009-09-29 17:28:24 -070010766 mStringBuilder.toString(), r.app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010767 synchronized (r.stats.getBatteryStats()) {
10768 r.stats.startLaunchedLocked();
10769 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -070010770 ensurePackageDexOpt(r.serviceInfo.packageName);
Dianne Hackborne2515ee2011-04-27 18:52:56 -040010771 app.thread.scheduleCreateService(r, r.serviceInfo,
10772 compatibilityInfoForPackageLocked(r.serviceInfo.applicationInfo));
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070010773 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010774 created = true;
10775 } finally {
10776 if (!created) {
10777 app.services.remove(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010778 scheduleServiceRestartLocked(r, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010779 }
10780 }
10781
10782 requestServiceBindingsLocked(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010783
10784 // If the service is in the started state, and there are no
10785 // pending arguments, then fake up one so its onStartCommand() will
10786 // be called.
10787 if (r.startRequested && r.callStart && r.pendingStarts.size() == 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070010788 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
10789 null, -1));
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010790 }
10791
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010792 sendServiceArgsLocked(r, true);
10793 }
10794
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010795 private final boolean scheduleServiceRestartLocked(ServiceRecord r,
10796 boolean allowCancel) {
10797 boolean canceled = false;
10798
Dianne Hackbornfd12af42009-08-27 00:44:33 -070010799 final long now = SystemClock.uptimeMillis();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010800 long minDuration = SERVICE_RESTART_DURATION;
Dianne Hackborn6ccd2af2009-08-27 12:26:44 -070010801 long resetTime = SERVICE_RESET_RUN_DURATION;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010802
Dianne Hackborn070783f2010-12-29 16:46:28 -080010803 if ((r.serviceInfo.applicationInfo.flags
10804 &ApplicationInfo.FLAG_PERSISTENT) != 0) {
10805 minDuration /= 4;
10806 }
10807
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010808 // Any delivered but not yet finished starts should be put back
10809 // on the pending list.
10810 final int N = r.deliveredStarts.size();
10811 if (N > 0) {
10812 for (int i=N-1; i>=0; i--) {
10813 ServiceRecord.StartItem si = r.deliveredStarts.get(i);
Dianne Hackborn39792d22010-08-19 18:01:52 -070010814 si.removeUriPermissionsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010815 if (si.intent == null) {
10816 // We'll generate this again if needed.
10817 } else if (!allowCancel || (si.deliveryCount < ServiceRecord.MAX_DELIVERY_COUNT
10818 && si.doneExecutingCount < ServiceRecord.MAX_DONE_EXECUTING_COUNT)) {
10819 r.pendingStarts.add(0, si);
10820 long dur = SystemClock.uptimeMillis() - si.deliveredTime;
10821 dur *= 2;
10822 if (minDuration < dur) minDuration = dur;
10823 if (resetTime < dur) resetTime = dur;
10824 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010825 Slog.w(TAG, "Canceling start item " + si.intent + " in service "
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010826 + r.name);
10827 canceled = true;
10828 }
10829 }
10830 r.deliveredStarts.clear();
10831 }
10832
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010833 r.totalRestartCount++;
10834 if (r.restartDelay == 0) {
10835 r.restartCount++;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010836 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010837 } else {
10838 // If it has been a "reasonably long time" since the service
10839 // was started, then reset our restart duration back to
10840 // the beginning, so we don't infinitely increase the duration
10841 // on a service that just occasionally gets killed (which is
10842 // a normal case, due to process being killed to reclaim memory).
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010843 if (now > (r.restartTime+resetTime)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010844 r.restartCount = 1;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010845 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010846 } else {
Dianne Hackborn070783f2010-12-29 16:46:28 -080010847 if ((r.serviceInfo.applicationInfo.flags
10848 &ApplicationInfo.FLAG_PERSISTENT) != 0) {
10849 // Services in peristent processes will restart much more
10850 // quickly, since they are pretty important. (Think SystemUI).
10851 r.restartDelay += minDuration/2;
10852 } else {
10853 r.restartDelay *= SERVICE_RESTART_DURATION_FACTOR;
10854 if (r.restartDelay < minDuration) {
10855 r.restartDelay = minDuration;
10856 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010857 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010858 }
10859 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070010860
10861 r.nextRestartTime = now + r.restartDelay;
10862
10863 // Make sure that we don't end up restarting a bunch of services
10864 // all at the same time.
10865 boolean repeat;
10866 do {
10867 repeat = false;
10868 for (int i=mRestartingServices.size()-1; i>=0; i--) {
10869 ServiceRecord r2 = mRestartingServices.get(i);
10870 if (r2 != r && r.nextRestartTime
10871 >= (r2.nextRestartTime-SERVICE_MIN_RESTART_TIME_BETWEEN)
10872 && r.nextRestartTime
10873 < (r2.nextRestartTime+SERVICE_MIN_RESTART_TIME_BETWEEN)) {
10874 r.nextRestartTime = r2.nextRestartTime + SERVICE_MIN_RESTART_TIME_BETWEEN;
10875 r.restartDelay = r.nextRestartTime - now;
10876 repeat = true;
10877 break;
10878 }
10879 }
10880 } while (repeat);
10881
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010882 if (!mRestartingServices.contains(r)) {
10883 mRestartingServices.add(r);
10884 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070010885
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070010886 r.cancelNotification();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010887
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010888 mHandler.removeCallbacks(r.restarter);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070010889 mHandler.postAtTime(r.restarter, r.nextRestartTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010890 r.nextRestartTime = SystemClock.uptimeMillis() + r.restartDelay;
Joe Onorato8a9b2202010-02-26 18:56:32 -080010891 Slog.w(TAG, "Scheduling restart of crashed service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010892 + r.shortName + " in " + r.restartDelay + "ms");
Doug Zongker2bec3d42009-12-04 12:52:44 -080010893 EventLog.writeEvent(EventLogTags.AM_SCHEDULE_SERVICE_RESTART,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010894 r.shortName, r.restartDelay);
10895
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010896 return canceled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010897 }
10898
10899 final void performServiceRestartLocked(ServiceRecord r) {
10900 if (!mRestartingServices.contains(r)) {
10901 return;
10902 }
10903 bringUpServiceLocked(r, r.intent.getIntent().getFlags(), true);
10904 }
10905
10906 private final boolean unscheduleServiceRestartLocked(ServiceRecord r) {
10907 if (r.restartDelay == 0) {
10908 return false;
10909 }
10910 r.resetRestartCounter();
10911 mRestartingServices.remove(r);
10912 mHandler.removeCallbacks(r.restarter);
10913 return true;
10914 }
10915
10916 private final boolean bringUpServiceLocked(ServiceRecord r,
10917 int intentFlags, boolean whileRestarting) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010918 //Slog.i(TAG, "Bring up service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010919 //r.dump(" ");
10920
Dianne Hackborn36124872009-10-08 16:22:03 -070010921 if (r.app != null && r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010922 sendServiceArgsLocked(r, false);
10923 return true;
10924 }
10925
10926 if (!whileRestarting && r.restartDelay > 0) {
10927 // If waiting for a restart, then do nothing.
10928 return true;
10929 }
10930
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010931 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing up " + r + " " + r.intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010932
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010933 // We are now bringing the service up, so no longer in the
10934 // restarting state.
10935 mRestartingServices.remove(r);
10936
Dianne Hackborne7f97212011-02-24 14:40:20 -080010937 // Service is now being launched, its package can't be stopped.
10938 try {
10939 AppGlobals.getPackageManager().setPackageStoppedState(
10940 r.packageName, false);
10941 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080010942 } catch (IllegalArgumentException e) {
10943 Slog.w(TAG, "Failed trying to unstop package "
10944 + r.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080010945 }
10946
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010947 final boolean isolated = (r.serviceInfo.flags&ServiceInfo.FLAG_ISOLATED_PROCESS) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010948 final String appName = r.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010949 ProcessRecord app;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010950
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010951 if (!isolated) {
10952 app = getProcessRecordLocked(appName, r.appInfo.uid);
10953 if (DEBUG_MU)
10954 Slog.v(TAG_MU, "bringUpServiceLocked: appInfo.uid=" + r.appInfo.uid + " app=" + app);
10955 if (app != null && app.thread != null) {
10956 try {
10957 app.addPackage(r.appInfo.packageName);
10958 realStartServiceLocked(r, app);
10959 return true;
10960 } catch (RemoteException e) {
10961 Slog.w(TAG, "Exception when starting service " + r.shortName, e);
10962 }
10963
10964 // If a dead object exception was thrown -- fall through to
10965 // restart the application.
10966 }
10967 } else {
10968 // If this service runs in an isolated process, then each time
10969 // we call startProcessLocked() we will get a new isolated
10970 // process, starting another process if we are currently waiting
10971 // for a previous process to come up. To deal with this, we store
10972 // in the service any current isolated process it is running in or
10973 // waiting to have come up.
10974 app = r.isolatedProc;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010975 }
10976
Dianne Hackborn36124872009-10-08 16:22:03 -070010977 // Not running -- get it started, and enqueue this service record
10978 // to be executed when the app comes up.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010979 if (app == null) {
10980 if ((app=startProcessLocked(appName, r.appInfo, true, intentFlags,
10981 "service", r.name, false, isolated)) == null) {
10982 Slog.w(TAG, "Unable to launch app "
10983 + r.appInfo.packageName + "/"
10984 + r.appInfo.uid + " for service "
10985 + r.intent.getIntent() + ": process is bad");
10986 bringDownServiceLocked(r, true);
10987 return false;
10988 }
10989 if (isolated) {
10990 r.isolatedProc = app;
10991 }
Dianne Hackborn36124872009-10-08 16:22:03 -070010992 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010993
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010994 if (!mPendingServices.contains(r)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010995 mPendingServices.add(r);
10996 }
Dianne Hackborn36124872009-10-08 16:22:03 -070010997
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010998 return true;
10999 }
11000
11001 private final void bringDownServiceLocked(ServiceRecord r, boolean force) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011002 //Slog.i(TAG, "Bring down service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011003 //r.dump(" ");
11004
11005 // Does it still need to run?
11006 if (!force && r.startRequested) {
11007 return;
11008 }
11009 if (r.connections.size() > 0) {
11010 if (!force) {
11011 // XXX should probably keep a count of the number of auto-create
11012 // connections directly in the service.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011013 Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011014 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011015 ArrayList<ConnectionRecord> cr = it.next();
11016 for (int i=0; i<cr.size(); i++) {
11017 if ((cr.get(i).flags&Context.BIND_AUTO_CREATE) != 0) {
11018 return;
11019 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011020 }
11021 }
11022 }
11023
11024 // Report to all of the connections that the service is no longer
11025 // available.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011026 Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011027 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011028 ArrayList<ConnectionRecord> c = it.next();
11029 for (int i=0; i<c.size(); i++) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011030 ConnectionRecord cr = c.get(i);
11031 // There is still a connection to the service that is
11032 // being brought down. Mark it as dead.
11033 cr.serviceDead = true;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011034 try {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011035 cr.conn.connected(r.name, null);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011036 } catch (Exception e) {
11037 Slog.w(TAG, "Failure disconnecting service " + r.name +
11038 " to connection " + c.get(i).conn.asBinder() +
11039 " (in " + c.get(i).binding.client.processName + ")", e);
11040 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011041 }
11042 }
11043 }
11044
11045 // Tell the service that it has been unbound.
11046 if (r.bindings.size() > 0 && r.app != null && r.app.thread != null) {
11047 Iterator<IntentBindRecord> it = r.bindings.values().iterator();
11048 while (it.hasNext()) {
11049 IntentBindRecord ibr = it.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -080011050 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down binding " + ibr
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011051 + ": hasBound=" + ibr.hasBound);
11052 if (r.app != null && r.app.thread != null && ibr.hasBound) {
11053 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011054 bumpServiceExecutingLocked(r, "bring down unbind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011055 updateOomAdjLocked(r.app);
11056 ibr.hasBound = false;
11057 r.app.thread.scheduleUnbindService(r,
11058 ibr.intent.getIntent());
11059 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011060 Slog.w(TAG, "Exception when unbinding service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011061 + r.shortName, e);
11062 serviceDoneExecutingLocked(r, true);
11063 }
11064 }
11065 }
11066 }
11067
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011068 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down " + r + " " + r.intent);
Doug Zongker2bec3d42009-12-04 12:52:44 -080011069 EventLog.writeEvent(EventLogTags.AM_DESTROY_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011070 System.identityHashCode(r), r.shortName,
11071 (r.app != null) ? r.app.pid : -1);
11072
Amith Yamasani742a6712011-05-04 14:49:28 -070011073 mServiceMap.removeServiceByName(r.name, r.userId);
11074 mServiceMap.removeServiceByIntent(r.intent, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011075 r.totalRestartCount = 0;
11076 unscheduleServiceRestartLocked(r);
11077
11078 // Also make sure it is not on the pending list.
11079 int N = mPendingServices.size();
11080 for (int i=0; i<N; i++) {
11081 if (mPendingServices.get(i) == r) {
11082 mPendingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011083 if (DEBUG_SERVICE) Slog.v(TAG, "Removed pending: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011084 i--;
11085 N--;
11086 }
11087 }
11088
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011089 r.cancelNotification();
11090 r.isForeground = false;
11091 r.foregroundId = 0;
11092 r.foregroundNoti = null;
11093
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011094 // Clear start entries.
Dianne Hackborn39792d22010-08-19 18:01:52 -070011095 r.clearDeliveredStartsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011096 r.pendingStarts.clear();
11097
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011098 if (r.app != null) {
11099 synchronized (r.stats.getBatteryStats()) {
11100 r.stats.stopLaunchedLocked();
11101 }
11102 r.app.services.remove(r);
11103 if (r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011104 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011105 bumpServiceExecutingLocked(r, "stop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011106 mStoppingServices.add(r);
11107 updateOomAdjLocked(r.app);
11108 r.app.thread.scheduleStopService(r);
11109 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011110 Slog.w(TAG, "Exception when stopping service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011111 + r.shortName, e);
11112 serviceDoneExecutingLocked(r, true);
11113 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011114 updateServiceForegroundLocked(r.app, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011115 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011116 if (DEBUG_SERVICE) Slog.v(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011117 TAG, "Removed service that has no process: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011118 }
11119 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011120 if (DEBUG_SERVICE) Slog.v(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011121 TAG, "Removed service that is not running: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011122 }
Vairavan Srinivasana207ce22010-12-23 13:51:48 -080011123
11124 if (r.bindings.size() > 0) {
11125 r.bindings.clear();
11126 }
11127
11128 if (r.restarter instanceof ServiceRestarter) {
11129 ((ServiceRestarter)r.restarter).setService(null);
11130 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011131 }
11132
11133 ComponentName startServiceLocked(IApplicationThread caller,
11134 Intent service, String resolvedType,
11135 int callingPid, int callingUid) {
11136 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011137 if (DEBUG_SERVICE) Slog.v(TAG, "startService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011138 + " type=" + resolvedType + " args=" + service.getExtras());
11139
11140 if (caller != null) {
11141 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11142 if (callerApp == null) {
11143 throw new SecurityException(
11144 "Unable to find app for caller " + caller
11145 + " (pid=" + Binder.getCallingPid()
11146 + ") when starting service " + service);
11147 }
11148 }
11149
11150 ServiceLookupResult res =
11151 retrieveServiceLocked(service, resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011152 callingPid, callingUid, UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011153 if (res == null) {
11154 return null;
11155 }
11156 if (res.record == null) {
11157 return new ComponentName("!", res.permission != null
11158 ? res.permission : "private to package");
11159 }
11160 ServiceRecord r = res.record;
Dianne Hackborn39792d22010-08-19 18:01:52 -070011161 int targetPermissionUid = checkGrantUriPermissionFromIntentLocked(
11162 callingUid, r.packageName, service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011163 if (unscheduleServiceRestartLocked(r)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011164 if (DEBUG_SERVICE) Slog.v(TAG, "START SERVICE WHILE RESTART PENDING: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011165 }
11166 r.startRequested = true;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011167 r.callStart = false;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011168 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Dianne Hackborn39792d22010-08-19 18:01:52 -070011169 service, targetPermissionUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011170 r.lastActivity = SystemClock.uptimeMillis();
11171 synchronized (r.stats.getBatteryStats()) {
11172 r.stats.startRunningLocked();
11173 }
11174 if (!bringUpServiceLocked(r, service.getFlags(), false)) {
11175 return new ComponentName("!", "Service process is bad");
11176 }
11177 return r.name;
11178 }
11179 }
11180
11181 public ComponentName startService(IApplicationThread caller, Intent service,
11182 String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011183 enforceNotIsolatedCaller("startService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011184 // Refuse possible leaked file descriptors
11185 if (service != null && service.hasFileDescriptors() == true) {
11186 throw new IllegalArgumentException("File descriptors passed in Intent");
11187 }
11188
Amith Yamasani742a6712011-05-04 14:49:28 -070011189 if (DEBUG_SERVICE)
11190 Slog.v(TAG, "startService: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011191 synchronized(this) {
11192 final int callingPid = Binder.getCallingPid();
11193 final int callingUid = Binder.getCallingUid();
11194 final long origId = Binder.clearCallingIdentity();
11195 ComponentName res = startServiceLocked(caller, service,
11196 resolvedType, callingPid, callingUid);
11197 Binder.restoreCallingIdentity(origId);
11198 return res;
11199 }
11200 }
11201
11202 ComponentName startServiceInPackage(int uid,
11203 Intent service, String resolvedType) {
11204 synchronized(this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070011205 if (DEBUG_SERVICE)
11206 Slog.v(TAG, "startServiceInPackage: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011207 final long origId = Binder.clearCallingIdentity();
11208 ComponentName res = startServiceLocked(null, service,
11209 resolvedType, -1, uid);
11210 Binder.restoreCallingIdentity(origId);
11211 return res;
11212 }
11213 }
11214
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011215 private void stopServiceLocked(ServiceRecord service) {
11216 synchronized (service.stats.getBatteryStats()) {
11217 service.stats.stopRunningLocked();
11218 }
11219 service.startRequested = false;
11220 service.callStart = false;
11221 bringDownServiceLocked(service, false);
11222 }
11223
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011224 public int stopService(IApplicationThread caller, Intent service,
11225 String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011226 enforceNotIsolatedCaller("stopService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011227 // Refuse possible leaked file descriptors
11228 if (service != null && service.hasFileDescriptors() == true) {
11229 throw new IllegalArgumentException("File descriptors passed in Intent");
11230 }
11231
11232 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011233 if (DEBUG_SERVICE) Slog.v(TAG, "stopService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011234 + " type=" + resolvedType);
11235
11236 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11237 if (caller != null && callerApp == null) {
11238 throw new SecurityException(
11239 "Unable to find app for caller " + caller
11240 + " (pid=" + Binder.getCallingPid()
11241 + ") when stopping service " + service);
11242 }
11243
11244 // If this service is active, make sure it is stopped.
11245 ServiceLookupResult r = findServiceLocked(service, resolvedType);
11246 if (r != null) {
11247 if (r.record != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011248 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011249 try {
11250 stopServiceLocked(r.record);
11251 } finally {
11252 Binder.restoreCallingIdentity(origId);
11253 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011254 return 1;
11255 }
11256 return -1;
11257 }
11258 }
11259
11260 return 0;
11261 }
11262
11263 public IBinder peekService(Intent service, String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011264 enforceNotIsolatedCaller("peekService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011265 // Refuse possible leaked file descriptors
11266 if (service != null && service.hasFileDescriptors() == true) {
11267 throw new IllegalArgumentException("File descriptors passed in Intent");
11268 }
11269
11270 IBinder ret = null;
11271
11272 synchronized(this) {
11273 ServiceLookupResult r = findServiceLocked(service, resolvedType);
11274
11275 if (r != null) {
11276 // r.record is null if findServiceLocked() failed the caller permission check
11277 if (r.record == null) {
11278 throw new SecurityException(
11279 "Permission Denial: Accessing service " + r.record.name
11280 + " from pid=" + Binder.getCallingPid()
11281 + ", uid=" + Binder.getCallingUid()
11282 + " requires " + r.permission);
11283 }
11284 IntentBindRecord ib = r.record.bindings.get(r.record.intent);
11285 if (ib != null) {
11286 ret = ib.binder;
11287 }
11288 }
11289 }
11290
11291 return ret;
11292 }
11293
11294 public boolean stopServiceToken(ComponentName className, IBinder token,
11295 int startId) {
11296 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011297 if (DEBUG_SERVICE) Slog.v(TAG, "stopServiceToken: " + className
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011298 + " " + token + " startId=" + startId);
11299 ServiceRecord r = findServiceLocked(className, token);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011300 if (r != null) {
11301 if (startId >= 0) {
11302 // Asked to only stop if done with all work. Note that
11303 // to avoid leaks, we will take this as dropping all
11304 // start items up to and including this one.
11305 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
11306 if (si != null) {
11307 while (r.deliveredStarts.size() > 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -070011308 ServiceRecord.StartItem cur = r.deliveredStarts.remove(0);
11309 cur.removeUriPermissionsLocked();
11310 if (cur == si) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011311 break;
11312 }
11313 }
11314 }
11315
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011316 if (r.getLastStartId() != startId) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011317 return false;
11318 }
11319
11320 if (r.deliveredStarts.size() > 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011321 Slog.w(TAG, "stopServiceToken startId " + startId
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011322 + " is last, but have " + r.deliveredStarts.size()
11323 + " remaining args");
11324 }
11325 }
11326
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011327 synchronized (r.stats.getBatteryStats()) {
11328 r.stats.stopRunningLocked();
11329 r.startRequested = false;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011330 r.callStart = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011331 }
11332 final long origId = Binder.clearCallingIdentity();
11333 bringDownServiceLocked(r, false);
11334 Binder.restoreCallingIdentity(origId);
11335 return true;
11336 }
11337 }
11338 return false;
11339 }
11340
11341 public void setServiceForeground(ComponentName className, IBinder token,
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011342 int id, Notification notification, boolean removeNotification) {
11343 final long origId = Binder.clearCallingIdentity();
11344 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011345 synchronized(this) {
11346 ServiceRecord r = findServiceLocked(className, token);
11347 if (r != null) {
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011348 if (id != 0) {
11349 if (notification == null) {
11350 throw new IllegalArgumentException("null notification");
11351 }
11352 if (r.foregroundId != id) {
11353 r.cancelNotification();
11354 r.foregroundId = id;
11355 }
11356 notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
11357 r.foregroundNoti = notification;
11358 r.isForeground = true;
11359 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011360 if (r.app != null) {
11361 updateServiceForegroundLocked(r.app, true);
11362 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011363 } else {
11364 if (r.isForeground) {
11365 r.isForeground = false;
11366 if (r.app != null) {
Dianne Hackborn8633e682010-04-22 16:03:41 -070011367 updateLruProcessLocked(r.app, false, true);
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011368 updateServiceForegroundLocked(r.app, true);
11369 }
11370 }
11371 if (removeNotification) {
11372 r.cancelNotification();
11373 r.foregroundId = 0;
11374 r.foregroundNoti = null;
11375 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011376 }
11377 }
11378 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011379 } finally {
11380 Binder.restoreCallingIdentity(origId);
11381 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011382 }
11383
11384 public void updateServiceForegroundLocked(ProcessRecord proc, boolean oomAdj) {
11385 boolean anyForeground = false;
Dianne Hackborn860755f2010-06-03 18:47:52 -070011386 for (ServiceRecord sr : proc.services) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011387 if (sr.isForeground) {
11388 anyForeground = true;
11389 break;
11390 }
11391 }
11392 if (anyForeground != proc.foregroundServices) {
11393 proc.foregroundServices = anyForeground;
11394 if (oomAdj) {
11395 updateOomAdjLocked();
11396 }
11397 }
11398 }
11399
11400 public int bindService(IApplicationThread caller, IBinder token,
11401 Intent service, String resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011402 IServiceConnection connection, int flags, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011403 enforceNotIsolatedCaller("bindService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011404 // Refuse possible leaked file descriptors
11405 if (service != null && service.hasFileDescriptors() == true) {
11406 throw new IllegalArgumentException("File descriptors passed in Intent");
11407 }
11408
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011409 checkValidCaller(Binder.getCallingUid(), userId);
11410
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011411 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011412 if (DEBUG_SERVICE) Slog.v(TAG, "bindService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011413 + " type=" + resolvedType + " conn=" + connection.asBinder()
11414 + " flags=0x" + Integer.toHexString(flags));
Amith Yamasani742a6712011-05-04 14:49:28 -070011415 if (DEBUG_MU)
11416 Slog.i(TAG_MU, "bindService uid=" + Binder.getCallingUid() + " origUid="
11417 + Binder.getOrigCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011418 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11419 if (callerApp == null) {
11420 throw new SecurityException(
11421 "Unable to find app for caller " + caller
11422 + " (pid=" + Binder.getCallingPid()
11423 + ") when binding service " + service);
11424 }
11425
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011426 ActivityRecord activity = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011427 if (token != null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070011428 activity = mMainStack.isInStackLocked(token);
11429 if (activity == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011430 Slog.w(TAG, "Binding with unknown activity: " + token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011431 return 0;
11432 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011433 }
11434
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011435 int clientLabel = 0;
11436 PendingIntent clientIntent = null;
11437
11438 if (callerApp.info.uid == Process.SYSTEM_UID) {
11439 // Hacky kind of thing -- allow system stuff to tell us
11440 // what they are, so we can report this elsewhere for
11441 // others to know why certain services are running.
11442 try {
11443 clientIntent = (PendingIntent)service.getParcelableExtra(
11444 Intent.EXTRA_CLIENT_INTENT);
11445 } catch (RuntimeException e) {
11446 }
11447 if (clientIntent != null) {
11448 clientLabel = service.getIntExtra(Intent.EXTRA_CLIENT_LABEL, 0);
11449 if (clientLabel != 0) {
11450 // There are no useful extras in the intent, trash them.
11451 // System code calling with this stuff just needs to know
11452 // this will happen.
11453 service = service.cloneFilter();
11454 }
11455 }
11456 }
11457
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011458 ServiceLookupResult res =
11459 retrieveServiceLocked(service, resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011460 Binder.getCallingPid(), Binder.getCallingUid(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011461 if (res == null) {
11462 return 0;
11463 }
11464 if (res.record == null) {
11465 return -1;
11466 }
11467 ServiceRecord s = res.record;
11468
11469 final long origId = Binder.clearCallingIdentity();
11470
11471 if (unscheduleServiceRestartLocked(s)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011472 if (DEBUG_SERVICE) Slog.v(TAG, "BIND SERVICE WHILE RESTART PENDING: "
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011473 + s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011474 }
11475
11476 AppBindRecord b = s.retrieveAppBindingLocked(service, callerApp);
11477 ConnectionRecord c = new ConnectionRecord(b, activity,
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011478 connection, flags, clientLabel, clientIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011479
11480 IBinder binder = connection.asBinder();
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011481 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
11482 if (clist == null) {
11483 clist = new ArrayList<ConnectionRecord>();
11484 s.connections.put(binder, clist);
11485 }
11486 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011487 b.connections.add(c);
11488 if (activity != null) {
11489 if (activity.connections == null) {
11490 activity.connections = new HashSet<ConnectionRecord>();
11491 }
11492 activity.connections.add(c);
11493 }
11494 b.client.connections.add(c);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070011495 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
11496 b.client.hasAboveClient = true;
11497 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011498 clist = mServiceConnections.get(binder);
11499 if (clist == null) {
11500 clist = new ArrayList<ConnectionRecord>();
11501 mServiceConnections.put(binder, clist);
11502 }
11503 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011504
11505 if ((flags&Context.BIND_AUTO_CREATE) != 0) {
11506 s.lastActivity = SystemClock.uptimeMillis();
11507 if (!bringUpServiceLocked(s, service.getFlags(), false)) {
11508 return 0;
11509 }
11510 }
11511
11512 if (s.app != null) {
11513 // This could have made the service more important.
11514 updateOomAdjLocked(s.app);
11515 }
11516
Joe Onorato8a9b2202010-02-26 18:56:32 -080011517 if (DEBUG_SERVICE) Slog.v(TAG, "Bind " + s + " with " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011518 + ": received=" + b.intent.received
11519 + " apps=" + b.intent.apps.size()
11520 + " doRebind=" + b.intent.doRebind);
11521
11522 if (s.app != null && b.intent.received) {
11523 // Service is already running, so we can immediately
11524 // publish the connection.
11525 try {
11526 c.conn.connected(s.name, b.intent.binder);
11527 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011528 Slog.w(TAG, "Failure sending service " + s.shortName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011529 + " to connection " + c.conn.asBinder()
11530 + " (in " + c.binding.client.processName + ")", e);
11531 }
11532
11533 // If this is the first app connected back to this binding,
11534 // and the service had previously asked to be told when
11535 // rebound, then do so.
11536 if (b.intent.apps.size() == 1 && b.intent.doRebind) {
11537 requestServiceBindingLocked(s, b.intent, true);
11538 }
11539 } else if (!b.intent.requested) {
11540 requestServiceBindingLocked(s, b.intent, false);
11541 }
11542
11543 Binder.restoreCallingIdentity(origId);
11544 }
11545
11546 return 1;
11547 }
11548
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070011549 void removeConnectionLocked(
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011550 ConnectionRecord c, ProcessRecord skipApp, ActivityRecord skipAct) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011551 IBinder binder = c.conn.asBinder();
11552 AppBindRecord b = c.binding;
11553 ServiceRecord s = b.service;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011554 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
11555 if (clist != null) {
11556 clist.remove(c);
11557 if (clist.size() == 0) {
11558 s.connections.remove(binder);
11559 }
11560 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011561 b.connections.remove(c);
11562 if (c.activity != null && c.activity != skipAct) {
11563 if (c.activity.connections != null) {
11564 c.activity.connections.remove(c);
11565 }
11566 }
11567 if (b.client != skipApp) {
11568 b.client.connections.remove(c);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070011569 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
11570 b.client.updateHasAboveClientLocked();
11571 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011572 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011573 clist = mServiceConnections.get(binder);
11574 if (clist != null) {
11575 clist.remove(c);
11576 if (clist.size() == 0) {
11577 mServiceConnections.remove(binder);
11578 }
11579 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011580
11581 if (b.connections.size() == 0) {
11582 b.intent.apps.remove(b.client);
11583 }
11584
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011585 if (!c.serviceDead) {
11586 if (DEBUG_SERVICE) Slog.v(TAG, "Disconnecting binding " + b.intent
11587 + ": shouldUnbind=" + b.intent.hasBound);
11588 if (s.app != null && s.app.thread != null && b.intent.apps.size() == 0
11589 && b.intent.hasBound) {
11590 try {
11591 bumpServiceExecutingLocked(s, "unbind");
11592 updateOomAdjLocked(s.app);
11593 b.intent.hasBound = false;
11594 // Assume the client doesn't want to know about a rebind;
11595 // we will deal with that later if it asks for one.
11596 b.intent.doRebind = false;
11597 s.app.thread.scheduleUnbindService(s, b.intent.intent.getIntent());
11598 } catch (Exception e) {
11599 Slog.w(TAG, "Exception when unbinding service " + s.shortName, e);
11600 serviceDoneExecutingLocked(s, true);
11601 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011602 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011603
11604 if ((c.flags&Context.BIND_AUTO_CREATE) != 0) {
11605 bringDownServiceLocked(s, false);
11606 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011607 }
11608 }
11609
11610 public boolean unbindService(IServiceConnection connection) {
11611 synchronized (this) {
11612 IBinder binder = connection.asBinder();
Joe Onorato8a9b2202010-02-26 18:56:32 -080011613 if (DEBUG_SERVICE) Slog.v(TAG, "unbindService: conn=" + binder);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011614 ArrayList<ConnectionRecord> clist = mServiceConnections.get(binder);
11615 if (clist == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011616 Slog.w(TAG, "Unbind failed: could not find connection for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011617 + connection.asBinder());
11618 return false;
11619 }
11620
11621 final long origId = Binder.clearCallingIdentity();
11622
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011623 while (clist.size() > 0) {
11624 ConnectionRecord r = clist.get(0);
11625 removeConnectionLocked(r, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011626
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011627 if (r.binding.service.app != null) {
11628 // This could have made the service less important.
11629 updateOomAdjLocked(r.binding.service.app);
11630 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011631 }
11632
11633 Binder.restoreCallingIdentity(origId);
11634 }
11635
11636 return true;
11637 }
11638
11639 public void publishService(IBinder token, Intent intent, IBinder service) {
11640 // Refuse possible leaked file descriptors
11641 if (intent != null && intent.hasFileDescriptors() == true) {
11642 throw new IllegalArgumentException("File descriptors passed in Intent");
11643 }
11644
11645 synchronized(this) {
11646 if (!(token instanceof ServiceRecord)) {
11647 throw new IllegalArgumentException("Invalid service token");
11648 }
11649 ServiceRecord r = (ServiceRecord)token;
11650
11651 final long origId = Binder.clearCallingIdentity();
11652
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011653 if (DEBUG_SERVICE) Slog.v(TAG, "PUBLISHING " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011654 + " " + intent + ": " + service);
11655 if (r != null) {
11656 Intent.FilterComparison filter
11657 = new Intent.FilterComparison(intent);
11658 IntentBindRecord b = r.bindings.get(filter);
11659 if (b != null && !b.received) {
11660 b.binder = service;
11661 b.requested = true;
11662 b.received = true;
11663 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011664 Iterator<ArrayList<ConnectionRecord>> it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011665 = r.connections.values().iterator();
11666 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011667 ArrayList<ConnectionRecord> clist = it.next();
11668 for (int i=0; i<clist.size(); i++) {
11669 ConnectionRecord c = clist.get(i);
11670 if (!filter.equals(c.binding.intent.intent)) {
11671 if (DEBUG_SERVICE) Slog.v(
11672 TAG, "Not publishing to: " + c);
11673 if (DEBUG_SERVICE) Slog.v(
11674 TAG, "Bound intent: " + c.binding.intent.intent);
11675 if (DEBUG_SERVICE) Slog.v(
11676 TAG, "Published intent: " + intent);
11677 continue;
11678 }
11679 if (DEBUG_SERVICE) Slog.v(TAG, "Publishing to: " + c);
11680 try {
11681 c.conn.connected(r.name, service);
11682 } catch (Exception e) {
11683 Slog.w(TAG, "Failure sending service " + r.name +
11684 " to connection " + c.conn.asBinder() +
11685 " (in " + c.binding.client.processName + ")", e);
11686 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011687 }
11688 }
11689 }
11690 }
11691
11692 serviceDoneExecutingLocked(r, mStoppingServices.contains(r));
11693
11694 Binder.restoreCallingIdentity(origId);
11695 }
11696 }
11697 }
11698
11699 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
11700 // Refuse possible leaked file descriptors
11701 if (intent != null && intent.hasFileDescriptors() == true) {
11702 throw new IllegalArgumentException("File descriptors passed in Intent");
11703 }
11704
11705 synchronized(this) {
11706 if (!(token instanceof ServiceRecord)) {
11707 throw new IllegalArgumentException("Invalid service token");
11708 }
11709 ServiceRecord r = (ServiceRecord)token;
11710
11711 final long origId = Binder.clearCallingIdentity();
11712
11713 if (r != null) {
11714 Intent.FilterComparison filter
11715 = new Intent.FilterComparison(intent);
11716 IntentBindRecord b = r.bindings.get(filter);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011717 if (DEBUG_SERVICE) Slog.v(TAG, "unbindFinished in " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011718 + " at " + b + ": apps="
11719 + (b != null ? b.apps.size() : 0));
Per Edelberg78f9fff2010-08-30 20:01:35 +020011720
11721 boolean inStopping = mStoppingServices.contains(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011722 if (b != null) {
Per Edelberg78f9fff2010-08-30 20:01:35 +020011723 if (b.apps.size() > 0 && !inStopping) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011724 // Applications have already bound since the last
11725 // unbind, so just rebind right here.
11726 requestServiceBindingLocked(r, b, true);
11727 } else {
11728 // Note to tell the service the next time there is
11729 // a new client.
11730 b.doRebind = true;
11731 }
11732 }
11733
Per Edelberg78f9fff2010-08-30 20:01:35 +020011734 serviceDoneExecutingLocked(r, inStopping);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011735
11736 Binder.restoreCallingIdentity(origId);
11737 }
11738 }
11739 }
11740
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011741 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011742 synchronized(this) {
11743 if (!(token instanceof ServiceRecord)) {
11744 throw new IllegalArgumentException("Invalid service token");
11745 }
11746 ServiceRecord r = (ServiceRecord)token;
11747 boolean inStopping = mStoppingServices.contains(token);
11748 if (r != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011749 if (r != token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011750 Slog.w(TAG, "Done executing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011751 + " with incorrect token: given " + token
11752 + ", expected " + r);
11753 return;
11754 }
11755
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011756 if (type == 1) {
11757 // This is a call from a service start... take care of
11758 // book-keeping.
11759 r.callStart = true;
11760 switch (res) {
11761 case Service.START_STICKY_COMPATIBILITY:
11762 case Service.START_STICKY: {
11763 // We are done with the associated start arguments.
11764 r.findDeliveredStart(startId, true);
11765 // Don't stop if killed.
11766 r.stopIfKilled = false;
11767 break;
11768 }
11769 case Service.START_NOT_STICKY: {
11770 // We are done with the associated start arguments.
11771 r.findDeliveredStart(startId, true);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011772 if (r.getLastStartId() == startId) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011773 // There is no more work, and this service
11774 // doesn't want to hang around if killed.
11775 r.stopIfKilled = true;
11776 }
11777 break;
11778 }
11779 case Service.START_REDELIVER_INTENT: {
11780 // We'll keep this item until they explicitly
11781 // call stop for it, but keep track of the fact
11782 // that it was delivered.
11783 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
11784 if (si != null) {
11785 si.deliveryCount = 0;
11786 si.doneExecutingCount++;
11787 // Don't stop if killed.
11788 r.stopIfKilled = true;
11789 }
11790 break;
11791 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011792 case Service.START_TASK_REMOVED_COMPLETE: {
11793 // Special processing for onTaskRemoved(). Don't
11794 // impact normal onStartCommand() processing.
11795 r.findDeliveredStart(startId, true);
11796 break;
11797 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011798 default:
11799 throw new IllegalArgumentException(
11800 "Unknown service start result: " + res);
11801 }
11802 if (res == Service.START_STICKY_COMPATIBILITY) {
11803 r.callStart = false;
11804 }
11805 }
Amith Yamasani742a6712011-05-04 14:49:28 -070011806 if (DEBUG_MU)
11807 Slog.v(TAG_MU, "before serviceDontExecutingLocked, uid="
11808 + Binder.getOrigCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011809 final long origId = Binder.clearCallingIdentity();
11810 serviceDoneExecutingLocked(r, inStopping);
11811 Binder.restoreCallingIdentity(origId);
11812 } else {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011813 Slog.w(TAG, "Done executing unknown service from pid "
11814 + Binder.getCallingPid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011815 }
11816 }
11817 }
11818
11819 public void serviceDoneExecutingLocked(ServiceRecord r, boolean inStopping) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011820 if (DEBUG_SERVICE) Slog.v(TAG, "<<< DONE EXECUTING " + r
11821 + ": nesting=" + r.executeNesting
11822 + ", inStopping=" + inStopping + ", app=" + r.app);
Dianne Hackborn287952c2010-09-22 22:34:31 -070011823 else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG, "<<< DONE EXECUTING " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011824 r.executeNesting--;
11825 if (r.executeNesting <= 0 && r.app != null) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011826 if (DEBUG_SERVICE) Slog.v(TAG,
11827 "Nesting at 0 of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011828 r.app.executingServices.remove(r);
11829 if (r.app.executingServices.size() == 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011830 if (DEBUG_SERVICE || DEBUG_SERVICE_EXECUTING) Slog.v(TAG,
11831 "No more executingServices of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011832 mHandler.removeMessages(SERVICE_TIMEOUT_MSG, r.app);
11833 }
11834 if (inStopping) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011835 if (DEBUG_SERVICE) Slog.v(TAG,
11836 "doneExecuting remove stopping " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011837 mStoppingServices.remove(r);
Mattias Petersson3996b412010-10-27 09:32:51 +020011838 r.bindings.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011839 }
11840 updateOomAdjLocked(r.app);
11841 }
11842 }
11843
11844 void serviceTimeout(ProcessRecord proc) {
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011845 String anrMessage = null;
11846
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011847 synchronized(this) {
11848 if (proc.executingServices.size() == 0 || proc.thread == null) {
11849 return;
11850 }
11851 long maxTime = SystemClock.uptimeMillis() - SERVICE_TIMEOUT;
11852 Iterator<ServiceRecord> it = proc.executingServices.iterator();
11853 ServiceRecord timeout = null;
11854 long nextTime = 0;
11855 while (it.hasNext()) {
11856 ServiceRecord sr = it.next();
11857 if (sr.executingStart < maxTime) {
11858 timeout = sr;
11859 break;
11860 }
11861 if (sr.executingStart > nextTime) {
11862 nextTime = sr.executingStart;
11863 }
11864 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011865 if (timeout != null && mLruProcesses.contains(proc)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011866 Slog.w(TAG, "Timeout executing service: " + timeout);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011867 anrMessage = "Executing service " + timeout.shortName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011868 } else {
11869 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
11870 msg.obj = proc;
11871 mHandler.sendMessageAtTime(msg, nextTime+SERVICE_TIMEOUT);
11872 }
11873 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011874
11875 if (anrMessage != null) {
11876 appNotResponding(proc, null, null, anrMessage);
11877 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011878 }
11879
11880 // =========================================================
Christopher Tate181fafa2009-05-14 11:12:14 -070011881 // BACKUP AND RESTORE
11882 // =========================================================
11883
11884 // Cause the target app to be launched if necessary and its backup agent
11885 // instantiated. The backup agent will invoke backupAgentCreated() on the
11886 // activity manager to announce its creation.
11887 public boolean bindBackupAgent(ApplicationInfo app, int backupMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011888 if (DEBUG_BACKUP) Slog.v(TAG, "startBackupAgent: app=" + app + " mode=" + backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070011889 enforceCallingPermission("android.permission.BACKUP", "startBackupAgent");
11890
11891 synchronized(this) {
11892 // !!! TODO: currently no check here that we're already bound
11893 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
11894 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
11895 synchronized (stats) {
11896 ss = stats.getServiceStatsLocked(app.uid, app.packageName, app.name);
11897 }
11898
Dianne Hackborne7f97212011-02-24 14:40:20 -080011899 // Backup agent is now in use, its package can't be stopped.
11900 try {
11901 AppGlobals.getPackageManager().setPackageStoppedState(
11902 app.packageName, false);
11903 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080011904 } catch (IllegalArgumentException e) {
11905 Slog.w(TAG, "Failed trying to unstop package "
11906 + app.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080011907 }
11908
Christopher Tate181fafa2009-05-14 11:12:14 -070011909 BackupRecord r = new BackupRecord(ss, app, backupMode);
Christopher Tate4a627c72011-04-01 14:43:32 -070011910 ComponentName hostingName = (backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL)
11911 ? new ComponentName(app.packageName, app.backupAgentName)
11912 : new ComponentName("android", "FullBackupAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -070011913 // startProcessLocked() returns existing proc's record if it's already running
11914 ProcessRecord proc = startProcessLocked(app.processName, app,
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011915 false, 0, "backup", hostingName, false, false);
Christopher Tate181fafa2009-05-14 11:12:14 -070011916 if (proc == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011917 Slog.e(TAG, "Unable to start backup agent process " + r);
Christopher Tate181fafa2009-05-14 11:12:14 -070011918 return false;
11919 }
11920
11921 r.app = proc;
11922 mBackupTarget = r;
11923 mBackupAppName = app.packageName;
11924
Christopher Tate6fa95972009-06-05 18:43:55 -070011925 // Try not to kill the process during backup
11926 updateOomAdjLocked(proc);
11927
Christopher Tate181fafa2009-05-14 11:12:14 -070011928 // If the process is already attached, schedule the creation of the backup agent now.
11929 // If it is not yet live, this will be done when it attaches to the framework.
11930 if (proc.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011931 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc already running: " + proc);
Christopher Tate181fafa2009-05-14 11:12:14 -070011932 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040011933 proc.thread.scheduleCreateBackupAgent(app,
11934 compatibilityInfoForPackageLocked(app), backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070011935 } catch (RemoteException e) {
Christopher Tate436344a2009-09-30 16:17:37 -070011936 // Will time out on the backup manager side
Christopher Tate181fafa2009-05-14 11:12:14 -070011937 }
11938 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011939 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc not running, waiting for attach");
Christopher Tate181fafa2009-05-14 11:12:14 -070011940 }
11941 // Invariants: at this point, the target app process exists and the application
11942 // is either already running or in the process of coming up. mBackupTarget and
11943 // mBackupAppName describe the app, so that when it binds back to the AM we
11944 // know that it's scheduled for a backup-agent operation.
11945 }
11946
11947 return true;
11948 }
11949
11950 // A backup agent has just come up
11951 public void backupAgentCreated(String agentPackageName, IBinder agent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011952 if (DEBUG_BACKUP) Slog.v(TAG, "backupAgentCreated: " + agentPackageName
Christopher Tate181fafa2009-05-14 11:12:14 -070011953 + " = " + agent);
11954
11955 synchronized(this) {
11956 if (!agentPackageName.equals(mBackupAppName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011957 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
Christopher Tate181fafa2009-05-14 11:12:14 -070011958 return;
11959 }
Dianne Hackborn06740692010-09-22 22:46:21 -070011960 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011961
Dianne Hackborn06740692010-09-22 22:46:21 -070011962 long oldIdent = Binder.clearCallingIdentity();
11963 try {
11964 IBackupManager bm = IBackupManager.Stub.asInterface(
11965 ServiceManager.getService(Context.BACKUP_SERVICE));
11966 bm.agentConnected(agentPackageName, agent);
11967 } catch (RemoteException e) {
11968 // can't happen; the backup manager service is local
11969 } catch (Exception e) {
11970 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: ");
11971 e.printStackTrace();
11972 } finally {
11973 Binder.restoreCallingIdentity(oldIdent);
Christopher Tate181fafa2009-05-14 11:12:14 -070011974 }
11975 }
11976
11977 // done with this agent
11978 public void unbindBackupAgent(ApplicationInfo appInfo) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011979 if (DEBUG_BACKUP) Slog.v(TAG, "unbindBackupAgent: " + appInfo);
Christopher Tate8a27f922009-06-26 11:49:18 -070011980 if (appInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011981 Slog.w(TAG, "unbind backup agent for null app");
Christopher Tate8a27f922009-06-26 11:49:18 -070011982 return;
11983 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011984
11985 synchronized(this) {
Christopher Tate8a27f922009-06-26 11:49:18 -070011986 if (mBackupAppName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011987 Slog.w(TAG, "Unbinding backup agent with no active backup");
Christopher Tate8a27f922009-06-26 11:49:18 -070011988 return;
11989 }
11990
Christopher Tate181fafa2009-05-14 11:12:14 -070011991 if (!mBackupAppName.equals(appInfo.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011992 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
Christopher Tate181fafa2009-05-14 11:12:14 -070011993 return;
11994 }
11995
Christopher Tate6fa95972009-06-05 18:43:55 -070011996 ProcessRecord proc = mBackupTarget.app;
11997 mBackupTarget = null;
11998 mBackupAppName = null;
11999
12000 // Not backing this app up any more; reset its OOM adjustment
12001 updateOomAdjLocked(proc);
12002
Christopher Tatec7b31e32009-06-10 15:49:30 -070012003 // If the app crashed during backup, 'thread' will be null here
12004 if (proc.thread != null) {
12005 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040012006 proc.thread.scheduleDestroyBackupAgent(appInfo,
12007 compatibilityInfoForPackageLocked(appInfo));
Christopher Tatec7b31e32009-06-10 15:49:30 -070012008 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012009 Slog.e(TAG, "Exception when unbinding backup agent:");
Christopher Tatec7b31e32009-06-10 15:49:30 -070012010 e.printStackTrace();
12011 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012012 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012013 }
12014 }
12015 // =========================================================
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012016 // BROADCASTS
12017 // =========================================================
12018
Josh Bartel7f208742010-02-25 11:01:44 -060012019 private final List getStickiesLocked(String action, IntentFilter filter,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012020 List cur) {
12021 final ContentResolver resolver = mContext.getContentResolver();
12022 final ArrayList<Intent> list = mStickyBroadcasts.get(action);
12023 if (list == null) {
12024 return cur;
12025 }
12026 int N = list.size();
12027 for (int i=0; i<N; i++) {
12028 Intent intent = list.get(i);
12029 if (filter.match(resolver, intent, true, TAG) >= 0) {
12030 if (cur == null) {
12031 cur = new ArrayList<Intent>();
12032 }
12033 cur.add(intent);
12034 }
12035 }
12036 return cur;
12037 }
12038
Christopher Tatef46723b2012-01-26 14:19:24 -080012039 boolean isPendingBroadcastProcessLocked(int pid) {
12040 return mFgBroadcastQueue.isPendingBroadcastProcessLocked(pid)
12041 || mBgBroadcastQueue.isPendingBroadcastProcessLocked(pid);
12042 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012043
Christopher Tatef46723b2012-01-26 14:19:24 -080012044 void skipPendingBroadcastLocked(int pid) {
12045 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
12046 for (BroadcastQueue queue : mBroadcastQueues) {
12047 queue.skipPendingBroadcastLocked(pid);
12048 }
12049 }
12050
12051 // The app just attached; send any pending broadcasts that it should receive
12052 boolean sendPendingBroadcastsLocked(ProcessRecord app) {
12053 boolean didSomething = false;
12054 for (BroadcastQueue queue : mBroadcastQueues) {
12055 didSomething |= queue.sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012056 }
Christopher Tatef46723b2012-01-26 14:19:24 -080012057 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012058 }
12059
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012060 public Intent registerReceiver(IApplicationThread caller, String callerPackage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012061 IIntentReceiver receiver, IntentFilter filter, String permission) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012062 enforceNotIsolatedCaller("registerReceiver");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012063 synchronized(this) {
12064 ProcessRecord callerApp = null;
12065 if (caller != null) {
12066 callerApp = getRecordForAppLocked(caller);
12067 if (callerApp == null) {
12068 throw new SecurityException(
12069 "Unable to find app for caller " + caller
12070 + " (pid=" + Binder.getCallingPid()
12071 + ") when registering receiver " + receiver);
12072 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012073 if (callerApp.info.uid != Process.SYSTEM_UID &&
12074 !callerApp.pkgList.contains(callerPackage)) {
12075 throw new SecurityException("Given caller package " + callerPackage
12076 + " is not running in process " + callerApp);
12077 }
12078 } else {
12079 callerPackage = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012080 }
12081
12082 List allSticky = null;
12083
12084 // Look for any matching sticky broadcasts...
12085 Iterator actions = filter.actionsIterator();
12086 if (actions != null) {
12087 while (actions.hasNext()) {
12088 String action = (String)actions.next();
Josh Bartel7f208742010-02-25 11:01:44 -060012089 allSticky = getStickiesLocked(action, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012090 }
12091 } else {
Josh Bartel7f208742010-02-25 11:01:44 -060012092 allSticky = getStickiesLocked(null, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012093 }
12094
12095 // The first sticky in the list is returned directly back to
12096 // the client.
12097 Intent sticky = allSticky != null ? (Intent)allSticky.get(0) : null;
12098
Joe Onorato8a9b2202010-02-26 18:56:32 -080012099 if (DEBUG_BROADCAST) Slog.v(TAG, "Register receiver " + filter
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012100 + ": " + sticky);
12101
12102 if (receiver == null) {
12103 return sticky;
12104 }
12105
12106 ReceiverList rl
12107 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
12108 if (rl == null) {
12109 rl = new ReceiverList(this, callerApp,
12110 Binder.getCallingPid(),
12111 Binder.getCallingUid(), receiver);
12112 if (rl.app != null) {
12113 rl.app.receivers.add(rl);
12114 } else {
12115 try {
12116 receiver.asBinder().linkToDeath(rl, 0);
12117 } catch (RemoteException e) {
12118 return sticky;
12119 }
12120 rl.linkedToDeath = true;
12121 }
12122 mRegisteredReceivers.put(receiver.asBinder(), rl);
12123 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012124 BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage, permission);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012125 rl.add(bf);
12126 if (!bf.debugCheck()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012127 Slog.w(TAG, "==> For Dynamic broadast");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012128 }
12129 mReceiverResolver.addFilter(bf);
12130
12131 // Enqueue broadcasts for all existing stickies that match
12132 // this filter.
12133 if (allSticky != null) {
12134 ArrayList receivers = new ArrayList();
12135 receivers.add(bf);
12136
12137 int N = allSticky.size();
12138 for (int i=0; i<N; i++) {
12139 Intent intent = (Intent)allSticky.get(i);
Christopher Tatef46723b2012-01-26 14:19:24 -080012140 BroadcastQueue queue = broadcastQueueForIntent(intent);
12141 BroadcastRecord r = new BroadcastRecord(queue, intent, null,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012142 null, -1, -1, null, receivers, null, 0, null, null,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012143 false, true, true);
Christopher Tatef46723b2012-01-26 14:19:24 -080012144 queue.enqueueParallelBroadcastLocked(r);
12145 queue.scheduleBroadcastsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012146 }
12147 }
12148
12149 return sticky;
12150 }
12151 }
12152
12153 public void unregisterReceiver(IIntentReceiver receiver) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012154 if (DEBUG_BROADCAST) Slog.v(TAG, "Unregister receiver: " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012155
Christopher Tatef46723b2012-01-26 14:19:24 -080012156 final long origId = Binder.clearCallingIdentity();
12157 try {
12158 boolean doTrim = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012159
Christopher Tatef46723b2012-01-26 14:19:24 -080012160 synchronized(this) {
12161 ReceiverList rl
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012162 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
Christopher Tatef46723b2012-01-26 14:19:24 -080012163 if (rl != null) {
12164 if (rl.curBroadcast != null) {
12165 BroadcastRecord r = rl.curBroadcast;
12166 final boolean doNext = finishReceiverLocked(
12167 receiver.asBinder(), r.resultCode, r.resultData,
12168 r.resultExtras, r.resultAbort, true);
12169 if (doNext) {
12170 doTrim = true;
12171 r.queue.processNextBroadcast(false);
12172 }
12173 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012174
Christopher Tatef46723b2012-01-26 14:19:24 -080012175 if (rl.app != null) {
12176 rl.app.receivers.remove(rl);
12177 }
12178 removeReceiverLocked(rl);
12179 if (rl.linkedToDeath) {
12180 rl.linkedToDeath = false;
12181 rl.receiver.asBinder().unlinkToDeath(rl, 0);
12182 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012183 }
12184 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012185
Christopher Tatef46723b2012-01-26 14:19:24 -080012186 // If we actually concluded any broadcasts, we might now be able
12187 // to trim the recipients' apps from our working set
12188 if (doTrim) {
12189 trimApplications();
12190 return;
12191 }
12192
12193 } finally {
12194 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012195 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012196 }
12197
12198 void removeReceiverLocked(ReceiverList rl) {
12199 mRegisteredReceivers.remove(rl.receiver.asBinder());
12200 int N = rl.size();
12201 for (int i=0; i<N; i++) {
12202 mReceiverResolver.removeFilter(rl.get(i));
12203 }
12204 }
12205
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012206 private final void sendPackageBroadcastLocked(int cmd, String[] packages) {
12207 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
12208 ProcessRecord r = mLruProcesses.get(i);
12209 if (r.thread != null) {
12210 try {
12211 r.thread.dispatchPackageBroadcast(cmd, packages);
12212 } catch (RemoteException ex) {
12213 }
12214 }
12215 }
12216 }
12217
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012218 private final int broadcastIntentLocked(ProcessRecord callerApp,
12219 String callerPackage, Intent intent, String resolvedType,
12220 IIntentReceiver resultTo, int resultCode, String resultData,
12221 Bundle map, String requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070012222 boolean ordered, boolean sticky, int callingPid, int callingUid,
12223 int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012224 intent = new Intent(intent);
12225
Dianne Hackborne7f97212011-02-24 14:40:20 -080012226 // By default broadcasts do not go to stopped apps.
12227 intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
12228
Joe Onorato8a9b2202010-02-26 18:56:32 -080012229 if (DEBUG_BROADCAST_LIGHT) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012230 TAG, (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
12231 + " ordered=" + ordered);
12232 if ((resultTo != null) && !ordered) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012233 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012234 }
12235
12236 // Handle special intents: if this broadcast is from the package
12237 // manager about a package being removed, we need to remove all of
12238 // its activities from the history stack.
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012239 final boolean uidRemoved = Intent.ACTION_UID_REMOVED.equals(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012240 intent.getAction());
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012241 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())
12242 || Intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction())
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080012243 || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012244 || uidRemoved) {
12245 if (checkComponentPermission(
12246 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080012247 callingPid, callingUid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012248 == PackageManager.PERMISSION_GRANTED) {
12249 if (uidRemoved) {
12250 final Bundle intentExtras = intent.getExtras();
12251 final int uid = intentExtras != null
12252 ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
12253 if (uid >= 0) {
12254 BatteryStatsImpl bs = mBatteryStatsService.getActiveStatistics();
12255 synchronized (bs) {
12256 bs.removeUidStatsLocked(uid);
12257 }
12258 }
12259 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012260 // If resources are unvailble just force stop all
12261 // those packages and flush the attribute cache as well.
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080012262 if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012263 String list[] = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
12264 if (list != null && (list.length > 0)) {
12265 for (String pkg : list) {
Christopher Tate3dacd842011-08-19 14:56:15 -070012266 forceStopPackageLocked(pkg, -1, false, true, true, false);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012267 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012268 sendPackageBroadcastLocked(
12269 IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE, list);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012270 }
12271 } else {
12272 Uri data = intent.getData();
12273 String ssp;
12274 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
12275 if (!intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false)) {
12276 forceStopPackageLocked(ssp,
Christopher Tate3dacd842011-08-19 14:56:15 -070012277 intent.getIntExtra(Intent.EXTRA_UID, -1), false, true, true, false);
Dianne Hackbornde7faf62009-06-30 13:27:30 -070012278 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012279 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012280 sendPackageBroadcastLocked(IApplicationThread.PACKAGE_REMOVED,
12281 new String[] {ssp});
12282 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012283 }
12284 }
12285 }
12286 } else {
12287 String msg = "Permission Denial: " + intent.getAction()
12288 + " broadcast from " + callerPackage + " (pid=" + callingPid
12289 + ", uid=" + callingUid + ")"
12290 + " requires "
12291 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012292 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012293 throw new SecurityException(msg);
12294 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012295
12296 // Special case for adding a package: by default turn on compatibility
12297 // mode.
12298 } else if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -070012299 Uri data = intent.getData();
12300 String ssp;
12301 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
12302 mCompatModePackages.handlePackageAddedLocked(ssp,
12303 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false));
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012304 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012305 }
12306
12307 /*
12308 * If this is the time zone changed action, queue up a message that will reset the timezone
12309 * of all currently running processes. This message will get queued up before the broadcast
12310 * happens.
12311 */
12312 if (intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) {
12313 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
12314 }
12315
Robert Greenwalt03595d02010-11-02 14:08:23 -070012316 if (intent.ACTION_CLEAR_DNS_CACHE.equals(intent.getAction())) {
12317 mHandler.sendEmptyMessage(CLEAR_DNS_CACHE);
12318 }
12319
Robert Greenwalt434203a2010-10-11 16:00:27 -070012320 if (Proxy.PROXY_CHANGE_ACTION.equals(intent.getAction())) {
12321 ProxyProperties proxy = intent.getParcelableExtra("proxy");
12322 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY, proxy));
12323 }
12324
Dianne Hackborn854060af2009-07-09 18:14:31 -070012325 /*
12326 * Prevent non-system code (defined here to be non-persistent
12327 * processes) from sending protected broadcasts.
12328 */
12329 if (callingUid == Process.SYSTEM_UID || callingUid == Process.PHONE_UID
12330 || callingUid == Process.SHELL_UID || callingUid == 0) {
12331 // Always okay.
12332 } else if (callerApp == null || !callerApp.persistent) {
12333 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012334 if (AppGlobals.getPackageManager().isProtectedBroadcast(
Dianne Hackborn854060af2009-07-09 18:14:31 -070012335 intent.getAction())) {
12336 String msg = "Permission Denial: not allowed to send broadcast "
12337 + intent.getAction() + " from pid="
12338 + callingPid + ", uid=" + callingUid;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012339 Slog.w(TAG, msg);
Dianne Hackborn854060af2009-07-09 18:14:31 -070012340 throw new SecurityException(msg);
12341 }
12342 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012343 Slog.w(TAG, "Remote exception", e);
Dianne Hackborn854060af2009-07-09 18:14:31 -070012344 return BROADCAST_SUCCESS;
12345 }
12346 }
12347
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012348 // Add to the sticky list if requested.
12349 if (sticky) {
12350 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
12351 callingPid, callingUid)
12352 != PackageManager.PERMISSION_GRANTED) {
12353 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
12354 + callingPid + ", uid=" + callingUid
12355 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012356 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012357 throw new SecurityException(msg);
12358 }
12359 if (requiredPermission != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012360 Slog.w(TAG, "Can't broadcast sticky intent " + intent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012361 + " and enforce permission " + requiredPermission);
12362 return BROADCAST_STICKY_CANT_HAVE_PERMISSION;
12363 }
12364 if (intent.getComponent() != null) {
12365 throw new SecurityException(
12366 "Sticky broadcasts can't target a specific component");
12367 }
12368 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
12369 if (list == null) {
12370 list = new ArrayList<Intent>();
12371 mStickyBroadcasts.put(intent.getAction(), list);
12372 }
12373 int N = list.size();
12374 int i;
12375 for (i=0; i<N; i++) {
12376 if (intent.filterEquals(list.get(i))) {
12377 // This sticky already exists, replace it.
12378 list.set(i, new Intent(intent));
12379 break;
12380 }
12381 }
12382 if (i >= N) {
12383 list.add(new Intent(intent));
12384 }
12385 }
12386
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012387 // Figure out who all will receive this broadcast.
12388 List receivers = null;
12389 List<BroadcastFilter> registeredReceivers = null;
12390 try {
12391 if (intent.getComponent() != null) {
12392 // Broadcast is going to one specific receiver class...
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012393 ActivityInfo ai = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -070012394 getReceiverInfo(intent.getComponent(), STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012395 if (ai != null) {
12396 receivers = new ArrayList();
12397 ResolveInfo ri = new ResolveInfo();
Amith Yamasani742a6712011-05-04 14:49:28 -070012398 ri.activityInfo = getActivityInfoForUser(ai, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012399 receivers.add(ri);
12400 }
12401 } else {
Amith Yamasani742a6712011-05-04 14:49:28 -070012402 // TODO: Apply userId
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012403 // Need to resolve the intent to interested receivers...
12404 if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
12405 == 0) {
12406 receivers =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012407 AppGlobals.getPackageManager().queryIntentReceivers(
Dianne Hackborn1655be42009-05-08 14:29:01 -070012408 intent, resolvedType, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012409 }
Mihai Preda074edef2009-05-18 17:13:31 +020012410 registeredReceivers = mReceiverResolver.queryIntent(intent, resolvedType, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012411 }
12412 } catch (RemoteException ex) {
12413 // pm is in same process, this will never happen.
12414 }
12415
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012416 final boolean replacePending =
12417 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
12418
Joe Onorato8a9b2202010-02-26 18:56:32 -080012419 if (DEBUG_BROADCAST) Slog.v(TAG, "Enqueing broadcast: " + intent.getAction()
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012420 + " replacePending=" + replacePending);
12421
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012422 int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
12423 if (!ordered && NR > 0) {
12424 // If we are not serializing this broadcast, then send the
12425 // registered receivers separately so they don't wait for the
12426 // components to be launched.
Christopher Tatef46723b2012-01-26 14:19:24 -080012427 final BroadcastQueue queue = broadcastQueueForIntent(intent);
12428 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012429 callerPackage, callingPid, callingUid, requiredPermission,
12430 registeredReceivers, resultTo, resultCode, resultData, map,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012431 ordered, sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012432 if (DEBUG_BROADCAST) Slog.v(
Christopher Tatef46723b2012-01-26 14:19:24 -080012433 TAG, "Enqueueing parallel broadcast " + r);
12434 final boolean replaced = replacePending && queue.replaceParallelBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012435 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012436 queue.enqueueParallelBroadcastLocked(r);
12437 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012438 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012439 registeredReceivers = null;
12440 NR = 0;
12441 }
12442
12443 // Merge into one list.
12444 int ir = 0;
12445 if (receivers != null) {
12446 // A special case for PACKAGE_ADDED: do not allow the package
12447 // being added to see this broadcast. This prevents them from
12448 // using this as a back door to get run as soon as they are
12449 // installed. Maybe in the future we want to have a special install
12450 // broadcast or such for apps, but we'd like to deliberately make
12451 // this decision.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012452 String skipPackages[] = null;
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012453 if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
12454 || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
12455 || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012456 Uri data = intent.getData();
12457 if (data != null) {
12458 String pkgName = data.getSchemeSpecificPart();
12459 if (pkgName != null) {
12460 skipPackages = new String[] { pkgName };
12461 }
12462 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012463 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012464 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
The Android Open Source Project10592532009-03-18 17:39:46 -070012465 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012466 if (skipPackages != null && (skipPackages.length > 0)) {
12467 for (String skipPackage : skipPackages) {
12468 if (skipPackage != null) {
12469 int NT = receivers.size();
12470 for (int it=0; it<NT; it++) {
12471 ResolveInfo curt = (ResolveInfo)receivers.get(it);
12472 if (curt.activityInfo.packageName.equals(skipPackage)) {
12473 receivers.remove(it);
12474 it--;
12475 NT--;
12476 }
12477 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012478 }
12479 }
12480 }
12481
12482 int NT = receivers != null ? receivers.size() : 0;
12483 int it = 0;
12484 ResolveInfo curt = null;
12485 BroadcastFilter curr = null;
12486 while (it < NT && ir < NR) {
12487 if (curt == null) {
12488 curt = (ResolveInfo)receivers.get(it);
12489 }
12490 if (curr == null) {
12491 curr = registeredReceivers.get(ir);
12492 }
12493 if (curr.getPriority() >= curt.priority) {
12494 // Insert this broadcast record into the final list.
12495 receivers.add(it, curr);
12496 ir++;
12497 curr = null;
12498 it++;
12499 NT++;
12500 } else {
12501 // Skip to the next ResolveInfo in the final list.
12502 it++;
12503 curt = null;
12504 }
12505 }
12506 }
12507 while (ir < NR) {
12508 if (receivers == null) {
12509 receivers = new ArrayList();
12510 }
12511 receivers.add(registeredReceivers.get(ir));
12512 ir++;
12513 }
12514
12515 if ((receivers != null && receivers.size() > 0)
12516 || resultTo != null) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012517 BroadcastQueue queue = broadcastQueueForIntent(intent);
12518 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012519 callerPackage, callingPid, callingUid, requiredPermission,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012520 receivers, resultTo, resultCode, resultData, map, ordered,
12521 sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012522 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012523 TAG, "Enqueueing ordered broadcast " + r
Christopher Tatef46723b2012-01-26 14:19:24 -080012524 + ": prev had " + queue.mOrderedBroadcasts.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012525 if (DEBUG_BROADCAST) {
12526 int seq = r.intent.getIntExtra("seq", -1);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012527 Slog.i(TAG, "Enqueueing broadcast " + r.intent.getAction() + " seq=" + seq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012528 }
Christopher Tatef46723b2012-01-26 14:19:24 -080012529 boolean replaced = replacePending && queue.replaceOrderedBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012530 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012531 queue.enqueueOrderedBroadcastLocked(r);
12532 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012533 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012534 }
12535
12536 return BROADCAST_SUCCESS;
12537 }
12538
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012539 final Intent verifyBroadcastLocked(Intent intent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012540 // Refuse possible leaked file descriptors
12541 if (intent != null && intent.hasFileDescriptors() == true) {
12542 throw new IllegalArgumentException("File descriptors passed in Intent");
12543 }
12544
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012545 int flags = intent.getFlags();
12546
12547 if (!mProcessesReady) {
12548 // if the caller really truly claims to know what they're doing, go
12549 // ahead and allow the broadcast without launching any receivers
12550 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
12551 intent = new Intent(intent);
12552 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
12553 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
12554 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
12555 + " before boot completion");
12556 throw new IllegalStateException("Cannot broadcast before boot completed");
12557 }
12558 }
12559
12560 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
12561 throw new IllegalArgumentException(
12562 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
12563 }
12564
12565 return intent;
12566 }
12567
12568 public final int broadcastIntent(IApplicationThread caller,
12569 Intent intent, String resolvedType, IIntentReceiver resultTo,
12570 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070012571 String requiredPermission, boolean serialized, boolean sticky, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012572 enforceNotIsolatedCaller("broadcastIntent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012573 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012574 intent = verifyBroadcastLocked(intent);
Dianne Hackborn9acc0302009-08-25 00:27:12 -070012575
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012576 final ProcessRecord callerApp = getRecordForAppLocked(caller);
12577 final int callingPid = Binder.getCallingPid();
12578 final int callingUid = Binder.getCallingUid();
12579 final long origId = Binder.clearCallingIdentity();
12580 int res = broadcastIntentLocked(callerApp,
12581 callerApp != null ? callerApp.info.packageName : null,
12582 intent, resolvedType, resultTo,
Amith Yamasani742a6712011-05-04 14:49:28 -070012583 resultCode, resultData, map, requiredPermission, serialized, sticky,
12584 callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012585 Binder.restoreCallingIdentity(origId);
12586 return res;
12587 }
12588 }
12589
12590 int broadcastIntentInPackage(String packageName, int uid,
12591 Intent intent, String resolvedType, IIntentReceiver resultTo,
12592 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070012593 String requiredPermission, boolean serialized, boolean sticky, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012594 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012595 intent = verifyBroadcastLocked(intent);
12596
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012597 final long origId = Binder.clearCallingIdentity();
12598 int res = broadcastIntentLocked(null, packageName, intent, resolvedType,
12599 resultTo, resultCode, resultData, map, requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070012600 serialized, sticky, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012601 Binder.restoreCallingIdentity(origId);
12602 return res;
12603 }
12604 }
12605
Amith Yamasani742a6712011-05-04 14:49:28 -070012606 // TODO: Use the userId; maybe mStickyBroadcasts need to be tied to the user.
12607 public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012608 // Refuse possible leaked file descriptors
12609 if (intent != null && intent.hasFileDescriptors() == true) {
12610 throw new IllegalArgumentException("File descriptors passed in Intent");
12611 }
12612
12613 synchronized(this) {
12614 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
12615 != PackageManager.PERMISSION_GRANTED) {
12616 String msg = "Permission Denial: unbroadcastIntent() from pid="
12617 + Binder.getCallingPid()
12618 + ", uid=" + Binder.getCallingUid()
12619 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012620 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012621 throw new SecurityException(msg);
12622 }
12623 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
12624 if (list != null) {
12625 int N = list.size();
12626 int i;
12627 for (i=0; i<N; i++) {
12628 if (intent.filterEquals(list.get(i))) {
12629 list.remove(i);
12630 break;
12631 }
12632 }
12633 }
12634 }
12635 }
12636
12637 private final boolean finishReceiverLocked(IBinder receiver, int resultCode,
12638 String resultData, Bundle resultExtras, boolean resultAbort,
12639 boolean explicit) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012640 final BroadcastRecord r = broadcastRecordForReceiverLocked(receiver);
12641 if (r == null) {
12642 Slog.w(TAG, "finishReceiver called but not found on queue");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012643 return false;
12644 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012645
Christopher Tatef46723b2012-01-26 14:19:24 -080012646 return r.queue.finishReceiverLocked(r, resultCode, resultData, resultExtras, resultAbort,
12647 explicit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012648 }
12649
12650 public void finishReceiver(IBinder who, int resultCode, String resultData,
12651 Bundle resultExtras, boolean resultAbort) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012652 if (DEBUG_BROADCAST) Slog.v(TAG, "Finish receiver: " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012653
12654 // Refuse possible leaked file descriptors
12655 if (resultExtras != null && resultExtras.hasFileDescriptors()) {
12656 throw new IllegalArgumentException("File descriptors passed in Bundle");
12657 }
12658
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012659 final long origId = Binder.clearCallingIdentity();
Christopher Tatef46723b2012-01-26 14:19:24 -080012660 try {
12661 boolean doNext = false;
12662 BroadcastRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012663
Christopher Tatef46723b2012-01-26 14:19:24 -080012664 synchronized(this) {
12665 r = broadcastRecordForReceiverLocked(who);
12666 if (r != null) {
12667 doNext = r.queue.finishReceiverLocked(r, resultCode,
12668 resultData, resultExtras, resultAbort, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012669 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012670 }
Jeff Brown4d94a762010-09-23 11:33:28 -070012671
Christopher Tatef46723b2012-01-26 14:19:24 -080012672 if (doNext) {
12673 r.queue.processNextBroadcast(false);
12674 }
12675 trimApplications();
12676 } finally {
12677 Binder.restoreCallingIdentity(origId);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012678 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012679 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012680
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012681 // =========================================================
12682 // INSTRUMENTATION
12683 // =========================================================
12684
12685 public boolean startInstrumentation(ComponentName className,
12686 String profileFile, int flags, Bundle arguments,
12687 IInstrumentationWatcher watcher) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012688 enforceNotIsolatedCaller("startInstrumentation");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012689 // Refuse possible leaked file descriptors
12690 if (arguments != null && arguments.hasFileDescriptors()) {
12691 throw new IllegalArgumentException("File descriptors passed in Bundle");
12692 }
12693
12694 synchronized(this) {
12695 InstrumentationInfo ii = null;
12696 ApplicationInfo ai = null;
12697 try {
12698 ii = mContext.getPackageManager().getInstrumentationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070012699 className, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012700 ai = mContext.getPackageManager().getApplicationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070012701 ii.targetPackage, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012702 } catch (PackageManager.NameNotFoundException e) {
12703 }
12704 if (ii == null) {
12705 reportStartInstrumentationFailure(watcher, className,
12706 "Unable to find instrumentation info for: " + className);
12707 return false;
12708 }
12709 if (ai == null) {
12710 reportStartInstrumentationFailure(watcher, className,
12711 "Unable to find instrumentation target package: " + ii.targetPackage);
12712 return false;
12713 }
12714
12715 int match = mContext.getPackageManager().checkSignatures(
12716 ii.targetPackage, ii.packageName);
12717 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
12718 String msg = "Permission Denial: starting instrumentation "
12719 + className + " from pid="
12720 + Binder.getCallingPid()
12721 + ", uid=" + Binder.getCallingPid()
12722 + " not allowed because package " + ii.packageName
12723 + " does not have a signature matching the target "
12724 + ii.targetPackage;
12725 reportStartInstrumentationFailure(watcher, className, msg);
12726 throw new SecurityException(msg);
12727 }
12728
12729 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -070012730 // Instrumentation can kill and relaunch even persistent processes
12731 forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080012732 ProcessRecord app = addAppLocked(ai, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012733 app.instrumentationClass = className;
Dianne Hackborn1655be42009-05-08 14:29:01 -070012734 app.instrumentationInfo = ai;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012735 app.instrumentationProfileFile = profileFile;
12736 app.instrumentationArguments = arguments;
12737 app.instrumentationWatcher = watcher;
12738 app.instrumentationResultClass = className;
12739 Binder.restoreCallingIdentity(origId);
12740 }
12741
12742 return true;
12743 }
12744
12745 /**
12746 * Report errors that occur while attempting to start Instrumentation. Always writes the
12747 * error to the logs, but if somebody is watching, send the report there too. This enables
12748 * the "am" command to report errors with more information.
12749 *
12750 * @param watcher The IInstrumentationWatcher. Null if there isn't one.
12751 * @param cn The component name of the instrumentation.
12752 * @param report The error report.
12753 */
12754 private void reportStartInstrumentationFailure(IInstrumentationWatcher watcher,
12755 ComponentName cn, String report) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012756 Slog.w(TAG, report);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012757 try {
12758 if (watcher != null) {
12759 Bundle results = new Bundle();
12760 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
12761 results.putString("Error", report);
12762 watcher.instrumentationStatus(cn, -1, results);
12763 }
12764 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012765 Slog.w(TAG, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012766 }
12767 }
12768
12769 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
12770 if (app.instrumentationWatcher != null) {
12771 try {
12772 // NOTE: IInstrumentationWatcher *must* be oneway here
12773 app.instrumentationWatcher.instrumentationFinished(
12774 app.instrumentationClass,
12775 resultCode,
12776 results);
12777 } catch (RemoteException e) {
12778 }
12779 }
12780 app.instrumentationWatcher = null;
12781 app.instrumentationClass = null;
Dianne Hackborn1655be42009-05-08 14:29:01 -070012782 app.instrumentationInfo = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012783 app.instrumentationProfileFile = null;
12784 app.instrumentationArguments = null;
12785
Christopher Tate3dacd842011-08-19 14:56:15 -070012786 forceStopPackageLocked(app.processName, -1, false, false, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012787 }
12788
12789 public void finishInstrumentation(IApplicationThread target,
12790 int resultCode, Bundle results) {
12791 // Refuse possible leaked file descriptors
12792 if (results != null && results.hasFileDescriptors()) {
12793 throw new IllegalArgumentException("File descriptors passed in Intent");
12794 }
12795
12796 synchronized(this) {
12797 ProcessRecord app = getRecordForAppLocked(target);
12798 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012799 Slog.w(TAG, "finishInstrumentation: no app for " + target);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012800 return;
12801 }
12802 final long origId = Binder.clearCallingIdentity();
12803 finishInstrumentationLocked(app, resultCode, results);
12804 Binder.restoreCallingIdentity(origId);
12805 }
12806 }
12807
12808 // =========================================================
12809 // CONFIGURATION
12810 // =========================================================
12811
12812 public ConfigurationInfo getDeviceConfigurationInfo() {
12813 ConfigurationInfo config = new ConfigurationInfo();
12814 synchronized (this) {
12815 config.reqTouchScreen = mConfiguration.touchscreen;
12816 config.reqKeyboardType = mConfiguration.keyboard;
12817 config.reqNavigation = mConfiguration.navigation;
Dianne Hackbornfae76f52009-07-16 13:41:23 -070012818 if (mConfiguration.navigation == Configuration.NAVIGATION_DPAD
12819 || mConfiguration.navigation == Configuration.NAVIGATION_TRACKBALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012820 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
12821 }
Dianne Hackbornfae76f52009-07-16 13:41:23 -070012822 if (mConfiguration.keyboard != Configuration.KEYBOARD_UNDEFINED
12823 && mConfiguration.keyboard != Configuration.KEYBOARD_NOKEYS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012824 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
12825 }
Jack Palevichb90d28c2009-07-22 15:35:24 -070012826 config.reqGlEsVersion = GL_ES_VERSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012827 }
12828 return config;
12829 }
12830
12831 public Configuration getConfiguration() {
12832 Configuration ci;
12833 synchronized(this) {
12834 ci = new Configuration(mConfiguration);
12835 }
12836 return ci;
12837 }
12838
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012839 public void updatePersistentConfiguration(Configuration values) {
12840 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
12841 "updateConfiguration()");
12842 enforceCallingPermission(android.Manifest.permission.WRITE_SETTINGS,
12843 "updateConfiguration()");
12844 if (values == null) {
12845 throw new NullPointerException("Configuration must not be null");
12846 }
12847
12848 synchronized(this) {
12849 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn813075a62011-11-14 17:45:19 -080012850 updateConfigurationLocked(values, null, true, false);
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012851 Binder.restoreCallingIdentity(origId);
12852 }
12853 }
12854
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012855 public void updateConfiguration(Configuration values) {
12856 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
12857 "updateConfiguration()");
12858
12859 synchronized(this) {
12860 if (values == null && mWindowManager != null) {
12861 // sentinel: fetch the current configuration from the window manager
12862 values = mWindowManager.computeNewConfiguration();
12863 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012864
12865 if (mWindowManager != null) {
12866 mProcessList.applyDisplaySize(mWindowManager);
12867 }
12868
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012869 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012870 if (values != null) {
12871 Settings.System.clearConfiguration(values);
12872 }
Dianne Hackborn813075a62011-11-14 17:45:19 -080012873 updateConfigurationLocked(values, null, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012874 Binder.restoreCallingIdentity(origId);
12875 }
12876 }
12877
12878 /**
12879 * Do either or both things: (1) change the current configuration, and (2)
12880 * make sure the given activity is running with the (now) current
12881 * configuration. Returns true if the activity has been left running, or
12882 * false if <var>starting</var> is being destroyed to match the new
12883 * configuration.
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012884 * @param persistent TODO
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012885 */
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012886 boolean updateConfigurationLocked(Configuration values,
Dianne Hackborn813075a62011-11-14 17:45:19 -080012887 ActivityRecord starting, boolean persistent, boolean initLocale) {
Mike Lockwood3a74bd32011-08-12 13:55:22 -070012888 // do nothing if we are headless
12889 if (mHeadless) return true;
12890
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012891 int changes = 0;
12892
12893 boolean kept = true;
12894
12895 if (values != null) {
12896 Configuration newConfig = new Configuration(mConfiguration);
12897 changes = newConfig.updateFrom(values);
12898 if (changes != 0) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070012899 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012900 Slog.i(TAG, "Updating configuration to: " + values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012901 }
12902
Doug Zongker2bec3d42009-12-04 12:52:44 -080012903 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012904
Dianne Hackborn813075a62011-11-14 17:45:19 -080012905 if (values.locale != null && !initLocale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012906 saveLocaleLocked(values.locale,
12907 !values.locale.equals(mConfiguration.locale),
12908 values.userSetLocale);
12909 }
12910
Dianne Hackborne36d6e22010-02-17 19:46:25 -080012911 mConfigurationSeq++;
12912 if (mConfigurationSeq <= 0) {
12913 mConfigurationSeq = 1;
12914 }
12915 newConfig.seq = mConfigurationSeq;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012916 mConfiguration = newConfig;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012917 Slog.i(TAG, "Config changed: " + newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012918
12919 final Configuration configCopy = new Configuration(mConfiguration);
Joe Onorato54a4a412011-11-02 20:50:08 -070012920
12921 // TODO: If our config changes, should we auto dismiss any currently
12922 // showing dialogs?
12923 mShowDialogs = shouldShowDialogs(newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012924
Dianne Hackborn826d17c2009-11-12 12:55:51 -080012925 AttributeCache ac = AttributeCache.instance();
12926 if (ac != null) {
Dianne Hackborn813075a62011-11-14 17:45:19 -080012927 ac.updateConfiguration(configCopy);
Dianne Hackborn826d17c2009-11-12 12:55:51 -080012928 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012929
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070012930 // Make sure all resources in our process are updated
12931 // right now, so that anyone who is going to retrieve
12932 // resource values after we return will be sure to get
12933 // the new ones. This is especially important during
12934 // boot, where the first config change needs to guarantee
12935 // all resources have that config before following boot
12936 // code is executed.
Dianne Hackborn813075a62011-11-14 17:45:19 -080012937 mSystemThread.applyConfigurationToResources(configCopy);
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070012938
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012939 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080012940 Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012941 msg.obj = new Configuration(configCopy);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080012942 mHandler.sendMessage(msg);
12943 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012944
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012945 for (int i=mLruProcesses.size()-1; i>=0; i--) {
12946 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012947 try {
12948 if (app.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012949 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending to proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -070012950 + app.processName + " new config " + mConfiguration);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012951 app.thread.scheduleConfigurationChanged(configCopy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012952 }
12953 } catch (Exception e) {
12954 }
12955 }
12956 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012957 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
12958 | Intent.FLAG_RECEIVER_REPLACE_PENDING);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012959 broadcastIntentLocked(null, null, intent, null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070012960 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080012961 if ((changes&ActivityInfo.CONFIG_LOCALE) != 0) {
12962 broadcastIntentLocked(null, null,
12963 new Intent(Intent.ACTION_LOCALE_CHANGED),
12964 null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070012965 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080012966 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012967 }
12968 }
12969
12970 if (changes != 0 && starting == null) {
12971 // If the configuration changed, and the caller is not already
12972 // in the process of starting an activity, then find the top
12973 // activity to check if its configuration needs to change.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012974 starting = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012975 }
12976
12977 if (starting != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012978 kept = mMainStack.ensureActivityConfigurationLocked(starting, changes);
Dianne Hackborn5f4d6432010-12-21 20:40:11 -080012979 // And we need to make sure at this point that all other activities
12980 // are made visible with the correct configuration.
12981 mMainStack.ensureActivitiesVisibleLocked(starting, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012982 }
12983
Dianne Hackborne36d6e22010-02-17 19:46:25 -080012984 if (values != null && mWindowManager != null) {
12985 mWindowManager.setNewConfiguration(mConfiguration);
12986 }
12987
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012988 return kept;
12989 }
Joe Onorato54a4a412011-11-02 20:50:08 -070012990
12991 /**
12992 * Decide based on the configuration whether we should shouw the ANR,
12993 * crash, etc dialogs. The idea is that if there is no affordnace to
12994 * press the on-screen buttons, we shouldn't show the dialog.
12995 *
12996 * A thought: SystemUI might also want to get told about this, the Power
12997 * dialog / global actions also might want different behaviors.
12998 */
12999 private static final boolean shouldShowDialogs(Configuration config) {
13000 return !(config.keyboard == Configuration.KEYBOARD_NOKEYS
13001 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH);
13002 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013003
13004 /**
13005 * Save the locale. You must be inside a synchronized (this) block.
13006 */
13007 private void saveLocaleLocked(Locale l, boolean isDiff, boolean isPersist) {
13008 if(isDiff) {
13009 SystemProperties.set("user.language", l.getLanguage());
13010 SystemProperties.set("user.region", l.getCountry());
13011 }
13012
13013 if(isPersist) {
13014 SystemProperties.set("persist.sys.language", l.getLanguage());
13015 SystemProperties.set("persist.sys.country", l.getCountry());
13016 SystemProperties.set("persist.sys.localevar", l.getVariant());
13017 }
13018 }
13019
13020 // =========================================================
13021 // LIFETIME MANAGEMENT
13022 // =========================================================
13023
Christopher Tatef46723b2012-01-26 14:19:24 -080013024 // Returns which broadcast queue the app is the current [or imminent] receiver
13025 // on, or 'null' if the app is not an active broadcast recipient.
13026 private BroadcastQueue isReceivingBroadcast(ProcessRecord app) {
13027 BroadcastRecord r = app.curReceiver;
13028 if (r != null) {
13029 return r.queue;
13030 }
13031
13032 // It's not the current receiver, but it might be starting up to become one
13033 synchronized (this) {
13034 for (BroadcastQueue queue : mBroadcastQueues) {
13035 r = queue.mPendingBroadcast;
13036 if (r != null && r.curApp == app) {
13037 // found it; report which queue it's in
13038 return queue;
13039 }
13040 }
13041 }
13042
13043 return null;
13044 }
13045
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013046 private final int computeOomAdjLocked(ProcessRecord app, int hiddenAdj,
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013047 ProcessRecord TOP_APP, boolean recursed, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013048 if (mAdjSeq == app.adjSeq) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013049 // This adjustment has already been computed. If we are calling
13050 // from the top, we may have already computed our adjustment with
13051 // an earlier hidden adjustment that isn't really for us... if
13052 // so, use the new hidden adjustment.
13053 if (!recursed && app.hidden) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013054 app.curAdj = app.curRawAdj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013055 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013056 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013057 }
13058
13059 if (app.thread == null) {
13060 app.adjSeq = mAdjSeq;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013061 app.curSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013062 return (app.curAdj=ProcessList.HIDDEN_APP_MAX_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013063 }
13064
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013065 app.adjTypeCode = ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN;
13066 app.adjSource = null;
13067 app.adjTarget = null;
13068 app.empty = false;
13069 app.hidden = false;
13070
13071 final int activitiesSize = app.activities.size();
13072
Dianne Hackborn7d608422011-08-07 16:24:18 -070013073 if (app.maxAdj <= ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013074 // The max adjustment doesn't allow this app to be anything
13075 // below foreground, so it is not worth doing work for it.
13076 app.adjType = "fixed";
13077 app.adjSeq = mAdjSeq;
13078 app.curRawAdj = app.maxAdj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013079 app.foregroundActivities = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013080 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013081 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013082 // System process can do UI, and when they do we want to have
13083 // them trim their memory after the user leaves the UI. To
13084 // facilitate this, here we need to determine whether or not it
13085 // is currently showing UI.
13086 app.systemNoUi = true;
13087 if (app == TOP_APP) {
13088 app.systemNoUi = false;
13089 } else if (activitiesSize > 0) {
13090 for (int j = 0; j < activitiesSize; j++) {
13091 final ActivityRecord r = app.activities.get(j);
13092 if (r.visible) {
13093 app.systemNoUi = false;
13094 break;
13095 }
13096 }
13097 }
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013098 return (app.curAdj=app.maxAdj);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013099 }
13100
13101 final boolean hadForegroundActivities = app.foregroundActivities;
13102
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013103 app.foregroundActivities = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013104 app.keeping = false;
13105 app.systemNoUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013106
The Android Open Source Project4df24232009-03-05 14:34:35 -080013107 // Determine the importance of the process, starting with most
13108 // important to least, and assign an appropriate OOM adjustment.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013109 int adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013110 int schedGroup;
Christopher Tatef46723b2012-01-26 14:19:24 -080013111 BroadcastQueue queue;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013112 if (app == TOP_APP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013113 // The last app on the list is the foreground app.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013114 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013115 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013116 app.adjType = "top-activity";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013117 app.foregroundActivities = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013118 } else if (app.instrumentationClass != null) {
13119 // Don't want to kill running instrumentation.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013120 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013121 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013122 app.adjType = "instrumentation";
Christopher Tatef46723b2012-01-26 14:19:24 -080013123 } else if ((queue = isReceivingBroadcast(app)) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013124 // An app that is currently receiving a broadcast also
Christopher Tatef46723b2012-01-26 14:19:24 -080013125 // counts as being in the foreground for OOM killer purposes.
13126 // It's placed in a sched group based on the nature of the
13127 // broadcast as reflected by which queue it's active in.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013128 adj = ProcessList.FOREGROUND_APP_ADJ;
Christopher Tatef46723b2012-01-26 14:19:24 -080013129 schedGroup = (queue == mFgBroadcastQueue)
13130 ? Process.THREAD_GROUP_DEFAULT : Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013131 app.adjType = "broadcast";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013132 } else if (app.executingServices.size() > 0) {
13133 // An app that is currently executing a service callback also
13134 // counts as being in the foreground.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013135 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013136 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013137 app.adjType = "exec-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013138 } else if (activitiesSize > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013139 // This app is in the background with paused activities.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013140 // We inspect activities to potentially upgrade adjustment further below.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013141 adj = hiddenAdj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013142 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013143 app.hidden = true;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013144 app.adjType = "bg-activities";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013145 } else {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013146 // A very not-needed process. If this is lower in the lru list,
13147 // we will push it in to the empty bucket.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013148 adj = hiddenAdj;
13149 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013150 app.hidden = true;
13151 app.empty = true;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013152 app.adjType = "bg-empty";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013153 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013154
13155 // Examine all activities if not already foreground.
13156 if (!app.foregroundActivities && activitiesSize > 0) {
13157 for (int j = 0; j < activitiesSize; j++) {
13158 final ActivityRecord r = app.activities.get(j);
13159 if (r.visible) {
13160 // App has a visible activity; only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013161 if (adj > ProcessList.VISIBLE_APP_ADJ) {
13162 adj = ProcessList.VISIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013163 app.adjType = "visible";
13164 }
13165 schedGroup = Process.THREAD_GROUP_DEFAULT;
13166 app.hidden = false;
13167 app.foregroundActivities = true;
13168 break;
13169 } else if (r.state == ActivityState.PAUSING || r.state == ActivityState.PAUSED
13170 || r.state == ActivityState.STOPPING) {
13171 // Only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013172 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13173 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013174 app.adjType = "stopping";
13175 }
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -080013176 app.hidden = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013177 app.foregroundActivities = true;
13178 }
13179 }
13180 }
13181
Dianne Hackborn7d608422011-08-07 16:24:18 -070013182 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013183 if (app.foregroundServices) {
13184 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013185 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013186 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013187 app.adjType = "foreground-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013188 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013189 } else if (app.forcingToForeground != null) {
13190 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013191 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013192 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013193 app.adjType = "force-foreground";
13194 app.adjSource = app.forcingToForeground;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013195 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013196 }
13197 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013198
Dianne Hackborn7d608422011-08-07 16:24:18 -070013199 if (adj > ProcessList.HEAVY_WEIGHT_APP_ADJ && app == mHeavyWeightProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013200 // We don't want to kill the current heavy-weight process.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013201 adj = ProcessList.HEAVY_WEIGHT_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013202 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013203 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013204 app.adjType = "heavy";
13205 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013206
Dianne Hackborn7d608422011-08-07 16:24:18 -070013207 if (adj > ProcessList.HOME_APP_ADJ && app == mHomeProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013208 // This process is hosting what we currently consider to be the
13209 // home app, so we don't want to let it go into the background.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013210 adj = ProcessList.HOME_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013211 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013212 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013213 app.adjType = "home";
13214 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013215
Dianne Hackbornf35fe232011-11-01 19:25:20 -070013216 if (adj > ProcessList.PREVIOUS_APP_ADJ && app == mPreviousProcess
13217 && app.activities.size() > 0) {
13218 // This was the previous process that showed UI to the user.
13219 // We want to try to keep it around more aggressively, to give
13220 // a good experience around switching between two apps.
13221 adj = ProcessList.PREVIOUS_APP_ADJ;
13222 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
13223 app.hidden = false;
13224 app.adjType = "previous";
13225 }
13226
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013227 if (false) Slog.i(TAG, "OOM " + app + ": initial adj=" + adj
13228 + " reason=" + app.adjType);
13229
The Android Open Source Project4df24232009-03-05 14:34:35 -080013230 // By default, we use the computed adjustment. It may be changed if
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013231 // there are applications dependent on our services or providers, but
13232 // this gives us a baseline and makes sure we don't get into an
13233 // infinite recursion.
13234 app.adjSeq = mAdjSeq;
13235 app.curRawAdj = adj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013236
Christopher Tate6fa95972009-06-05 18:43:55 -070013237 if (mBackupTarget != null && app == mBackupTarget.app) {
13238 // If possible we want to avoid killing apps while they're being backed up
Dianne Hackborn7d608422011-08-07 16:24:18 -070013239 if (adj > ProcessList.BACKUP_APP_ADJ) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013240 if (DEBUG_BACKUP) Slog.v(TAG, "oom BACKUP_APP_ADJ for " + app);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013241 adj = ProcessList.BACKUP_APP_ADJ;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013242 app.adjType = "backup";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013243 app.hidden = false;
Christopher Tate6fa95972009-06-05 18:43:55 -070013244 }
13245 }
13246
Dianne Hackborn7d608422011-08-07 16:24:18 -070013247 if (app.services.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013248 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013249 final long now = SystemClock.uptimeMillis();
13250 // This process is more important if the top activity is
13251 // bound to the service.
Dianne Hackborn860755f2010-06-03 18:47:52 -070013252 Iterator<ServiceRecord> jt = app.services.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013253 while (jt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013254 ServiceRecord s = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013255 if (s.startRequested) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013256 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013257 // If this process has shown some UI, let it immediately
13258 // go to the LRU list because it may be pretty heavy with
13259 // UI stuff. We'll tag it with a label just to help
13260 // debug and understand what is going on.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013261 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013262 app.adjType = "started-bg-ui-services";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013263 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013264 } else {
13265 if (now < (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
13266 // This service has seen some activity within
13267 // recent memory, so we will keep its process ahead
13268 // of the background processes.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013269 if (adj > ProcessList.SERVICE_ADJ) {
13270 adj = ProcessList.SERVICE_ADJ;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013271 app.adjType = "started-services";
13272 app.hidden = false;
13273 }
13274 }
13275 // If we have let the service slide into the background
13276 // state, still have some text describing what it is doing
13277 // even though the service no longer has an impact.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013278 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013279 app.adjType = "started-bg-services";
13280 }
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080013281 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013282 // Don't kill this process because it is doing work; it
13283 // has said it is doing work.
13284 app.keeping = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013285 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013286 if (s.connections.size() > 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013287 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013288 Iterator<ArrayList<ConnectionRecord>> kt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013289 = s.connections.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013290 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013291 ArrayList<ConnectionRecord> clist = kt.next();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013292 for (int i=0; i<clist.size() && adj > ProcessList.FOREGROUND_APP_ADJ; i++) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013293 // XXX should compute this based on the max of
13294 // all connected clients.
13295 ConnectionRecord cr = clist.get(i);
13296 if (cr.binding.client == app) {
13297 // Binding to ourself is not interesting.
13298 continue;
13299 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013300 if ((cr.flags&Context.BIND_WAIVE_PRIORITY) == 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013301 ProcessRecord client = cr.binding.client;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013302 int clientAdj = adj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013303 int myHiddenAdj = hiddenAdj;
13304 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013305 if (client.hiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013306 myHiddenAdj = client.hiddenAdj;
13307 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013308 myHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013309 }
13310 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013311 clientAdj = computeOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013312 client, myHiddenAdj, TOP_APP, true, doingAll);
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013313 String adjType = null;
13314 if ((cr.flags&Context.BIND_ALLOW_OOM_MANAGEMENT) != 0) {
13315 // Not doing bind OOM management, so treat
13316 // this guy more like a started service.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013317 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013318 // If this process has shown some UI, let it immediately
13319 // go to the LRU list because it may be pretty heavy with
13320 // UI stuff. We'll tag it with a label just to help
13321 // debug and understand what is going on.
13322 if (adj > clientAdj) {
13323 adjType = "bound-bg-ui-services";
13324 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013325 app.hidden = false;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013326 clientAdj = adj;
13327 } else {
13328 if (now >= (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
13329 // This service has not seen activity within
13330 // recent memory, so allow it to drop to the
13331 // LRU list if there is no other reason to keep
13332 // it around. We'll also tag it with a label just
13333 // to help debug and undertand what is going on.
13334 if (adj > clientAdj) {
13335 adjType = "bound-bg-services";
13336 }
13337 clientAdj = adj;
13338 }
13339 }
13340 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013341 if (adj > clientAdj) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013342 // If this process has recently shown UI, and
13343 // the process that is binding to it is less
13344 // important than being visible, then we don't
13345 // care about the binding as much as we care
13346 // about letting this process get into the LRU
13347 // list to be killed and restarted if needed for
13348 // memory.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013349 if (app.hasShownUi && app != mHomeProcess
13350 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013351 adjType = "bound-bg-ui-services";
13352 } else {
13353 if ((cr.flags&(Context.BIND_ABOVE_CLIENT
13354 |Context.BIND_IMPORTANT)) != 0) {
13355 adj = clientAdj;
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070013356 } else if ((cr.flags&Context.BIND_NOT_VISIBLE) != 0
13357 && clientAdj < ProcessList.PERCEPTIBLE_APP_ADJ
13358 && adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13359 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13360 } else if (clientAdj > ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013361 adj = clientAdj;
13362 } else {
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070013363 app.pendingUiClean = true;
13364 if (adj > ProcessList.VISIBLE_APP_ADJ) {
13365 adj = ProcessList.VISIBLE_APP_ADJ;
13366 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013367 }
13368 if (!client.hidden) {
13369 app.hidden = false;
13370 }
13371 if (client.keeping) {
13372 app.keeping = true;
13373 }
13374 adjType = "service";
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013375 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013376 }
13377 if (adjType != null) {
13378 app.adjType = adjType;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013379 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13380 .REASON_SERVICE_IN_USE;
13381 app.adjSource = cr.binding.client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013382 app.adjSourceOom = clientAdj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013383 app.adjTarget = s.name;
13384 }
13385 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
13386 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
13387 schedGroup = Process.THREAD_GROUP_DEFAULT;
13388 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013389 }
13390 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013391 if ((cr.flags&Context.BIND_ADJUST_WITH_ACTIVITY) != 0) {
13392 ActivityRecord a = cr.activity;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013393 if (a != null && adj > ProcessList.FOREGROUND_APP_ADJ &&
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013394 (a.visible || a.state == ActivityState.RESUMED
13395 || a.state == ActivityState.PAUSING)) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013396 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013397 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
13398 schedGroup = Process.THREAD_GROUP_DEFAULT;
13399 }
13400 app.hidden = false;
13401 app.adjType = "service";
13402 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13403 .REASON_SERVICE_IN_USE;
13404 app.adjSource = a;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013405 app.adjSourceOom = adj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013406 app.adjTarget = s.name;
13407 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013408 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013409 }
13410 }
13411 }
13412 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013413
Dianne Hackborn287952c2010-09-22 22:34:31 -070013414 // Finally, if this process has active services running in it, we
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013415 // would like to avoid killing it unless it would prevent the current
13416 // application from running. By default we put the process in
13417 // with the rest of the background processes; as we scan through
13418 // its services we may bump it up from there.
13419 if (adj > hiddenAdj) {
13420 adj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013421 app.hidden = false;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013422 app.adjType = "bg-services";
13423 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013424 }
13425
Dianne Hackborn7d608422011-08-07 16:24:18 -070013426 if (app.pubProviders.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013427 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013428 Iterator<ContentProviderRecord> jt = app.pubProviders.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013429 while (jt.hasNext() && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013430 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013431 ContentProviderRecord cpr = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013432 if (cpr.clients.size() != 0) {
13433 Iterator<ProcessRecord> kt = cpr.clients.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013434 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013435 ProcessRecord client = kt.next();
The Android Open Source Project10592532009-03-18 17:39:46 -070013436 if (client == app) {
13437 // Being our own client is not interesting.
13438 continue;
13439 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013440 int myHiddenAdj = hiddenAdj;
13441 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013442 if (client.hiddenAdj > ProcessList.FOREGROUND_APP_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013443 myHiddenAdj = client.hiddenAdj;
13444 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013445 myHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013446 }
13447 }
13448 int clientAdj = computeOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013449 client, myHiddenAdj, TOP_APP, true, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013450 if (adj > clientAdj) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013451 if (app.hasShownUi && app != mHomeProcess
13452 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013453 app.adjType = "bg-ui-provider";
13454 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013455 adj = clientAdj > ProcessList.FOREGROUND_APP_ADJ
13456 ? clientAdj : ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013457 app.adjType = "provider";
13458 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013459 if (!client.hidden) {
13460 app.hidden = false;
13461 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013462 if (client.keeping) {
13463 app.keeping = true;
13464 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070013465 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13466 .REASON_PROVIDER_IN_USE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013467 app.adjSource = client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013468 app.adjSourceOom = clientAdj;
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070013469 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013470 }
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013471 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
13472 schedGroup = Process.THREAD_GROUP_DEFAULT;
13473 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013474 }
13475 }
13476 // If the provider has external (non-framework) process
13477 // dependencies, ensure that its adjustment is at least
13478 // FOREGROUND_APP_ADJ.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080013479 if (cpr.hasExternalProcessHandles()) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013480 if (adj > ProcessList.FOREGROUND_APP_ADJ) {
13481 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013482 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013483 app.hidden = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013484 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013485 app.adjType = "provider";
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070013486 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013487 }
13488 }
13489 }
13490 }
13491
13492 app.curRawAdj = adj;
13493
Joe Onorato8a9b2202010-02-26 18:56:32 -080013494 //Slog.i(TAG, "OOM ADJ " + app + ": pid=" + app.pid +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013495 // " adj=" + adj + " curAdj=" + app.curAdj + " maxAdj=" + app.maxAdj);
13496 if (adj > app.maxAdj) {
13497 adj = app.maxAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013498 if (app.maxAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013499 schedGroup = Process.THREAD_GROUP_DEFAULT;
13500 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013501 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013502 if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070013503 app.keeping = true;
13504 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013505
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013506 if (app.hasAboveClient) {
13507 // If this process has bound to any services with BIND_ABOVE_CLIENT,
13508 // then we need to drop its adjustment to be lower than the service's
13509 // in order to honor the request. We want to drop it by one adjustment
13510 // level... but there is special meaning applied to various levels so
13511 // we will skip some of them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013512 if (adj < ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013513 // System process will not get dropped, ever
Dianne Hackborn7d608422011-08-07 16:24:18 -070013514 } else if (adj < ProcessList.VISIBLE_APP_ADJ) {
13515 adj = ProcessList.VISIBLE_APP_ADJ;
13516 } else if (adj < ProcessList.PERCEPTIBLE_APP_ADJ) {
13517 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13518 } else if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
13519 adj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013520 } else if (adj < ProcessList.HIDDEN_APP_MAX_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013521 adj++;
13522 }
13523 }
13524
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013525 if (adj == ProcessList.SERVICE_ADJ) {
13526 if (doingAll) {
13527 app.serviceb = mNewNumServiceProcs > (mNumServiceProcs/3);
13528 mNewNumServiceProcs++;
13529 }
13530 if (app.serviceb) {
13531 adj = ProcessList.SERVICE_B_ADJ;
13532 }
13533 } else {
13534 app.serviceb = false;
13535 }
13536
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013537 app.curAdj = adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013538 app.curSchedGroup = schedGroup;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013539
13540 if (hadForegroundActivities != app.foregroundActivities) {
Jeff Sharkey287bd832011-05-28 19:36:26 -070013541 mHandler.obtainMessage(DISPATCH_FOREGROUND_ACTIVITIES_CHANGED, app.pid, app.info.uid,
13542 app.foregroundActivities).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013543 }
13544
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013545 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013546 }
13547
13548 /**
13549 * Ask a given process to GC right now.
13550 */
13551 final void performAppGcLocked(ProcessRecord app) {
13552 try {
13553 app.lastRequestedGc = SystemClock.uptimeMillis();
13554 if (app.thread != null) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013555 if (app.reportLowMemory) {
13556 app.reportLowMemory = false;
13557 app.thread.scheduleLowMemory();
13558 } else {
13559 app.thread.processInBackground();
13560 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013561 }
13562 } catch (Exception e) {
13563 // whatever.
13564 }
13565 }
13566
13567 /**
13568 * Returns true if things are idle enough to perform GCs.
13569 */
Josh Bartel7f208742010-02-25 11:01:44 -060013570 private final boolean canGcNowLocked() {
Christopher Tatef46723b2012-01-26 14:19:24 -080013571 boolean processingBroadcasts = false;
13572 for (BroadcastQueue q : mBroadcastQueues) {
13573 if (q.mParallelBroadcasts.size() != 0 || q.mOrderedBroadcasts.size() != 0) {
13574 processingBroadcasts = true;
13575 }
13576 }
13577 return !processingBroadcasts
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013578 && (mSleeping || (mMainStack.mResumedActivity != null &&
13579 mMainStack.mResumedActivity.idle));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013580 }
13581
13582 /**
13583 * Perform GCs on all processes that are waiting for it, but only
13584 * if things are idle.
13585 */
13586 final void performAppGcsLocked() {
13587 final int N = mProcessesToGc.size();
13588 if (N <= 0) {
13589 return;
13590 }
Josh Bartel7f208742010-02-25 11:01:44 -060013591 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013592 while (mProcessesToGc.size() > 0) {
13593 ProcessRecord proc = mProcessesToGc.remove(0);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013594 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013595 if ((proc.lastRequestedGc+GC_MIN_INTERVAL)
13596 <= SystemClock.uptimeMillis()) {
13597 // To avoid spamming the system, we will GC processes one
13598 // at a time, waiting a few seconds between each.
13599 performAppGcLocked(proc);
13600 scheduleAppGcsLocked();
13601 return;
13602 } else {
13603 // It hasn't been long enough since we last GCed this
13604 // process... put it in the list to wait for its time.
13605 addProcessToGcListLocked(proc);
13606 break;
13607 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013608 }
13609 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013610
13611 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013612 }
13613 }
13614
13615 /**
13616 * If all looks good, perform GCs on all processes waiting for them.
13617 */
13618 final void performAppGcsIfAppropriateLocked() {
Josh Bartel7f208742010-02-25 11:01:44 -060013619 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013620 performAppGcsLocked();
13621 return;
13622 }
13623 // Still not idle, wait some more.
13624 scheduleAppGcsLocked();
13625 }
13626
13627 /**
13628 * Schedule the execution of all pending app GCs.
13629 */
13630 final void scheduleAppGcsLocked() {
13631 mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013632
13633 if (mProcessesToGc.size() > 0) {
13634 // Schedule a GC for the time to the next process.
13635 ProcessRecord proc = mProcessesToGc.get(0);
13636 Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG);
13637
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013638 long when = proc.lastRequestedGc + GC_MIN_INTERVAL;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013639 long now = SystemClock.uptimeMillis();
13640 if (when < (now+GC_TIMEOUT)) {
13641 when = now + GC_TIMEOUT;
13642 }
13643 mHandler.sendMessageAtTime(msg, when);
13644 }
13645 }
13646
13647 /**
13648 * Add a process to the array of processes waiting to be GCed. Keeps the
13649 * list in sorted order by the last GC time. The process can't already be
13650 * on the list.
13651 */
13652 final void addProcessToGcListLocked(ProcessRecord proc) {
13653 boolean added = false;
13654 for (int i=mProcessesToGc.size()-1; i>=0; i--) {
13655 if (mProcessesToGc.get(i).lastRequestedGc <
13656 proc.lastRequestedGc) {
13657 added = true;
13658 mProcessesToGc.add(i+1, proc);
13659 break;
13660 }
13661 }
13662 if (!added) {
13663 mProcessesToGc.add(0, proc);
13664 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013665 }
13666
13667 /**
13668 * Set up to ask a process to GC itself. This will either do it
13669 * immediately, or put it on the list of processes to gc the next
13670 * time things are idle.
13671 */
13672 final void scheduleAppGcLocked(ProcessRecord app) {
13673 long now = SystemClock.uptimeMillis();
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013674 if ((app.lastRequestedGc+GC_MIN_INTERVAL) > now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013675 return;
13676 }
13677 if (!mProcessesToGc.contains(app)) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013678 addProcessToGcListLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013679 scheduleAppGcsLocked();
13680 }
13681 }
13682
Dianne Hackborn287952c2010-09-22 22:34:31 -070013683 final void checkExcessivePowerUsageLocked(boolean doKills) {
13684 updateCpuStatsNow();
13685
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013686 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013687 boolean doWakeKills = doKills;
13688 boolean doCpuKills = doKills;
13689 if (mLastPowerCheckRealtime == 0) {
13690 doWakeKills = false;
13691 }
13692 if (mLastPowerCheckUptime == 0) {
13693 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013694 }
13695 if (stats.isScreenOn()) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070013696 doWakeKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013697 }
13698 final long curRealtime = SystemClock.elapsedRealtime();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013699 final long realtimeSince = curRealtime - mLastPowerCheckRealtime;
13700 final long curUptime = SystemClock.uptimeMillis();
13701 final long uptimeSince = curUptime - mLastPowerCheckUptime;
13702 mLastPowerCheckRealtime = curRealtime;
13703 mLastPowerCheckUptime = curUptime;
13704 if (realtimeSince < WAKE_LOCK_MIN_CHECK_DURATION) {
13705 doWakeKills = false;
13706 }
13707 if (uptimeSince < CPU_MIN_CHECK_DURATION) {
13708 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013709 }
13710 int i = mLruProcesses.size();
13711 while (i > 0) {
13712 i--;
13713 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013714 if (!app.keeping) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013715 long wtime;
13716 synchronized (stats) {
13717 wtime = stats.getProcessWakeTime(app.info.uid,
13718 app.pid, curRealtime);
13719 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013720 long wtimeUsed = wtime - app.lastWakeTime;
13721 long cputimeUsed = app.curCpuTime - app.lastCpuTime;
13722 if (DEBUG_POWER) {
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013723 StringBuilder sb = new StringBuilder(128);
13724 sb.append("Wake for ");
13725 app.toShortString(sb);
13726 sb.append(": over ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013727 TimeUtils.formatDuration(realtimeSince, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013728 sb.append(" used ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013729 TimeUtils.formatDuration(wtimeUsed, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013730 sb.append(" (");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013731 sb.append((wtimeUsed*100)/realtimeSince);
13732 sb.append("%)");
13733 Slog.i(TAG, sb.toString());
13734 sb.setLength(0);
13735 sb.append("CPU for ");
13736 app.toShortString(sb);
13737 sb.append(": over ");
13738 TimeUtils.formatDuration(uptimeSince, sb);
13739 sb.append(" used ");
13740 TimeUtils.formatDuration(cputimeUsed, sb);
13741 sb.append(" (");
13742 sb.append((cputimeUsed*100)/uptimeSince);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013743 sb.append("%)");
13744 Slog.i(TAG, sb.toString());
13745 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013746 // If a process has held a wake lock for more
13747 // than 50% of the time during this period,
13748 // that sounds pad. Kill!
Dianne Hackborn287952c2010-09-22 22:34:31 -070013749 if (doWakeKills && realtimeSince > 0
13750 && ((wtimeUsed*100)/realtimeSince) >= 50) {
13751 synchronized (stats) {
13752 stats.reportExcessiveWakeLocked(app.info.uid, app.processName,
13753 realtimeSince, wtimeUsed);
13754 }
13755 Slog.w(TAG, "Excessive wake lock in " + app.processName
13756 + " (pid " + app.pid + "): held " + wtimeUsed
13757 + " during " + realtimeSince);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013758 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13759 app.processName, app.setAdj, "excessive wake lock");
13760 Process.killProcessQuiet(app.pid);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013761 } else if (doCpuKills && uptimeSince > 0
13762 && ((cputimeUsed*100)/uptimeSince) >= 50) {
13763 synchronized (stats) {
13764 stats.reportExcessiveCpuLocked(app.info.uid, app.processName,
13765 uptimeSince, cputimeUsed);
13766 }
13767 Slog.w(TAG, "Excessive CPU in " + app.processName
13768 + " (pid " + app.pid + "): used " + cputimeUsed
13769 + " during " + uptimeSince);
13770 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13771 app.processName, app.setAdj, "excessive cpu");
13772 Process.killProcessQuiet(app.pid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013773 } else {
13774 app.lastWakeTime = wtime;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013775 app.lastCpuTime = app.curCpuTime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013776 }
13777 }
13778 }
13779 }
13780
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013781 private final boolean updateOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013782 ProcessRecord app, int hiddenAdj, ProcessRecord TOP_APP, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013783 app.hiddenAdj = hiddenAdj;
13784
13785 if (app.thread == null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013786 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013787 }
13788
Dianne Hackborn287952c2010-09-22 22:34:31 -070013789 final boolean wasKeeping = app.keeping;
13790
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013791 boolean success = true;
13792
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013793 computeOomAdjLocked(app, hiddenAdj, TOP_APP, false, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013794
Jeff Brown10e89712011-07-08 18:52:57 -070013795 if (app.curRawAdj != app.setRawAdj) {
Dianne Hackborn905577f2011-09-07 18:31:28 -070013796 if (false) {
13797 // Removing for now. Forcing GCs is not so useful anymore
13798 // with Dalvik, and the new memory level hint facility is
13799 // better for what we need to do these days.
13800 if (app.curRawAdj > ProcessList.FOREGROUND_APP_ADJ
13801 && app.setRawAdj <= ProcessList.FOREGROUND_APP_ADJ) {
13802 // If this app is transitioning from foreground to
13803 // non-foreground, have it do a gc.
13804 scheduleAppGcLocked(app);
13805 } else if (app.curRawAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13806 && app.setRawAdj < ProcessList.HIDDEN_APP_MIN_ADJ) {
13807 // Likewise do a gc when an app is moving in to the
13808 // background (such as a service stopping).
13809 scheduleAppGcLocked(app);
13810 }
Jeff Brown10e89712011-07-08 18:52:57 -070013811 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013812
Jeff Brown10e89712011-07-08 18:52:57 -070013813 if (wasKeeping && !app.keeping) {
13814 // This app is no longer something we want to keep. Note
13815 // its current wake lock time to later know to kill it if
13816 // it is not behaving well.
13817 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
13818 synchronized (stats) {
13819 app.lastWakeTime = stats.getProcessWakeTime(app.info.uid,
13820 app.pid, SystemClock.elapsedRealtime());
13821 }
13822 app.lastCpuTime = app.curCpuTime;
13823 }
13824
13825 app.setRawAdj = app.curRawAdj;
13826 }
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013827
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013828 if (app.curAdj != app.setAdj) {
13829 if (Process.setOomAdj(app.pid, app.curAdj)) {
Dianne Hackbornbbb09ac2011-11-30 11:31:29 -080013830 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013831 TAG, "Set " + app.pid + " " + app.processName +
13832 " adj " + app.curAdj + ": " + app.adjType);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013833 app.setAdj = app.curAdj;
Jeff Brown10e89712011-07-08 18:52:57 -070013834 } else {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013835 success = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013836 Slog.w(TAG, "Failed setting oom adj of " + app + " to " + app.curAdj);
Jeff Brown10e89712011-07-08 18:52:57 -070013837 }
13838 }
13839 if (app.setSchedGroup != app.curSchedGroup) {
13840 app.setSchedGroup = app.curSchedGroup;
13841 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
13842 "Setting process group of " + app.processName
13843 + " to " + app.curSchedGroup);
13844 if (app.waitingToKill != null &&
13845 app.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
13846 Slog.i(TAG, "Killing " + app.toShortString() + ": " + app.waitingToKill);
13847 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13848 app.processName, app.setAdj, app.waitingToKill);
13849 Process.killProcessQuiet(app.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013850 success = false;
Jeff Brown10e89712011-07-08 18:52:57 -070013851 } else {
13852 if (true) {
13853 long oldId = Binder.clearCallingIdentity();
13854 try {
13855 Process.setProcessGroup(app.pid, app.curSchedGroup);
13856 } catch (Exception e) {
13857 Slog.w(TAG, "Failed setting process group of " + app.pid
13858 + " to " + app.curSchedGroup);
13859 e.printStackTrace();
13860 } finally {
13861 Binder.restoreCallingIdentity(oldId);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013862 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013863 } else {
Jeff Brown10e89712011-07-08 18:52:57 -070013864 if (app.thread != null) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070013865 try {
Jeff Brown10e89712011-07-08 18:52:57 -070013866 app.thread.setSchedulingGroup(app.curSchedGroup);
13867 } catch (RemoteException e) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070013868 }
13869 }
13870 }
13871 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013872 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013873 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013874 }
13875
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013876 private final ActivityRecord resumedAppLocked() {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013877 ActivityRecord resumedActivity = mMainStack.mResumedActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013878 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborncbb722e2012-02-07 18:33:49 -080013879 for (int i=mMainStack.mPausingActivities.size()-1; i>=0; i--) {
13880 ActivityRecord r = mMainStack.mPausingActivities.get(i);
13881 if (r.app != null) {
13882 resumedActivity = r;
13883 break;
13884 }
13885 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013886 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013887 resumedActivity = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013888 }
13889 }
13890 return resumedActivity;
13891 }
13892
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013893 private final boolean updateOomAdjLocked(ProcessRecord app) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013894 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013895 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
13896 int curAdj = app.curAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013897 final boolean wasHidden = curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13898 && curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013899
13900 mAdjSeq++;
13901
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013902 boolean success = updateOomAdjLocked(app, app.hiddenAdj, TOP_APP, false);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013903 final boolean nowHidden = app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13904 && app.curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013905 if (nowHidden != wasHidden) {
13906 // Changed to/from hidden state, so apps after it in the LRU
13907 // list may also be changed.
13908 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013909 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013910 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013911 }
13912
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013913 final void updateOomAdjLocked() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013914 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013915 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
13916
13917 if (false) {
13918 RuntimeException e = new RuntimeException();
13919 e.fillInStackTrace();
Joe Onorato8a9b2202010-02-26 18:56:32 -080013920 Slog.i(TAG, "updateOomAdj: top=" + TOP_ACT, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013921 }
13922
13923 mAdjSeq++;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013924 mNewNumServiceProcs = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013925
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080013926 // Let's determine how many processes we have running vs.
13927 // how many slots we have for background processes; we may want
13928 // to put multiple processes in a slot of there are enough of
13929 // them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013930 int numSlots = ProcessList.HIDDEN_APP_MAX_ADJ - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080013931 int factor = (mLruProcesses.size()-4)/numSlots;
13932 if (factor < 1) factor = 1;
13933 int step = 0;
Dianne Hackborn8633e682010-04-22 16:03:41 -070013934 int numHidden = 0;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080013935
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013936 // First update the OOM adjustment for each of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013937 // application processes based on their current state.
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013938 int i = mLruProcesses.size();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013939 int curHiddenAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013940 while (i > 0) {
13941 i--;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013942 ProcessRecord app = mLruProcesses.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080013943 //Slog.i(TAG, "OOM " + app + ": cur hidden=" + curHiddenAdj);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013944 updateOomAdjLocked(app, curHiddenAdj, TOP_APP, true);
13945 if (curHiddenAdj < ProcessList.HIDDEN_APP_MAX_ADJ
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013946 && app.curAdj == curHiddenAdj) {
13947 step++;
13948 if (step >= factor) {
13949 step = 0;
13950 curHiddenAdj++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013951 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013952 }
13953 if (!app.killedBackground) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013954 if (app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013955 numHidden++;
13956 if (numHidden > mProcessLimit) {
13957 Slog.i(TAG, "No longer want " + app.processName
13958 + " (pid " + app.pid + "): hidden #" + numHidden);
13959 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13960 app.processName, app.setAdj, "too many background");
13961 app.killedBackground = true;
13962 Process.killProcessQuiet(app.pid);
Dianne Hackborn8633e682010-04-22 16:03:41 -070013963 }
13964 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013965 if (!app.killedBackground && app.isolated && app.services.size() <= 0) {
13966 // If this is an isolated process, and there are no
13967 // services running in it, then the process is no longer
13968 // needed. We agressively kill these because we can by
13969 // definition not re-use the same process again, and it is
13970 // good to avoid having whatever code was running in them
13971 // left sitting around after no longer needed.
13972 Slog.i(TAG, "Isolated process " + app.processName
13973 + " (pid " + app.pid + ") no longer needed");
13974 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13975 app.processName, app.setAdj, "isolated not needed");
13976 app.killedBackground = true;
13977 Process.killProcessQuiet(app.pid);
13978 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013979 }
13980 }
13981
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013982 mNumServiceProcs = mNewNumServiceProcs;
13983
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013984 // Now determine the memory trimming level of background processes.
13985 // Unfortunately we need to start at the back of the list to do this
13986 // properly. We only do this if the number of background apps we
13987 // are managing to keep around is less than half the maximum we desire;
13988 // if we are keeping a good number around, we'll let them use whatever
13989 // memory they want.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013990 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/2)) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013991 final int N = mLruProcesses.size();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080013992 factor = numHidden/3;
13993 int minFactor = 2;
13994 if (mHomeProcess != null) minFactor++;
13995 if (mPreviousProcess != null) minFactor++;
13996 if (factor < minFactor) factor = minFactor;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013997 step = 0;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013998 int curLevel = ComponentCallbacks2.TRIM_MEMORY_COMPLETE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013999 for (i=0; i<N; i++) {
14000 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080014001 if (app.curAdj >= ProcessList.HOME_APP_ADJ
14002 && app.curAdj != ProcessList.SERVICE_B_ADJ
14003 && !app.killedBackground) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014004 if (app.trimMemoryLevel < curLevel && app.thread != null) {
14005 try {
14006 app.thread.scheduleTrimMemory(curLevel);
14007 } catch (RemoteException e) {
14008 }
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080014009 if (false) {
14010 // For now we won't do this; our memory trimming seems
14011 // to be good enough at this point that destroying
14012 // activities causes more harm than good.
14013 if (curLevel >= ComponentCallbacks2.TRIM_MEMORY_COMPLETE
14014 && app != mHomeProcess && app != mPreviousProcess) {
14015 // For these apps we will also finish their activities
14016 // to help them free memory.
14017 mMainStack.destroyActivitiesLocked(app, false, "trim");
14018 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014019 }
14020 }
14021 app.trimMemoryLevel = curLevel;
14022 step++;
14023 if (step >= factor) {
14024 switch (curLevel) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014025 case ComponentCallbacks2.TRIM_MEMORY_COMPLETE:
14026 curLevel = ComponentCallbacks2.TRIM_MEMORY_MODERATE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014027 break;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014028 case ComponentCallbacks2.TRIM_MEMORY_MODERATE:
14029 curLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014030 break;
14031 }
14032 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070014033 } else if (app.curAdj == ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014034 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014035 && app.thread != null) {
14036 try {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014037 app.thread.scheduleTrimMemory(
14038 ComponentCallbacks2.TRIM_MEMORY_BACKGROUND);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014039 } catch (RemoteException e) {
14040 }
14041 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014042 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackborn7d608422011-08-07 16:24:18 -070014043 } else if ((app.curAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014044 && app.pendingUiClean) {
14045 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
14046 && app.thread != null) {
14047 try {
14048 app.thread.scheduleTrimMemory(
14049 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
14050 } catch (RemoteException e) {
14051 }
14052 }
14053 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
14054 app.pendingUiClean = false;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014055 } else {
14056 app.trimMemoryLevel = 0;
14057 }
14058 }
14059 } else {
14060 final int N = mLruProcesses.size();
14061 for (i=0; i<N; i++) {
14062 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -070014063 if ((app.curAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014064 && app.pendingUiClean) {
14065 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
14066 && app.thread != null) {
14067 try {
14068 app.thread.scheduleTrimMemory(
14069 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
14070 } catch (RemoteException e) {
14071 }
14072 }
14073 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
14074 app.pendingUiClean = false;
14075 } else {
14076 app.trimMemoryLevel = 0;
14077 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014078 }
14079 }
14080
14081 if (mAlwaysFinishActivities) {
Dianne Hackborn28695e02011-11-02 21:59:51 -070014082 mMainStack.destroyActivitiesLocked(null, false, "always-finish");
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014083 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014084 }
14085
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014086 final void trimApplications() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014087 synchronized (this) {
14088 int i;
14089
14090 // First remove any unused application processes whose package
14091 // has been removed.
14092 for (i=mRemovedProcesses.size()-1; i>=0; i--) {
14093 final ProcessRecord app = mRemovedProcesses.get(i);
14094 if (app.activities.size() == 0
14095 && app.curReceiver == null && app.services.size() == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080014096 Slog.i(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014097 TAG, "Exiting empty application process "
14098 + app.processName + " ("
14099 + (app.thread != null ? app.thread.asBinder() : null)
14100 + ")\n");
14101 if (app.pid > 0 && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070014102 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14103 app.processName, app.setAdj, "empty");
14104 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014105 } else {
14106 try {
14107 app.thread.scheduleExit();
14108 } catch (Exception e) {
14109 // Ignore exceptions.
14110 }
14111 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070014112 cleanUpApplicationRecordLocked(app, false, true, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014113 mRemovedProcesses.remove(i);
14114
14115 if (app.persistent) {
14116 if (app.persistent) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080014117 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014118 }
14119 }
14120 }
14121 }
14122
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014123 // Now update the oom adj for all processes.
14124 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014125 }
14126 }
14127
14128 /** This method sends the specified signal to each of the persistent apps */
14129 public void signalPersistentProcesses(int sig) throws RemoteException {
14130 if (sig != Process.SIGNAL_USR1) {
14131 throw new SecurityException("Only SIGNAL_USR1 is allowed");
14132 }
14133
14134 synchronized (this) {
14135 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
14136 != PackageManager.PERMISSION_GRANTED) {
14137 throw new SecurityException("Requires permission "
14138 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
14139 }
14140
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014141 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
14142 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014143 if (r.thread != null && r.persistent) {
14144 Process.sendSignal(r.pid, sig);
14145 }
14146 }
14147 }
14148 }
14149
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014150 private void stopProfilerLocked(ProcessRecord proc, String path, int profileType) {
14151 if (proc == null || proc == mProfileProc) {
14152 proc = mProfileProc;
14153 path = mProfileFile;
14154 profileType = mProfileType;
14155 clearProfilerLocked();
14156 }
14157 if (proc == null) {
14158 return;
14159 }
14160 try {
14161 proc.thread.profilerControl(false, path, null, profileType);
14162 } catch (RemoteException e) {
14163 throw new IllegalStateException("Process disappeared");
14164 }
14165 }
14166
14167 private void clearProfilerLocked() {
14168 if (mProfileFd != null) {
14169 try {
14170 mProfileFd.close();
14171 } catch (IOException e) {
14172 }
14173 }
14174 mProfileApp = null;
14175 mProfileProc = null;
14176 mProfileFile = null;
14177 mProfileType = 0;
14178 mAutoStopProfiler = false;
14179 }
14180
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014181 public boolean profileControl(String process, boolean start,
Romain Guy7eabe552011-07-21 14:56:34 -070014182 String path, ParcelFileDescriptor fd, int profileType) throws RemoteException {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014183
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014184 try {
14185 synchronized (this) {
14186 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14187 // its own permission.
14188 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14189 != PackageManager.PERMISSION_GRANTED) {
14190 throw new SecurityException("Requires permission "
14191 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014192 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014193
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014194 if (start && fd == null) {
14195 throw new IllegalArgumentException("null fd");
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014196 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014197
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014198 ProcessRecord proc = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014199 if (process != null) {
14200 try {
14201 int pid = Integer.parseInt(process);
14202 synchronized (mPidsSelfLocked) {
14203 proc = mPidsSelfLocked.get(pid);
14204 }
14205 } catch (NumberFormatException e) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014206 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014207
14208 if (proc == null) {
14209 HashMap<String, SparseArray<ProcessRecord>> all
14210 = mProcessNames.getMap();
14211 SparseArray<ProcessRecord> procs = all.get(process);
14212 if (procs != null && procs.size() > 0) {
14213 proc = procs.valueAt(0);
14214 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014215 }
14216 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014217
14218 if (start && (proc == null || proc.thread == null)) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014219 throw new IllegalArgumentException("Unknown process: " + process);
14220 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014221
14222 if (start) {
14223 stopProfilerLocked(null, null, 0);
14224 setProfileApp(proc.info, proc.processName, path, fd, false);
14225 mProfileProc = proc;
14226 mProfileType = profileType;
14227 try {
14228 fd = fd.dup();
14229 } catch (IOException e) {
14230 fd = null;
14231 }
14232 proc.thread.profilerControl(start, path, fd, profileType);
14233 fd = null;
14234 mProfileFd = null;
14235 } else {
14236 stopProfilerLocked(proc, path, profileType);
14237 if (fd != null) {
14238 try {
14239 fd.close();
14240 } catch (IOException e) {
14241 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014242 }
14243 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014244
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014245 return true;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014246 }
14247 } catch (RemoteException e) {
14248 throw new IllegalStateException("Process disappeared");
14249 } finally {
14250 if (fd != null) {
14251 try {
14252 fd.close();
14253 } catch (IOException e) {
14254 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014255 }
14256 }
14257 }
Andy McFadden824c5102010-07-09 16:26:57 -070014258
14259 public boolean dumpHeap(String process, boolean managed,
14260 String path, ParcelFileDescriptor fd) throws RemoteException {
14261
14262 try {
14263 synchronized (this) {
14264 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14265 // its own permission (same as profileControl).
14266 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14267 != PackageManager.PERMISSION_GRANTED) {
14268 throw new SecurityException("Requires permission "
14269 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
14270 }
14271
14272 if (fd == null) {
14273 throw new IllegalArgumentException("null fd");
14274 }
14275
14276 ProcessRecord proc = null;
14277 try {
14278 int pid = Integer.parseInt(process);
14279 synchronized (mPidsSelfLocked) {
14280 proc = mPidsSelfLocked.get(pid);
14281 }
14282 } catch (NumberFormatException e) {
14283 }
14284
14285 if (proc == null) {
14286 HashMap<String, SparseArray<ProcessRecord>> all
14287 = mProcessNames.getMap();
14288 SparseArray<ProcessRecord> procs = all.get(process);
14289 if (procs != null && procs.size() > 0) {
14290 proc = procs.valueAt(0);
14291 }
14292 }
14293
14294 if (proc == null || proc.thread == null) {
14295 throw new IllegalArgumentException("Unknown process: " + process);
14296 }
14297
Dianne Hackbornf02e57b2011-03-01 22:21:04 -080014298 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
14299 if (!isDebuggable) {
Andy McFadden824c5102010-07-09 16:26:57 -070014300 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
14301 throw new SecurityException("Process not debuggable: " + proc);
14302 }
14303 }
14304
14305 proc.thread.dumpHeap(managed, path, fd);
14306 fd = null;
14307 return true;
14308 }
14309 } catch (RemoteException e) {
14310 throw new IllegalStateException("Process disappeared");
14311 } finally {
14312 if (fd != null) {
14313 try {
14314 fd.close();
14315 } catch (IOException e) {
14316 }
14317 }
14318 }
14319 }
14320
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014321 /** In this method we try to acquire our lock to make sure that we have not deadlocked */
14322 public void monitor() {
14323 synchronized (this) { }
14324 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014325
Dianne Hackborna573f6a2012-02-09 16:12:18 -080014326 void onCoreSettingsChange(Bundle settings) {
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014327 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
14328 ProcessRecord processRecord = mLruProcesses.get(i);
14329 try {
14330 if (processRecord.thread != null) {
14331 processRecord.thread.setCoreSettings(settings);
14332 }
14333 } catch (RemoteException re) {
14334 /* ignore */
14335 }
14336 }
14337 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014338
14339 // Multi-user methods
14340
Amith Yamasani742a6712011-05-04 14:49:28 -070014341 private int mCurrentUserId;
14342 private SparseIntArray mLoggedInUsers = new SparseIntArray(5);
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014343 private ArrayList<UserListener> mUserListeners = new ArrayList<UserListener>(3);
14344
14345 public interface UserListener {
14346 public void onUserChanged(int userId);
14347
14348 public void onUserAdded(int userId);
14349
14350 public void onUserRemoved(int userId);
14351
14352 public void onUserLoggedOut(int userId);
14353 }
14354
14355 public void addUserListener(UserListener listener) {
14356 synchronized (this) {
14357 if (!mUserListeners.contains(listener)) {
14358 mUserListeners.add(listener);
14359 }
14360 }
14361 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014362
14363 public boolean switchUser(int userId) {
14364 final int callingUid = Binder.getCallingUid();
14365 if (callingUid != 0 && callingUid != Process.myUid()) {
14366 Slog.e(TAG, "Trying to switch user from unauthorized app");
14367 return false;
14368 }
14369 if (mCurrentUserId == userId)
14370 return true;
14371
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014372 ArrayList<UserListener> listeners;
14373
Amith Yamasani742a6712011-05-04 14:49:28 -070014374 synchronized (this) {
14375 // Check if user is already logged in, otherwise check if user exists first before
14376 // adding to the list of logged in users.
14377 if (mLoggedInUsers.indexOfKey(userId) < 0) {
14378 if (!userExists(userId)) {
14379 return false;
14380 }
14381 mLoggedInUsers.append(userId, userId);
14382 }
14383
14384 mCurrentUserId = userId;
14385 boolean haveActivities = mMainStack.switchUser(userId);
14386 if (!haveActivities) {
14387 startHomeActivityLocked(userId);
14388 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014389
14390 listeners = (ArrayList<UserListener>) mUserListeners.clone();
14391 }
14392 // Inform the listeners
14393 for (UserListener listener : listeners) {
14394 listener.onUserChanged(userId);
Amith Yamasani742a6712011-05-04 14:49:28 -070014395 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014396 return true;
14397 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014398
14399 private boolean userExists(int userId) {
14400 try {
14401 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
14402 for (UserInfo user : users) {
14403 if (user.id == userId) {
14404 return true;
14405 }
14406 }
14407 } catch (RemoteException re) {
14408 // Won't happen, in same process
14409 }
14410
14411 return false;
14412 }
14413
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014414 private void checkValidCaller(int uid, int userId) {
14415 if (UserId.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) return;
14416
14417 throw new SecurityException("Caller uid=" + uid
14418 + " is not privileged to communicate with user=" + userId);
14419 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014420
14421 private int applyUserId(int uid, int userId) {
14422 return UserId.getUid(userId, uid);
14423 }
14424
14425 private ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080014426 if (info == null) return null;
Amith Yamasani742a6712011-05-04 14:49:28 -070014427 ApplicationInfo newInfo = new ApplicationInfo(info);
14428 newInfo.uid = applyUserId(info.uid, userId);
14429 if (newInfo.uid >= Process.FIRST_APPLICATION_UID) {
14430 newInfo.dataDir = USER_DATA_DIR + userId + "/"
14431 + info.packageName;
14432 }
14433 return newInfo;
14434 }
14435
14436 ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080014437 if (aInfo == null || aInfo.applicationInfo.uid < Process.FIRST_APPLICATION_UID
Amith Yamasani742a6712011-05-04 14:49:28 -070014438 || userId < 1) {
14439 return aInfo;
14440 }
14441
14442 ActivityInfo info = new ActivityInfo(aInfo);
14443 info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId);
14444 return info;
14445 }
14446
14447 static class ServiceMap {
14448
14449 private final SparseArray<HashMap<ComponentName, ServiceRecord>> mServicesByNamePerUser
14450 = new SparseArray<HashMap<ComponentName, ServiceRecord>>();
14451 private final SparseArray<HashMap<Intent.FilterComparison, ServiceRecord>>
14452 mServicesByIntentPerUser = new SparseArray<
14453 HashMap<Intent.FilterComparison, ServiceRecord>>();
14454
14455 ServiceRecord getServiceByName(ComponentName name, int callingUser) {
14456 // TODO: Deal with global services
14457 if (DEBUG_MU)
14458 Slog.v(TAG_MU, "getServiceByName(" + name + "), callingUser = " + callingUser);
14459 return getServices(callingUser).get(name);
14460 }
14461
14462 ServiceRecord getServiceByName(ComponentName name) {
14463 return getServiceByName(name, -1);
14464 }
14465
14466 ServiceRecord getServiceByIntent(Intent.FilterComparison filter, int callingUser) {
14467 // TODO: Deal with global services
14468 if (DEBUG_MU)
14469 Slog.v(TAG_MU, "getServiceByIntent(" + filter + "), callingUser = " + callingUser);
14470 return getServicesByIntent(callingUser).get(filter);
14471 }
14472
14473 ServiceRecord getServiceByIntent(Intent.FilterComparison filter) {
14474 return getServiceByIntent(filter, -1);
14475 }
14476
14477 void putServiceByName(ComponentName name, int callingUser, ServiceRecord value) {
14478 // TODO: Deal with global services
14479 getServices(callingUser).put(name, value);
14480 }
14481
14482 void putServiceByIntent(Intent.FilterComparison filter, int callingUser,
14483 ServiceRecord value) {
14484 // TODO: Deal with global services
14485 getServicesByIntent(callingUser).put(filter, value);
14486 }
14487
14488 void removeServiceByName(ComponentName name, int callingUser) {
14489 // TODO: Deal with global services
14490 ServiceRecord removed = getServices(callingUser).remove(name);
14491 if (DEBUG_MU)
14492 Slog.v(TAG, "removeServiceByName user=" + callingUser + " name=" + name
14493 + " removed=" + removed);
14494 }
14495
14496 void removeServiceByIntent(Intent.FilterComparison filter, int callingUser) {
14497 // TODO: Deal with global services
14498 ServiceRecord removed = getServicesByIntent(callingUser).remove(filter);
14499 if (DEBUG_MU)
14500 Slog.v(TAG_MU, "removeServiceByIntent user=" + callingUser + " intent=" + filter
14501 + " removed=" + removed);
14502 }
14503
14504 Collection<ServiceRecord> getAllServices(int callingUser) {
14505 // TODO: Deal with global services
14506 return getServices(callingUser).values();
14507 }
14508
14509 private HashMap<ComponentName, ServiceRecord> getServices(int callingUser) {
14510 HashMap map = mServicesByNamePerUser.get(callingUser);
14511 if (map == null) {
14512 map = new HashMap<ComponentName, ServiceRecord>();
14513 mServicesByNamePerUser.put(callingUser, map);
14514 }
14515 return map;
14516 }
14517
14518 private HashMap<Intent.FilterComparison, ServiceRecord> getServicesByIntent(
14519 int callingUser) {
14520 HashMap map = mServicesByIntentPerUser.get(callingUser);
14521 if (map == null) {
14522 map = new HashMap<Intent.FilterComparison, ServiceRecord>();
14523 mServicesByIntentPerUser.put(callingUser, map);
14524 }
14525 return map;
14526 }
14527 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014528}