blob: 6464d7fdcf1e19054e5b262ea5345d5559bae215 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006-2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.am;
18
Jeff Sharkey110a6b62012-03-12 11:12:41 -070019import static android.content.pm.PackageManager.PERMISSION_GRANTED;
20
Dianne Hackborn860755f2010-06-03 18:47:52 -070021import com.android.internal.R;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080022import com.android.internal.os.BatteryStatsImpl;
Dianne Hackborn45ce8642011-07-14 16:10:16 -070023import com.android.internal.os.ProcessStats;
Dianne Hackbornde7faf62009-06-30 13:27:30 -070024import com.android.server.AttributeCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025import com.android.server.IntentResolver;
26import com.android.server.ProcessMap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080027import com.android.server.SystemServer;
28import com.android.server.Watchdog;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070029import com.android.server.am.ActivityStack.ActivityState;
Dianne Hackborna924dc0d2011-02-17 14:22:17 -080030import com.android.server.wm.WindowManagerService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031
Dianne Hackborndd71fc82009-12-16 19:24:32 -080032import dalvik.system.Zygote;
33
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080034import android.app.Activity;
35import android.app.ActivityManager;
36import android.app.ActivityManagerNative;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -070037import android.app.ActivityOptions;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038import android.app.ActivityThread;
39import android.app.AlertDialog;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070040import android.app.AppGlobals;
Jacek Surazskif5b9c722009-05-18 12:09:59 +020041import android.app.ApplicationErrorReport;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import android.app.Dialog;
Dianne Hackbornb06ea702009-07-13 13:07:51 -070043import android.app.IActivityController;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044import android.app.IApplicationThread;
45import android.app.IInstrumentationWatcher;
Dianne Hackborn860755f2010-06-03 18:47:52 -070046import android.app.INotificationManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -070047import android.app.IProcessObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048import android.app.IServiceConnection;
49import android.app.IThumbnailReceiver;
50import android.app.Instrumentation;
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070051import android.app.Notification;
Dianne Hackborn860755f2010-06-03 18:47:52 -070052import android.app.NotificationManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080053import android.app.PendingIntent;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070054import android.app.Service;
Christopher Tate45281862010-03-05 15:46:30 -080055import android.app.backup.IBackupManager;
Jacek Surazskif5b9c722009-05-18 12:09:59 +020056import android.content.ActivityNotFoundException;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -080057import android.content.BroadcastReceiver;
Dianne Hackborn21c241e2012-03-08 13:57:23 -080058import android.content.ClipData;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070059import android.content.ComponentCallbacks2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060import android.content.ComponentName;
Jeff Sharkey110a6b62012-03-12 11:12:41 -070061import android.content.ContentProvider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062import android.content.ContentResolver;
63import android.content.Context;
Christian Mehlmauer7664e202010-07-20 08:46:17 +020064import android.content.DialogInterface;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070065import android.content.IIntentReceiver;
66import android.content.IIntentSender;
Adam Powelldd8fab22012-03-22 17:47:27 -070067import android.content.Intent;
68import android.content.IntentFilter;
Dianne Hackbornfa82f222009-09-17 15:14:12 -070069import android.content.IntentSender;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070import android.content.pm.ActivityInfo;
71import android.content.pm.ApplicationInfo;
72import android.content.pm.ConfigurationInfo;
73import android.content.pm.IPackageDataObserver;
74import android.content.pm.IPackageManager;
75import android.content.pm.InstrumentationInfo;
Dan Egnor66c40e72010-01-26 16:23:11 -080076import android.content.pm.PackageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077import android.content.pm.PackageManager;
Adam Powelldd8fab22012-03-22 17:47:27 -070078import android.content.pm.PackageManager.NameNotFoundException;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070079import android.content.pm.PathPermission;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080080import android.content.pm.ProviderInfo;
81import android.content.pm.ResolveInfo;
82import android.content.pm.ServiceInfo;
Amith Yamasani742a6712011-05-04 14:49:28 -070083import android.content.pm.UserInfo;
Dianne Hackborne2515ee2011-04-27 18:52:56 -040084import android.content.res.CompatibilityInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085import android.content.res.Configuration;
86import android.graphics.Bitmap;
Robert Greenwalt434203a2010-10-11 16:00:27 -070087import android.net.Proxy;
88import android.net.ProxyProperties;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080089import android.net.Uri;
90import android.os.Binder;
Dan Egnor60d87622009-12-16 16:32:58 -080091import android.os.Build;
Dan Egnor42471dd2010-01-07 17:25:22 -080092import android.os.Bundle;
Dianne Hackborn3025ef32009-08-31 21:31:47 -070093import android.os.Debug;
Dan Egnor60d87622009-12-16 16:32:58 -080094import android.os.DropBoxManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080095import android.os.Environment;
Dan Egnor42471dd2010-01-07 17:25:22 -080096import android.os.FileObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080097import android.os.FileUtils;
98import android.os.Handler;
99import android.os.IBinder;
100import android.os.IPermissionController;
101import android.os.Looper;
102import android.os.Message;
103import android.os.Parcel;
104import android.os.ParcelFileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800105import android.os.Process;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700106import android.os.RemoteCallbackList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107import android.os.RemoteException;
108import android.os.ServiceManager;
Brad Fitzpatrick46d42382010-06-11 13:57:58 -0700109import android.os.StrictMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110import android.os.SystemClock;
111import android.os.SystemProperties;
Amith Yamasani742a6712011-05-04 14:49:28 -0700112import android.os.UserId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113import android.provider.Settings;
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700114import android.text.format.Time;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800115import android.util.EventLog;
Joe Onorato5d3bea62010-03-01 13:44:29 -0800116import android.util.Log;
Adam Powelldd8fab22012-03-22 17:47:27 -0700117import android.util.Pair;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118import android.util.PrintWriterPrinter;
Adam Powelldd8fab22012-03-22 17:47:27 -0700119import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800120import android.util.SparseArray;
Amith Yamasani742a6712011-05-04 14:49:28 -0700121import android.util.SparseIntArray;
Dianne Hackborn1ebccf52010-08-15 13:04:34 -0700122import android.util.TimeUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800123import android.view.Gravity;
124import android.view.LayoutInflater;
125import android.view.View;
126import android.view.WindowManager;
127import android.view.WindowManagerPolicy;
128
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700129import java.io.BufferedInputStream;
130import java.io.BufferedOutputStream;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700131import java.io.BufferedReader;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700132import java.io.DataInputStream;
133import java.io.DataOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800134import java.io.File;
135import java.io.FileDescriptor;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700136import java.io.FileInputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800137import java.io.FileNotFoundException;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700138import java.io.FileOutputStream;
Jacek Surazskif5b9c722009-05-18 12:09:59 +0200139import java.io.IOException;
Dan Egnora455d192010-03-12 08:52:28 -0800140import java.io.InputStreamReader;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800141import java.io.PrintWriter;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700142import java.io.StringWriter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800143import java.lang.ref.WeakReference;
144import java.util.ArrayList;
Amith Yamasani742a6712011-05-04 14:49:28 -0700145import java.util.Collection;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700146import java.util.Collections;
147import java.util.Comparator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800148import java.util.HashMap;
149import java.util.HashSet;
150import java.util.Iterator;
151import java.util.List;
152import java.util.Locale;
153import java.util.Map;
Amith Yamasani13593602012-03-22 16:16:17 -0700154import java.util.Map.Entry;
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -0700155import java.util.Set;
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700156import java.util.concurrent.atomic.AtomicBoolean;
157import java.util.concurrent.atomic.AtomicLong;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800158
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700159public final class ActivityManagerService extends ActivityManagerNative
160 implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
Amith Yamasani742a6712011-05-04 14:49:28 -0700161 private static final String USER_DATA_DIR = "/data/user/";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800162 static final String TAG = "ActivityManager";
Amith Yamasani742a6712011-05-04 14:49:28 -0700163 static final String TAG_MU = "ActivityManagerServiceMU";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800164 static final boolean DEBUG = false;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400165 static final boolean localLOGV = DEBUG;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800166 static final boolean DEBUG_SWITCH = localLOGV || false;
167 static final boolean DEBUG_TASKS = localLOGV || false;
168 static final boolean DEBUG_PAUSE = localLOGV || false;
169 static final boolean DEBUG_OOM_ADJ = localLOGV || false;
170 static final boolean DEBUG_TRANSITION = localLOGV || false;
171 static final boolean DEBUG_BROADCAST = localLOGV || false;
Christopher Tatef46723b2012-01-26 14:19:24 -0800172 static final boolean DEBUG_BACKGROUND_BROADCAST = DEBUG_BROADCAST || false;
Dianne Hackborn82f3f002009-06-16 18:49:05 -0700173 static final boolean DEBUG_BROADCAST_LIGHT = DEBUG_BROADCAST || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800174 static final boolean DEBUG_SERVICE = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700175 static final boolean DEBUG_SERVICE_EXECUTING = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800176 static final boolean DEBUG_VISBILITY = localLOGV || false;
177 static final boolean DEBUG_PROCESSES = localLOGV || false;
Dianne Hackborna1e989b2009-09-01 19:54:29 -0700178 static final boolean DEBUG_PROVIDER = localLOGV || false;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800179 static final boolean DEBUG_URI_PERMISSION = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800180 static final boolean DEBUG_USER_LEAVING = localLOGV || false;
The Android Open Source Project10592532009-03-18 17:39:46 -0700181 static final boolean DEBUG_RESULTS = localLOGV || false;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -0700182 static final boolean DEBUG_BACKUP = localLOGV || false;
Dianne Hackborndc6b6352009-09-30 14:20:09 -0700183 static final boolean DEBUG_CONFIGURATION = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700184 static final boolean DEBUG_POWER = localLOGV || false;
185 static final boolean DEBUG_POWER_QUICK = DEBUG_POWER || false;
Amith Yamasani742a6712011-05-04 14:49:28 -0700186 static final boolean DEBUG_MU = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800187 static final boolean VALIDATE_TOKENS = false;
188 static final boolean SHOW_ACTIVITY_START_TIME = true;
189
190 // Control over CPU and battery monitoring.
191 static final long BATTERY_STATS_TIME = 30*60*1000; // write battery stats every 30 minutes.
192 static final boolean MONITOR_CPU_USAGE = true;
193 static final long MONITOR_CPU_MIN_TIME = 5*1000; // don't sample cpu less than every 5 seconds.
194 static final long MONITOR_CPU_MAX_TIME = 0x0fffffff; // wait possibly forever for next cpu sample.
195 static final boolean MONITOR_THREAD_CPU_USAGE = false;
196
Dianne Hackborn1655be42009-05-08 14:29:01 -0700197 // The flags that are set for all calls we make to the package manager.
Dianne Hackborn11b822d2009-07-21 20:03:02 -0700198 static final int STOCK_PM_FLAGS = PackageManager.GET_SHARED_LIBRARY_FILES;
Dianne Hackborn1655be42009-05-08 14:29:01 -0700199
Dianne Hackbornf02e57b2011-03-01 22:21:04 -0800200 private static final String SYSTEM_DEBUGGABLE = "ro.debuggable";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800201
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700202 static final boolean IS_USER_BUILD = "user".equals(Build.TYPE);
203
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800204 // Maximum number of recent tasks that we can remember.
205 static final int MAX_RECENT_TASKS = 20;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700206
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700207 // Amount of time after a call to stopAppSwitches() during which we will
208 // prevent further untrusted switches from happening.
209 static final long APP_SWITCH_DELAY_TIME = 5*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800210
211 // How long we wait for a launched process to attach to the activity manager
212 // before we decide it's never going to come up for real.
213 static final int PROC_START_TIMEOUT = 10*1000;
214
Jeff Brown3f9dd282011-07-08 20:02:19 -0700215 // How long we wait for a launched process to attach to the activity manager
216 // before we decide it's never going to come up for real, when the process was
217 // started with a wrapper for instrumentation (such as Valgrind) because it
218 // could take much longer than usual.
219 static final int PROC_START_TIMEOUT_WITH_WRAPPER = 300*1000;
220
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800221 // How long to wait after going idle before forcing apps to GC.
222 static final int GC_TIMEOUT = 5*1000;
223
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700224 // The minimum amount of time between successive GC requests for a process.
225 static final int GC_MIN_INTERVAL = 60*1000;
226
Dianne Hackborn287952c2010-09-22 22:34:31 -0700227 // The rate at which we check for apps using excessive power -- 15 mins.
228 static final int POWER_CHECK_DELAY = (DEBUG_POWER_QUICK ? 2 : 15) * 60*1000;
229
230 // The minimum sample duration we will allow before deciding we have
231 // enough data on wake locks to start killing things.
232 static final int WAKE_LOCK_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
233
234 // The minimum sample duration we will allow before deciding we have
235 // enough data on CPU usage to start killing things.
236 static final int CPU_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700237
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800238 // How long we allow a receiver to run before giving up on it.
Christopher Tatef46723b2012-01-26 14:19:24 -0800239 static final int BROADCAST_FG_TIMEOUT = 10*1000;
240 static final int BROADCAST_BG_TIMEOUT = 60*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800241
242 // How long we wait for a service to finish executing.
243 static final int SERVICE_TIMEOUT = 20*1000;
244
245 // How long a service needs to be running until restarting its process
246 // is no longer considered to be a relaunch of the service.
247 static final int SERVICE_RESTART_DURATION = 5*1000;
248
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700249 // How long a service needs to be running until it will start back at
250 // SERVICE_RESTART_DURATION after being killed.
251 static final int SERVICE_RESET_RUN_DURATION = 60*1000;
252
253 // Multiplying factor to increase restart duration time by, for each time
254 // a service is killed before it has run for SERVICE_RESET_RUN_DURATION.
255 static final int SERVICE_RESTART_DURATION_FACTOR = 4;
256
257 // The minimum amount of time between restarting services that we allow.
258 // That is, when multiple services are restarting, we won't allow each
259 // to restart less than this amount of time from the last one.
260 static final int SERVICE_MIN_RESTART_TIME_BETWEEN = 10*1000;
261
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800262 // Maximum amount of time for there to be no activity on a service before
263 // we consider it non-essential and allow its process to go on the
264 // LRU background list.
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700265 static final int MAX_SERVICE_INACTIVITY = 30*60*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800266
267 // How long we wait until we timeout on key dispatching.
268 static final int KEY_DISPATCHING_TIMEOUT = 5*1000;
269
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800270 // How long we wait until we timeout on key dispatching during instrumentation.
271 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT = 60*1000;
272
Dan Egnor42471dd2010-01-07 17:25:22 -0800273 static final int MY_PID = Process.myPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800274
275 static final String[] EMPTY_STRING_ARRAY = new String[0];
276
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700277 public ActivityStack mMainStack;
Mike Lockwood3a74bd32011-08-12 13:55:22 -0700278
279 private final boolean mHeadless;
280
Joe Onorato54a4a412011-11-02 20:50:08 -0700281 // Whether we should show our dialogs (ANR, crash, etc) or just perform their
282 // default actuion automatically. Important for devices without direct input
283 // devices.
284 private boolean mShowDialogs = true;
285
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800286 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700287 * Description of a request to start a new activity, which has been held
288 * due to app switches being disabled.
289 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700290 static class PendingActivityLaunch {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700291 ActivityRecord r;
292 ActivityRecord sourceRecord;
Dianne Hackborna4972e92012-03-14 10:38:05 -0700293 int startFlags;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700294 }
295
296 final ArrayList<PendingActivityLaunch> mPendingActivityLaunches
297 = new ArrayList<PendingActivityLaunch>();
298
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800299
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800300 BroadcastQueue mFgBroadcastQueue;
301 BroadcastQueue mBgBroadcastQueue;
Christopher Tatef46723b2012-01-26 14:19:24 -0800302 // Convenient for easy iteration over the queues. Foreground is first
303 // so that dispatch of foreground broadcasts gets precedence.
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800304 final BroadcastQueue[] mBroadcastQueues = new BroadcastQueue[2];
Christopher Tatef46723b2012-01-26 14:19:24 -0800305
306 BroadcastQueue broadcastQueueForIntent(Intent intent) {
307 final boolean isFg = (intent.getFlags() & Intent.FLAG_RECEIVER_FOREGROUND) != 0;
308 if (DEBUG_BACKGROUND_BROADCAST) {
309 Slog.i(TAG, "Broadcast intent " + intent + " on "
310 + (isFg ? "foreground" : "background")
311 + " queue");
312 }
313 return (isFg) ? mFgBroadcastQueue : mBgBroadcastQueue;
314 }
315
316 BroadcastRecord broadcastRecordForReceiverLocked(IBinder receiver) {
317 for (BroadcastQueue queue : mBroadcastQueues) {
318 BroadcastRecord r = queue.getMatchingOrderedReceiver(receiver);
319 if (r != null) {
320 return r;
321 }
322 }
323 return null;
324 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800325
326 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800327 * Activity we have told the window manager to have key focus.
328 */
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700329 ActivityRecord mFocusedActivity = null;
Dianne Hackbornbfe319e2009-09-21 00:34:05 -0700330 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800331 * List of intents that were used to start the most recent tasks.
332 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700333 final ArrayList<TaskRecord> mRecentTasks = new ArrayList<TaskRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800334
335 /**
Dianne Hackborn7d608422011-08-07 16:24:18 -0700336 * Process management.
337 */
338 final ProcessList mProcessList = new ProcessList();
339
340 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800341 * All of the applications we currently have running organized by name.
342 * The keys are strings of the application package name (as
343 * returned by the package manager), and the keys are ApplicationRecord
344 * objects.
345 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700346 final ProcessMap<ProcessRecord> mProcessNames = new ProcessMap<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800347
348 /**
Dianne Hackborna0c283e2012-02-09 10:47:01 -0800349 * The currently running isolated processes.
350 */
351 final SparseArray<ProcessRecord> mIsolatedProcesses = new SparseArray<ProcessRecord>();
352
353 /**
354 * Counter for assigning isolated process uids, to avoid frequently reusing the
355 * same ones.
356 */
357 int mNextIsolatedProcessUid = 0;
358
359 /**
Dianne Hackborn860755f2010-06-03 18:47:52 -0700360 * The currently running heavy-weight process, if any.
361 */
362 ProcessRecord mHeavyWeightProcess = null;
363
364 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800365 * The last time that various processes have crashed.
366 */
367 final ProcessMap<Long> mProcessCrashTimes = new ProcessMap<Long>();
368
369 /**
370 * Set of applications that we consider to be bad, and will reject
371 * incoming broadcasts from (which the user has no control over).
372 * Processes are added to this set when they have crashed twice within
373 * a minimum amount of time; they are removed from it when they are
374 * later restarted (hopefully due to some user action). The value is the
375 * time it was added to the list.
376 */
377 final ProcessMap<Long> mBadProcesses = new ProcessMap<Long>();
378
379 /**
380 * All of the processes we currently have running organized by pid.
381 * The keys are the pid running the application.
382 *
383 * <p>NOTE: This object is protected by its own lock, NOT the global
384 * activity manager lock!
385 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700386 final SparseArray<ProcessRecord> mPidsSelfLocked = new SparseArray<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800387
388 /**
389 * All of the processes that have been forced to be foreground. The key
390 * is the pid of the caller who requested it (we hold a death
391 * link on it).
392 */
393 abstract class ForegroundToken implements IBinder.DeathRecipient {
394 int pid;
395 IBinder token;
396 }
397 final SparseArray<ForegroundToken> mForegroundProcesses
398 = new SparseArray<ForegroundToken>();
399
400 /**
401 * List of records for processes that someone had tried to start before the
402 * system was ready. We don't start them at that point, but ensure they
403 * are started by the time booting is complete.
404 */
405 final ArrayList<ProcessRecord> mProcessesOnHold
406 = new ArrayList<ProcessRecord>();
407
408 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800409 * List of persistent applications that are in the process
410 * of being started.
411 */
412 final ArrayList<ProcessRecord> mPersistentStartingProcesses
413 = new ArrayList<ProcessRecord>();
414
415 /**
416 * Processes that are being forcibly torn down.
417 */
418 final ArrayList<ProcessRecord> mRemovedProcesses
419 = new ArrayList<ProcessRecord>();
420
421 /**
422 * List of running applications, sorted by recent usage.
423 * The first entry in the list is the least recently used.
424 * It contains ApplicationRecord objects. This list does NOT include
425 * any persistent application records (since we never want to exit them).
426 */
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800427 final ArrayList<ProcessRecord> mLruProcesses
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800428 = new ArrayList<ProcessRecord>();
429
430 /**
431 * List of processes that should gc as soon as things are idle.
432 */
433 final ArrayList<ProcessRecord> mProcessesToGc
434 = new ArrayList<ProcessRecord>();
435
436 /**
The Android Open Source Project4df24232009-03-05 14:34:35 -0800437 * This is the process holding what we currently consider to be
438 * the "home" activity.
439 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700440 ProcessRecord mHomeProcess;
The Android Open Source Project4df24232009-03-05 14:34:35 -0800441
442 /**
Dianne Hackbornf35fe232011-11-01 19:25:20 -0700443 * This is the process holding the activity the user last visited that
444 * is in a different process from the one they are currently in.
445 */
446 ProcessRecord mPreviousProcess;
Dianne Hackborn50685602011-12-01 12:23:37 -0800447
448 /**
449 * The time at which the previous process was last visible.
450 */
451 long mPreviousProcessVisibleTime;
452
Dianne Hackbornf35fe232011-11-01 19:25:20 -0700453 /**
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400454 * Packages that the user has asked to have run in screen size
455 * compatibility mode instead of filling the screen.
456 */
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -0700457 final CompatModePackages mCompatModePackages;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400458
459 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800460 * Set of PendingResultRecord objects that are currently active.
461 */
462 final HashSet mPendingResultRecords = new HashSet();
463
464 /**
465 * Set of IntentSenderRecord objects that are currently active.
466 */
467 final HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>> mIntentSenderRecords
468 = new HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>>();
469
470 /**
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -0800471 * Fingerprints (hashCode()) of stack traces that we've
Brad Fitzpatrick143666f2010-06-14 12:40:21 -0700472 * already logged DropBox entries for. Guarded by itself. If
473 * something (rogue user app) forces this over
474 * MAX_DUP_SUPPRESSED_STACKS entries, the contents are cleared.
475 */
476 private final HashSet<Integer> mAlreadyLoggedViolatedStacks = new HashSet<Integer>();
477 private static final int MAX_DUP_SUPPRESSED_STACKS = 5000;
478
479 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -0700480 * Strict Mode background batched logging state.
481 *
482 * The string buffer is guarded by itself, and its lock is also
483 * used to determine if another batched write is already
484 * in-flight.
485 */
486 private final StringBuilder mStrictModeBuffer = new StringBuilder();
487
488 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800489 * Keeps track of all IIntentReceivers that have been registered for
490 * broadcasts. Hash keys are the receiver IBinder, hash value is
491 * a ReceiverList.
492 */
493 final HashMap mRegisteredReceivers = new HashMap();
494
495 /**
496 * Resolver for broadcast intents to registered receivers.
497 * Holds BroadcastFilter (subclass of IntentFilter).
498 */
499 final IntentResolver<BroadcastFilter, BroadcastFilter> mReceiverResolver
500 = new IntentResolver<BroadcastFilter, BroadcastFilter>() {
501 @Override
502 protected boolean allowFilterResult(
503 BroadcastFilter filter, List<BroadcastFilter> dest) {
504 IBinder target = filter.receiverList.receiver.asBinder();
505 for (int i=dest.size()-1; i>=0; i--) {
506 if (dest.get(i).receiverList.receiver.asBinder() == target) {
507 return false;
508 }
509 }
510 return true;
511 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700512
513 @Override
514 protected String packageForFilter(BroadcastFilter filter) {
515 return filter.packageName;
516 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800517 };
518
519 /**
520 * State of all active sticky broadcasts. Keys are the action of the
521 * sticky Intent, values are an ArrayList of all broadcasted intents with
522 * that action (which should usually be one).
523 */
524 final HashMap<String, ArrayList<Intent>> mStickyBroadcasts =
525 new HashMap<String, ArrayList<Intent>>();
526
Amith Yamasani742a6712011-05-04 14:49:28 -0700527 final ServiceMap mServiceMap = new ServiceMap();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800528
529 /**
530 * All currently bound service connections. Keys are the IBinder of
531 * the client's IServiceConnection.
532 */
Dianne Hackborn43d9ac82010-08-25 15:06:25 -0700533 final HashMap<IBinder, ArrayList<ConnectionRecord>> mServiceConnections
534 = new HashMap<IBinder, ArrayList<ConnectionRecord>>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800535
536 /**
537 * List of services that we have been asked to start,
538 * but haven't yet been able to. It is used to hold start requests
539 * while waiting for their corresponding application thread to get
540 * going.
541 */
542 final ArrayList<ServiceRecord> mPendingServices
543 = new ArrayList<ServiceRecord>();
544
545 /**
546 * List of services that are scheduled to restart following a crash.
547 */
548 final ArrayList<ServiceRecord> mRestartingServices
549 = new ArrayList<ServiceRecord>();
550
551 /**
552 * List of services that are in the process of being stopped.
553 */
554 final ArrayList<ServiceRecord> mStoppingServices
555 = new ArrayList<ServiceRecord>();
556
557 /**
Christopher Tate181fafa2009-05-14 11:12:14 -0700558 * Backup/restore process management
559 */
560 String mBackupAppName = null;
561 BackupRecord mBackupTarget = null;
562
563 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800564 * List of PendingThumbnailsRecord objects of clients who are still
565 * waiting to receive all of the thumbnails for a task.
566 */
567 final ArrayList mPendingThumbnails = new ArrayList();
568
569 /**
570 * List of HistoryRecord objects that have been finished and must
571 * still report back to a pending thumbnail receiver.
572 */
573 final ArrayList mCancelledThumbnails = new ArrayList();
574
Amith Yamasani742a6712011-05-04 14:49:28 -0700575 final ProviderMap mProviderMap = new ProviderMap();
576
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800577 /**
578 * List of content providers who have clients waiting for them. The
579 * application is currently being launched and the provider will be
580 * removed from this list once it is published.
581 */
Dianne Hackborn860755f2010-06-03 18:47:52 -0700582 final ArrayList<ContentProviderRecord> mLaunchingProviders
583 = new ArrayList<ContentProviderRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800584
585 /**
586 * Global set of specific Uri permissions that have been granted.
587 */
588 final private SparseArray<HashMap<Uri, UriPermission>> mGrantedUriPermissions
589 = new SparseArray<HashMap<Uri, UriPermission>>();
590
Svetoslav Ganov54d068e2011-03-02 12:58:40 -0800591 CoreSettingsObserver mCoreSettingsObserver;
592
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800593 /**
594 * Thread-local storage used to carry caller permissions over through
595 * indirect content-provider access.
596 * @see #ActivityManagerService.openContentUri()
597 */
598 private class Identity {
599 public int pid;
600 public int uid;
601
602 Identity(int _pid, int _uid) {
603 pid = _pid;
604 uid = _uid;
605 }
606 }
Amith Yamasani742a6712011-05-04 14:49:28 -0700607
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800608 private static ThreadLocal<Identity> sCallerIdentity = new ThreadLocal<Identity>();
609
610 /**
611 * All information we have collected about the runtime performance of
612 * any user id that can impact battery performance.
613 */
614 final BatteryStatsService mBatteryStatsService;
615
616 /**
617 * information about component usage
618 */
619 final UsageStatsService mUsageStatsService;
620
621 /**
622 * Current configuration information. HistoryRecord objects are given
623 * a reference to this object to indicate which configuration they are
624 * currently running in, so this object must be kept immutable.
625 */
626 Configuration mConfiguration = new Configuration();
627
628 /**
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800629 * Current sequencing integer of the configuration, for skipping old
630 * configurations.
631 */
632 int mConfigurationSeq = 0;
633
634 /**
Jack Palevichb90d28c2009-07-22 15:35:24 -0700635 * Hardware-reported OpenGLES version.
636 */
637 final int GL_ES_VERSION;
638
639 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800640 * List of initialization arguments to pass to all processes when binding applications to them.
641 * For example, references to the commonly used services.
642 */
643 HashMap<String, IBinder> mAppBindArgs;
644
645 /**
Dianne Hackbornf210d6b2009-04-13 18:42:49 -0700646 * Temporary to avoid allocations. Protected by main lock.
647 */
648 final StringBuilder mStringBuilder = new StringBuilder(256);
649
650 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800651 * Used to control how we initialize the service.
652 */
653 boolean mStartRunning = false;
654 ComponentName mTopComponent;
655 String mTopAction;
656 String mTopData;
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700657 boolean mProcessesReady = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800658 boolean mSystemReady = false;
659 boolean mBooting = false;
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700660 boolean mWaitingUpdate = false;
661 boolean mDidUpdate = false;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700662 boolean mOnBattery = false;
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700663 boolean mLaunchWarningShown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800664
665 Context mContext;
666
667 int mFactoryTest;
668
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -0700669 boolean mCheckedForSetup;
670
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800671 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700672 * The time at which we will allow normal application switches again,
673 * after a call to {@link #stopAppSwitches()}.
674 */
675 long mAppSwitchesAllowedTime;
676
677 /**
678 * This is set to true after the first switch after mAppSwitchesAllowedTime
679 * is set; any switches after that will clear the time.
680 */
681 boolean mDidAppSwitch;
682
683 /**
Dianne Hackborn287952c2010-09-22 22:34:31 -0700684 * Last time (in realtime) at which we checked for power usage.
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700685 */
Dianne Hackborn287952c2010-09-22 22:34:31 -0700686 long mLastPowerCheckRealtime;
687
688 /**
689 * Last time (in uptime) at which we checked for power usage.
690 */
691 long mLastPowerCheckUptime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700692
693 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800694 * Set while we are wanting to sleep, to prevent any
695 * activities from being started/resumed.
696 */
697 boolean mSleeping = false;
698
699 /**
Dianne Hackbornff5b1582012-04-12 17:24:07 -0700700 * State of external calls telling us if the device is asleep.
701 */
702 boolean mWentToSleep = false;
703
704 /**
705 * State of external call telling us if the lock screen is shown.
706 */
707 boolean mLockScreenShown = false;
708
709 /**
Dianne Hackborn55280a92009-05-07 15:53:46 -0700710 * Set if we are shutting down the system, similar to sleeping.
711 */
712 boolean mShuttingDown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800713
714 /**
715 * Task identifier that activities are currently being started
716 * in. Incremented each time a new task is created.
717 * todo: Replace this with a TokenSpace class that generates non-repeating
718 * integers that won't wrap.
719 */
720 int mCurTask = 1;
721
722 /**
723 * Current sequence id for oom_adj computation traversal.
724 */
725 int mAdjSeq = 0;
726
727 /**
Dianne Hackborn906497c2010-05-10 15:57:38 -0700728 * Current sequence id for process LRU updating.
729 */
730 int mLruSeq = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800731
732 /**
Dianne Hackborne02c88a2011-10-28 13:58:15 -0700733 * Keep track of the number of service processes we last found, to
734 * determine on the next iteration which should be B services.
735 */
736 int mNumServiceProcs = 0;
737 int mNewNumServiceProcs = 0;
738
739 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800740 * System monitoring: number of processes that died since the last
741 * N procs were started.
742 */
743 int[] mProcDeaths = new int[20];
744
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700745 /**
746 * This is set if we had to do a delayed dexopt of an app before launching
747 * it, to increasing the ANR timeouts in that case.
748 */
749 boolean mDidDexOpt;
750
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800751 String mDebugApp = null;
752 boolean mWaitForDebugger = false;
753 boolean mDebugTransient = false;
754 String mOrigDebugApp = null;
755 boolean mOrigWaitForDebugger = false;
756 boolean mAlwaysFinishActivities = false;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700757 IActivityController mController = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700758 String mProfileApp = null;
759 ProcessRecord mProfileProc = null;
760 String mProfileFile;
761 ParcelFileDescriptor mProfileFd;
762 int mProfileType = 0;
763 boolean mAutoStopProfiler = false;
Siva Velusamy92a8b222012-03-09 16:24:04 -0800764 String mOpenGlTraceApp = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800765
Jeff Sharkeya4620792011-05-20 15:29:23 -0700766 final RemoteCallbackList<IProcessObserver> mProcessObservers
767 = new RemoteCallbackList<IProcessObserver>();
768
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800769 /**
770 * Callback of last caller to {@link #requestPss}.
771 */
772 Runnable mRequestPssCallback;
773
774 /**
775 * Remaining processes for which we are waiting results from the last
776 * call to {@link #requestPss}.
777 */
778 final ArrayList<ProcessRecord> mRequestPssList
779 = new ArrayList<ProcessRecord>();
780
781 /**
782 * Runtime statistics collection thread. This object's lock is used to
783 * protect all related state.
784 */
785 final Thread mProcessStatsThread;
786
787 /**
788 * Used to collect process stats when showing not responding dialog.
789 * Protected by mProcessStatsThread.
790 */
791 final ProcessStats mProcessStats = new ProcessStats(
792 MONITOR_THREAD_CPU_USAGE);
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700793 final AtomicLong mLastCpuTime = new AtomicLong(0);
794 final AtomicBoolean mProcessStatsMutexFree = new AtomicBoolean(true);
795
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800796 long mLastWriteTime = 0;
797
798 /**
799 * Set to true after the system has finished booting.
800 */
801 boolean mBooted = false;
802
Dianne Hackborn7d608422011-08-07 16:24:18 -0700803 int mProcessLimit = ProcessList.MAX_HIDDEN_APPS;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700804 int mProcessLimitOverride = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800805
806 WindowManagerService mWindowManager;
807
808 static ActivityManagerService mSelf;
809 static ActivityThread mSystemThread;
810
811 private final class AppDeathRecipient implements IBinder.DeathRecipient {
812 final ProcessRecord mApp;
813 final int mPid;
814 final IApplicationThread mAppThread;
815
816 AppDeathRecipient(ProcessRecord app, int pid,
817 IApplicationThread thread) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800818 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800819 TAG, "New death recipient " + this
820 + " for thread " + thread.asBinder());
821 mApp = app;
822 mPid = pid;
823 mAppThread = thread;
824 }
825
826 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800827 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800828 TAG, "Death received in " + this
829 + " for thread " + mAppThread.asBinder());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800830 synchronized(ActivityManagerService.this) {
831 appDiedLocked(mApp, mPid, mAppThread);
832 }
833 }
834 }
835
836 static final int SHOW_ERROR_MSG = 1;
837 static final int SHOW_NOT_RESPONDING_MSG = 2;
838 static final int SHOW_FACTORY_ERROR_MSG = 3;
839 static final int UPDATE_CONFIGURATION_MSG = 4;
840 static final int GC_BACKGROUND_PROCESSES_MSG = 5;
841 static final int WAIT_FOR_DEBUGGER_MSG = 6;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800842 static final int SERVICE_TIMEOUT_MSG = 12;
843 static final int UPDATE_TIME_ZONE = 13;
844 static final int SHOW_UID_ERROR_MSG = 14;
845 static final int IM_FEELING_LUCKY_MSG = 15;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800846 static final int PROC_START_TIMEOUT_MSG = 20;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700847 static final int DO_PENDING_ACTIVITY_LAUNCHES_MSG = 21;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -0700848 static final int KILL_APPLICATION_MSG = 22;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800849 static final int FINALIZE_PENDING_INTENT_MSG = 23;
Dianne Hackborn860755f2010-06-03 18:47:52 -0700850 static final int POST_HEAVY_NOTIFICATION_MSG = 24;
851 static final int CANCEL_HEAVY_NOTIFICATION_MSG = 25;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700852 static final int SHOW_STRICT_MODE_VIOLATION_MSG = 26;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700853 static final int CHECK_EXCESSIVE_WAKE_LOCKS_MSG = 27;
Robert Greenwalt03595d02010-11-02 14:08:23 -0700854 static final int CLEAR_DNS_CACHE = 28;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700855 static final int UPDATE_HTTP_PROXY = 29;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700856 static final int SHOW_COMPAT_MODE_DIALOG_MSG = 30;
Dianne Hackborn36f80f32011-05-31 18:26:45 -0700857 static final int DISPATCH_FOREGROUND_ACTIVITIES_CHANGED = 31;
858 static final int DISPATCH_PROCESS_DIED = 32;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700859 static final int REPORT_MEM_USAGE = 33;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800860
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800861 static final int FIRST_ACTIVITY_STACK_MSG = 100;
862 static final int FIRST_BROADCAST_QUEUE_MSG = 200;
863 static final int FIRST_COMPAT_MODE_MSG = 300;
864
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800865 AlertDialog mUidAlert;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700866 CompatModeDialog mCompatModeDialog;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700867 long mLastMemUsageReportTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800868
869 final Handler mHandler = new Handler() {
870 //public Handler() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800871 // if (localLOGV) Slog.v(TAG, "Handler started!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800872 //}
873
874 public void handleMessage(Message msg) {
875 switch (msg.what) {
876 case SHOW_ERROR_MSG: {
877 HashMap data = (HashMap) msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800878 synchronized (ActivityManagerService.this) {
879 ProcessRecord proc = (ProcessRecord)data.get("app");
880 if (proc != null && proc.crashDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800881 Slog.e(TAG, "App already has crash dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800882 return;
883 }
884 AppErrorResult res = (AppErrorResult) data.get("result");
Joe Onorato54a4a412011-11-02 20:50:08 -0700885 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Dan Egnorb7f03672009-12-09 16:22:32 -0800886 Dialog d = new AppErrorDialog(mContext, res, proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800887 d.show();
888 proc.crashDialog = d;
889 } else {
890 // The device is asleep, so just pretend that the user
891 // saw a crash dialog and hit "force quit".
892 res.set(0);
893 }
894 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700895
896 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800897 } break;
898 case SHOW_NOT_RESPONDING_MSG: {
899 synchronized (ActivityManagerService.this) {
900 HashMap data = (HashMap) msg.obj;
901 ProcessRecord proc = (ProcessRecord)data.get("app");
902 if (proc != null && proc.anrDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800903 Slog.e(TAG, "App already has anr dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800904 return;
905 }
The Android Open Source Project4df24232009-03-05 14:34:35 -0800906
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700907 Intent intent = new Intent("android.intent.action.ANR");
908 if (!mProcessesReady) {
Christopher Tatef46723b2012-01-26 14:19:24 -0800909 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
910 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700911 }
912 broadcastIntentLocked(null, null, intent,
The Android Open Source Project4df24232009-03-05 14:34:35 -0800913 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -0700914 false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
The Android Open Source Project4df24232009-03-05 14:34:35 -0800915
Justin Kohbc52ca22012-03-29 15:11:44 -0700916 if (mShowDialogs) {
917 Dialog d = new AppNotRespondingDialog(ActivityManagerService.this,
Mike Lockwood69ccdbd2012-04-03 11:53:47 -0700918 mContext, proc, (ActivityRecord)data.get("activity"));
Justin Kohbc52ca22012-03-29 15:11:44 -0700919 d.show();
920 proc.anrDialog = d;
921 } else {
922 // Just kill the app if there is no dialog to be shown.
923 killAppAtUsersRequest(proc, null);
924 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800925 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700926
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700927 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800928 } break;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700929 case SHOW_STRICT_MODE_VIOLATION_MSG: {
930 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj;
931 synchronized (ActivityManagerService.this) {
932 ProcessRecord proc = (ProcessRecord) data.get("app");
933 if (proc == null) {
934 Slog.e(TAG, "App not found when showing strict mode dialog.");
935 break;
936 }
937 if (proc.crashDialog != null) {
938 Slog.e(TAG, "App already has strict mode dialog: " + proc);
939 return;
940 }
941 AppErrorResult res = (AppErrorResult) data.get("result");
Joe Onorato54a4a412011-11-02 20:50:08 -0700942 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700943 Dialog d = new StrictModeViolationDialog(mContext, res, proc);
944 d.show();
945 proc.crashDialog = d;
946 } else {
947 // The device is asleep, so just pretend that the user
948 // saw a crash dialog and hit "force quit".
949 res.set(0);
950 }
951 }
952 ensureBootCompleted();
953 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800954 case SHOW_FACTORY_ERROR_MSG: {
955 Dialog d = new FactoryErrorDialog(
956 mContext, msg.getData().getCharSequence("msg"));
957 d.show();
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700958 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800959 } break;
960 case UPDATE_CONFIGURATION_MSG: {
961 final ContentResolver resolver = mContext.getContentResolver();
962 Settings.System.putConfiguration(resolver, (Configuration)msg.obj);
963 } break;
964 case GC_BACKGROUND_PROCESSES_MSG: {
965 synchronized (ActivityManagerService.this) {
966 performAppGcsIfAppropriateLocked();
967 }
968 } break;
969 case WAIT_FOR_DEBUGGER_MSG: {
970 synchronized (ActivityManagerService.this) {
971 ProcessRecord app = (ProcessRecord)msg.obj;
972 if (msg.arg1 != 0) {
973 if (!app.waitedForDebugger) {
974 Dialog d = new AppWaitingForDebuggerDialog(
975 ActivityManagerService.this,
976 mContext, app);
977 app.waitDialog = d;
978 app.waitedForDebugger = true;
979 d.show();
980 }
981 } else {
982 if (app.waitDialog != null) {
983 app.waitDialog.dismiss();
984 app.waitDialog = null;
985 }
986 }
987 }
988 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800989 case SERVICE_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700990 if (mDidDexOpt) {
991 mDidDexOpt = false;
992 Message nmsg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
993 nmsg.obj = msg.obj;
994 mHandler.sendMessageDelayed(nmsg, SERVICE_TIMEOUT);
995 return;
996 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800997 serviceTimeout((ProcessRecord)msg.obj);
998 } break;
999 case UPDATE_TIME_ZONE: {
1000 synchronized (ActivityManagerService.this) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001001 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1002 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001003 if (r.thread != null) {
1004 try {
1005 r.thread.updateTimeZone();
1006 } catch (RemoteException ex) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001007 Slog.w(TAG, "Failed to update time zone for: " + r.info.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001008 }
1009 }
1010 }
1011 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001012 } break;
Robert Greenwalt03595d02010-11-02 14:08:23 -07001013 case CLEAR_DNS_CACHE: {
1014 synchronized (ActivityManagerService.this) {
1015 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1016 ProcessRecord r = mLruProcesses.get(i);
1017 if (r.thread != null) {
1018 try {
1019 r.thread.clearDnsCache();
1020 } catch (RemoteException ex) {
1021 Slog.w(TAG, "Failed to clear dns cache for: " + r.info.processName);
1022 }
1023 }
1024 }
1025 }
1026 } break;
Robert Greenwalt434203a2010-10-11 16:00:27 -07001027 case UPDATE_HTTP_PROXY: {
1028 ProxyProperties proxy = (ProxyProperties)msg.obj;
1029 String host = "";
1030 String port = "";
1031 String exclList = "";
1032 if (proxy != null) {
1033 host = proxy.getHost();
1034 port = Integer.toString(proxy.getPort());
1035 exclList = proxy.getExclusionList();
1036 }
1037 synchronized (ActivityManagerService.this) {
1038 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1039 ProcessRecord r = mLruProcesses.get(i);
1040 if (r.thread != null) {
1041 try {
1042 r.thread.setHttpProxy(host, port, exclList);
1043 } catch (RemoteException ex) {
1044 Slog.w(TAG, "Failed to update http proxy for: " +
1045 r.info.processName);
1046 }
1047 }
1048 }
1049 }
1050 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001051 case SHOW_UID_ERROR_MSG: {
Joe Onorato54a4a412011-11-02 20:50:08 -07001052 String title = "System UIDs Inconsistent";
1053 String text = "UIDs on the system are inconsistent, you need to wipe your"
1054 + " data partition or your device will be unstable.";
1055 Log.e(TAG, title + ": " + text);
1056 if (mShowDialogs) {
1057 // XXX This is a temporary dialog, no need to localize.
1058 AlertDialog d = new BaseErrorDialog(mContext);
1059 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
1060 d.setCancelable(false);
1061 d.setTitle(title);
1062 d.setMessage(text);
1063 d.setButton(DialogInterface.BUTTON_POSITIVE, "I'm Feeling Lucky",
1064 mHandler.obtainMessage(IM_FEELING_LUCKY_MSG));
1065 mUidAlert = d;
1066 d.show();
1067 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001068 } break;
1069 case IM_FEELING_LUCKY_MSG: {
1070 if (mUidAlert != null) {
1071 mUidAlert.dismiss();
1072 mUidAlert = null;
1073 }
1074 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001075 case PROC_START_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001076 if (mDidDexOpt) {
1077 mDidDexOpt = false;
1078 Message nmsg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
1079 nmsg.obj = msg.obj;
1080 mHandler.sendMessageDelayed(nmsg, PROC_START_TIMEOUT);
1081 return;
1082 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001083 ProcessRecord app = (ProcessRecord)msg.obj;
1084 synchronized (ActivityManagerService.this) {
1085 processStartTimedOutLocked(app);
1086 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001087 } break;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07001088 case DO_PENDING_ACTIVITY_LAUNCHES_MSG: {
1089 synchronized (ActivityManagerService.this) {
1090 doPendingActivityLaunchesLocked(true);
1091 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001092 } break;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001093 case KILL_APPLICATION_MSG: {
1094 synchronized (ActivityManagerService.this) {
1095 int uid = msg.arg1;
1096 boolean restart = (msg.arg2 == 1);
1097 String pkg = (String) msg.obj;
Amith Yamasani483f3b02012-03-13 16:08:00 -07001098 forceStopPackageLocked(pkg, uid, restart, false, true, false,
1099 UserId.getUserId(uid));
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001100 }
1101 } break;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001102 case FINALIZE_PENDING_INTENT_MSG: {
1103 ((PendingIntentRecord)msg.obj).completeFinalize();
1104 } break;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001105 case POST_HEAVY_NOTIFICATION_MSG: {
1106 INotificationManager inm = NotificationManager.getService();
1107 if (inm == null) {
1108 return;
1109 }
1110
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001111 ActivityRecord root = (ActivityRecord)msg.obj;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001112 ProcessRecord process = root.app;
1113 if (process == null) {
1114 return;
1115 }
1116
1117 try {
1118 Context context = mContext.createPackageContext(process.info.packageName, 0);
1119 String text = mContext.getString(R.string.heavy_weight_notification,
1120 context.getApplicationInfo().loadLabel(context.getPackageManager()));
1121 Notification notification = new Notification();
1122 notification.icon = com.android.internal.R.drawable.stat_sys_adb; //context.getApplicationInfo().icon;
1123 notification.when = 0;
1124 notification.flags = Notification.FLAG_ONGOING_EVENT;
1125 notification.tickerText = text;
1126 notification.defaults = 0; // please be quiet
1127 notification.sound = null;
1128 notification.vibrate = null;
1129 notification.setLatestEventInfo(context, text,
1130 mContext.getText(R.string.heavy_weight_notification_detail),
1131 PendingIntent.getActivity(mContext, 0, root.intent,
1132 PendingIntent.FLAG_CANCEL_CURRENT));
1133
1134 try {
1135 int[] outId = new int[1];
1136 inm.enqueueNotification("android", R.string.heavy_weight_notification,
1137 notification, outId);
1138 } catch (RuntimeException e) {
1139 Slog.w(ActivityManagerService.TAG,
1140 "Error showing notification for heavy-weight app", e);
1141 } catch (RemoteException e) {
1142 }
1143 } catch (NameNotFoundException e) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07001144 Slog.w(TAG, "Unable to create context for heavy notification", e);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001145 }
1146 } break;
1147 case CANCEL_HEAVY_NOTIFICATION_MSG: {
1148 INotificationManager inm = NotificationManager.getService();
1149 if (inm == null) {
1150 return;
1151 }
1152 try {
1153 inm.cancelNotification("android",
1154 R.string.heavy_weight_notification);
1155 } catch (RuntimeException e) {
1156 Slog.w(ActivityManagerService.TAG,
1157 "Error canceling notification for service", e);
1158 } catch (RemoteException e) {
1159 }
1160 } break;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001161 case CHECK_EXCESSIVE_WAKE_LOCKS_MSG: {
1162 synchronized (ActivityManagerService.this) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001163 checkExcessivePowerUsageLocked(true);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07001164 removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001165 Message nmsg = obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
1166 sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001167 }
1168 } break;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001169 case SHOW_COMPAT_MODE_DIALOG_MSG: {
1170 synchronized (ActivityManagerService.this) {
1171 ActivityRecord ar = (ActivityRecord)msg.obj;
1172 if (mCompatModeDialog != null) {
1173 if (mCompatModeDialog.mAppInfo.packageName.equals(
1174 ar.info.applicationInfo.packageName)) {
1175 return;
1176 }
1177 mCompatModeDialog.dismiss();
1178 mCompatModeDialog = null;
1179 }
Dianne Hackborn29478262011-06-07 15:44:22 -07001180 if (ar != null && false) {
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001181 if (mCompatModePackages.getPackageAskCompatModeLocked(
1182 ar.packageName)) {
1183 int mode = mCompatModePackages.computeCompatModeLocked(
1184 ar.info.applicationInfo);
1185 if (mode == ActivityManager.COMPAT_MODE_DISABLED
1186 || mode == ActivityManager.COMPAT_MODE_ENABLED) {
1187 mCompatModeDialog = new CompatModeDialog(
1188 ActivityManagerService.this, mContext,
1189 ar.info.applicationInfo);
1190 mCompatModeDialog.show();
1191 }
1192 }
1193 }
1194 }
Dianne Hackborn36f80f32011-05-31 18:26:45 -07001195 break;
1196 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001197 case DISPATCH_FOREGROUND_ACTIVITIES_CHANGED: {
Jeff Sharkey287bd832011-05-28 19:36:26 -07001198 final int pid = msg.arg1;
1199 final int uid = msg.arg2;
1200 final boolean foregroundActivities = (Boolean) msg.obj;
1201 dispatchForegroundActivitiesChanged(pid, uid, foregroundActivities);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001202 break;
1203 }
1204 case DISPATCH_PROCESS_DIED: {
Jeff Sharkey287bd832011-05-28 19:36:26 -07001205 final int pid = msg.arg1;
1206 final int uid = msg.arg2;
1207 dispatchProcessDied(pid, uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001208 break;
1209 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001210 case REPORT_MEM_USAGE: {
1211 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
1212 if (!isDebuggable) {
1213 return;
1214 }
1215 synchronized (ActivityManagerService.this) {
1216 long now = SystemClock.uptimeMillis();
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001217 if (now < (mLastMemUsageReportTime+5*60*1000)) {
1218 // Don't report more than every 5 minutes to somewhat
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001219 // avoid spamming.
1220 return;
1221 }
1222 mLastMemUsageReportTime = now;
1223 }
1224 Thread thread = new Thread() {
1225 @Override public void run() {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001226 StringBuilder dropBuilder = new StringBuilder(1024);
1227 StringBuilder logBuilder = new StringBuilder(1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -08001228 StringWriter oomSw = new StringWriter();
1229 PrintWriter oomPw = new PrintWriter(oomSw);
1230 StringWriter catSw = new StringWriter();
1231 PrintWriter catPw = new PrintWriter(catSw);
1232 String[] emptyArgs = new String[] { };
1233 StringBuilder tag = new StringBuilder(128);
1234 StringBuilder stack = new StringBuilder(128);
1235 tag.append("Low on memory -- ");
1236 dumpApplicationMemoryUsage(null, oomPw, " ", emptyArgs, true, catPw,
1237 tag, stack);
1238 dropBuilder.append(stack);
1239 dropBuilder.append('\n');
1240 dropBuilder.append('\n');
1241 String oomString = oomSw.toString();
1242 dropBuilder.append(oomString);
1243 dropBuilder.append('\n');
1244 logBuilder.append(oomString);
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001245 try {
1246 java.lang.Process proc = Runtime.getRuntime().exec(new String[] {
1247 "procrank", });
1248 final InputStreamReader converter = new InputStreamReader(
1249 proc.getInputStream());
1250 BufferedReader in = new BufferedReader(converter);
1251 String line;
1252 while (true) {
1253 line = in.readLine();
1254 if (line == null) {
1255 break;
1256 }
1257 if (line.length() > 0) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001258 logBuilder.append(line);
1259 logBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001260 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001261 dropBuilder.append(line);
1262 dropBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001263 }
1264 converter.close();
1265 } catch (IOException e) {
1266 }
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001267 synchronized (ActivityManagerService.this) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08001268 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001269 dumpProcessesLocked(null, catPw, emptyArgs, 0, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001270 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001271 dumpServicesLocked(null, catPw, emptyArgs, 0, false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001272 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001273 dumpActivitiesLocked(null, catPw, emptyArgs, 0, false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001274 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001275 dropBuilder.append(catSw.toString());
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001276 addErrorToDropBox("lowmem", null, "system_server", null,
1277 null, tag.toString(), dropBuilder.toString(), null, null);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001278 Slog.i(TAG, logBuilder.toString());
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001279 synchronized (ActivityManagerService.this) {
1280 long now = SystemClock.uptimeMillis();
1281 if (mLastMemUsageReportTime < now) {
1282 mLastMemUsageReportTime = now;
1283 }
1284 }
1285 }
1286 };
1287 thread.start();
1288 break;
1289 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001290 }
1291 }
1292 };
1293
1294 public static void setSystemProcess() {
1295 try {
1296 ActivityManagerService m = mSelf;
1297
Dianne Hackborna573f6a2012-02-09 16:12:18 -08001298 ServiceManager.addService("activity", m, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001299 ServiceManager.addService("meminfo", new MemBinder(m));
Chet Haase9c1e23b2011-03-24 10:51:31 -07001300 ServiceManager.addService("gfxinfo", new GraphicsBinder(m));
Jeff Brown6754ba22011-12-14 20:20:01 -08001301 ServiceManager.addService("dbinfo", new DbBinder(m));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001302 if (MONITOR_CPU_USAGE) {
1303 ServiceManager.addService("cpuinfo", new CpuBinder(m));
1304 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001305 ServiceManager.addService("permission", new PermissionController(m));
1306
1307 ApplicationInfo info =
1308 mSelf.mContext.getPackageManager().getApplicationInfo(
Amith Yamasani483f3b02012-03-13 16:08:00 -07001309 "android", STOCK_PM_FLAGS);
Mike Cleron432b7132009-09-24 15:28:29 -07001310 mSystemThread.installSystemApplicationInfo(info);
1311
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001312 synchronized (mSelf) {
1313 ProcessRecord app = mSelf.newProcessRecordLocked(
1314 mSystemThread.getApplicationThread(), info,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001315 info.processName, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001316 app.persistent = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08001317 app.pid = MY_PID;
Dianne Hackborn7d608422011-08-07 16:24:18 -07001318 app.maxAdj = ProcessList.SYSTEM_ADJ;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001319 mSelf.mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001320 synchronized (mSelf.mPidsSelfLocked) {
1321 mSelf.mPidsSelfLocked.put(app.pid, app);
1322 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001323 mSelf.updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001324 }
1325 } catch (PackageManager.NameNotFoundException e) {
1326 throw new RuntimeException(
1327 "Unable to find android system package", e);
1328 }
1329 }
1330
1331 public void setWindowManager(WindowManagerService wm) {
1332 mWindowManager = wm;
1333 }
1334
1335 public static final Context main(int factoryTest) {
1336 AThread thr = new AThread();
1337 thr.start();
1338
1339 synchronized (thr) {
1340 while (thr.mService == null) {
1341 try {
1342 thr.wait();
1343 } catch (InterruptedException e) {
1344 }
1345 }
1346 }
1347
1348 ActivityManagerService m = thr.mService;
1349 mSelf = m;
1350 ActivityThread at = ActivityThread.systemMain();
1351 mSystemThread = at;
1352 Context context = at.getSystemContext();
Dianne Hackborn247fe742011-01-08 17:25:57 -08001353 context.setTheme(android.R.style.Theme_Holo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001354 m.mContext = context;
1355 m.mFactoryTest = factoryTest;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001356 m.mMainStack = new ActivityStack(m, context, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001357
1358 m.mBatteryStatsService.publish(context);
1359 m.mUsageStatsService.publish(context);
1360
1361 synchronized (thr) {
1362 thr.mReady = true;
1363 thr.notifyAll();
1364 }
1365
1366 m.startRunning(null, null, null, null);
1367
1368 return context;
1369 }
1370
1371 public static ActivityManagerService self() {
1372 return mSelf;
1373 }
1374
1375 static class AThread extends Thread {
1376 ActivityManagerService mService;
1377 boolean mReady = false;
1378
1379 public AThread() {
1380 super("ActivityManager");
1381 }
1382
1383 public void run() {
1384 Looper.prepare();
1385
1386 android.os.Process.setThreadPriority(
1387 android.os.Process.THREAD_PRIORITY_FOREGROUND);
Christopher Tate160edb32010-06-30 17:46:30 -07001388 android.os.Process.setCanSelfBackground(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001389
1390 ActivityManagerService m = new ActivityManagerService();
1391
1392 synchronized (this) {
1393 mService = m;
1394 notifyAll();
1395 }
1396
1397 synchronized (this) {
1398 while (!mReady) {
1399 try {
1400 wait();
1401 } catch (InterruptedException e) {
1402 }
1403 }
1404 }
1405
Brad Fitzpatrickec062f62010-11-03 09:56:54 -07001406 // For debug builds, log event loop stalls to dropbox for analysis.
1407 if (StrictMode.conditionallyEnableDebugLogging()) {
1408 Slog.i(TAG, "Enabled StrictMode logging for AThread's Looper");
1409 }
1410
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001411 Looper.loop();
1412 }
1413 }
1414
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001415 static class MemBinder extends Binder {
1416 ActivityManagerService mActivityManagerService;
1417 MemBinder(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 meminfo from from pid="
1426 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1427 + " without permission " + android.Manifest.permission.DUMP);
1428 return;
1429 }
1430
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001431 mActivityManagerService.dumpApplicationMemoryUsage(fd, pw, " ", args,
Dianne Hackborn672342c2011-11-29 11:29:02 -08001432 false, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001433 }
1434 }
1435
Chet Haase9c1e23b2011-03-24 10:51:31 -07001436 static class GraphicsBinder extends Binder {
1437 ActivityManagerService mActivityManagerService;
1438 GraphicsBinder(ActivityManagerService activityManagerService) {
1439 mActivityManagerService = activityManagerService;
1440 }
1441
1442 @Override
1443 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001444 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1445 != PackageManager.PERMISSION_GRANTED) {
1446 pw.println("Permission Denial: can't dump gfxinfo from from pid="
1447 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1448 + " without permission " + android.Manifest.permission.DUMP);
1449 return;
1450 }
1451
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001452 mActivityManagerService.dumpGraphicsHardwareUsage(fd, pw, args);
Chet Haase9c1e23b2011-03-24 10:51:31 -07001453 }
1454 }
1455
Jeff Brown6754ba22011-12-14 20:20:01 -08001456 static class DbBinder extends Binder {
1457 ActivityManagerService mActivityManagerService;
1458 DbBinder(ActivityManagerService activityManagerService) {
1459 mActivityManagerService = activityManagerService;
1460 }
1461
1462 @Override
1463 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1464 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1465 != PackageManager.PERMISSION_GRANTED) {
1466 pw.println("Permission Denial: can't dump dbinfo from from pid="
1467 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1468 + " without permission " + android.Manifest.permission.DUMP);
1469 return;
1470 }
1471
1472 mActivityManagerService.dumpDbInfo(fd, pw, args);
1473 }
1474 }
1475
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001476 static class CpuBinder extends Binder {
1477 ActivityManagerService mActivityManagerService;
1478 CpuBinder(ActivityManagerService activityManagerService) {
1479 mActivityManagerService = activityManagerService;
1480 }
1481
1482 @Override
1483 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001484 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1485 != PackageManager.PERMISSION_GRANTED) {
1486 pw.println("Permission Denial: can't dump cpuinfo from from pid="
1487 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1488 + " without permission " + android.Manifest.permission.DUMP);
1489 return;
1490 }
1491
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001492 synchronized (mActivityManagerService.mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07001493 pw.print(mActivityManagerService.mProcessStats.printCurrentLoad());
1494 pw.print(mActivityManagerService.mProcessStats.printCurrentState(
1495 SystemClock.uptimeMillis()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001496 }
1497 }
1498 }
1499
1500 private ActivityManagerService() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001501 Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
Dianne Hackborn2c6c5e62009-10-08 17:55:49 -07001502
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001503 mFgBroadcastQueue = new BroadcastQueue(this, "foreground", BROADCAST_FG_TIMEOUT);
1504 mBgBroadcastQueue = new BroadcastQueue(this, "background", BROADCAST_BG_TIMEOUT);
1505 mBroadcastQueues[0] = mFgBroadcastQueue;
1506 mBroadcastQueues[1] = mBgBroadcastQueue;
1507
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001508 File dataDir = Environment.getDataDirectory();
1509 File systemDir = new File(dataDir, "system");
1510 systemDir.mkdirs();
1511 mBatteryStatsService = new BatteryStatsService(new File(
1512 systemDir, "batterystats.bin").toString());
1513 mBatteryStatsService.getActiveStatistics().readLocked();
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001514 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
Dianne Hackborn287952c2010-09-22 22:34:31 -07001515 mOnBattery = DEBUG_POWER ? true
1516 : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001517 mBatteryStatsService.getActiveStatistics().setCallback(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001518
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001519 mUsageStatsService = new UsageStatsService(new File(
Dianne Hackborn6447ca32009-04-07 19:50:08 -07001520 systemDir, "usagestats").toString());
Mike Lockwood3a74bd32011-08-12 13:55:22 -07001521 mHeadless = "1".equals(SystemProperties.get("ro.config.headless", "0"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001522
Jack Palevichb90d28c2009-07-22 15:35:24 -07001523 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",
1524 ConfigurationInfo.GL_ES_VERSION_UNDEFINED);
1525
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001526 mConfiguration.setToDefaults();
1527 mConfiguration.locale = Locale.getDefault();
Dianne Hackborn813075a62011-11-14 17:45:19 -08001528 mConfigurationSeq = mConfiguration.seq = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001529 mProcessStats.init();
1530
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07001531 mCompatModePackages = new CompatModePackages(this, systemDir);
1532
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001533 // Add ourself to the Watchdog monitors.
1534 Watchdog.getInstance().addMonitor(this);
1535
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001536 mProcessStatsThread = new Thread("ProcessStats") {
1537 public void run() {
1538 while (true) {
1539 try {
1540 try {
1541 synchronized(this) {
1542 final long now = SystemClock.uptimeMillis();
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001543 long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001544 long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001545 //Slog.i(TAG, "Cpu delay=" + nextCpuDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001546 // + ", write delay=" + nextWriteDelay);
1547 if (nextWriteDelay < nextCpuDelay) {
1548 nextCpuDelay = nextWriteDelay;
1549 }
1550 if (nextCpuDelay > 0) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001551 mProcessStatsMutexFree.set(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001552 this.wait(nextCpuDelay);
1553 }
1554 }
1555 } catch (InterruptedException e) {
1556 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001557 updateCpuStatsNow();
1558 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001559 Slog.e(TAG, "Unexpected exception collecting process stats", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001560 }
1561 }
1562 }
1563 };
1564 mProcessStatsThread.start();
1565 }
1566
1567 @Override
1568 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1569 throws RemoteException {
Dianne Hackborna53de062012-05-08 18:53:51 -07001570 if (code == SYSPROPS_TRANSACTION) {
1571 // We need to tell all apps about the system property change.
1572 ArrayList<IBinder> procs = new ArrayList<IBinder>();
1573 synchronized(this) {
1574 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
1575 final int NA = apps.size();
1576 for (int ia=0; ia<NA; ia++) {
1577 ProcessRecord app = apps.valueAt(ia);
1578 if (app.thread != null) {
1579 procs.add(app.thread.asBinder());
1580 }
1581 }
1582 }
1583 }
1584
1585 int N = procs.size();
1586 for (int i=0; i<N; i++) {
1587 Parcel data2 = Parcel.obtain();
1588 try {
1589 procs.get(i).transact(IBinder.SYSPROPS_TRANSACTION, data2, null, 0);
1590 } catch (RemoteException e) {
1591 }
1592 data2.recycle();
1593 }
1594 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001595 try {
1596 return super.onTransact(code, data, reply, flags);
1597 } catch (RuntimeException e) {
1598 // The activity manager only throws security exceptions, so let's
1599 // log all others.
1600 if (!(e instanceof SecurityException)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001601 Slog.e(TAG, "Activity Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001602 }
1603 throw e;
1604 }
1605 }
1606
1607 void updateCpuStats() {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001608 final long now = SystemClock.uptimeMillis();
1609 if (mLastCpuTime.get() >= now - MONITOR_CPU_MIN_TIME) {
1610 return;
1611 }
1612 if (mProcessStatsMutexFree.compareAndSet(true, false)) {
1613 synchronized (mProcessStatsThread) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001614 mProcessStatsThread.notify();
1615 }
1616 }
1617 }
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001618
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001619 void updateCpuStatsNow() {
1620 synchronized (mProcessStatsThread) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001621 mProcessStatsMutexFree.set(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001622 final long now = SystemClock.uptimeMillis();
1623 boolean haveNewCpuStats = false;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07001624
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001625 if (MONITOR_CPU_USAGE &&
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001626 mLastCpuTime.get() < (now-MONITOR_CPU_MIN_TIME)) {
1627 mLastCpuTime.set(now);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001628 haveNewCpuStats = true;
1629 mProcessStats.update();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001630 //Slog.i(TAG, mProcessStats.printCurrentState());
1631 //Slog.i(TAG, "Total CPU usage: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001632 // + mProcessStats.getTotalCpuPercent() + "%");
1633
Joe Onorato8a9b2202010-02-26 18:56:32 -08001634 // Slog the cpu usage if the property is set.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001635 if ("true".equals(SystemProperties.get("events.cpu"))) {
1636 int user = mProcessStats.getLastUserTime();
1637 int system = mProcessStats.getLastSystemTime();
1638 int iowait = mProcessStats.getLastIoWaitTime();
1639 int irq = mProcessStats.getLastIrqTime();
1640 int softIrq = mProcessStats.getLastSoftIrqTime();
1641 int idle = mProcessStats.getLastIdleTime();
1642
1643 int total = user + system + iowait + irq + softIrq + idle;
1644 if (total == 0) total = 1;
1645
Doug Zongker2bec3d42009-12-04 12:52:44 -08001646 EventLog.writeEvent(EventLogTags.CPU,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001647 ((user+system+iowait+irq+softIrq) * 100) / total,
1648 (user * 100) / total,
1649 (system * 100) / total,
1650 (iowait * 100) / total,
1651 (irq * 100) / total,
1652 (softIrq * 100) / total);
1653 }
1654 }
1655
Amith Yamasanie43530a2009-08-21 13:11:37 -07001656 long[] cpuSpeedTimes = mProcessStats.getLastCpuSpeedTimes();
Amith Yamasani819f9282009-06-24 23:18:15 -07001657 final BatteryStatsImpl bstats = mBatteryStatsService.getActiveStatistics();
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001658 synchronized(bstats) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001659 synchronized(mPidsSelfLocked) {
1660 if (haveNewCpuStats) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001661 if (mOnBattery) {
1662 int perc = bstats.startAddingCpuLocked();
1663 int totalUTime = 0;
1664 int totalSTime = 0;
Dianne Hackborn287952c2010-09-22 22:34:31 -07001665 final int N = mProcessStats.countStats();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001666 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001667 ProcessStats.Stats st = mProcessStats.getStats(i);
1668 if (!st.working) {
1669 continue;
1670 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001671 ProcessRecord pr = mPidsSelfLocked.get(st.pid);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001672 int otherUTime = (st.rel_utime*perc)/100;
1673 int otherSTime = (st.rel_stime*perc)/100;
1674 totalUTime += otherUTime;
1675 totalSTime += otherSTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001676 if (pr != null) {
1677 BatteryStatsImpl.Uid.Proc ps = pr.batteryStats;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001678 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1679 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001680 ps.addSpeedStepTimes(cpuSpeedTimes);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001681 pr.curCpuTime += (st.rel_utime+st.rel_stime) * 10;
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001682 } else {
1683 BatteryStatsImpl.Uid.Proc ps =
Amith Yamasani819f9282009-06-24 23:18:15 -07001684 bstats.getProcessStatsLocked(st.name, st.pid);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001685 if (ps != null) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001686 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1687 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001688 ps.addSpeedStepTimes(cpuSpeedTimes);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001689 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001690 }
1691 }
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001692 bstats.finishAddingCpuLocked(perc, totalUTime,
1693 totalSTime, cpuSpeedTimes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001694 }
1695 }
1696 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001697
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001698 if (mLastWriteTime < (now-BATTERY_STATS_TIME)) {
1699 mLastWriteTime = now;
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001700 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001701 }
1702 }
1703 }
1704 }
1705
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001706 @Override
1707 public void batteryNeedsCpuUpdate() {
1708 updateCpuStatsNow();
1709 }
1710
1711 @Override
1712 public void batteryPowerChanged(boolean onBattery) {
1713 // When plugging in, update the CPU stats first before changing
1714 // the plug state.
1715 updateCpuStatsNow();
1716 synchronized (this) {
1717 synchronized(mPidsSelfLocked) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001718 mOnBattery = DEBUG_POWER ? true : onBattery;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001719 }
1720 }
1721 }
1722
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001723 /**
1724 * Initialize the application bind args. These are passed to each
1725 * process when the bindApplication() IPC is sent to the process. They're
1726 * lazily setup to make sure the services are running when they're asked for.
1727 */
1728 private HashMap<String, IBinder> getCommonServicesLocked() {
1729 if (mAppBindArgs == null) {
1730 mAppBindArgs = new HashMap<String, IBinder>();
1731
1732 // Setup the application init args
1733 mAppBindArgs.put("package", ServiceManager.getService("package"));
1734 mAppBindArgs.put("window", ServiceManager.getService("window"));
1735 mAppBindArgs.put(Context.ALARM_SERVICE,
1736 ServiceManager.getService(Context.ALARM_SERVICE));
1737 }
1738 return mAppBindArgs;
1739 }
1740
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001741 final void setFocusedActivityLocked(ActivityRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001742 if (mFocusedActivity != r) {
1743 mFocusedActivity = r;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001744 if (r != null) {
1745 mWindowManager.setFocusedApp(r.appToken, true);
1746 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001747 }
1748 }
1749
Dianne Hackborn906497c2010-05-10 15:57:38 -07001750 private final void updateLruProcessInternalLocked(ProcessRecord app,
1751 boolean oomAdj, boolean updateActivityTime, int bestPos) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001752 // put it on the LRU to keep track of when it should be exited.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001753 int lrui = mLruProcesses.indexOf(app);
1754 if (lrui >= 0) mLruProcesses.remove(lrui);
1755
1756 int i = mLruProcesses.size()-1;
1757 int skipTop = 0;
1758
Dianne Hackborn906497c2010-05-10 15:57:38 -07001759 app.lruSeq = mLruSeq;
1760
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001761 // compute the new weight for this process.
1762 if (updateActivityTime) {
1763 app.lastActivityTime = SystemClock.uptimeMillis();
1764 }
1765 if (app.activities.size() > 0) {
1766 // If this process has activities, we more strongly want to keep
1767 // it around.
1768 app.lruWeight = app.lastActivityTime;
1769 } else if (app.pubProviders.size() > 0) {
1770 // If this process contains content providers, we want to keep
1771 // it a little more strongly.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001772 app.lruWeight = app.lastActivityTime - ProcessList.CONTENT_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001773 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001774 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001775 } else {
1776 // If this process doesn't have activities, we less strongly
1777 // want to keep it around, and generally want to avoid getting
1778 // in front of any very recently used activities.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001779 app.lruWeight = app.lastActivityTime - ProcessList.EMPTY_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001780 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001781 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001782 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001783
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001784 while (i >= 0) {
1785 ProcessRecord p = mLruProcesses.get(i);
1786 // If this app shouldn't be in front of the first N background
1787 // apps, then skip over that many that are currently hidden.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001788 if (skipTop > 0 && p.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001789 skipTop--;
1790 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001791 if (p.lruWeight <= app.lruWeight || i < bestPos) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001792 mLruProcesses.add(i+1, app);
1793 break;
1794 }
1795 i--;
1796 }
1797 if (i < 0) {
1798 mLruProcesses.add(0, app);
1799 }
1800
Dianne Hackborn906497c2010-05-10 15:57:38 -07001801 // If the app is currently using a content provider or service,
1802 // bump those processes as well.
1803 if (app.connections.size() > 0) {
1804 for (ConnectionRecord cr : app.connections) {
1805 if (cr.binding != null && cr.binding.service != null
1806 && cr.binding.service.app != null
1807 && cr.binding.service.app.lruSeq != mLruSeq) {
1808 updateLruProcessInternalLocked(cr.binding.service.app, oomAdj,
1809 updateActivityTime, i+1);
1810 }
1811 }
1812 }
1813 if (app.conProviders.size() > 0) {
1814 for (ContentProviderRecord cpr : app.conProviders.keySet()) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07001815 if (cpr.proc != null && cpr.proc.lruSeq != mLruSeq) {
1816 updateLruProcessInternalLocked(cpr.proc, oomAdj,
Dianne Hackborn906497c2010-05-10 15:57:38 -07001817 updateActivityTime, i+1);
1818 }
1819 }
1820 }
1821
Joe Onorato8a9b2202010-02-26 18:56:32 -08001822 //Slog.i(TAG, "Putting proc to front: " + app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001823 if (oomAdj) {
1824 updateOomAdjLocked();
1825 }
1826 }
1827
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001828 final void updateLruProcessLocked(ProcessRecord app,
Dianne Hackborn906497c2010-05-10 15:57:38 -07001829 boolean oomAdj, boolean updateActivityTime) {
1830 mLruSeq++;
1831 updateLruProcessInternalLocked(app, oomAdj, updateActivityTime, 0);
1832 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001833
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001834 final ProcessRecord getProcessRecordLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001835 String processName, int uid) {
Amith Yamasania4a54e22012-04-16 15:44:19 -07001836 if (uid == Process.SYSTEM_UID) {
Amith Yamasani0184ce92012-03-28 22:41:41 -07001837 // The system gets to run in any process. If there are multiple
1838 // processes with the same uid, just pick the first (this
1839 // should never happen).
1840 SparseArray<ProcessRecord> procs = mProcessNames.getMap().get(
1841 processName);
Amith Yamasania4a54e22012-04-16 15:44:19 -07001842 if (procs == null) return null;
1843 final int N = procs.size();
1844 for (int i = 0; i < N; i++) {
1845 if (UserId.isSameUser(procs.keyAt(i), uid)) return procs.valueAt(i);
1846 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001847 }
1848 ProcessRecord proc = mProcessNames.get(processName, uid);
1849 return proc;
1850 }
1851
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001852 void ensurePackageDexOpt(String packageName) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001853 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001854 try {
1855 if (pm.performDexOpt(packageName)) {
1856 mDidDexOpt = true;
1857 }
1858 } catch (RemoteException e) {
1859 }
1860 }
1861
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001862 boolean isNextTransitionForward() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001863 int transit = mWindowManager.getPendingAppTransition();
1864 return transit == WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
1865 || transit == WindowManagerPolicy.TRANSIT_TASK_OPEN
1866 || transit == WindowManagerPolicy.TRANSIT_TASK_TO_FRONT;
1867 }
1868
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001869 final ProcessRecord startProcessLocked(String processName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001870 ApplicationInfo info, boolean knownToBeDead, int intentFlags,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001871 String hostingType, ComponentName hostingName, boolean allowWhileBooting,
1872 boolean isolated) {
1873 ProcessRecord app;
1874 if (!isolated) {
1875 app = getProcessRecordLocked(processName, info.uid);
1876 } else {
1877 // If this is an isolated process, it can't re-use an existing process.
1878 app = null;
1879 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001880 // We don't have to do anything more if:
1881 // (1) There is an existing application record; and
1882 // (2) The caller doesn't think it is dead, OR there is no thread
1883 // object attached to it so we know it couldn't have crashed; and
1884 // (3) There is a pid assigned to it, so it is either starting or
1885 // already running.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001886 if (DEBUG_PROCESSES) Slog.v(TAG, "startProcess: name=" + processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001887 + " app=" + app + " knownToBeDead=" + knownToBeDead
1888 + " thread=" + (app != null ? app.thread : null)
1889 + " pid=" + (app != null ? app.pid : -1));
Magnus Edlund7bb25812010-02-24 15:45:06 +01001890 if (app != null && app.pid > 0) {
1891 if (!knownToBeDead || app.thread == null) {
Dianne Hackborn20cb56e2010-03-04 00:58:29 -08001892 // We already have the app running, or are waiting for it to
1893 // come up (we have a pid but not yet its thread), so keep it.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001894 if (DEBUG_PROCESSES) Slog.v(TAG, "App already running: " + app);
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001895 // If this is a new package in the process, add the package to the list
1896 app.addPackage(info.packageName);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001897 return app;
1898 } else {
1899 // An application record is attached to a previous process,
1900 // clean it up now.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001901 if (DEBUG_PROCESSES) Slog.v(TAG, "App died: " + app);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07001902 handleAppDiedLocked(app, true, true);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001903 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001904 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01001905
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001906 String hostingNameStr = hostingName != null
1907 ? hostingName.flattenToShortString() : null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001908
1909 if (!isolated) {
1910 if ((intentFlags&Intent.FLAG_FROM_BACKGROUND) != 0) {
1911 // If we are in the background, then check to see if this process
1912 // is bad. If so, we will just silently fail.
1913 if (mBadProcesses.get(info.processName, info.uid) != null) {
1914 if (DEBUG_PROCESSES) Slog.v(TAG, "Bad process: " + info.uid
1915 + "/" + info.processName);
1916 return null;
1917 }
1918 } else {
1919 // When the user is explicitly starting a process, then clear its
1920 // crash count so that we won't make it bad until they see at
1921 // least one crash dialog again, and make the process good again
1922 // if it had been bad.
1923 if (DEBUG_PROCESSES) Slog.v(TAG, "Clearing bad process: " + info.uid
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001924 + "/" + info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001925 mProcessCrashTimes.remove(info.processName, info.uid);
1926 if (mBadProcesses.get(info.processName, info.uid) != null) {
1927 EventLog.writeEvent(EventLogTags.AM_PROC_GOOD, info.uid,
1928 info.processName);
1929 mBadProcesses.remove(info.processName, info.uid);
1930 if (app != null) {
1931 app.bad = false;
1932 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001933 }
1934 }
1935 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001936
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001937 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001938 app = newProcessRecordLocked(null, info, processName, isolated);
1939 if (app == null) {
1940 Slog.w(TAG, "Failed making new process record for "
1941 + processName + "/" + info.uid + " isolated=" + isolated);
1942 return null;
1943 }
1944 mProcessNames.put(processName, app.uid, app);
1945 if (isolated) {
1946 mIsolatedProcesses.put(app.uid, app);
1947 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001948 } else {
1949 // If this is a new package in the process, add the package to the list
1950 app.addPackage(info.packageName);
1951 }
1952
1953 // If the system is not ready yet, then hold off on starting this
1954 // process until it is.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001955 if (!mProcessesReady
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001956 && !isAllowedWhileBooting(info)
1957 && !allowWhileBooting) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001958 if (!mProcessesOnHold.contains(app)) {
1959 mProcessesOnHold.add(app);
1960 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001961 if (DEBUG_PROCESSES) Slog.v(TAG, "System not ready, putting on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001962 return app;
1963 }
1964
1965 startProcessLocked(app, hostingType, hostingNameStr);
1966 return (app.pid != 0) ? app : null;
1967 }
1968
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001969 boolean isAllowedWhileBooting(ApplicationInfo ai) {
1970 return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0;
1971 }
1972
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001973 private final void startProcessLocked(ProcessRecord app,
1974 String hostingType, String hostingNameStr) {
1975 if (app.pid > 0 && app.pid != MY_PID) {
1976 synchronized (mPidsSelfLocked) {
1977 mPidsSelfLocked.remove(app.pid);
1978 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
1979 }
1980 app.pid = 0;
1981 }
1982
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001983 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
1984 "startProcessLocked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001985 mProcessesOnHold.remove(app);
1986
1987 updateCpuStats();
1988
1989 System.arraycopy(mProcDeaths, 0, mProcDeaths, 1, mProcDeaths.length-1);
1990 mProcDeaths[0] = 0;
1991
1992 try {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001993 int uid = app.uid;
Amith Yamasani742a6712011-05-04 14:49:28 -07001994
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001995 int[] gids = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001996 if (!app.isolated) {
1997 try {
1998 gids = mContext.getPackageManager().getPackageGids(
1999 app.info.packageName);
2000 } catch (PackageManager.NameNotFoundException e) {
2001 Slog.w(TAG, "Unable to retrieve gids", e);
2002 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002003 }
2004 if (mFactoryTest != SystemServer.FACTORY_TEST_OFF) {
2005 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2006 && mTopComponent != null
2007 && app.processName.equals(mTopComponent.getPackageName())) {
2008 uid = 0;
2009 }
2010 if (mFactoryTest == SystemServer.FACTORY_TEST_HIGH_LEVEL
2011 && (app.info.flags&ApplicationInfo.FLAG_FACTORY_TEST) != 0) {
2012 uid = 0;
2013 }
2014 }
2015 int debugFlags = 0;
2016 if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
2017 debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;
Elliott Hughesfa36aee2011-06-17 14:39:41 -07002018 // Also turn on CheckJNI for debuggable apps. It's quite
2019 // awkward to turn on otherwise.
2020 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002021 }
Ben Cheng6c0afff2010-02-14 16:18:56 -08002022 // Run the app in safe mode if its manifest requests so or the
2023 // system is booted in safe mode.
2024 if ((app.info.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0 ||
2025 Zygote.systemInSafeMode == true) {
Ben Cheng23085b72010-02-08 16:06:32 -08002026 debugFlags |= Zygote.DEBUG_ENABLE_SAFEMODE;
2027 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002028 if ("1".equals(SystemProperties.get("debug.checkjni"))) {
2029 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
2030 }
Elliott Hughesae07ecf2011-07-06 17:33:27 -07002031 if ("1".equals(SystemProperties.get("debug.jni.logging"))) {
2032 debugFlags |= Zygote.DEBUG_ENABLE_JNI_LOGGING;
2033 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002034 if ("1".equals(SystemProperties.get("debug.assert"))) {
2035 debugFlags |= Zygote.DEBUG_ENABLE_ASSERT;
2036 }
Jeff Brown3f9dd282011-07-08 20:02:19 -07002037
2038 // Start the process. It will either succeed and return a result containing
2039 // the PID of the new process, or else throw a RuntimeException.
2040 Process.ProcessStartResult startResult = Process.start("android.app.ActivityThread",
Elliott Hughese1dfcb72011-07-08 11:08:07 -07002041 app.processName, uid, uid, gids, debugFlags,
2042 app.info.targetSdkVersion, null);
Jeff Brown3f9dd282011-07-08 20:02:19 -07002043
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002044 BatteryStatsImpl bs = app.batteryStats.getBatteryStats();
2045 synchronized (bs) {
2046 if (bs.isOnBattery()) {
2047 app.batteryStats.incStartsLocked();
2048 }
2049 }
2050
Jeff Brown3f9dd282011-07-08 20:02:19 -07002051 EventLog.writeEvent(EventLogTags.AM_PROC_START, startResult.pid, uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002052 app.processName, hostingType,
2053 hostingNameStr != null ? hostingNameStr : "");
2054
2055 if (app.persistent) {
Jeff Brown3f9dd282011-07-08 20:02:19 -07002056 Watchdog.getInstance().processStarted(app.processName, startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002057 }
2058
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07002059 StringBuilder buf = mStringBuilder;
2060 buf.setLength(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002061 buf.append("Start proc ");
2062 buf.append(app.processName);
2063 buf.append(" for ");
2064 buf.append(hostingType);
2065 if (hostingNameStr != null) {
2066 buf.append(" ");
2067 buf.append(hostingNameStr);
2068 }
2069 buf.append(": pid=");
Jeff Brown3f9dd282011-07-08 20:02:19 -07002070 buf.append(startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002071 buf.append(" uid=");
2072 buf.append(uid);
2073 buf.append(" gids={");
2074 if (gids != null) {
2075 for (int gi=0; gi<gids.length; gi++) {
2076 if (gi != 0) buf.append(", ");
2077 buf.append(gids[gi]);
2078
2079 }
2080 }
2081 buf.append("}");
Joe Onorato8a9b2202010-02-26 18:56:32 -08002082 Slog.i(TAG, buf.toString());
Jeff Brown3f9dd282011-07-08 20:02:19 -07002083 app.pid = startResult.pid;
2084 app.usingWrapper = startResult.usingWrapper;
2085 app.removed = false;
2086 synchronized (mPidsSelfLocked) {
2087 this.mPidsSelfLocked.put(startResult.pid, app);
2088 Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
2089 msg.obj = app;
2090 mHandler.sendMessageDelayed(msg, startResult.usingWrapper
2091 ? PROC_START_TIMEOUT_WITH_WRAPPER : PROC_START_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002092 }
2093 } catch (RuntimeException e) {
2094 // XXX do better error recovery.
2095 app.pid = 0;
Joe Onorato8a9b2202010-02-26 18:56:32 -08002096 Slog.e(TAG, "Failure starting process " + app.processName, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002097 }
2098 }
2099
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002100 void updateUsageStats(ActivityRecord resumedComponent, boolean resumed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002101 if (resumed) {
2102 mUsageStatsService.noteResumeComponent(resumedComponent.realActivity);
2103 } else {
2104 mUsageStatsService.notePauseComponent(resumedComponent.realActivity);
2105 }
2106 }
2107
Amith Yamasani742a6712011-05-04 14:49:28 -07002108 boolean startHomeActivityLocked(int userId) {
Mike Lockwooda8f767a2011-08-31 14:32:37 -04002109 if (mHeadless) {
2110 // Added because none of the other calls to ensureBootCompleted seem to fire
2111 // when running headless.
2112 ensureBootCompleted();
2113 return false;
2114 }
2115
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002116 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2117 && mTopAction == null) {
2118 // We are running in factory test mode, but unable to find
2119 // the factory test app, so just sit around displaying the
2120 // error message and don't try to start anything.
2121 return false;
2122 }
2123 Intent intent = new Intent(
2124 mTopAction,
2125 mTopData != null ? Uri.parse(mTopData) : null);
2126 intent.setComponent(mTopComponent);
2127 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
2128 intent.addCategory(Intent.CATEGORY_HOME);
2129 }
2130 ActivityInfo aInfo =
2131 intent.resolveActivityInfo(mContext.getPackageManager(),
2132 STOCK_PM_FLAGS);
2133 if (aInfo != null) {
2134 intent.setComponent(new ComponentName(
2135 aInfo.applicationInfo.packageName, aInfo.name));
2136 // Don't do this if the home app is currently being
2137 // instrumented.
Amith Yamasani742a6712011-05-04 14:49:28 -07002138 aInfo = new ActivityInfo(aInfo);
2139 aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002140 ProcessRecord app = getProcessRecordLocked(aInfo.processName,
2141 aInfo.applicationInfo.uid);
2142 if (app == null || app.instrumentationClass == null) {
2143 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002144 mMainStack.startActivityLocked(null, intent, null, aInfo,
2145 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002146 }
2147 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002148
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002149 return true;
2150 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002151
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002152 /**
2153 * Starts the "new version setup screen" if appropriate.
2154 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002155 void startSetupActivityLocked() {
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002156 // Only do this once per boot.
2157 if (mCheckedForSetup) {
2158 return;
2159 }
2160
2161 // We will show this screen if the current one is a different
2162 // version than the last one shown, and we are not running in
2163 // low-level factory test mode.
2164 final ContentResolver resolver = mContext.getContentResolver();
2165 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL &&
2166 Settings.Secure.getInt(resolver,
2167 Settings.Secure.DEVICE_PROVISIONED, 0) != 0) {
2168 mCheckedForSetup = true;
2169
2170 // See if we should be showing the platform update setup UI.
2171 Intent intent = new Intent(Intent.ACTION_UPGRADE_SETUP);
2172 List<ResolveInfo> ris = mSelf.mContext.getPackageManager()
2173 .queryIntentActivities(intent, PackageManager.GET_META_DATA);
2174
2175 // We don't allow third party apps to replace this.
2176 ResolveInfo ri = null;
2177 for (int i=0; ris != null && i<ris.size(); i++) {
2178 if ((ris.get(i).activityInfo.applicationInfo.flags
2179 & ApplicationInfo.FLAG_SYSTEM) != 0) {
2180 ri = ris.get(i);
2181 break;
2182 }
2183 }
2184
2185 if (ri != null) {
2186 String vers = ri.activityInfo.metaData != null
2187 ? ri.activityInfo.metaData.getString(Intent.METADATA_SETUP_VERSION)
2188 : null;
2189 if (vers == null && ri.activityInfo.applicationInfo.metaData != null) {
2190 vers = ri.activityInfo.applicationInfo.metaData.getString(
2191 Intent.METADATA_SETUP_VERSION);
2192 }
2193 String lastVers = Settings.Secure.getString(
2194 resolver, Settings.Secure.LAST_SETUP_SHOWN);
2195 if (vers != null && !vers.equals(lastVers)) {
2196 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2197 intent.setComponent(new ComponentName(
2198 ri.activityInfo.packageName, ri.activityInfo.name));
Dianne Hackborna4972e92012-03-14 10:38:05 -07002199 mMainStack.startActivityLocked(null, intent, null, ri.activityInfo,
2200 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002201 }
2202 }
2203 }
2204 }
2205
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002206 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002207 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002208 }
2209
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002210 void enforceNotIsolatedCaller(String caller) {
2211 if (UserId.isIsolated(Binder.getCallingUid())) {
2212 throw new SecurityException("Isolated process not allowed to call " + caller);
2213 }
2214 }
2215
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002216 public int getFrontActivityScreenCompatMode() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002217 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002218 synchronized (this) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002219 return mCompatModePackages.getFrontActivityScreenCompatModeLocked();
2220 }
2221 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002222
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002223 public void setFrontActivityScreenCompatMode(int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002224 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2225 "setFrontActivityScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002226 synchronized (this) {
2227 mCompatModePackages.setFrontActivityScreenCompatModeLocked(mode);
2228 }
2229 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002230
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002231 public int getPackageScreenCompatMode(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002232 enforceNotIsolatedCaller("getPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002233 synchronized (this) {
2234 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
2235 }
2236 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002237
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002238 public void setPackageScreenCompatMode(String packageName, int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002239 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2240 "setPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002241 synchronized (this) {
2242 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002243 }
2244 }
2245
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002246 public boolean getPackageAskScreenCompat(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002247 enforceNotIsolatedCaller("getPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002248 synchronized (this) {
2249 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
2250 }
2251 }
2252
2253 public void setPackageAskScreenCompat(String packageName, boolean ask) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002254 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2255 "setPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002256 synchronized (this) {
2257 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
2258 }
2259 }
2260
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002261 void reportResumedActivityLocked(ActivityRecord r) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002262 //Slog.i(TAG, "**** REPORT RESUME: " + r);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002263
2264 final int identHash = System.identityHashCode(r);
2265 updateUsageStats(r, true);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002266 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002267
Jeff Sharkeya4620792011-05-20 15:29:23 -07002268 private void dispatchForegroundActivitiesChanged(int pid, int uid, boolean foregroundActivities) {
2269 int i = mProcessObservers.beginBroadcast();
2270 while (i > 0) {
2271 i--;
2272 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2273 if (observer != null) {
2274 try {
2275 observer.onForegroundActivitiesChanged(pid, uid, foregroundActivities);
2276 } catch (RemoteException e) {
2277 }
2278 }
2279 }
2280 mProcessObservers.finishBroadcast();
2281 }
2282
2283 private void dispatchProcessDied(int pid, int uid) {
2284 int i = mProcessObservers.beginBroadcast();
2285 while (i > 0) {
2286 i--;
2287 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2288 if (observer != null) {
2289 try {
2290 observer.onProcessDied(pid, uid);
2291 } catch (RemoteException e) {
2292 }
2293 }
2294 }
2295 mProcessObservers.finishBroadcast();
2296 }
2297
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002298 final void doPendingActivityLaunchesLocked(boolean doResume) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002299 final int N = mPendingActivityLaunches.size();
2300 if (N <= 0) {
2301 return;
2302 }
2303 for (int i=0; i<N; i++) {
2304 PendingActivityLaunch pal = mPendingActivityLaunches.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002305 mMainStack.startActivityUncheckedLocked(pal.r, pal.sourceRecord,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002306 pal.startFlags, doResume && i == (N-1), null);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002307 }
2308 mPendingActivityLaunches.clear();
2309 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002310
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002311 public final int startActivity(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002312 Intent intent, String resolvedType, IBinder resultTo,
2313 String resultWho, int requestCode, int startFlags,
2314 String profileFile, ParcelFileDescriptor profileFd, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002315 enforceNotIsolatedCaller("startActivity");
Amith Yamasani742a6712011-05-04 14:49:28 -07002316 int userId = 0;
2317 if (intent.getCategories() != null && intent.getCategories().contains(Intent.CATEGORY_HOME)) {
2318 // Requesting home, set the identity to the current user
2319 // HACK!
2320 userId = mCurrentUserId;
2321 } else {
2322 // TODO: Fix this in a better way - calls coming from SystemUI should probably carry
2323 // the current user's userId
2324 if (Binder.getCallingUid() < Process.FIRST_APPLICATION_UID) {
2325 userId = 0;
2326 } else {
2327 userId = Binder.getOrigCallingUser();
2328 }
2329 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002330 return mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002331 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
2332 null, null, options, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002333 }
2334
2335 public final WaitResult startActivityAndWait(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002336 Intent intent, String resolvedType, IBinder resultTo,
2337 String resultWho, int requestCode, int startFlags, String profileFile,
2338 ParcelFileDescriptor profileFd, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002339 enforceNotIsolatedCaller("startActivityAndWait");
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002340 WaitResult res = new WaitResult();
Amith Yamasani742a6712011-05-04 14:49:28 -07002341 int userId = Binder.getOrigCallingUser();
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002342 mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002343 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
2344 res, null, options, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002345 return res;
2346 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08002347
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002348 public final int startActivityWithConfig(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002349 Intent intent, String resolvedType, IBinder resultTo,
2350 String resultWho, int requestCode, int startFlags, Configuration config,
2351 Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002352 enforceNotIsolatedCaller("startActivityWithConfig");
Amith Yamasani742a6712011-05-04 14:49:28 -07002353 int ret = mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002354 resultTo, resultWho, requestCode, startFlags,
2355 null, null, null, config, options, Binder.getOrigCallingUser());
Amith Yamasani742a6712011-05-04 14:49:28 -07002356 return ret;
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002357 }
2358
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002359 public int startActivityIntentSender(IApplicationThread caller,
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002360 IntentSender intent, Intent fillInIntent, String resolvedType,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002361 IBinder resultTo, String resultWho, int requestCode,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002362 int flagsMask, int flagsValues, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002363 enforceNotIsolatedCaller("startActivityIntentSender");
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002364 // Refuse possible leaked file descriptors
2365 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
2366 throw new IllegalArgumentException("File descriptors passed in Intent");
2367 }
2368
2369 IIntentSender sender = intent.getTarget();
2370 if (!(sender instanceof PendingIntentRecord)) {
2371 throw new IllegalArgumentException("Bad PendingIntent object");
2372 }
2373
2374 PendingIntentRecord pir = (PendingIntentRecord)sender;
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002375
2376 synchronized (this) {
2377 // If this is coming from the currently resumed activity, it is
2378 // effectively saying that app switches are allowed at this point.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002379 if (mMainStack.mResumedActivity != null
2380 && mMainStack.mResumedActivity.info.applicationInfo.uid ==
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002381 Binder.getCallingUid()) {
2382 mAppSwitchesAllowedTime = 0;
2383 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002384 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002385 int ret = pir.sendInner(0, fillInIntent, resolvedType, null, null,
2386 resultTo, resultWho, requestCode, flagsMask, flagsValues, options);
Amith Yamasani742a6712011-05-04 14:49:28 -07002387 return ret;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002388 }
2389
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002390 public boolean startNextMatchingActivity(IBinder callingActivity,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002391 Intent intent, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002392 // Refuse possible leaked file descriptors
2393 if (intent != null && intent.hasFileDescriptors() == true) {
2394 throw new IllegalArgumentException("File descriptors passed in Intent");
2395 }
2396
2397 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002398 ActivityRecord r = mMainStack.isInStackLocked(callingActivity);
2399 if (r == null) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002400 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002401 return false;
2402 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002403 if (r.app == null || r.app.thread == null) {
2404 // The caller is not running... d'oh!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002405 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002406 return false;
2407 }
2408 intent = new Intent(intent);
2409 // The caller is not allowed to change the data.
2410 intent.setDataAndType(r.intent.getData(), r.intent.getType());
2411 // And we are resetting to find the next component...
2412 intent.setComponent(null);
2413
2414 ActivityInfo aInfo = null;
2415 try {
2416 List<ResolveInfo> resolves =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002417 AppGlobals.getPackageManager().queryIntentActivities(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002418 intent, r.resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002419 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
2420 UserId.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002421
2422 // Look for the original activity in the list...
2423 final int N = resolves != null ? resolves.size() : 0;
2424 for (int i=0; i<N; i++) {
2425 ResolveInfo rInfo = resolves.get(i);
2426 if (rInfo.activityInfo.packageName.equals(r.packageName)
2427 && rInfo.activityInfo.name.equals(r.info.name)) {
2428 // We found the current one... the next matching is
2429 // after it.
2430 i++;
2431 if (i<N) {
2432 aInfo = resolves.get(i).activityInfo;
2433 }
2434 break;
2435 }
2436 }
2437 } catch (RemoteException e) {
2438 }
2439
2440 if (aInfo == null) {
2441 // Nobody who is next!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002442 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002443 return false;
2444 }
2445
2446 intent.setComponent(new ComponentName(
2447 aInfo.applicationInfo.packageName, aInfo.name));
2448 intent.setFlags(intent.getFlags()&~(
2449 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
2450 Intent.FLAG_ACTIVITY_CLEAR_TOP|
2451 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
2452 Intent.FLAG_ACTIVITY_NEW_TASK));
2453
2454 // Okay now we need to start the new activity, replacing the
2455 // currently running activity. This is a little tricky because
2456 // we want to start the new one as if the current one is finished,
2457 // but not finish the current one first so that there is no flicker.
2458 // And thus...
2459 final boolean wasFinishing = r.finishing;
2460 r.finishing = true;
2461
2462 // Propagate reply information over to the new activity.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002463 final ActivityRecord resultTo = r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002464 final String resultWho = r.resultWho;
2465 final int requestCode = r.requestCode;
2466 r.resultTo = null;
2467 if (resultTo != null) {
2468 resultTo.removeResultsLocked(r, resultWho, requestCode);
2469 }
2470
2471 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002472 int res = mMainStack.startActivityLocked(r.app.thread, intent,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002473 r.resolvedType, aInfo, resultTo != null ? resultTo.appToken : null,
2474 resultWho, requestCode, -1, r.launchedFromUid, 0,
2475 options, false, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002476 Binder.restoreCallingIdentity(origId);
2477
2478 r.finishing = wasFinishing;
Dianne Hackborna4972e92012-03-14 10:38:05 -07002479 if (res != ActivityManager.START_SUCCESS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002480 return false;
2481 }
2482 return true;
2483 }
2484 }
2485
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002486 public final int startActivityInPackage(int uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002487 Intent intent, String resolvedType, IBinder resultTo,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002488 String resultWho, int requestCode, int startFlags, Bundle options) {
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002489
2490 // This is so super not safe, that only the system (or okay root)
2491 // can do it.
Amith Yamasani742a6712011-05-04 14:49:28 -07002492 int userId = Binder.getOrigCallingUser();
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002493 final int callingUid = Binder.getCallingUid();
2494 if (callingUid != 0 && callingUid != Process.myUid()) {
2495 throw new SecurityException(
2496 "startActivityInPackage only available to the system");
2497 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002498
Amith Yamasani742a6712011-05-04 14:49:28 -07002499 int ret = mMainStack.startActivityMayWait(null, uid, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002500 resultTo, resultWho, requestCode, startFlags,
2501 null, null, null, null, options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002502 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002503 }
2504
2505 public final int startActivities(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002506 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002507 enforceNotIsolatedCaller("startActivities");
Amith Yamasani742a6712011-05-04 14:49:28 -07002508 int ret = mMainStack.startActivities(caller, -1, intents, resolvedTypes, resultTo,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002509 options, Binder.getOrigCallingUser());
Amith Yamasani742a6712011-05-04 14:49:28 -07002510 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002511 }
2512
2513 public final int startActivitiesInPackage(int uid,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002514 Intent[] intents, String[] resolvedTypes, IBinder resultTo,
2515 Bundle options) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002516
2517 // This is so super not safe, that only the system (or okay root)
2518 // can do it.
2519 final int callingUid = Binder.getCallingUid();
2520 if (callingUid != 0 && callingUid != Process.myUid()) {
2521 throw new SecurityException(
2522 "startActivityInPackage only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002523 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002524 int ret = mMainStack.startActivities(null, uid, intents, resolvedTypes, resultTo,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002525 options, UserId.getUserId(uid));
Amith Yamasani742a6712011-05-04 14:49:28 -07002526 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002527 }
2528
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002529 final void addRecentTaskLocked(TaskRecord task) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002530 int N = mRecentTasks.size();
Dianne Hackborn7c0e75e2010-12-21 19:15:40 -08002531 // Quick case: check if the top-most recent task is the same.
2532 if (N > 0 && mRecentTasks.get(0) == task) {
2533 return;
2534 }
2535 // Remove any existing entries that are the same kind of task.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002536 for (int i=0; i<N; i++) {
2537 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07002538 if (task.userId == tr.userId
2539 && ((task.affinity != null && task.affinity.equals(tr.affinity))
2540 || (task.intent != null && task.intent.filterEquals(tr.intent)))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002541 mRecentTasks.remove(i);
2542 i--;
2543 N--;
2544 if (task.intent == null) {
2545 // If the new recent task we are adding is not fully
2546 // specified, then replace it with the existing recent task.
2547 task = tr;
2548 }
2549 }
2550 }
2551 if (N >= MAX_RECENT_TASKS) {
2552 mRecentTasks.remove(N-1);
2553 }
2554 mRecentTasks.add(0, task);
2555 }
2556
2557 public void setRequestedOrientation(IBinder token,
2558 int requestedOrientation) {
2559 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002560 ActivityRecord r = mMainStack.isInStackLocked(token);
2561 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002562 return;
2563 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002564 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornbe707852011-11-11 14:32:10 -08002565 mWindowManager.setAppOrientation(r.appToken, requestedOrientation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002566 Configuration config = mWindowManager.updateOrientationFromAppTokens(
The Android Open Source Project10592532009-03-18 17:39:46 -07002567 mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -08002568 r.mayFreezeScreenLocked(r.app) ? r.appToken : null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002569 if (config != null) {
2570 r.frozenBeforeDestroy = true;
Dianne Hackborn813075a62011-11-14 17:45:19 -08002571 if (!updateConfigurationLocked(config, r, false, false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002572 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002573 }
2574 }
2575 Binder.restoreCallingIdentity(origId);
2576 }
2577 }
2578
2579 public int getRequestedOrientation(IBinder token) {
2580 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002581 ActivityRecord r = mMainStack.isInStackLocked(token);
2582 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002583 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
2584 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08002585 return mWindowManager.getAppOrientation(r.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002586 }
2587 }
2588
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002589 /**
2590 * This is the internal entry point for handling Activity.finish().
2591 *
2592 * @param token The Binder token referencing the Activity we want to finish.
2593 * @param resultCode Result code, if any, from this Activity.
2594 * @param resultData Result data (Intent), if any, from this Activity.
2595 *
Alexey Tarasov83bad3d2009-08-12 15:05:43 +11002596 * @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 -08002597 */
2598 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData) {
2599 // Refuse possible leaked file descriptors
2600 if (resultData != null && resultData.hasFileDescriptors() == true) {
2601 throw new IllegalArgumentException("File descriptors passed in Intent");
2602 }
2603
2604 synchronized(this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002605 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002606 // Find the first activity that is not finishing.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002607 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002608 if (next != null) {
2609 // ask watcher if this is allowed
2610 boolean resumeOK = true;
2611 try {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002612 resumeOK = mController.activityResuming(next.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002613 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002614 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002615 }
2616
2617 if (!resumeOK) {
2618 return false;
2619 }
2620 }
2621 }
2622 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002623 boolean res = mMainStack.requestFinishActivityLocked(token, resultCode,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002624 resultData, "app-request");
2625 Binder.restoreCallingIdentity(origId);
2626 return res;
2627 }
2628 }
2629
Dianne Hackborn860755f2010-06-03 18:47:52 -07002630 public final void finishHeavyWeightApp() {
2631 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2632 != PackageManager.PERMISSION_GRANTED) {
2633 String msg = "Permission Denial: finishHeavyWeightApp() from pid="
2634 + Binder.getCallingPid()
2635 + ", uid=" + Binder.getCallingUid()
2636 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2637 Slog.w(TAG, msg);
2638 throw new SecurityException(msg);
2639 }
2640
2641 synchronized(this) {
2642 if (mHeavyWeightProcess == null) {
2643 return;
2644 }
2645
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002646 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>(
Dianne Hackborn860755f2010-06-03 18:47:52 -07002647 mHeavyWeightProcess.activities);
2648 for (int i=0; i<activities.size(); i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002649 ActivityRecord r = activities.get(i);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002650 if (!r.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002651 int index = mMainStack.indexOfTokenLocked(r.appToken);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002652 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002653 mMainStack.finishActivityLocked(r, index, Activity.RESULT_CANCELED,
Dianne Hackborn860755f2010-06-03 18:47:52 -07002654 null, "finish-heavy");
2655 }
2656 }
2657 }
2658
2659 mHeavyWeightProcess = null;
2660 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
2661 }
2662 }
2663
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002664 public void crashApplication(int uid, int initialPid, String packageName,
2665 String message) {
2666 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2667 != PackageManager.PERMISSION_GRANTED) {
2668 String msg = "Permission Denial: crashApplication() from pid="
2669 + Binder.getCallingPid()
2670 + ", uid=" + Binder.getCallingUid()
2671 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2672 Slog.w(TAG, msg);
2673 throw new SecurityException(msg);
2674 }
2675
2676 synchronized(this) {
2677 ProcessRecord proc = null;
2678
2679 // Figure out which process to kill. We don't trust that initialPid
2680 // still has any relation to current pids, so must scan through the
2681 // list.
2682 synchronized (mPidsSelfLocked) {
2683 for (int i=0; i<mPidsSelfLocked.size(); i++) {
2684 ProcessRecord p = mPidsSelfLocked.valueAt(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002685 if (p.uid != uid) {
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002686 continue;
2687 }
2688 if (p.pid == initialPid) {
2689 proc = p;
2690 break;
2691 }
2692 for (String str : p.pkgList) {
2693 if (str.equals(packageName)) {
2694 proc = p;
2695 }
2696 }
2697 }
2698 }
2699
2700 if (proc == null) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07002701 Slog.w(TAG, "crashApplication: nothing for uid=" + uid
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002702 + " initialPid=" + initialPid
2703 + " packageName=" + packageName);
2704 return;
2705 }
2706
2707 if (proc.thread != null) {
Dianne Hackborn9f531192010-08-04 17:48:03 -07002708 if (proc.pid == Process.myPid()) {
2709 Log.w(TAG, "crashApplication: trying to crash self!");
2710 return;
2711 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002712 long ident = Binder.clearCallingIdentity();
2713 try {
2714 proc.thread.scheduleCrash(message);
2715 } catch (RemoteException e) {
2716 }
2717 Binder.restoreCallingIdentity(ident);
2718 }
2719 }
2720 }
2721
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002722 public final void finishSubActivity(IBinder token, String resultWho,
2723 int requestCode) {
2724 synchronized(this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002725 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07002726 mMainStack.finishSubActivityLocked(token, resultWho, requestCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002727 Binder.restoreCallingIdentity(origId);
2728 }
2729 }
2730
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07002731 public boolean finishActivityAffinity(IBinder token) {
2732 synchronized(this) {
2733 final long origId = Binder.clearCallingIdentity();
2734 boolean res = mMainStack.finishActivityAffinityLocked(token);
2735 Binder.restoreCallingIdentity(origId);
2736 return res;
2737 }
2738 }
2739
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002740 public boolean willActivityBeVisible(IBinder token) {
2741 synchronized(this) {
2742 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002743 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2744 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08002745 if (r.appToken == token) {
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002746 return true;
2747 }
2748 if (r.fullscreen && !r.finishing) {
2749 return false;
2750 }
2751 }
2752 return true;
2753 }
2754 }
2755
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002756 public void overridePendingTransition(IBinder token, String packageName,
2757 int enterAnim, int exitAnim) {
2758 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002759 ActivityRecord self = mMainStack.isInStackLocked(token);
2760 if (self == null) {
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002761 return;
2762 }
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002763
2764 final long origId = Binder.clearCallingIdentity();
2765
2766 if (self.state == ActivityState.RESUMED
2767 || self.state == ActivityState.PAUSING) {
2768 mWindowManager.overridePendingAppTransition(packageName,
2769 enterAnim, exitAnim);
2770 }
2771
2772 Binder.restoreCallingIdentity(origId);
2773 }
2774 }
2775
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002776 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002777 * Main function for removing an existing process from the activity manager
2778 * as a result of that process going away. Clears out all connections
2779 * to the process.
2780 */
2781 private final void handleAppDiedLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002782 boolean restarting, boolean allowRestart) {
2783 cleanUpApplicationRecordLocked(app, restarting, allowRestart, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002784 if (!restarting) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002785 mLruProcesses.remove(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002786 }
2787
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002788 if (mProfileProc == app) {
2789 clearProfilerLocked();
2790 }
2791
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002792 // Just in case...
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002793 if (mMainStack.mPausingActivity != null && mMainStack.mPausingActivity.app == app) {
2794 if (DEBUG_PAUSE) Slog.v(TAG, "App died while pausing: " +mMainStack.mPausingActivity);
2795 mMainStack.mPausingActivity = null;
2796 }
2797 if (mMainStack.mLastPausedActivity != null && mMainStack.mLastPausedActivity.app == app) {
2798 mMainStack.mLastPausedActivity = null;
2799 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002800
2801 // Remove this application's activities from active lists.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002802 mMainStack.removeHistoryRecordsForAppLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002803
2804 boolean atTop = true;
2805 boolean hasVisibleActivities = false;
2806
2807 // Clean out the history list.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002808 int i = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08002809 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002810 TAG, "Removing app " + app + " from history with " + i + " entries");
2811 while (i > 0) {
2812 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002813 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002814 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002815 TAG, "Record #" + i + " " + r + ": app=" + r.app);
2816 if (r.app == app) {
2817 if ((!r.haveState && !r.stateNotNeeded) || r.finishing) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002818 if (ActivityStack.DEBUG_ADD_REMOVE) {
2819 RuntimeException here = new RuntimeException("here");
2820 here.fillInStackTrace();
2821 Slog.i(TAG, "Removing activity " + r + " from stack at " + i
2822 + ": haveState=" + r.haveState
2823 + " stateNotNeeded=" + r.stateNotNeeded
2824 + " finishing=" + r.finishing
2825 + " state=" + r.state, here);
2826 }
2827 if (!r.finishing) {
2828 Slog.w(TAG, "Force removing " + r + ": app died, no saved state");
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -08002829 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
2830 System.identityHashCode(r),
2831 r.task.taskId, r.shortComponentName,
2832 "proc died without state saved");
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002833 }
Dianne Hackborn5c607432012-02-28 14:44:19 -08002834 mMainStack.removeActivityFromHistoryLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002835
2836 } else {
2837 // We have the current state for this activity, so
2838 // it can be restarted later when needed.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002839 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002840 TAG, "Keeping entry, setting app to null");
2841 if (r.visible) {
2842 hasVisibleActivities = true;
2843 }
2844 r.app = null;
2845 r.nowVisible = false;
2846 if (!r.haveState) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002847 if (ActivityStack.DEBUG_SAVED_STATE) Slog.i(TAG,
2848 "App died, clearing saved state of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002849 r.icicle = null;
2850 }
2851 }
2852
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002853 r.stack.cleanUpActivityLocked(r, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002854 }
2855 atTop = false;
2856 }
2857
2858 app.activities.clear();
2859
2860 if (app.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002861 Slog.w(TAG, "Crash of app " + app.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002862 + " running instrumentation " + app.instrumentationClass);
2863 Bundle info = new Bundle();
2864 info.putString("shortMsg", "Process crashed.");
2865 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
2866 }
2867
2868 if (!restarting) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002869 if (!mMainStack.resumeTopActivityLocked(null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002870 // If there was nothing to resume, and we are not already
2871 // restarting this process, but there is a visible activity that
2872 // is hosted by the process... then make sure all visible
2873 // activities are running, taking care of restarting this
2874 // process.
2875 if (hasVisibleActivities) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002876 mMainStack.ensureActivitiesVisibleLocked(null, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002877 }
2878 }
2879 }
2880 }
2881
2882 private final int getLRURecordIndexForAppLocked(IApplicationThread thread) {
2883 IBinder threadBinder = thread.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002884 // Find the application record.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002885 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2886 ProcessRecord rec = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002887 if (rec.thread != null && rec.thread.asBinder() == threadBinder) {
2888 return i;
2889 }
2890 }
2891 return -1;
2892 }
2893
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002894 final ProcessRecord getRecordForAppLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002895 IApplicationThread thread) {
2896 if (thread == null) {
2897 return null;
2898 }
2899
2900 int appIndex = getLRURecordIndexForAppLocked(thread);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002901 return appIndex >= 0 ? mLruProcesses.get(appIndex) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002902 }
2903
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002904 final void appDiedLocked(ProcessRecord app, int pid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002905 IApplicationThread thread) {
2906
2907 mProcDeaths[0]++;
2908
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002909 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
2910 synchronized (stats) {
2911 stats.noteProcessDiedLocked(app.info.uid, pid);
2912 }
2913
Magnus Edlund7bb25812010-02-24 15:45:06 +01002914 // Clean up already done if the process has been re-started.
2915 if (app.pid == pid && app.thread != null &&
2916 app.thread.asBinder() == thread.asBinder()) {
Dianne Hackborn906497c2010-05-10 15:57:38 -07002917 if (!app.killedBackground) {
2918 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
2919 + ") has died.");
2920 }
Doug Zongker2bec3d42009-12-04 12:52:44 -08002921 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002922 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002923 TAG, "Dying app: " + app + ", pid: " + pid
2924 + ", thread: " + thread.asBinder());
2925 boolean doLowMem = app.instrumentationClass == null;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002926 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002927
2928 if (doLowMem) {
2929 // If there are no longer any background processes running,
2930 // and the app that died was not running instrumentation,
2931 // then tell everyone we are now low on memory.
2932 boolean haveBg = false;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002933 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2934 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -07002935 if (rec.thread != null && rec.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002936 haveBg = true;
2937 break;
2938 }
2939 }
2940
2941 if (!haveBg) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002942 EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mLruProcesses.size());
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002943 long now = SystemClock.uptimeMillis();
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002944 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2945 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn36124872009-10-08 16:22:03 -07002946 if (rec != app && rec.thread != null &&
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002947 (rec.lastLowMemory+GC_MIN_INTERVAL) <= now) {
2948 // The low memory report is overriding any current
2949 // state for a GC request. Make sure to do
Dianne Hackborn32907cf2010-06-10 17:50:20 -07002950 // heavy/important/visible/foreground processes first.
Dianne Hackborn7d608422011-08-07 16:24:18 -07002951 if (rec.setAdj <= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002952 rec.lastRequestedGc = 0;
2953 } else {
2954 rec.lastRequestedGc = rec.lastLowMemory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002955 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002956 rec.reportLowMemory = true;
2957 rec.lastLowMemory = now;
2958 mProcessesToGc.remove(rec);
2959 addProcessToGcListLocked(rec);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002960 }
2961 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07002962 mHandler.sendEmptyMessage(REPORT_MEM_USAGE);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002963 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002964 }
2965 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01002966 } else if (app.pid != pid) {
2967 // A new process has already been started.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002968 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
Magnus Edlund7bb25812010-02-24 15:45:06 +01002969 + ") has died and restarted (pid " + app.pid + ").");
Dianne Hackborn28a8c2b2010-03-01 11:30:02 -08002970 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08002971 } else if (DEBUG_PROCESSES) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002972 Slog.d(TAG, "Received spurious death notification for thread "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002973 + thread.asBinder());
2974 }
2975 }
2976
Dan Egnor42471dd2010-01-07 17:25:22 -08002977 /**
2978 * If a stack trace dump file is configured, dump process stack traces.
Christopher Tate6ee412d2010-05-28 12:01:56 -07002979 * @param clearTraces causes the dump file to be erased prior to the new
2980 * traces being written, if true; when false, the new traces will be
2981 * appended to any existing file content.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002982 * @param firstPids of dalvik VM processes to dump stack traces for first
2983 * @param lastPids of dalvik VM processes to dump stack traces for last
Dan Egnor42471dd2010-01-07 17:25:22 -08002984 * @return file containing stack traces, or null if no dump file is configured
2985 */
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002986 public static File dumpStackTraces(boolean clearTraces, ArrayList<Integer> firstPids,
2987 ProcessStats processStats, SparseArray<Boolean> lastPids) {
Dan Egnor42471dd2010-01-07 17:25:22 -08002988 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
2989 if (tracesPath == null || tracesPath.length() == 0) {
2990 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002991 }
Dan Egnor42471dd2010-01-07 17:25:22 -08002992
2993 File tracesFile = new File(tracesPath);
2994 try {
2995 File tracesDir = tracesFile.getParentFile();
2996 if (!tracesDir.exists()) tracesFile.mkdirs();
2997 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
2998
Christopher Tate6ee412d2010-05-28 12:01:56 -07002999 if (clearTraces && tracesFile.exists()) tracesFile.delete();
Dan Egnor42471dd2010-01-07 17:25:22 -08003000 tracesFile.createNewFile();
3001 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
3002 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003003 Slog.w(TAG, "Unable to prepare ANR traces file: " + tracesPath, e);
Dan Egnor42471dd2010-01-07 17:25:22 -08003004 return null;
3005 }
3006
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003007 dumpStackTraces(tracesPath, firstPids, processStats, lastPids);
3008 return tracesFile;
3009 }
3010
3011 private static void dumpStackTraces(String tracesPath, ArrayList<Integer> firstPids,
3012 ProcessStats processStats, SparseArray<Boolean> lastPids) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003013 // Use a FileObserver to detect when traces finish writing.
3014 // The order of traces is considered important to maintain for legibility.
3015 FileObserver observer = new FileObserver(tracesPath, FileObserver.CLOSE_WRITE) {
3016 public synchronized void onEvent(int event, String path) { notify(); }
3017 };
3018
3019 try {
3020 observer.startWatching();
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003021
3022 // First collect all of the stacks of the most important pids.
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003023 if (firstPids != null) {
3024 try {
3025 int num = firstPids.size();
3026 for (int i = 0; i < num; i++) {
3027 synchronized (observer) {
3028 Process.sendSignal(firstPids.get(i), Process.SIGNAL_QUIT);
3029 observer.wait(200); // Wait for write-close, give up after 200msec
3030 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003031 }
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003032 } catch (InterruptedException e) {
3033 Log.wtf(TAG, e);
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003034 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003035 }
3036
3037 // Next measure CPU usage.
3038 if (processStats != null) {
3039 processStats.init();
3040 System.gc();
3041 processStats.update();
3042 try {
3043 synchronized (processStats) {
3044 processStats.wait(500); // measure over 1/2 second.
3045 }
3046 } catch (InterruptedException e) {
3047 }
3048 processStats.update();
3049
3050 // We'll take the stack crawls of just the top apps using CPU.
3051 final int N = processStats.countWorkingStats();
3052 int numProcs = 0;
3053 for (int i=0; i<N && numProcs<5; i++) {
3054 ProcessStats.Stats stats = processStats.getWorkingStats(i);
3055 if (lastPids.indexOfKey(stats.pid) >= 0) {
3056 numProcs++;
3057 try {
3058 synchronized (observer) {
3059 Process.sendSignal(stats.pid, Process.SIGNAL_QUIT);
3060 observer.wait(200); // Wait for write-close, give up after 200msec
3061 }
3062 } catch (InterruptedException e) {
3063 Log.wtf(TAG, e);
3064 }
3065
3066 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003067 }
3068 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003069
Dan Egnor42471dd2010-01-07 17:25:22 -08003070 } finally {
3071 observer.stopWatching();
3072 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003073 }
3074
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003075 final void logAppTooSlow(ProcessRecord app, long startTime, String msg) {
Dianne Hackborn69dc66e2012-03-26 10:50:54 -07003076 if (true || IS_USER_BUILD) {
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003077 return;
3078 }
3079 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
3080 if (tracesPath == null || tracesPath.length() == 0) {
3081 return;
3082 }
3083
3084 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
3085 StrictMode.allowThreadDiskWrites();
3086 try {
3087 final File tracesFile = new File(tracesPath);
3088 final File tracesDir = tracesFile.getParentFile();
3089 final File tracesTmp = new File(tracesDir, "__tmp__");
3090 try {
3091 if (!tracesDir.exists()) tracesFile.mkdirs();
3092 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
3093
3094 if (tracesFile.exists()) {
3095 tracesTmp.delete();
3096 tracesFile.renameTo(tracesTmp);
3097 }
3098 StringBuilder sb = new StringBuilder();
3099 Time tobj = new Time();
3100 tobj.set(System.currentTimeMillis());
3101 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
3102 sb.append(": ");
3103 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
3104 sb.append(" since ");
3105 sb.append(msg);
3106 FileOutputStream fos = new FileOutputStream(tracesFile);
3107 fos.write(sb.toString().getBytes());
3108 if (app == null) {
3109 fos.write("\n*** No application process!".getBytes());
3110 }
3111 fos.close();
3112 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
3113 } catch (IOException e) {
3114 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesPath, e);
3115 return;
3116 }
3117
3118 if (app != null) {
3119 ArrayList<Integer> firstPids = new ArrayList<Integer>();
3120 firstPids.add(app.pid);
3121 dumpStackTraces(tracesPath, firstPids, null, null);
3122 }
3123
3124 File lastTracesFile = null;
3125 File curTracesFile = null;
3126 for (int i=9; i>=0; i--) {
3127 String name = String.format("slow%02d.txt", i);
3128 curTracesFile = new File(tracesDir, name);
3129 if (curTracesFile.exists()) {
3130 if (lastTracesFile != null) {
3131 curTracesFile.renameTo(lastTracesFile);
3132 } else {
3133 curTracesFile.delete();
3134 }
3135 }
3136 lastTracesFile = curTracesFile;
3137 }
3138 tracesFile.renameTo(curTracesFile);
3139 if (tracesTmp.exists()) {
3140 tracesTmp.renameTo(tracesFile);
3141 }
3142 } finally {
3143 StrictMode.setThreadPolicy(oldPolicy);
3144 }
3145 }
3146
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003147 final void appNotResponding(ProcessRecord app, ActivityRecord activity,
3148 ActivityRecord parent, final String annotation) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003149 ArrayList<Integer> firstPids = new ArrayList<Integer>(5);
3150 SparseArray<Boolean> lastPids = new SparseArray<Boolean>(20);
3151
Dianne Hackborn287952c2010-09-22 22:34:31 -07003152 if (mController != null) {
3153 try {
3154 // 0 == continue, -1 = kill process immediately
3155 int res = mController.appEarlyNotResponding(app.processName, app.pid, annotation);
3156 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3157 } catch (RemoteException e) {
3158 mController = null;
3159 }
3160 }
3161
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003162 long anrTime = SystemClock.uptimeMillis();
3163 if (MONITOR_CPU_USAGE) {
3164 updateCpuStatsNow();
3165 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003166
3167 synchronized (this) {
3168 // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down.
3169 if (mShuttingDown) {
3170 Slog.i(TAG, "During shutdown skipping ANR: " + app + " " + annotation);
3171 return;
3172 } else if (app.notResponding) {
3173 Slog.i(TAG, "Skipping duplicate ANR: " + app + " " + annotation);
3174 return;
3175 } else if (app.crashing) {
3176 Slog.i(TAG, "Crashing app skipping ANR: " + app + " " + annotation);
3177 return;
3178 }
3179
3180 // In case we come through here for the same app before completing
3181 // this one, mark as anring now so we will bail out.
3182 app.notResponding = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08003183
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003184 // Log the ANR to the event log.
3185 EventLog.writeEvent(EventLogTags.AM_ANR, app.pid, app.processName, app.info.flags,
3186 annotation);
Dan Egnor42471dd2010-01-07 17:25:22 -08003187
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003188 // Dump thread traces as quickly as we can, starting with "interesting" processes.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003189 firstPids.add(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003190
3191 int parentPid = app.pid;
3192 if (parent != null && parent.app != null && parent.app.pid > 0) parentPid = parent.app.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003193 if (parentPid != app.pid) firstPids.add(parentPid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003194
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003195 if (MY_PID != app.pid && MY_PID != parentPid) firstPids.add(MY_PID);
Dan Egnor42471dd2010-01-07 17:25:22 -08003196
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003197 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
3198 ProcessRecord r = mLruProcesses.get(i);
3199 if (r != null && r.thread != null) {
3200 int pid = r.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003201 if (pid > 0 && pid != app.pid && pid != parentPid && pid != MY_PID) {
3202 if (r.persistent) {
3203 firstPids.add(pid);
3204 } else {
3205 lastPids.put(pid, Boolean.TRUE);
3206 }
3207 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003208 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003209 }
3210 }
3211
Dan Egnor42471dd2010-01-07 17:25:22 -08003212 // Log the ANR to the main log.
Jeff Browndeb6ed82012-04-10 14:26:26 -07003213 StringBuilder info = new StringBuilder();
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07003214 info.setLength(0);
Dan Egnor42471dd2010-01-07 17:25:22 -08003215 info.append("ANR in ").append(app.processName);
3216 if (activity != null && activity.shortComponentName != null) {
3217 info.append(" (").append(activity.shortComponentName).append(")");
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07003218 }
Eric Rowe6f4f6192010-02-17 18:29:04 -08003219 info.append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003220 if (annotation != null) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003221 info.append("Reason: ").append(annotation).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003222 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003223 if (parent != null && parent != activity) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003224 info.append("Parent: ").append(parent.shortComponentName).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003225 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003226
Dianne Hackborn287952c2010-09-22 22:34:31 -07003227 final ProcessStats processStats = new ProcessStats(true);
3228
3229 File tracesFile = dumpStackTraces(true, firstPids, processStats, lastPids);
3230
Dan Egnor42471dd2010-01-07 17:25:22 -08003231 String cpuInfo = null;
3232 if (MONITOR_CPU_USAGE) {
3233 updateCpuStatsNow();
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003234 synchronized (mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003235 cpuInfo = mProcessStats.printCurrentState(anrTime);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003236 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003237 info.append(processStats.printCurrentLoad());
Dan Egnor42471dd2010-01-07 17:25:22 -08003238 info.append(cpuInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003239 }
3240
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003241 info.append(processStats.printCurrentState(anrTime));
3242
Joe Onorato8a9b2202010-02-26 18:56:32 -08003243 Slog.e(TAG, info.toString());
Dan Egnor42471dd2010-01-07 17:25:22 -08003244 if (tracesFile == null) {
3245 // There is no trace file, so dump (only) the alleged culprit's threads to the log
3246 Process.sendSignal(app.pid, Process.SIGNAL_QUIT);
3247 }
3248
Jeff Sharkeya353d262011-10-28 11:12:06 -07003249 addErrorToDropBox("anr", app, app.processName, activity, parent, annotation,
3250 cpuInfo, tracesFile, null);
Dan Egnor42471dd2010-01-07 17:25:22 -08003251
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003252 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003253 try {
Dan Egnor42471dd2010-01-07 17:25:22 -08003254 // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately
3255 int res = mController.appNotResponding(app.processName, app.pid, info.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003256 if (res != 0) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003257 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3258 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003259 }
3260 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003261 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003262 }
3263 }
3264
Dan Egnor42471dd2010-01-07 17:25:22 -08003265 // Unless configured otherwise, swallow ANRs in background processes & kill the process.
3266 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
3267 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003268
3269 synchronized (this) {
3270 if (!showBackground && !app.isInterestingToUserLocked() && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003271 Slog.w(TAG, "Killing " + app + ": background ANR");
3272 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
3273 app.processName, app.setAdj, "background ANR");
3274 Process.killProcessQuiet(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003275 return;
3276 }
3277
3278 // Set the app's notResponding state, and look up the errorReportReceiver
3279 makeAppNotRespondingLocked(app,
3280 activity != null ? activity.shortComponentName : null,
3281 annotation != null ? "ANR " + annotation : "ANR",
3282 info.toString());
3283
3284 // Bring up the infamous App Not Responding dialog
3285 Message msg = Message.obtain();
3286 HashMap map = new HashMap();
3287 msg.what = SHOW_NOT_RESPONDING_MSG;
3288 msg.obj = map;
3289 map.put("app", app);
3290 if (activity != null) {
3291 map.put("activity", activity);
3292 }
3293
3294 mHandler.sendMessage(msg);
Dan Egnor42471dd2010-01-07 17:25:22 -08003295 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003296 }
3297
Dianne Hackborn0dad3642010-09-09 21:25:35 -07003298 final void showLaunchWarningLocked(final ActivityRecord cur, final ActivityRecord next) {
3299 if (!mLaunchWarningShown) {
3300 mLaunchWarningShown = true;
3301 mHandler.post(new Runnable() {
3302 @Override
3303 public void run() {
3304 synchronized (ActivityManagerService.this) {
3305 final Dialog d = new LaunchWarningWindow(mContext, cur, next);
3306 d.show();
3307 mHandler.postDelayed(new Runnable() {
3308 @Override
3309 public void run() {
3310 synchronized (ActivityManagerService.this) {
3311 d.dismiss();
3312 mLaunchWarningShown = false;
3313 }
3314 }
3315 }, 4000);
3316 }
3317 }
3318 });
3319 }
3320 }
3321
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003322 public boolean clearApplicationUserData(final String packageName,
Amith Yamasani742a6712011-05-04 14:49:28 -07003323 final IPackageDataObserver observer, final int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003324 enforceNotIsolatedCaller("clearApplicationUserData");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003325 int uid = Binder.getCallingUid();
3326 int pid = Binder.getCallingPid();
3327 long callingId = Binder.clearCallingIdentity();
3328 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003329 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003330 int pkgUid = -1;
3331 synchronized(this) {
3332 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003333 pkgUid = pm.getPackageUid(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003334 } catch (RemoteException e) {
3335 }
3336 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003337 Slog.w(TAG, "Invalid packageName:" + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003338 return false;
3339 }
3340 if (uid == pkgUid || checkComponentPermission(
3341 android.Manifest.permission.CLEAR_APP_USER_DATA,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08003342 pid, uid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003343 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003344 forceStopPackageLocked(packageName, pkgUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003345 } else {
3346 throw new SecurityException(pid+" does not have permission:"+
3347 android.Manifest.permission.CLEAR_APP_USER_DATA+" to clear data" +
3348 "for process:"+packageName);
3349 }
3350 }
3351
3352 try {
3353 //clear application user data
Amith Yamasani483f3b02012-03-13 16:08:00 -07003354 pm.clearApplicationUserData(packageName, observer, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003355 Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED,
3356 Uri.fromParts("package", packageName, null));
3357 intent.putExtra(Intent.EXTRA_UID, pkgUid);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003358 broadcastIntentInPackage("android", Process.SYSTEM_UID, intent,
Amith Yamasani742a6712011-05-04 14:49:28 -07003359 null, null, 0, null, null, null, false, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003360 } catch (RemoteException e) {
3361 }
3362 } finally {
3363 Binder.restoreCallingIdentity(callingId);
3364 }
3365 return true;
3366 }
3367
Dianne Hackborn03abb812010-01-04 18:43:19 -08003368 public void killBackgroundProcesses(final String packageName) {
3369 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3370 != PackageManager.PERMISSION_GRANTED &&
3371 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES)
3372 != PackageManager.PERMISSION_GRANTED) {
3373 String msg = "Permission Denial: killBackgroundProcesses() from pid="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003374 + Binder.getCallingPid()
3375 + ", uid=" + Binder.getCallingUid()
Dianne Hackborn03abb812010-01-04 18:43:19 -08003376 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003377 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003378 throw new SecurityException(msg);
3379 }
3380
Amith Yamasani483f3b02012-03-13 16:08:00 -07003381 int userId = UserId.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003382 long callingId = Binder.clearCallingIdentity();
3383 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003384 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003385 int pkgUid = -1;
3386 synchronized(this) {
3387 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003388 pkgUid = pm.getPackageUid(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003389 } catch (RemoteException e) {
3390 }
3391 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003392 Slog.w(TAG, "Invalid packageName: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003393 return;
3394 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003395 killPackageProcessesLocked(packageName, pkgUid,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003396 ProcessList.SERVICE_ADJ, false, true, true, false, "kill background");
3397 }
3398 } finally {
3399 Binder.restoreCallingIdentity(callingId);
3400 }
3401 }
3402
3403 public void killAllBackgroundProcesses() {
3404 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3405 != PackageManager.PERMISSION_GRANTED) {
3406 String msg = "Permission Denial: killAllBackgroundProcesses() from pid="
3407 + Binder.getCallingPid()
3408 + ", uid=" + Binder.getCallingUid()
3409 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
3410 Slog.w(TAG, msg);
3411 throw new SecurityException(msg);
3412 }
3413
3414 long callingId = Binder.clearCallingIdentity();
3415 try {
3416 synchronized(this) {
3417 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
3418 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3419 final int NA = apps.size();
3420 for (int ia=0; ia<NA; ia++) {
3421 ProcessRecord app = apps.valueAt(ia);
3422 if (app.persistent) {
3423 // we don't kill persistent processes
3424 continue;
3425 }
3426 if (app.removed) {
3427 procs.add(app);
3428 } else if (app.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
3429 app.removed = true;
3430 procs.add(app);
3431 }
3432 }
3433 }
3434
3435 int N = procs.size();
3436 for (int i=0; i<N; i++) {
3437 removeProcessLocked(procs.get(i), false, true, "kill all background");
3438 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003439 }
3440 } finally {
3441 Binder.restoreCallingIdentity(callingId);
3442 }
3443 }
3444
3445 public void forceStopPackage(final String packageName) {
3446 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3447 != PackageManager.PERMISSION_GRANTED) {
3448 String msg = "Permission Denial: forceStopPackage() from pid="
3449 + Binder.getCallingPid()
3450 + ", uid=" + Binder.getCallingUid()
3451 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003452 Slog.w(TAG, msg);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003453 throw new SecurityException(msg);
3454 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07003455 final int userId = UserId.getCallingUserId();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003456 long callingId = Binder.clearCallingIdentity();
3457 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003458 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003459 int pkgUid = -1;
3460 synchronized(this) {
3461 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003462 pkgUid = pm.getPackageUid(packageName, userId);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003463 } catch (RemoteException e) {
3464 }
3465 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003466 Slog.w(TAG, "Invalid packageName: " + packageName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003467 return;
3468 }
3469 forceStopPackageLocked(packageName, pkgUid);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003470 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003471 pm.setPackageStoppedState(packageName, true, userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003472 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08003473 } catch (IllegalArgumentException e) {
3474 Slog.w(TAG, "Failed trying to unstop package "
3475 + packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003476 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003477 }
3478 } finally {
3479 Binder.restoreCallingIdentity(callingId);
3480 }
3481 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003482
3483 /*
3484 * The pkg name and uid have to be specified.
3485 * @see android.app.IActivityManager#killApplicationWithUid(java.lang.String, int)
3486 */
3487 public void killApplicationWithUid(String pkg, int uid) {
3488 if (pkg == null) {
3489 return;
3490 }
3491 // Make sure the uid is valid.
3492 if (uid < 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003493 Slog.w(TAG, "Invalid uid specified for pkg : " + pkg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003494 return;
3495 }
3496 int callerUid = Binder.getCallingUid();
3497 // Only the system server can kill an application
3498 if (callerUid == Process.SYSTEM_UID) {
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07003499 // Post an aysnc message to kill the application
3500 Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG);
3501 msg.arg1 = uid;
3502 msg.arg2 = 0;
3503 msg.obj = pkg;
Suchi Amalapurapud50066f2009-08-18 16:57:41 -07003504 mHandler.sendMessage(msg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003505 } else {
3506 throw new SecurityException(callerUid + " cannot kill pkg: " +
3507 pkg);
3508 }
3509 }
3510
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003511 public void closeSystemDialogs(String reason) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003512 enforceNotIsolatedCaller("closeSystemDialogs");
Dianne Hackborne302a162012-05-15 14:58:32 -07003513
3514 final int uid = Binder.getCallingUid();
3515 final long origId = Binder.clearCallingIdentity();
3516 synchronized (this) {
3517 closeSystemDialogsLocked(uid, reason);
3518 }
3519 Binder.restoreCallingIdentity(origId);
3520 }
3521
3522 void closeSystemDialogsLocked(int callingUid, String reason) {
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003523 Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003524 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003525 if (reason != null) {
3526 intent.putExtra("reason", reason);
3527 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003528 mWindowManager.closeSystemDialogs(reason);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003529
Dianne Hackborne302a162012-05-15 14:58:32 -07003530 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
3531 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
3532 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) {
3533 r.stack.finishActivityLocked(r, i,
3534 Activity.RESULT_CANCELED, null, "close-sys");
Dianne Hackbornffa42482009-09-23 22:20:11 -07003535 }
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003536 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003537
3538 broadcastIntentLocked(null, null, intent, null,
3539 null, 0, null, null, null, false, false, -1,
3540 callingUid, 0 /* TODO: Verify */);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003541 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003542
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003543 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids)
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003544 throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003545 enforceNotIsolatedCaller("getProcessMemoryInfo");
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003546 Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length];
3547 for (int i=pids.length-1; i>=0; i--) {
3548 infos[i] = new Debug.MemoryInfo();
3549 Debug.getMemoryInfo(pids[i], infos[i]);
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003550 }
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003551 return infos;
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003552 }
Christopher Tate5e1ab332009-09-01 20:32:49 -07003553
Dianne Hackbornb437e092011-08-05 17:50:29 -07003554 public long[] getProcessPss(int[] pids) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003555 enforceNotIsolatedCaller("getProcessPss");
Dianne Hackbornb437e092011-08-05 17:50:29 -07003556 long[] pss = new long[pids.length];
3557 for (int i=pids.length-1; i>=0; i--) {
3558 pss[i] = Debug.getPss(pids[i]);
3559 }
3560 return pss;
3561 }
3562
Christopher Tate5e1ab332009-09-01 20:32:49 -07003563 public void killApplicationProcess(String processName, int uid) {
3564 if (processName == null) {
3565 return;
3566 }
3567
3568 int callerUid = Binder.getCallingUid();
3569 // Only the system server can kill an application
3570 if (callerUid == Process.SYSTEM_UID) {
3571 synchronized (this) {
3572 ProcessRecord app = getProcessRecordLocked(processName, uid);
Christopher Tate4a627c72011-04-01 14:43:32 -07003573 if (app != null && app.thread != null) {
Christopher Tate5e1ab332009-09-01 20:32:49 -07003574 try {
3575 app.thread.scheduleSuicide();
3576 } catch (RemoteException e) {
3577 // If the other end already died, then our work here is done.
3578 }
3579 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003580 Slog.w(TAG, "Process/uid not found attempting kill of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07003581 + processName + " / " + uid);
3582 }
3583 }
3584 } else {
3585 throw new SecurityException(callerUid + " cannot kill app process: " +
3586 processName);
3587 }
3588 }
3589
Dianne Hackborn03abb812010-01-04 18:43:19 -08003590 private void forceStopPackageLocked(final String packageName, int uid) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003591 forceStopPackageLocked(packageName, uid, false, false, true, false, UserId.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003592 Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED,
3593 Uri.fromParts("package", packageName, null));
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003594 if (!mProcessesReady) {
3595 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3596 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003597 intent.putExtra(Intent.EXTRA_UID, uid);
3598 broadcastIntentLocked(null, null, intent,
3599 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07003600 false, false,
3601 MY_PID, Process.SYSTEM_UID, UserId.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003602 }
3603
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003604 private final boolean killPackageProcessesLocked(String packageName, int uid,
Christopher Tate3dacd842011-08-19 14:56:15 -07003605 int minOomAdj, boolean callerWillRestart, boolean allowRestart, boolean doit,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003606 boolean evenPersistent, String reason) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003607 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003608
Dianne Hackborn03abb812010-01-04 18:43:19 -08003609 // Remove all processes this package may have touched: all with the
3610 // same UID (except for the system or root user), and all whose name
3611 // matches the package name.
3612 final String procNamePrefix = packageName + ":";
3613 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3614 final int NA = apps.size();
3615 for (int ia=0; ia<NA; ia++) {
3616 ProcessRecord app = apps.valueAt(ia);
Christopher Tate3dacd842011-08-19 14:56:15 -07003617 if (app.persistent && !evenPersistent) {
Christopher Tate064d8422011-07-26 15:38:07 -07003618 // we don't kill persistent processes
3619 continue;
3620 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003621 if (app.removed) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003622 if (doit) {
3623 procs.add(app);
3624 }
Amith Yamasani13593602012-03-22 16:16:17 -07003625 // If uid is specified and the uid and process name match
3626 // Or, the uid is not specified and the process name matches
3627 } else if (((uid > 0 && uid != Process.SYSTEM_UID && app.info.uid == uid)
Amith Yamasani34db3d62012-04-02 16:35:19 -07003628 || ((app.processName.equals(packageName)
3629 || app.processName.startsWith(procNamePrefix))
3630 && uid < 0))) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003631 if (app.setAdj >= minOomAdj) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003632 if (!doit) {
3633 return true;
3634 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003635 app.removed = true;
3636 procs.add(app);
3637 }
3638 }
3639 }
3640 }
3641
3642 int N = procs.size();
3643 for (int i=0; i<N; i++) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003644 removeProcessLocked(procs.get(i), callerWillRestart, allowRestart, reason);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003645 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003646 return N > 0;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003647 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003648
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003649 private final boolean forceStopPackageLocked(String name, int uid,
Christopher Tate3dacd842011-08-19 14:56:15 -07003650 boolean callerWillRestart, boolean purgeCache, boolean doit,
Amith Yamasani483f3b02012-03-13 16:08:00 -07003651 boolean evenPersistent, int userId) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003652 int i;
3653 int N;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003654
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003655 if (uid < 0) {
3656 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003657 uid = AppGlobals.getPackageManager().getPackageUid(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003658 } catch (RemoteException e) {
3659 }
3660 }
3661
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003662 if (doit) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003663 Slog.i(TAG, "Force stopping package " + name + " uid=" + uid);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003664
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003665 Iterator<SparseArray<Long>> badApps = mProcessCrashTimes.getMap().values().iterator();
3666 while (badApps.hasNext()) {
3667 SparseArray<Long> ba = badApps.next();
3668 if (ba.get(uid) != null) {
3669 badApps.remove();
3670 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003671 }
3672 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003673
3674 boolean didSomething = killPackageProcessesLocked(name, uid, -100,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003675 callerWillRestart, false, doit, evenPersistent, "force stop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003676
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003677 TaskRecord lastTask = null;
3678 for (i=0; i<mMainStack.mHistory.size(); i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003679 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003680 final boolean samePackage = r.packageName.equals(name);
Amith Yamasani13593602012-03-22 16:16:17 -07003681 if (r.userId == userId
3682 && (samePackage || r.task == lastTask)
Christopher Tate3dacd842011-08-19 14:56:15 -07003683 && (r.app == null || evenPersistent || !r.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003684 if (!doit) {
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003685 if (r.finishing) {
3686 // If this activity is just finishing, then it is not
3687 // interesting as far as something to stop.
3688 continue;
3689 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003690 return true;
3691 }
3692 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003693 Slog.i(TAG, " Force finishing activity " + r);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003694 if (samePackage) {
3695 if (r.app != null) {
3696 r.app.removed = true;
3697 }
3698 r.app = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003699 }
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003700 lastTask = r.task;
3701 if (r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003702 null, "force-stop", true)) {
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003703 i--;
3704 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003705 }
3706 }
3707
3708 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
Amith Yamasani742a6712011-05-04 14:49:28 -07003709 for (ServiceRecord service : mServiceMap.getAllServices(userId)) {
Christopher Tate064d8422011-07-26 15:38:07 -07003710 if (service.packageName.equals(name)
Christopher Tate3dacd842011-08-19 14:56:15 -07003711 && (service.app == null || evenPersistent || !service.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003712 if (!doit) {
3713 return true;
3714 }
3715 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003716 Slog.i(TAG, " Force stopping service " + service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003717 if (service.app != null) {
3718 service.app.removed = true;
3719 }
3720 service.app = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003721 service.isolatedProc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003722 services.add(service);
3723 }
3724 }
3725
3726 N = services.size();
3727 for (i=0; i<N; i++) {
3728 bringDownServiceLocked(services.get(i), true);
3729 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003730
3731 ArrayList<ContentProviderRecord> providers = new ArrayList<ContentProviderRecord>();
Amith Yamasani13593602012-03-22 16:16:17 -07003732 for (ContentProviderRecord provider : mProviderMap.getProvidersByClass(userId).values()) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003733 if (provider.info.packageName.equals(name)
3734 && (provider.proc == null || evenPersistent || !provider.proc.persistent)) {
3735 if (!doit) {
3736 return true;
3737 }
3738 didSomething = true;
3739 providers.add(provider);
3740 }
3741 }
3742
3743 N = providers.size();
3744 for (i=0; i<N; i++) {
3745 removeDyingProviderLocked(null, providers.get(i));
3746 }
3747
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003748 if (doit) {
3749 if (purgeCache) {
3750 AttributeCache ac = AttributeCache.instance();
3751 if (ac != null) {
3752 ac.removePackage(name);
3753 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003754 }
Dianne Hackborn38cc8962011-10-13 11:33:55 -07003755 if (mBooted) {
3756 mMainStack.resumeTopActivityLocked(null);
3757 mMainStack.scheduleIdleLocked();
3758 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003759 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003760
3761 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003762 }
3763
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003764 private final boolean removeProcessLocked(ProcessRecord app,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003765 boolean callerWillRestart, boolean allowRestart, String reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003766 final String name = app.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003767 final int uid = app.uid;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003768 if (DEBUG_PROCESSES) Slog.d(
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003769 TAG, "Force removing proc " + app.toShortString() + " (" + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003770 + "/" + uid + ")");
3771
3772 mProcessNames.remove(name, uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003773 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003774 if (mHeavyWeightProcess == app) {
3775 mHeavyWeightProcess = null;
3776 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3777 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003778 boolean needRestart = false;
3779 if (app.pid > 0 && app.pid != MY_PID) {
3780 int pid = app.pid;
3781 synchronized (mPidsSelfLocked) {
3782 mPidsSelfLocked.remove(pid);
3783 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3784 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003785 Slog.i(TAG, "Killing proc " + app.toShortString() + ": " + reason);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003786 handleAppDiedLocked(app, true, allowRestart);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003787 mLruProcesses.remove(app);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003788 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003789
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003790 if (app.persistent && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003791 if (!callerWillRestart) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003792 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003793 } else {
3794 needRestart = true;
3795 }
3796 }
3797 } else {
3798 mRemovedProcesses.add(app);
3799 }
3800
3801 return needRestart;
3802 }
3803
3804 private final void processStartTimedOutLocked(ProcessRecord app) {
3805 final int pid = app.pid;
3806 boolean gone = false;
3807 synchronized (mPidsSelfLocked) {
3808 ProcessRecord knownApp = mPidsSelfLocked.get(pid);
3809 if (knownApp != null && knownApp.thread == null) {
3810 mPidsSelfLocked.remove(pid);
3811 gone = true;
3812 }
3813 }
3814
3815 if (gone) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003816 Slog.w(TAG, "Process " + app + " failed to attach");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003817 EventLog.writeEvent(EventLogTags.AM_PROCESS_START_TIMEOUT, pid, app.uid,
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003818 app.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003819 mProcessNames.remove(app.processName, app.uid);
3820 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003821 if (mHeavyWeightProcess == app) {
3822 mHeavyWeightProcess = null;
3823 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3824 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003825 // Take care of any launching providers waiting for this process.
3826 checkAppInLaunchingProvidersLocked(app, true);
3827 // Take care of any services that are waiting for the process.
3828 for (int i=0; i<mPendingServices.size(); i++) {
3829 ServiceRecord sr = mPendingServices.get(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003830 if ((app.uid == sr.appInfo.uid
3831 && app.processName.equals(sr.processName))
3832 || sr.isolatedProc == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003833 Slog.w(TAG, "Forcing bringing down service: " + sr);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003834 sr.isolatedProc = null;
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003835 mPendingServices.remove(i);
3836 i--;
3837 bringDownServiceLocked(sr, true);
3838 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003839 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003840 EventLog.writeEvent(EventLogTags.AM_KILL, pid,
3841 app.processName, app.setAdj, "start timeout");
3842 Process.killProcessQuiet(pid);
Christopher Tate181fafa2009-05-14 11:12:14 -07003843 if (mBackupTarget != null && mBackupTarget.app.pid == pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003844 Slog.w(TAG, "Unattached app died before backup, skipping");
Christopher Tate181fafa2009-05-14 11:12:14 -07003845 try {
3846 IBackupManager bm = IBackupManager.Stub.asInterface(
3847 ServiceManager.getService(Context.BACKUP_SERVICE));
3848 bm.agentDisconnected(app.info.packageName);
3849 } catch (RemoteException e) {
3850 // Can't happen; the backup manager is local
3851 }
3852 }
Christopher Tatef46723b2012-01-26 14:19:24 -08003853 if (isPendingBroadcastProcessLocked(pid)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003854 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
Christopher Tatef46723b2012-01-26 14:19:24 -08003855 skipPendingBroadcastLocked(pid);
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003856 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003857 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003858 Slog.w(TAG, "Spurious process start timeout - pid not known for " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003859 }
3860 }
3861
3862 private final boolean attachApplicationLocked(IApplicationThread thread,
3863 int pid) {
3864
3865 // Find the application record that is being attached... either via
3866 // the pid if we are running in multiple processes, or just pull the
3867 // next app record if we are emulating process with anonymous threads.
3868 ProcessRecord app;
3869 if (pid != MY_PID && pid >= 0) {
3870 synchronized (mPidsSelfLocked) {
3871 app = mPidsSelfLocked.get(pid);
3872 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003873 } else {
3874 app = null;
3875 }
3876
3877 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003878 Slog.w(TAG, "No pending application record for pid " + pid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003879 + " (IApplicationThread " + thread + "); dropping process");
Doug Zongker2bec3d42009-12-04 12:52:44 -08003880 EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003881 if (pid > 0 && pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003882 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003883 } else {
3884 try {
3885 thread.scheduleExit();
3886 } catch (Exception e) {
3887 // Ignore exceptions.
3888 }
3889 }
3890 return false;
3891 }
3892
3893 // If this application record is still attached to a previous
3894 // process, clean it up now.
3895 if (app.thread != null) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003896 handleAppDiedLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003897 }
3898
3899 // Tell the process all about itself.
3900
Joe Onorato8a9b2202010-02-26 18:56:32 -08003901 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003902 TAG, "Binding process pid " + pid + " to record " + app);
3903
3904 String processName = app.processName;
3905 try {
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07003906 AppDeathRecipient adr = new AppDeathRecipient(
3907 app, pid, thread);
3908 thread.asBinder().linkToDeath(adr, 0);
3909 app.deathRecipient = adr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003910 } catch (RemoteException e) {
3911 app.resetPackageList();
3912 startProcessLocked(app, "link fail", processName);
3913 return false;
3914 }
3915
Doug Zongker2bec3d42009-12-04 12:52:44 -08003916 EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.pid, app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003917
3918 app.thread = thread;
3919 app.curAdj = app.setAdj = -100;
Dianne Hackborn09c916b2009-12-08 14:50:51 -08003920 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
3921 app.setSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003922 app.forcingToForeground = null;
3923 app.foregroundServices = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07003924 app.hasShownUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003925 app.debugging = false;
3926
3927 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3928
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003929 boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003930 List providers = normalMode ? generateApplicationProvidersLocked(app) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003931
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003932 if (!normalMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003933 Slog.i(TAG, "Launching preboot mode app: " + app);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003934 }
3935
Joe Onorato8a9b2202010-02-26 18:56:32 -08003936 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003937 TAG, "New app record " + app
3938 + " thread=" + thread.asBinder() + " pid=" + pid);
3939 try {
3940 int testMode = IApplicationThread.DEBUG_OFF;
3941 if (mDebugApp != null && mDebugApp.equals(processName)) {
3942 testMode = mWaitForDebugger
3943 ? IApplicationThread.DEBUG_WAIT
3944 : IApplicationThread.DEBUG_ON;
3945 app.debugging = true;
3946 if (mDebugTransient) {
3947 mDebugApp = mOrigDebugApp;
3948 mWaitForDebugger = mOrigWaitForDebugger;
3949 }
3950 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003951 String profileFile = app.instrumentationProfileFile;
3952 ParcelFileDescriptor profileFd = null;
3953 boolean profileAutoStop = false;
3954 if (mProfileApp != null && mProfileApp.equals(processName)) {
3955 mProfileProc = app;
3956 profileFile = mProfileFile;
3957 profileFd = mProfileFd;
3958 profileAutoStop = mAutoStopProfiler;
3959 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08003960 boolean enableOpenGlTrace = false;
3961 if (mOpenGlTraceApp != null && mOpenGlTraceApp.equals(processName)) {
3962 enableOpenGlTrace = true;
3963 mOpenGlTraceApp = null;
3964 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003965
Christopher Tate181fafa2009-05-14 11:12:14 -07003966 // If the app is being launched for restore or full backup, set it up specially
3967 boolean isRestrictedBackupMode = false;
3968 if (mBackupTarget != null && mBackupAppName.equals(processName)) {
3969 isRestrictedBackupMode = (mBackupTarget.backupMode == BackupRecord.RESTORE)
Christopher Tate75a99702011-05-18 16:28:19 -07003970 || (mBackupTarget.backupMode == BackupRecord.RESTORE_FULL)
Christopher Tate181fafa2009-05-14 11:12:14 -07003971 || (mBackupTarget.backupMode == BackupRecord.BACKUP_FULL);
3972 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003973
Dianne Hackbornd7f6daa2009-06-22 17:06:35 -07003974 ensurePackageDexOpt(app.instrumentationInfo != null
3975 ? app.instrumentationInfo.packageName
3976 : app.info.packageName);
3977 if (app.instrumentationClass != null) {
3978 ensurePackageDexOpt(app.instrumentationClass.getPackageName());
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003979 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08003980 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Binding proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003981 + processName + " with config " + mConfiguration);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003982 ApplicationInfo appInfo = app.instrumentationInfo != null
3983 ? app.instrumentationInfo : app.info;
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -07003984 app.compat = compatibilityInfoForPackageLocked(appInfo);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003985 if (profileFd != null) {
3986 profileFd = profileFd.dup();
3987 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003988 thread.bindApplication(processName, appInfo, providers,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003989 app.instrumentationClass, profileFile, profileFd, profileAutoStop,
Siva Velusamy92a8b222012-03-09 16:24:04 -08003990 app.instrumentationArguments, app.instrumentationWatcher, testMode,
3991 enableOpenGlTrace, isRestrictedBackupMode || !normalMode, app.persistent,
Dianne Hackborn813075a62011-11-14 17:45:19 -08003992 new Configuration(mConfiguration), app.compat, getCommonServicesLocked(),
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08003993 mCoreSettingsObserver.getCoreSettingsLocked());
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003994 updateLruProcessLocked(app, false, true);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003995 app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003996 } catch (Exception e) {
3997 // todo: Yikes! What should we do? For now we will try to
3998 // start another process, but that could easily get us in
3999 // an infinite loop of restarting processes...
Joe Onorato8a9b2202010-02-26 18:56:32 -08004000 Slog.w(TAG, "Exception thrown during bind!", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004001
4002 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07004003 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004004 startProcessLocked(app, "bind fail", processName);
4005 return false;
4006 }
4007
4008 // Remove this record from the list of starting applications.
4009 mPersistentStartingProcesses.remove(app);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004010 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
4011 "Attach application locked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004012 mProcessesOnHold.remove(app);
4013
4014 boolean badApp = false;
4015 boolean didSomething = false;
4016
4017 // See if the top visible activity is waiting to run in this process...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004018 ActivityRecord hr = mMainStack.topRunningActivityLocked(null);
Christopher Tate04c0af82010-06-07 18:35:20 -07004019 if (hr != null && normalMode) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004020 if (hr.app == null && app.uid == hr.info.applicationInfo.uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004021 && processName.equals(hr.processName)) {
4022 try {
Mike Lockwood3a74bd32011-08-12 13:55:22 -07004023 if (mHeadless) {
4024 Slog.e(TAG, "Starting activities not supported on headless device: " + hr);
4025 } else if (mMainStack.realStartActivityLocked(hr, app, true, true)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004026 didSomething = true;
4027 }
4028 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004029 Slog.w(TAG, "Exception in new application when starting activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004030 + hr.intent.getComponent().flattenToShortString(), e);
4031 badApp = true;
4032 }
4033 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004034 mMainStack.ensureActivitiesVisibleLocked(hr, null, processName, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004035 }
4036 }
4037
4038 // Find any services that should be running in this process...
4039 if (!badApp && mPendingServices.size() > 0) {
4040 ServiceRecord sr = null;
4041 try {
4042 for (int i=0; i<mPendingServices.size(); i++) {
4043 sr = mPendingServices.get(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004044 if (app != sr.isolatedProc && (app.uid != sr.appInfo.uid
4045 || !processName.equals(sr.processName))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004046 continue;
4047 }
4048
4049 mPendingServices.remove(i);
4050 i--;
4051 realStartServiceLocked(sr, app);
4052 didSomething = true;
4053 }
4054 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004055 Slog.w(TAG, "Exception in new application when starting service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004056 + sr.shortName, e);
4057 badApp = true;
4058 }
4059 }
4060
Christopher Tatef46723b2012-01-26 14:19:24 -08004061 // Check if a next-broadcast receiver is in this process...
4062 if (!badApp && isPendingBroadcastProcessLocked(pid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004063 try {
Christopher Tatef46723b2012-01-26 14:19:24 -08004064 didSomething = sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004065 } catch (Exception e) {
Christopher Tatef46723b2012-01-26 14:19:24 -08004066 // If the app died trying to launch the receiver we declare it 'bad'
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004067 badApp = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004068 }
4069 }
4070
Christopher Tate181fafa2009-05-14 11:12:14 -07004071 // Check whether the next backup agent is in this process...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004072 if (!badApp && mBackupTarget != null && mBackupTarget.appInfo.uid == app.uid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004073 if (DEBUG_BACKUP) Slog.v(TAG, "New app is backup target, launching agent for " + app);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004074 ensurePackageDexOpt(mBackupTarget.appInfo.packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07004075 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004076 thread.scheduleCreateBackupAgent(mBackupTarget.appInfo,
4077 compatibilityInfoForPackageLocked(mBackupTarget.appInfo),
4078 mBackupTarget.backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -07004079 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004080 Slog.w(TAG, "Exception scheduling backup agent creation: ");
Christopher Tate181fafa2009-05-14 11:12:14 -07004081 e.printStackTrace();
4082 }
4083 }
4084
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004085 if (badApp) {
4086 // todo: Also need to kill application to deal with all
4087 // kinds of exceptions.
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004088 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004089 return false;
4090 }
4091
4092 if (!didSomething) {
4093 updateOomAdjLocked();
4094 }
4095
4096 return true;
4097 }
4098
4099 public final void attachApplication(IApplicationThread thread) {
4100 synchronized (this) {
4101 int callingPid = Binder.getCallingPid();
4102 final long origId = Binder.clearCallingIdentity();
4103 attachApplicationLocked(thread, callingPid);
4104 Binder.restoreCallingIdentity(origId);
4105 }
4106 }
4107
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004108 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004109 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004110 ActivityRecord r = mMainStack.activityIdleInternal(token, false, config);
4111 if (stopProfiling) {
4112 synchronized (this) {
4113 if (mProfileProc == r.app) {
4114 if (mProfileFd != null) {
4115 try {
4116 mProfileFd.close();
4117 } catch (IOException e) {
4118 }
4119 clearProfilerLocked();
4120 }
4121 }
4122 }
4123 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004124 Binder.restoreCallingIdentity(origId);
4125 }
4126
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004127 void enableScreenAfterBoot() {
Doug Zongker2bec3d42009-12-04 12:52:44 -08004128 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004129 SystemClock.uptimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004130 mWindowManager.enableScreenAfterBoot();
Jeff Brownc042ee22012-05-08 13:03:42 -07004131
4132 synchronized (this) {
4133 updateEventDispatchingLocked();
4134 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004135 }
4136
Dianne Hackborn661cd522011-08-22 00:26:20 -07004137 public void showBootMessage(final CharSequence msg, final boolean always) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004138 enforceNotIsolatedCaller("showBootMessage");
Dianne Hackborn661cd522011-08-22 00:26:20 -07004139 mWindowManager.showBootMessage(msg, always);
4140 }
4141
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004142 public void dismissKeyguardOnNextActivity() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004143 enforceNotIsolatedCaller("dismissKeyguardOnNextActivity");
Jeff Sharkey7ffaa982012-04-30 16:59:05 -07004144 final long token = Binder.clearCallingIdentity();
4145 try {
4146 synchronized (this) {
4147 if (mLockScreenShown) {
4148 mLockScreenShown = false;
4149 comeOutOfSleepIfNeededLocked();
4150 }
4151 mMainStack.dismissKeyguardOnNextActivityLocked();
Dianne Hackborn1e88e982012-04-24 18:35:55 -07004152 }
Jeff Sharkey7ffaa982012-04-30 16:59:05 -07004153 } finally {
4154 Binder.restoreCallingIdentity(token);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004155 }
4156 }
4157
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004158 final void finishBooting() {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004159 IntentFilter pkgFilter = new IntentFilter();
4160 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
4161 pkgFilter.addDataScheme("package");
4162 mContext.registerReceiver(new BroadcastReceiver() {
4163 @Override
4164 public void onReceive(Context context, Intent intent) {
4165 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
4166 if (pkgs != null) {
4167 for (String pkg : pkgs) {
Vairavan Srinivasan61f07652010-07-22 13:36:40 -07004168 synchronized (ActivityManagerService.this) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07004169 if (forceStopPackageLocked(pkg, -1, false, false, false, false, 0)) {
4170 setResultCode(Activity.RESULT_OK);
4171 return;
4172 }
4173 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004174 }
4175 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004176 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004177 }, pkgFilter);
Amith Yamasani13593602012-03-22 16:16:17 -07004178
4179 IntentFilter userFilter = new IntentFilter();
4180 userFilter.addAction(Intent.ACTION_USER_REMOVED);
4181 mContext.registerReceiver(new BroadcastReceiver() {
4182 @Override
4183 public void onReceive(Context context, Intent intent) {
4184 onUserRemoved(intent);
4185 }
4186 }, userFilter);
4187
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004188 synchronized (this) {
4189 // Ensure that any processes we had put on hold are now started
4190 // up.
4191 final int NP = mProcessesOnHold.size();
4192 if (NP > 0) {
4193 ArrayList<ProcessRecord> procs =
4194 new ArrayList<ProcessRecord>(mProcessesOnHold);
4195 for (int ip=0; ip<NP; ip++) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004196 if (DEBUG_PROCESSES) Slog.v(TAG, "Starting process on hold: "
4197 + procs.get(ip));
4198 startProcessLocked(procs.get(ip), "on-hold", null);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004199 }
4200 }
4201
4202 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004203 // Start looking for apps that are abusing wake locks.
4204 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07004205 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004206 // Tell anyone interested that we are done booting!
Dianne Hackbornf4c454b2010-08-11 12:47:41 -07004207 SystemProperties.set("sys.boot_completed", "1");
Guang Zhu191713a2012-01-12 12:02:22 -08004208 SystemProperties.set("dev.bootcomplete", "1");
Amith Yamasani742a6712011-05-04 14:49:28 -07004209 /* TODO: Send this to all users that are to be logged in on startup */
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004210 broadcastIntentLocked(null, null,
4211 new Intent(Intent.ACTION_BOOT_COMPLETED, null),
4212 null, null, 0, null, null,
4213 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
Amith Yamasani742a6712011-05-04 14:49:28 -07004214 false, false, MY_PID, Process.SYSTEM_UID, Binder.getOrigCallingUser());
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004215 }
4216 }
4217 }
4218
4219 final void ensureBootCompleted() {
4220 boolean booting;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004221 boolean enableScreen;
4222 synchronized (this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004223 booting = mBooting;
4224 mBooting = false;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004225 enableScreen = !mBooted;
4226 mBooted = true;
4227 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004228
4229 if (booting) {
4230 finishBooting();
4231 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004232
4233 if (enableScreen) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004234 enableScreenAfterBoot();
4235 }
4236 }
4237
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004238 public final void activityPaused(IBinder token) {
4239 final long origId = Binder.clearCallingIdentity();
4240 mMainStack.activityPaused(token, false);
4241 Binder.restoreCallingIdentity(origId);
4242 }
4243
4244 public final void activityStopped(IBinder token, Bundle icicle, Bitmap thumbnail,
4245 CharSequence description) {
4246 if (localLOGV) Slog.v(
4247 TAG, "Activity stopped: token=" + token);
4248
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004249 // Refuse possible leaked file descriptors
4250 if (icicle != null && icicle.hasFileDescriptors()) {
4251 throw new IllegalArgumentException("File descriptors passed in Bundle");
4252 }
4253
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004254 ActivityRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004255
4256 final long origId = Binder.clearCallingIdentity();
4257
4258 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004259 r = mMainStack.isInStackLocked(token);
4260 if (r != null) {
4261 r.stack.activityStoppedLocked(r, icicle, thumbnail, description);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004262 }
4263 }
4264
4265 if (r != null) {
4266 sendPendingThumbnail(r, null, null, null, false);
4267 }
4268
4269 trimApplications();
4270
4271 Binder.restoreCallingIdentity(origId);
4272 }
4273
4274 public final void activityDestroyed(IBinder token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004275 if (DEBUG_SWITCH) Slog.v(TAG, "ACTIVITY DESTROYED: " + token);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004276 mMainStack.activityDestroyed(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004277 }
4278
4279 public String getCallingPackage(IBinder token) {
4280 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004281 ActivityRecord r = getCallingRecordLocked(token);
Dianne Hackborn9bbcb912009-10-20 15:42:38 -07004282 return r != null && r.app != null ? r.info.packageName : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004283 }
4284 }
4285
4286 public ComponentName getCallingActivity(IBinder token) {
4287 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004288 ActivityRecord r = getCallingRecordLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004289 return r != null ? r.intent.getComponent() : null;
4290 }
4291 }
4292
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004293 private ActivityRecord getCallingRecordLocked(IBinder token) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004294 ActivityRecord r = mMainStack.isInStackLocked(token);
4295 if (r == null) {
4296 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004297 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004298 return r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004299 }
4300
4301 public ComponentName getActivityClassForToken(IBinder token) {
4302 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004303 ActivityRecord r = mMainStack.isInStackLocked(token);
4304 if (r == null) {
4305 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004306 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004307 return r.intent.getComponent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004308 }
4309 }
4310
4311 public String getPackageForToken(IBinder token) {
4312 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004313 ActivityRecord r = mMainStack.isInStackLocked(token);
4314 if (r == null) {
4315 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004316 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004317 return r.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004318 }
4319 }
4320
4321 public IIntentSender getIntentSender(int type,
4322 String packageName, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004323 int requestCode, Intent[] intents, String[] resolvedTypes,
4324 int flags, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004325 enforceNotIsolatedCaller("getIntentSender");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004326 // Refuse possible leaked file descriptors
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004327 if (intents != null) {
4328 if (intents.length < 1) {
4329 throw new IllegalArgumentException("Intents array length must be >= 1");
4330 }
4331 for (int i=0; i<intents.length; i++) {
4332 Intent intent = intents[i];
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004333 if (intent != null) {
4334 if (intent.hasFileDescriptors()) {
4335 throw new IllegalArgumentException("File descriptors passed in Intent");
4336 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07004337 if (type == ActivityManager.INTENT_SENDER_BROADCAST &&
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004338 (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
4339 throw new IllegalArgumentException(
4340 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
4341 }
4342 intents[i] = new Intent(intent);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004343 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004344 }
4345 if (resolvedTypes != null && resolvedTypes.length != intents.length) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004346 throw new IllegalArgumentException(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004347 "Intent array length does not match resolvedTypes length");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004348 }
4349 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004350 if (options != null) {
4351 if (options.hasFileDescriptors()) {
4352 throw new IllegalArgumentException("File descriptors passed in options");
4353 }
4354 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004355
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004356 synchronized(this) {
4357 int callingUid = Binder.getCallingUid();
4358 try {
Jeff Brown10e89712011-07-08 18:52:57 -07004359 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004360 int uid = AppGlobals.getPackageManager()
Amith Yamasani483f3b02012-03-13 16:08:00 -07004361 .getPackageUid(packageName, UserId.getUserId(callingUid));
4362 if (!UserId.isSameApp(callingUid, uid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004363 String msg = "Permission Denial: getIntentSender() from pid="
4364 + Binder.getCallingPid()
4365 + ", uid=" + Binder.getCallingUid()
4366 + ", (need uid=" + uid + ")"
4367 + " is not allowed to send as package " + packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004368 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004369 throw new SecurityException(msg);
4370 }
4371 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004372
Amith Yamasani742a6712011-05-04 14:49:28 -07004373 if (DEBUG_MU)
4374 Slog.i(TAG_MU, "Getting intent sender for origCallingUid="
4375 + Binder.getOrigCallingUid());
4376 return getIntentSenderLocked(type, packageName, Binder.getOrigCallingUid(),
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004377 token, resultWho, requestCode, intents, resolvedTypes, flags, options);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004378
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004379 } catch (RemoteException e) {
4380 throw new SecurityException(e);
4381 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004382 }
4383 }
4384
4385 IIntentSender getIntentSenderLocked(int type,
4386 String packageName, int callingUid, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004387 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
4388 Bundle options) {
Amith Yamasani742a6712011-05-04 14:49:28 -07004389 if (DEBUG_MU)
4390 Slog.v(TAG_MU, "getIntentSenderLocked(): uid=" + callingUid);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004391 ActivityRecord activity = null;
Dianne Hackborna4972e92012-03-14 10:38:05 -07004392 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004393 activity = mMainStack.isInStackLocked(token);
4394 if (activity == null) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004395 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004396 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004397 if (activity.finishing) {
4398 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004399 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004400 }
4401
4402 final boolean noCreate = (flags&PendingIntent.FLAG_NO_CREATE) != 0;
4403 final boolean cancelCurrent = (flags&PendingIntent.FLAG_CANCEL_CURRENT) != 0;
4404 final boolean updateCurrent = (flags&PendingIntent.FLAG_UPDATE_CURRENT) != 0;
4405 flags &= ~(PendingIntent.FLAG_NO_CREATE|PendingIntent.FLAG_CANCEL_CURRENT
4406 |PendingIntent.FLAG_UPDATE_CURRENT);
4407
4408 PendingIntentRecord.Key key = new PendingIntentRecord.Key(
4409 type, packageName, activity, resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004410 requestCode, intents, resolvedTypes, flags, options);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004411 WeakReference<PendingIntentRecord> ref;
4412 ref = mIntentSenderRecords.get(key);
4413 PendingIntentRecord rec = ref != null ? ref.get() : null;
4414 if (rec != null) {
4415 if (!cancelCurrent) {
4416 if (updateCurrent) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004417 if (rec.key.requestIntent != null) {
Adam Powell501d4a52012-04-30 15:03:57 -07004418 rec.key.requestIntent.replaceExtras(intents != null ?
4419 intents[intents.length - 1] : null);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004420 }
4421 if (intents != null) {
4422 intents[intents.length-1] = rec.key.requestIntent;
4423 rec.key.allIntents = intents;
4424 rec.key.allResolvedTypes = resolvedTypes;
4425 } else {
4426 rec.key.allIntents = null;
4427 rec.key.allResolvedTypes = null;
4428 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004429 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004430 return rec;
4431 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004432 rec.canceled = true;
4433 mIntentSenderRecords.remove(key);
4434 }
4435 if (noCreate) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004436 return rec;
4437 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004438 rec = new PendingIntentRecord(this, key, callingUid);
4439 mIntentSenderRecords.put(key, rec.ref);
Dianne Hackborna4972e92012-03-14 10:38:05 -07004440 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004441 if (activity.pendingResults == null) {
4442 activity.pendingResults
4443 = new HashSet<WeakReference<PendingIntentRecord>>();
4444 }
4445 activity.pendingResults.add(rec.ref);
4446 }
4447 return rec;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004448 }
4449
4450 public void cancelIntentSender(IIntentSender sender) {
4451 if (!(sender instanceof PendingIntentRecord)) {
4452 return;
4453 }
4454 synchronized(this) {
4455 PendingIntentRecord rec = (PendingIntentRecord)sender;
4456 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004457 int uid = AppGlobals.getPackageManager()
Amith Yamasani483f3b02012-03-13 16:08:00 -07004458 .getPackageUid(rec.key.packageName, UserId.getCallingUserId());
Amith Yamasani04e0d262012-02-14 11:50:53 -08004459 if (!UserId.isSameApp(uid, Binder.getCallingUid())) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004460 String msg = "Permission Denial: cancelIntentSender() from pid="
4461 + Binder.getCallingPid()
4462 + ", uid=" + Binder.getCallingUid()
4463 + " is not allowed to cancel packges "
4464 + rec.key.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004465 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004466 throw new SecurityException(msg);
4467 }
4468 } catch (RemoteException e) {
4469 throw new SecurityException(e);
4470 }
4471 cancelIntentSenderLocked(rec, true);
4472 }
4473 }
4474
4475 void cancelIntentSenderLocked(PendingIntentRecord rec, boolean cleanActivity) {
4476 rec.canceled = true;
4477 mIntentSenderRecords.remove(rec.key);
4478 if (cleanActivity && rec.key.activity != null) {
4479 rec.key.activity.pendingResults.remove(rec.ref);
4480 }
4481 }
4482
4483 public String getPackageForIntentSender(IIntentSender pendingResult) {
4484 if (!(pendingResult instanceof PendingIntentRecord)) {
4485 return null;
4486 }
Brad Fitzpatrickb213d102010-04-19 11:58:52 -07004487 try {
4488 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4489 return res.key.packageName;
4490 } catch (ClassCastException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004491 }
4492 return null;
4493 }
4494
Christopher Tatec4a07d12012-04-06 14:19:13 -07004495 public int getUidForIntentSender(IIntentSender sender) {
4496 if (sender instanceof PendingIntentRecord) {
4497 try {
4498 PendingIntentRecord res = (PendingIntentRecord)sender;
4499 return res.uid;
4500 } catch (ClassCastException e) {
4501 }
4502 }
4503 return -1;
4504 }
4505
Dianne Hackborn6c418d52011-06-29 14:05:33 -07004506 public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) {
4507 if (!(pendingResult instanceof PendingIntentRecord)) {
4508 return false;
4509 }
4510 try {
4511 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4512 if (res.key.allIntents == null) {
4513 return false;
4514 }
4515 for (int i=0; i<res.key.allIntents.length; i++) {
4516 Intent intent = res.key.allIntents[i];
4517 if (intent.getPackage() != null && intent.getComponent() != null) {
4518 return false;
4519 }
4520 }
4521 return true;
4522 } catch (ClassCastException e) {
4523 }
4524 return false;
4525 }
4526
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004527 public void setProcessLimit(int max) {
4528 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4529 "setProcessLimit()");
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004530 synchronized (this) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07004531 mProcessLimit = max < 0 ? ProcessList.MAX_HIDDEN_APPS : max;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004532 mProcessLimitOverride = max;
4533 }
4534 trimApplications();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004535 }
4536
4537 public int getProcessLimit() {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004538 synchronized (this) {
4539 return mProcessLimitOverride;
4540 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004541 }
4542
4543 void foregroundTokenDied(ForegroundToken token) {
4544 synchronized (ActivityManagerService.this) {
4545 synchronized (mPidsSelfLocked) {
4546 ForegroundToken cur
4547 = mForegroundProcesses.get(token.pid);
4548 if (cur != token) {
4549 return;
4550 }
4551 mForegroundProcesses.remove(token.pid);
4552 ProcessRecord pr = mPidsSelfLocked.get(token.pid);
4553 if (pr == null) {
4554 return;
4555 }
4556 pr.forcingToForeground = null;
4557 pr.foregroundServices = false;
4558 }
4559 updateOomAdjLocked();
4560 }
4561 }
4562
4563 public void setProcessForeground(IBinder token, int pid, boolean isForeground) {
4564 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4565 "setProcessForeground()");
4566 synchronized(this) {
4567 boolean changed = false;
4568
4569 synchronized (mPidsSelfLocked) {
4570 ProcessRecord pr = mPidsSelfLocked.get(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004571 if (pr == null && isForeground) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004572 Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004573 return;
4574 }
4575 ForegroundToken oldToken = mForegroundProcesses.get(pid);
4576 if (oldToken != null) {
4577 oldToken.token.unlinkToDeath(oldToken, 0);
4578 mForegroundProcesses.remove(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004579 if (pr != null) {
4580 pr.forcingToForeground = null;
4581 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004582 changed = true;
4583 }
4584 if (isForeground && token != null) {
4585 ForegroundToken newToken = new ForegroundToken() {
4586 public void binderDied() {
4587 foregroundTokenDied(this);
4588 }
4589 };
4590 newToken.pid = pid;
4591 newToken.token = token;
4592 try {
4593 token.linkToDeath(newToken, 0);
4594 mForegroundProcesses.put(pid, newToken);
4595 pr.forcingToForeground = token;
4596 changed = true;
4597 } catch (RemoteException e) {
4598 // If the process died while doing this, we will later
4599 // do the cleanup with the process death link.
4600 }
4601 }
4602 }
4603
4604 if (changed) {
4605 updateOomAdjLocked();
4606 }
4607 }
4608 }
4609
4610 // =========================================================
4611 // PERMISSIONS
4612 // =========================================================
4613
4614 static class PermissionController extends IPermissionController.Stub {
4615 ActivityManagerService mActivityManagerService;
4616 PermissionController(ActivityManagerService activityManagerService) {
4617 mActivityManagerService = activityManagerService;
4618 }
4619
4620 public boolean checkPermission(String permission, int pid, int uid) {
4621 return mActivityManagerService.checkPermission(permission, pid,
4622 uid) == PackageManager.PERMISSION_GRANTED;
4623 }
4624 }
4625
4626 /**
4627 * This can be called with or without the global lock held.
4628 */
4629 int checkComponentPermission(String permission, int pid, int uid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004630 int owningUid, boolean exported) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004631 // We might be performing an operation on behalf of an indirect binder
4632 // invocation, e.g. via {@link #openContentUri}. Check and adjust the
4633 // client identity accordingly before proceeding.
4634 Identity tlsIdentity = sCallerIdentity.get();
4635 if (tlsIdentity != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004636 Slog.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004637 + tlsIdentity.pid + "," + tlsIdentity.uid + "}");
4638 uid = tlsIdentity.uid;
4639 pid = tlsIdentity.pid;
4640 }
4641
Dianne Hackborn5320eb82012-05-18 12:05:04 -07004642 if (pid == MY_PID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004643 return PackageManager.PERMISSION_GRANTED;
4644 }
Dianne Hackborn5320eb82012-05-18 12:05:04 -07004645
4646 return ActivityManager.checkComponentPermission(permission, uid,
4647 owningUid, exported);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004648 }
4649
4650 /**
4651 * As the only public entry point for permissions checking, this method
4652 * can enforce the semantic that requesting a check on a null global
4653 * permission is automatically denied. (Internally a null permission
4654 * string is used when calling {@link #checkComponentPermission} in cases
4655 * when only uid-based security is needed.)
4656 *
4657 * This can be called with or without the global lock held.
4658 */
4659 public int checkPermission(String permission, int pid, int uid) {
4660 if (permission == null) {
4661 return PackageManager.PERMISSION_DENIED;
4662 }
Amith Yamasani742a6712011-05-04 14:49:28 -07004663 return checkComponentPermission(permission, pid, UserId.getAppId(uid), -1, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004664 }
4665
4666 /**
4667 * Binder IPC calls go through the public entry point.
4668 * This can be called with or without the global lock held.
4669 */
4670 int checkCallingPermission(String permission) {
4671 return checkPermission(permission,
4672 Binder.getCallingPid(),
Amith Yamasani742a6712011-05-04 14:49:28 -07004673 UserId.getAppId(Binder.getCallingUid()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004674 }
4675
4676 /**
4677 * This can be called with or without the global lock held.
4678 */
4679 void enforceCallingPermission(String permission, String func) {
4680 if (checkCallingPermission(permission)
4681 == PackageManager.PERMISSION_GRANTED) {
4682 return;
4683 }
4684
4685 String msg = "Permission Denial: " + func + " from pid="
4686 + Binder.getCallingPid()
4687 + ", uid=" + Binder.getCallingUid()
4688 + " requires " + permission;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004689 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004690 throw new SecurityException(msg);
4691 }
4692
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004693 /**
4694 * Determine if UID is holding permissions required to access {@link Uri} in
4695 * the given {@link ProviderInfo}. Final permission checking is always done
4696 * in {@link ContentProvider}.
4697 */
4698 private final boolean checkHoldingPermissionsLocked(
4699 IPackageManager pm, ProviderInfo pi, Uri uri, int uid, int modeFlags) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004700 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4701 "checkHoldingPermissionsLocked: uri=" + uri + " uid=" + uid);
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004702
4703 if (pi.applicationInfo.uid == uid) {
4704 return true;
4705 } else if (!pi.exported) {
4706 return false;
4707 }
4708
4709 boolean readMet = (modeFlags & Intent.FLAG_GRANT_READ_URI_PERMISSION) == 0;
4710 boolean writeMet = (modeFlags & Intent.FLAG_GRANT_WRITE_URI_PERMISSION) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004711 try {
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004712 // check if target holds top-level <provider> permissions
4713 if (!readMet && pi.readPermission != null
4714 && (pm.checkUidPermission(pi.readPermission, uid) == PERMISSION_GRANTED)) {
4715 readMet = true;
4716 }
4717 if (!writeMet && pi.writePermission != null
4718 && (pm.checkUidPermission(pi.writePermission, uid) == PERMISSION_GRANTED)) {
4719 writeMet = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004720 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004721
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004722 // track if unprotected read/write is allowed; any denied
4723 // <path-permission> below removes this ability
4724 boolean allowDefaultRead = pi.readPermission == null;
4725 boolean allowDefaultWrite = pi.writePermission == null;
Dianne Hackborn48058e82010-09-27 16:53:23 -07004726
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004727 // check if target holds any <path-permission> that match uri
4728 final PathPermission[] pps = pi.pathPermissions;
4729 if (pps != null) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004730 final String path = uri.getPath();
4731 int i = pps.length;
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004732 while (i > 0 && (!readMet || !writeMet)) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004733 i--;
4734 PathPermission pp = pps[i];
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004735 if (pp.match(path)) {
4736 if (!readMet) {
4737 final String pprperm = pp.getReadPermission();
4738 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking read perm for "
4739 + pprperm + " for " + pp.getPath()
4740 + ": match=" + pp.match(path)
4741 + " check=" + pm.checkUidPermission(pprperm, uid));
4742 if (pprperm != null) {
4743 if (pm.checkUidPermission(pprperm, uid) == PERMISSION_GRANTED) {
4744 readMet = true;
4745 } else {
4746 allowDefaultRead = false;
4747 }
4748 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004749 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004750 if (!writeMet) {
4751 final String ppwperm = pp.getWritePermission();
4752 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking write perm "
4753 + ppwperm + " for " + pp.getPath()
4754 + ": match=" + pp.match(path)
4755 + " check=" + pm.checkUidPermission(ppwperm, uid));
4756 if (ppwperm != null) {
4757 if (pm.checkUidPermission(ppwperm, uid) == PERMISSION_GRANTED) {
4758 writeMet = true;
4759 } else {
4760 allowDefaultWrite = false;
4761 }
4762 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004763 }
4764 }
4765 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07004766 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004767
4768 // grant unprotected <provider> read/write, if not blocked by
4769 // <path-permission> above
4770 if (allowDefaultRead) readMet = true;
4771 if (allowDefaultWrite) writeMet = true;
4772
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004773 } catch (RemoteException e) {
4774 return false;
4775 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004776
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004777 return readMet && writeMet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004778 }
4779
4780 private final boolean checkUriPermissionLocked(Uri uri, int uid,
4781 int modeFlags) {
4782 // Root gets to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07004783 if (uid == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004784 return true;
4785 }
4786 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(uid);
4787 if (perms == null) return false;
4788 UriPermission perm = perms.get(uri);
4789 if (perm == null) return false;
4790 return (modeFlags&perm.modeFlags) == modeFlags;
4791 }
4792
4793 public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004794 enforceNotIsolatedCaller("checkUriPermission");
4795
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004796 // Another redirected-binder-call permissions check as in
4797 // {@link checkComponentPermission}.
4798 Identity tlsIdentity = sCallerIdentity.get();
4799 if (tlsIdentity != null) {
4800 uid = tlsIdentity.uid;
4801 pid = tlsIdentity.pid;
4802 }
4803
Amith Yamasani742a6712011-05-04 14:49:28 -07004804 uid = UserId.getAppId(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004805 // Our own process gets to do everything.
4806 if (pid == MY_PID) {
4807 return PackageManager.PERMISSION_GRANTED;
4808 }
4809 synchronized(this) {
4810 return checkUriPermissionLocked(uri, uid, modeFlags)
4811 ? PackageManager.PERMISSION_GRANTED
4812 : PackageManager.PERMISSION_DENIED;
4813 }
4814 }
4815
Dianne Hackborn39792d22010-08-19 18:01:52 -07004816 /**
4817 * Check if the targetPkg can be granted permission to access uri by
4818 * the callingUid using the given modeFlags. Throws a security exception
4819 * if callingUid is not allowed to do this. Returns the uid of the target
4820 * if the URI permission grant should be performed; returns -1 if it is not
4821 * needed (for example targetPkg already has permission to access the URI).
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004822 * If you already know the uid of the target, you can supply it in
4823 * lastTargetUid else set that to -1.
Dianne Hackborn39792d22010-08-19 18:01:52 -07004824 */
4825 int checkGrantUriPermissionLocked(int callingUid, String targetPkg,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004826 Uri uri, int modeFlags, int lastTargetUid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004827 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4828 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4829 if (modeFlags == 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004830 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004831 }
4832
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004833 if (targetPkg != null) {
4834 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4835 "Checking grant " + targetPkg + " permission to " + uri);
4836 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004837
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004838 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004839
4840 // If this is not a content: uri, we can't do anything with it.
4841 if (!ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004842 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004843 "Can't grant URI permission for non-content URI: " + uri);
Dianne Hackborn39792d22010-08-19 18:01:52 -07004844 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004845 }
4846
4847 String name = uri.getAuthority();
4848 ProviderInfo pi = null;
Amith Yamasani742a6712011-05-04 14:49:28 -07004849 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
4850 UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004851 if (cpr != null) {
4852 pi = cpr.info;
4853 } else {
4854 try {
4855 pi = pm.resolveContentProvider(name,
Amith Yamasani483f3b02012-03-13 16:08:00 -07004856 PackageManager.GET_URI_PERMISSION_PATTERNS, UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004857 } catch (RemoteException ex) {
4858 }
4859 }
4860 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07004861 Slog.w(TAG, "No content provider found for permission check: " + uri.toSafeString());
Dianne Hackborn39792d22010-08-19 18:01:52 -07004862 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004863 }
4864
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004865 int targetUid = lastTargetUid;
4866 if (targetUid < 0 && targetPkg != null) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004867 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07004868 targetUid = pm.getPackageUid(targetPkg, UserId.getUserId(callingUid));
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004869 if (targetUid < 0) {
4870 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4871 "Can't grant URI permission no uid for: " + targetPkg);
4872 return -1;
4873 }
4874 } catch (RemoteException ex) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004875 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004876 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004877 }
4878
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004879 if (targetUid >= 0) {
4880 // First... does the target actually need this permission?
4881 if (checkHoldingPermissionsLocked(pm, pi, uri, targetUid, modeFlags)) {
4882 // No need to grant the target this permission.
4883 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4884 "Target " + targetPkg + " already has full permission to " + uri);
4885 return -1;
4886 }
4887 } else {
4888 // First... there is no target package, so can anyone access it?
4889 boolean allowed = pi.exported;
4890 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
4891 if (pi.readPermission != null) {
4892 allowed = false;
4893 }
4894 }
4895 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
4896 if (pi.writePermission != null) {
4897 allowed = false;
4898 }
4899 }
4900 if (allowed) {
4901 return -1;
4902 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004903 }
4904
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004905 // Second... is the provider allowing granting of URI permissions?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004906 if (!pi.grantUriPermissions) {
4907 throw new SecurityException("Provider " + pi.packageName
4908 + "/" + pi.name
4909 + " does not allow granting of Uri permissions (uri "
4910 + uri + ")");
4911 }
4912 if (pi.uriPermissionPatterns != null) {
4913 final int N = pi.uriPermissionPatterns.length;
4914 boolean allowed = false;
4915 for (int i=0; i<N; i++) {
4916 if (pi.uriPermissionPatterns[i] != null
4917 && pi.uriPermissionPatterns[i].match(uri.getPath())) {
4918 allowed = true;
4919 break;
4920 }
4921 }
4922 if (!allowed) {
4923 throw new SecurityException("Provider " + pi.packageName
4924 + "/" + pi.name
4925 + " does not allow granting of permission to path of Uri "
4926 + uri);
4927 }
4928 }
4929
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004930 // Third... does the caller itself have permission to access
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004931 // this uri?
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004932 if (callingUid != Process.myUid()) {
4933 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
4934 if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
4935 throw new SecurityException("Uid " + callingUid
4936 + " does not have permission to uri " + uri);
4937 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004938 }
4939 }
4940
Dianne Hackborn39792d22010-08-19 18:01:52 -07004941 return targetUid;
4942 }
4943
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004944 public int checkGrantUriPermission(int callingUid, String targetPkg,
4945 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004946 enforceNotIsolatedCaller("checkGrantUriPermission");
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004947 synchronized(this) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004948 return checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004949 }
4950 }
4951
Dianne Hackborn39792d22010-08-19 18:01:52 -07004952 void grantUriPermissionUncheckedLocked(int targetUid, String targetPkg,
4953 Uri uri, int modeFlags, UriPermissionOwner owner) {
4954 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4955 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4956 if (modeFlags == 0) {
4957 return;
4958 }
4959
4960 // So here we are: the caller has the assumed permission
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004961 // to the uri, and the target doesn't. Let's now give this to
4962 // the target.
4963
Joe Onorato8a9b2202010-02-26 18:56:32 -08004964 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn39792d22010-08-19 18:01:52 -07004965 "Granting " + targetPkg + "/" + targetUid + " permission to " + uri);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004966
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004967 HashMap<Uri, UriPermission> targetUris
4968 = mGrantedUriPermissions.get(targetUid);
4969 if (targetUris == null) {
4970 targetUris = new HashMap<Uri, UriPermission>();
4971 mGrantedUriPermissions.put(targetUid, targetUris);
4972 }
4973
4974 UriPermission perm = targetUris.get(uri);
4975 if (perm == null) {
4976 perm = new UriPermission(targetUid, uri);
4977 targetUris.put(uri, perm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004978 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07004979
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004980 perm.modeFlags |= modeFlags;
Dianne Hackborn39792d22010-08-19 18:01:52 -07004981 if (owner == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004982 perm.globalModeFlags |= modeFlags;
Vairavan Srinivasan91c12c22011-01-21 18:26:06 -08004983 } else {
4984 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
4985 perm.readOwners.add(owner);
4986 owner.addReadPermission(perm);
4987 }
4988 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
4989 perm.writeOwners.add(owner);
4990 owner.addWritePermission(perm);
4991 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004992 }
4993 }
4994
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004995 void grantUriPermissionLocked(int callingUid, String targetPkg, Uri uri,
4996 int modeFlags, UriPermissionOwner owner) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004997 if (targetPkg == null) {
4998 throw new NullPointerException("targetPkg");
4999 }
5000
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005001 int targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn39792d22010-08-19 18:01:52 -07005002 if (targetUid < 0) {
5003 return;
5004 }
5005
5006 grantUriPermissionUncheckedLocked(targetUid, targetPkg, uri, modeFlags, owner);
5007 }
5008
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005009 static class NeededUriGrants extends ArrayList<Uri> {
5010 final String targetPkg;
5011 final int targetUid;
5012 final int flags;
5013
5014 NeededUriGrants(String _targetPkg, int _targetUid, int _flags) {
5015 targetPkg = _targetPkg;
5016 targetUid = _targetUid;
5017 flags = _flags;
5018 }
5019 }
5020
Dianne Hackborn39792d22010-08-19 18:01:52 -07005021 /**
5022 * Like checkGrantUriPermissionLocked, but takes an Intent.
5023 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005024 NeededUriGrants checkGrantUriPermissionFromIntentLocked(int callingUid,
5025 String targetPkg, Intent intent, int mode, NeededUriGrants needed) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07005026 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005027 "Checking URI perm to data=" + (intent != null ? intent.getData() : null)
5028 + " clip=" + (intent != null ? intent.getClipData() : null)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005029 + " from " + intent + "; flags=0x"
5030 + Integer.toHexString(intent != null ? intent.getFlags() : 0));
5031
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005032 if (targetPkg == null) {
5033 throw new NullPointerException("targetPkg");
5034 }
5035
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005036 if (intent == null) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005037 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005038 }
5039 Uri data = intent.getData();
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005040 ClipData clip = intent.getClipData();
5041 if (data == null && clip == null) {
5042 return null;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005043 }
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005044 if (data != null) {
5045 int target = checkGrantUriPermissionLocked(callingUid, targetPkg, data,
5046 mode, needed != null ? needed.targetUid : -1);
5047 if (target > 0) {
5048 if (needed == null) {
5049 needed = new NeededUriGrants(targetPkg, target, mode);
5050 }
5051 needed.add(data);
5052 }
5053 }
5054 if (clip != null) {
5055 for (int i=0; i<clip.getItemCount(); i++) {
5056 Uri uri = clip.getItemAt(i).getUri();
5057 if (uri != null) {
5058 int target = -1;
5059 target = checkGrantUriPermissionLocked(callingUid, targetPkg, uri,
5060 mode, needed != null ? needed.targetUid : -1);
5061 if (target > 0) {
5062 if (needed == null) {
5063 needed = new NeededUriGrants(targetPkg, target, mode);
5064 }
5065 needed.add(uri);
5066 }
5067 } else {
5068 Intent clipIntent = clip.getItemAt(i).getIntent();
5069 if (clipIntent != null) {
5070 NeededUriGrants newNeeded = checkGrantUriPermissionFromIntentLocked(
5071 callingUid, targetPkg, clipIntent, mode, needed);
5072 if (newNeeded != null) {
5073 needed = newNeeded;
5074 }
5075 }
5076 }
5077 }
5078 }
5079
5080 return needed;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005081 }
5082
5083 /**
5084 * Like grantUriPermissionUncheckedLocked, but takes an Intent.
5085 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005086 void grantUriPermissionUncheckedFromIntentLocked(NeededUriGrants needed,
5087 UriPermissionOwner owner) {
5088 if (needed != null) {
5089 for (int i=0; i<needed.size(); i++) {
5090 grantUriPermissionUncheckedLocked(needed.targetUid, needed.targetPkg,
5091 needed.get(i), needed.flags, owner);
5092 }
5093 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005094 }
5095
5096 void grantUriPermissionFromIntentLocked(int callingUid,
5097 String targetPkg, Intent intent, UriPermissionOwner owner) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005098 NeededUriGrants needed = checkGrantUriPermissionFromIntentLocked(callingUid, targetPkg,
Dianne Hackbornd9781fe2012-03-08 18:04:18 -08005099 intent, intent != null ? intent.getFlags() : 0, null);
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005100 if (needed == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005101 return;
5102 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005103
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005104 grantUriPermissionUncheckedFromIntentLocked(needed, owner);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005105 }
5106
5107 public void grantUriPermission(IApplicationThread caller, String targetPkg,
5108 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005109 enforceNotIsolatedCaller("grantUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005110 synchronized(this) {
5111 final ProcessRecord r = getRecordForAppLocked(caller);
5112 if (r == null) {
5113 throw new SecurityException("Unable to find app for caller "
5114 + caller
5115 + " when granting permission to uri " + uri);
5116 }
5117 if (targetPkg == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005118 throw new IllegalArgumentException("null target");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005119 }
5120 if (uri == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005121 throw new IllegalArgumentException("null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005122 }
5123
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005124 grantUriPermissionLocked(r.uid, targetPkg, uri, modeFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005125 null);
5126 }
5127 }
5128
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005129 void removeUriPermissionIfNeededLocked(UriPermission perm) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005130 if ((perm.modeFlags&(Intent.FLAG_GRANT_READ_URI_PERMISSION
5131 |Intent.FLAG_GRANT_WRITE_URI_PERMISSION)) == 0) {
5132 HashMap<Uri, UriPermission> perms
5133 = mGrantedUriPermissions.get(perm.uid);
5134 if (perms != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005135 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005136 "Removing " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005137 perms.remove(perm.uri);
5138 if (perms.size() == 0) {
5139 mGrantedUriPermissions.remove(perm.uid);
5140 }
5141 }
5142 }
5143 }
5144
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005145 private void revokeUriPermissionLocked(int callingUid, Uri uri,
5146 int modeFlags) {
5147 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5148 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5149 if (modeFlags == 0) {
5150 return;
5151 }
5152
Joe Onorato8a9b2202010-02-26 18:56:32 -08005153 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005154 "Revoking all granted permissions to " + uri);
5155
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005156 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005157
5158 final String authority = uri.getAuthority();
5159 ProviderInfo pi = null;
Amith Yamasani483f3b02012-03-13 16:08:00 -07005160 int userId = UserId.getUserId(callingUid);
5161 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005162 if (cpr != null) {
5163 pi = cpr.info;
5164 } else {
5165 try {
5166 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005167 PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005168 } catch (RemoteException ex) {
5169 }
5170 }
5171 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005172 Slog.w(TAG, "No content provider found for permission revoke: " + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005173 return;
5174 }
5175
5176 // Does the caller have this permission on the URI?
Dianne Hackborn48058e82010-09-27 16:53:23 -07005177 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005178 // Right now, if you are not the original owner of the permission,
5179 // you are not allowed to revoke it.
5180 //if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5181 throw new SecurityException("Uid " + callingUid
5182 + " does not have permission to uri " + uri);
5183 //}
5184 }
5185
5186 // Go through all of the permissions and remove any that match.
5187 final List<String> SEGMENTS = uri.getPathSegments();
5188 if (SEGMENTS != null) {
5189 final int NS = SEGMENTS.size();
5190 int N = mGrantedUriPermissions.size();
5191 for (int i=0; i<N; i++) {
5192 HashMap<Uri, UriPermission> perms
5193 = mGrantedUriPermissions.valueAt(i);
5194 Iterator<UriPermission> it = perms.values().iterator();
5195 toploop:
5196 while (it.hasNext()) {
5197 UriPermission perm = it.next();
5198 Uri targetUri = perm.uri;
5199 if (!authority.equals(targetUri.getAuthority())) {
5200 continue;
5201 }
5202 List<String> targetSegments = targetUri.getPathSegments();
5203 if (targetSegments == null) {
5204 continue;
5205 }
5206 if (targetSegments.size() < NS) {
5207 continue;
5208 }
5209 for (int j=0; j<NS; j++) {
5210 if (!SEGMENTS.get(j).equals(targetSegments.get(j))) {
5211 continue toploop;
5212 }
5213 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08005214 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005215 "Revoking " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005216 perm.clearModes(modeFlags);
5217 if (perm.modeFlags == 0) {
5218 it.remove();
5219 }
5220 }
5221 if (perms.size() == 0) {
5222 mGrantedUriPermissions.remove(
5223 mGrantedUriPermissions.keyAt(i));
5224 N--;
5225 i--;
5226 }
5227 }
5228 }
5229 }
5230
5231 public void revokeUriPermission(IApplicationThread caller, Uri uri,
5232 int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005233 enforceNotIsolatedCaller("revokeUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005234 synchronized(this) {
5235 final ProcessRecord r = getRecordForAppLocked(caller);
5236 if (r == null) {
5237 throw new SecurityException("Unable to find app for caller "
5238 + caller
5239 + " when revoking permission to uri " + uri);
5240 }
5241 if (uri == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005242 Slog.w(TAG, "revokeUriPermission: null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005243 return;
5244 }
5245
5246 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5247 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5248 if (modeFlags == 0) {
5249 return;
5250 }
5251
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005252 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005253
5254 final String authority = uri.getAuthority();
5255 ProviderInfo pi = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005256 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005257 if (cpr != null) {
5258 pi = cpr.info;
5259 } else {
5260 try {
5261 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005262 PackageManager.GET_URI_PERMISSION_PATTERNS, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005263 } catch (RemoteException ex) {
5264 }
5265 }
5266 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005267 Slog.w(TAG, "No content provider found for permission revoke: "
5268 + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005269 return;
5270 }
5271
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005272 revokeUriPermissionLocked(r.uid, uri, modeFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005273 }
5274 }
5275
Dianne Hackborn7e269642010-08-25 19:50:20 -07005276 @Override
5277 public IBinder newUriPermissionOwner(String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005278 enforceNotIsolatedCaller("newUriPermissionOwner");
Dianne Hackborn7e269642010-08-25 19:50:20 -07005279 synchronized(this) {
5280 UriPermissionOwner owner = new UriPermissionOwner(this, name);
5281 return owner.getExternalTokenLocked();
5282 }
5283 }
5284
5285 @Override
5286 public void grantUriPermissionFromOwner(IBinder token, int fromUid, String targetPkg,
5287 Uri uri, int modeFlags) {
5288 synchronized(this) {
5289 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5290 if (owner == null) {
5291 throw new IllegalArgumentException("Unknown owner: " + token);
5292 }
5293 if (fromUid != Binder.getCallingUid()) {
5294 if (Binder.getCallingUid() != Process.myUid()) {
5295 // Only system code can grant URI permissions on behalf
5296 // of other users.
5297 throw new SecurityException("nice try");
5298 }
5299 }
5300 if (targetPkg == null) {
5301 throw new IllegalArgumentException("null target");
5302 }
5303 if (uri == null) {
5304 throw new IllegalArgumentException("null uri");
5305 }
5306
5307 grantUriPermissionLocked(fromUid, targetPkg, uri, modeFlags, owner);
5308 }
5309 }
5310
5311 @Override
5312 public void revokeUriPermissionFromOwner(IBinder token, Uri uri, int mode) {
5313 synchronized(this) {
5314 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5315 if (owner == null) {
5316 throw new IllegalArgumentException("Unknown owner: " + token);
5317 }
5318
5319 if (uri == null) {
5320 owner.removeUriPermissionsLocked(mode);
5321 } else {
5322 owner.removeUriPermissionLocked(uri, mode);
5323 }
5324 }
5325 }
5326
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005327 public void showWaitingForDebugger(IApplicationThread who, boolean waiting) {
5328 synchronized (this) {
5329 ProcessRecord app =
5330 who != null ? getRecordForAppLocked(who) : null;
5331 if (app == null) return;
5332
5333 Message msg = Message.obtain();
5334 msg.what = WAIT_FOR_DEBUGGER_MSG;
5335 msg.obj = app;
5336 msg.arg1 = waiting ? 1 : 0;
5337 mHandler.sendMessage(msg);
5338 }
5339 }
5340
5341 public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07005342 final long homeAppMem = mProcessList.getMemLevel(ProcessList.HOME_APP_ADJ);
5343 final long hiddenAppMem = mProcessList.getMemLevel(ProcessList.HIDDEN_APP_MIN_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005344 outInfo.availMem = Process.getFreeMemory();
Dianne Hackborn59325eb2012-05-09 18:45:20 -07005345 outInfo.totalMem = Process.getTotalMemory();
Dianne Hackborn7d608422011-08-07 16:24:18 -07005346 outInfo.threshold = homeAppMem;
5347 outInfo.lowMemory = outInfo.availMem < (homeAppMem + ((hiddenAppMem-homeAppMem)/2));
5348 outInfo.hiddenAppThreshold = hiddenAppMem;
5349 outInfo.secondaryServerThreshold = mProcessList.getMemLevel(
Dianne Hackborne02c88a2011-10-28 13:58:15 -07005350 ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07005351 outInfo.visibleAppThreshold = mProcessList.getMemLevel(
5352 ProcessList.VISIBLE_APP_ADJ);
5353 outInfo.foregroundAppThreshold = mProcessList.getMemLevel(
5354 ProcessList.FOREGROUND_APP_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005355 }
5356
5357 // =========================================================
5358 // TASK MANAGEMENT
5359 // =========================================================
5360
5361 public List getTasks(int maxNum, int flags,
5362 IThumbnailReceiver receiver) {
5363 ArrayList list = new ArrayList();
5364
5365 PendingThumbnailsRecord pending = null;
5366 IApplicationThread topThumbnail = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005367 ActivityRecord topRecord = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005368
5369 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005370 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005371 TAG, "getTasks: max=" + maxNum + ", flags=" + flags
5372 + ", receiver=" + receiver);
5373
5374 if (checkCallingPermission(android.Manifest.permission.GET_TASKS)
5375 != PackageManager.PERMISSION_GRANTED) {
5376 if (receiver != null) {
5377 // If the caller wants to wait for pending thumbnails,
5378 // it ain't gonna get them.
5379 try {
5380 receiver.finished();
5381 } catch (RemoteException ex) {
5382 }
5383 }
5384 String msg = "Permission Denial: getTasks() from pid="
5385 + Binder.getCallingPid()
5386 + ", uid=" + Binder.getCallingUid()
5387 + " requires " + android.Manifest.permission.GET_TASKS;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005388 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005389 throw new SecurityException(msg);
5390 }
5391
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005392 int pos = mMainStack.mHistory.size()-1;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005393 ActivityRecord next =
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005394 pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005395 ActivityRecord top = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005396 TaskRecord curTask = null;
5397 int numActivities = 0;
5398 int numRunning = 0;
5399 while (pos >= 0 && maxNum > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005400 final ActivityRecord r = next;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005401 pos--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005402 next = pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005403
5404 // Initialize state for next task if needed.
5405 if (top == null ||
5406 (top.state == ActivityState.INITIALIZING
5407 && top.task == r.task)) {
5408 top = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005409 curTask = r.task;
5410 numActivities = numRunning = 0;
5411 }
5412
5413 // Add 'r' into the current task.
5414 numActivities++;
5415 if (r.app != null && r.app.thread != null) {
5416 numRunning++;
5417 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005418
Joe Onorato8a9b2202010-02-26 18:56:32 -08005419 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005420 TAG, r.intent.getComponent().flattenToShortString()
5421 + ": task=" + r.task);
5422
5423 // If the next one is a different task, generate a new
5424 // TaskInfo entry for what we have.
5425 if (next == null || next.task != curTask) {
5426 ActivityManager.RunningTaskInfo ci
5427 = new ActivityManager.RunningTaskInfo();
5428 ci.id = curTask.taskId;
5429 ci.baseActivity = r.intent.getComponent();
5430 ci.topActivity = top.intent.getComponent();
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005431 if (top.thumbHolder != null) {
5432 ci.description = top.thumbHolder.lastDescription;
5433 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005434 ci.numActivities = numActivities;
5435 ci.numRunning = numRunning;
5436 //System.out.println(
5437 // "#" + maxNum + ": " + " descr=" + ci.description);
5438 if (ci.thumbnail == null && receiver != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005439 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005440 TAG, "State=" + top.state + "Idle=" + top.idle
5441 + " app=" + top.app
5442 + " thr=" + (top.app != null ? top.app.thread : null));
5443 if (top.state == ActivityState.RESUMED
5444 || top.state == ActivityState.PAUSING) {
5445 if (top.idle && top.app != null
5446 && top.app.thread != null) {
5447 topRecord = top;
5448 topThumbnail = top.app.thread;
5449 } else {
5450 top.thumbnailNeeded = true;
5451 }
5452 }
5453 if (pending == null) {
5454 pending = new PendingThumbnailsRecord(receiver);
5455 }
5456 pending.pendingRecords.add(top);
5457 }
5458 list.add(ci);
5459 maxNum--;
5460 top = null;
5461 }
5462 }
5463
5464 if (pending != null) {
5465 mPendingThumbnails.add(pending);
5466 }
5467 }
5468
Joe Onorato8a9b2202010-02-26 18:56:32 -08005469 if (localLOGV) Slog.v(TAG, "We have pending thumbnails: " + pending);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005470
5471 if (topThumbnail != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005472 if (localLOGV) Slog.v(TAG, "Requesting top thumbnail");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005473 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08005474 topThumbnail.requestThumbnail(topRecord.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005475 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005476 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005477 sendPendingThumbnail(null, topRecord.appToken, null, null, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005478 }
5479 }
5480
5481 if (pending == null && receiver != null) {
5482 // In this case all thumbnails were available and the client
5483 // is being asked to be told when the remaining ones come in...
5484 // which is unusually, since the top-most currently running
5485 // activity should never have a canned thumbnail! Oh well.
5486 try {
5487 receiver.finished();
5488 } catch (RemoteException ex) {
5489 }
5490 }
5491
5492 return list;
5493 }
5494
5495 public List<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum,
5496 int flags) {
Amith Yamasani742a6712011-05-04 14:49:28 -07005497 final int callingUid = Binder.getCallingUid();
5498 // If it's the system uid asking, then use the current user id.
5499 // TODO: Make sure that there aren't any other legitimate calls from the system uid that
5500 // require the entire list.
5501 final int callingUserId = callingUid == Process.SYSTEM_UID
5502 ? mCurrentUserId : UserId.getUserId(callingUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005503 synchronized (this) {
5504 enforceCallingPermission(android.Manifest.permission.GET_TASKS,
5505 "getRecentTasks()");
Dianne Hackborn8238e712012-04-24 11:15:40 -07005506 final boolean detailed = checkCallingPermission(
5507 android.Manifest.permission.GET_DETAILED_TASKS)
5508 == PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005509
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005510 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005511
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005512 final int N = mRecentTasks.size();
5513 ArrayList<ActivityManager.RecentTaskInfo> res
5514 = new ArrayList<ActivityManager.RecentTaskInfo>(
5515 maxNum < N ? maxNum : N);
5516 for (int i=0; i<N && maxNum > 0; i++) {
5517 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005518 // Only add calling user's recent tasks
5519 if (tr.userId != callingUserId) continue;
Dianne Hackborn905577f2011-09-07 18:31:28 -07005520 // Return the entry if desired by the caller. We always return
5521 // the first entry, because callers always expect this to be the
Amith Yamasani742a6712011-05-04 14:49:28 -07005522 // foreground app. We may filter others if the caller has
Dianne Hackborn905577f2011-09-07 18:31:28 -07005523 // not supplied RECENT_WITH_EXCLUDED and there is some reason
5524 // we should exclude the entry.
Amith Yamasani742a6712011-05-04 14:49:28 -07005525
Dianne Hackborn905577f2011-09-07 18:31:28 -07005526 if (i == 0
5527 || ((flags&ActivityManager.RECENT_WITH_EXCLUDED) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005528 || (tr.intent == null)
5529 || ((tr.intent.getFlags()
5530 &Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) == 0)) {
5531 ActivityManager.RecentTaskInfo rti
5532 = new ActivityManager.RecentTaskInfo();
5533 rti.id = tr.numActivities > 0 ? tr.taskId : -1;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005534 rti.persistentId = tr.taskId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005535 rti.baseIntent = new Intent(
5536 tr.intent != null ? tr.intent : tr.affinityIntent);
Dianne Hackborn8238e712012-04-24 11:15:40 -07005537 if (!detailed) {
5538 rti.baseIntent.replaceExtras((Bundle)null);
5539 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005540 rti.origActivity = tr.origActivity;
Dianne Hackbornd2835932010-12-13 16:28:46 -08005541 rti.description = tr.lastDescription;
5542
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005543 if ((flags&ActivityManager.RECENT_IGNORE_UNAVAILABLE) != 0) {
5544 // Check whether this activity is currently available.
5545 try {
5546 if (rti.origActivity != null) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07005547 if (pm.getActivityInfo(rti.origActivity, 0, callingUserId)
5548 == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005549 continue;
5550 }
5551 } else if (rti.baseIntent != null) {
5552 if (pm.queryIntentActivities(rti.baseIntent,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005553 null, 0, callingUserId) == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005554 continue;
5555 }
5556 }
5557 } catch (RemoteException e) {
5558 // Will never happen.
5559 }
5560 }
5561
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005562 res.add(rti);
5563 maxNum--;
5564 }
5565 }
5566 return res;
5567 }
5568 }
5569
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005570 private TaskRecord taskForIdLocked(int id) {
5571 final int N = mRecentTasks.size();
5572 for (int i=0; i<N; i++) {
5573 TaskRecord tr = mRecentTasks.get(i);
5574 if (tr.taskId == id) {
5575 return tr;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005576 }
5577 }
5578 return null;
5579 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005580
5581 public ActivityManager.TaskThumbnails getTaskThumbnails(int id) {
5582 synchronized (this) {
5583 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
5584 "getTaskThumbnails()");
5585 TaskRecord tr = taskForIdLocked(id);
5586 if (tr != null) {
5587 return mMainStack.getTaskThumbnailsLocked(tr);
5588 }
5589 }
5590 return null;
5591 }
5592
5593 public boolean removeSubTask(int taskId, int subTaskIndex) {
5594 synchronized (this) {
5595 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5596 "removeSubTask()");
5597 long ident = Binder.clearCallingIdentity();
5598 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005599 return mMainStack.removeTaskActivitiesLocked(taskId, subTaskIndex,
5600 true) != null;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005601 } finally {
5602 Binder.restoreCallingIdentity(ident);
5603 }
5604 }
5605 }
5606
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005607 private void cleanUpRemovedTaskLocked(TaskRecord tr, int flags) {
5608 final boolean killProcesses = (flags&ActivityManager.REMOVE_TASK_KILL_PROCESS) != 0;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005609 Intent baseIntent = new Intent(
5610 tr.intent != null ? tr.intent : tr.affinityIntent);
5611 ComponentName component = baseIntent.getComponent();
5612 if (component == null) {
5613 Slog.w(TAG, "Now component for base intent of task: " + tr);
5614 return;
5615 }
5616
5617 // Find any running services associated with this app.
5618 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005619 for (ServiceRecord sr : mServiceMap.getAllServices(tr.userId)) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005620 if (sr.packageName.equals(component.getPackageName())) {
5621 services.add(sr);
5622 }
5623 }
5624
5625 // Take care of any running services associated with the app.
5626 for (int i=0; i<services.size(); i++) {
5627 ServiceRecord sr = services.get(i);
5628 if (sr.startRequested) {
5629 if ((sr.serviceInfo.flags&ServiceInfo.FLAG_STOP_WITH_TASK) != 0) {
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005630 Slog.i(TAG, "Stopping service " + sr.shortName + ": remove task");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005631 stopServiceLocked(sr);
5632 } else {
5633 sr.pendingStarts.add(new ServiceRecord.StartItem(sr, true,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005634 sr.makeNextStartId(), baseIntent, null));
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005635 if (sr.app != null && sr.app.thread != null) {
5636 sendServiceArgsLocked(sr, false);
5637 }
5638 }
5639 }
5640 }
5641
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005642 if (killProcesses) {
5643 // Find any running processes associated with this app.
5644 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
5645 SparseArray<ProcessRecord> appProcs
5646 = mProcessNames.getMap().get(component.getPackageName());
5647 if (appProcs != null) {
5648 for (int i=0; i<appProcs.size(); i++) {
5649 procs.add(appProcs.valueAt(i));
5650 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005651 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005652
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005653 // Kill the running processes.
5654 for (int i=0; i<procs.size(); i++) {
5655 ProcessRecord pr = procs.get(i);
5656 if (pr.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
5657 Slog.i(TAG, "Killing " + pr.toShortString() + ": remove task");
5658 EventLog.writeEvent(EventLogTags.AM_KILL, pr.pid,
5659 pr.processName, pr.setAdj, "remove task");
5660 Process.killProcessQuiet(pr.pid);
5661 } else {
5662 pr.waitingToKill = "remove task";
5663 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005664 }
5665 }
5666 }
5667
5668 public boolean removeTask(int taskId, int flags) {
5669 synchronized (this) {
5670 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5671 "removeTask()");
5672 long ident = Binder.clearCallingIdentity();
5673 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005674 ActivityRecord r = mMainStack.removeTaskActivitiesLocked(taskId, -1,
5675 false);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005676 if (r != null) {
5677 mRecentTasks.remove(r.task);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005678 cleanUpRemovedTaskLocked(r.task, flags);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005679 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005680 } else {
5681 TaskRecord tr = null;
5682 int i=0;
5683 while (i < mRecentTasks.size()) {
5684 TaskRecord t = mRecentTasks.get(i);
5685 if (t.taskId == taskId) {
5686 tr = t;
5687 break;
5688 }
5689 i++;
5690 }
5691 if (tr != null) {
5692 if (tr.numActivities <= 0) {
5693 // Caller is just removing a recent task that is
5694 // not actively running. That is easy!
5695 mRecentTasks.remove(i);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005696 cleanUpRemovedTaskLocked(tr, flags);
5697 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005698 } else {
5699 Slog.w(TAG, "removeTask: task " + taskId
5700 + " does not have activities to remove, "
5701 + " but numActivities=" + tr.numActivities
5702 + ": " + tr);
5703 }
5704 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005705 }
5706 } finally {
5707 Binder.restoreCallingIdentity(ident);
5708 }
5709 }
5710 return false;
5711 }
Dianne Hackbornd94df452011-02-16 18:53:31 -08005712
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005713 private final int findAffinityTaskTopLocked(int startIndex, String affinity) {
5714 int j;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005715 TaskRecord startTask = ((ActivityRecord)mMainStack.mHistory.get(startIndex)).task;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005716 TaskRecord jt = startTask;
5717
5718 // First look backwards
5719 for (j=startIndex-1; j>=0; j--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005720 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005721 if (r.task != jt) {
5722 jt = r.task;
5723 if (affinity.equals(jt.affinity)) {
5724 return j;
5725 }
5726 }
5727 }
5728
5729 // Now look forwards
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005730 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005731 jt = startTask;
5732 for (j=startIndex+1; j<N; j++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005733 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005734 if (r.task != jt) {
5735 if (affinity.equals(jt.affinity)) {
5736 return j;
5737 }
5738 jt = r.task;
5739 }
5740 }
5741
5742 // Might it be at the top?
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005743 if (affinity.equals(((ActivityRecord)mMainStack.mHistory.get(N-1)).task.affinity)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005744 return N-1;
5745 }
5746
5747 return -1;
5748 }
5749
5750 /**
Dianne Hackbornb06ea702009-07-13 13:07:51 -07005751 * TODO: Add mController hook
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005752 */
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005753 public void moveTaskToFront(int task, int flags, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005754 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5755 "moveTaskToFront()");
5756
5757 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005758 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5759 Binder.getCallingUid(), "Task to front")) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005760 ActivityOptions.abort(options);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005761 return;
5762 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005763 final long origId = Binder.clearCallingIdentity();
5764 try {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005765 TaskRecord tr = taskForIdLocked(task);
5766 if (tr != null) {
5767 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5768 mMainStack.mUserLeaving = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005769 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005770 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5771 // Caller wants the home activity moved with it. To accomplish this,
5772 // we'll just move the home task to the top first.
5773 mMainStack.moveHomeToFrontLocked();
5774 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005775 mMainStack.moveTaskToFrontLocked(tr, null, options);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005776 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005777 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005778 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
5779 ActivityRecord hr = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005780 if (hr.task.taskId == task) {
Dianne Hackbornd94df452011-02-16 18:53:31 -08005781 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5782 mMainStack.mUserLeaving = true;
5783 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005784 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5785 // Caller wants the home activity moved with it. To accomplish this,
5786 // we'll just move the home task to the top first.
5787 mMainStack.moveHomeToFrontLocked();
5788 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005789 mMainStack.moveTaskToFrontLocked(hr.task, null, options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005790 return;
5791 }
5792 }
5793 } finally {
5794 Binder.restoreCallingIdentity(origId);
5795 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005796 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005797 }
5798 }
5799
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005800 public void moveTaskToBack(int task) {
5801 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5802 "moveTaskToBack()");
5803
5804 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005805 if (mMainStack.mResumedActivity != null
5806 && mMainStack.mResumedActivity.task.taskId == task) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005807 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5808 Binder.getCallingUid(), "Task to back")) {
5809 return;
5810 }
5811 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005812 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005813 mMainStack.moveTaskToBackLocked(task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005814 Binder.restoreCallingIdentity(origId);
5815 }
5816 }
5817
5818 /**
5819 * Moves an activity, and all of the other activities within the same task, to the bottom
5820 * of the history stack. The activity's order within the task is unchanged.
5821 *
5822 * @param token A reference to the activity we wish to move
5823 * @param nonRoot If false then this only works if the activity is the root
5824 * of a task; if true it will work for any activity in a task.
5825 * @return Returns true if the move completed, false if not.
5826 */
5827 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005828 enforceNotIsolatedCaller("moveActivityTaskToBack");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005829 synchronized(this) {
5830 final long origId = Binder.clearCallingIdentity();
5831 int taskId = getTaskForActivityLocked(token, !nonRoot);
5832 if (taskId >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005833 return mMainStack.moveTaskToBackLocked(taskId, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005834 }
5835 Binder.restoreCallingIdentity(origId);
5836 }
5837 return false;
5838 }
5839
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005840 public void moveTaskBackwards(int task) {
5841 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5842 "moveTaskBackwards()");
5843
5844 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005845 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5846 Binder.getCallingUid(), "Task backwards")) {
5847 return;
5848 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005849 final long origId = Binder.clearCallingIdentity();
5850 moveTaskBackwardsLocked(task);
5851 Binder.restoreCallingIdentity(origId);
5852 }
5853 }
5854
5855 private final void moveTaskBackwardsLocked(int task) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005856 Slog.e(TAG, "moveTaskBackwards not yet implemented!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005857 }
5858
5859 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
5860 synchronized(this) {
5861 return getTaskForActivityLocked(token, onlyRoot);
5862 }
5863 }
5864
5865 int getTaskForActivityLocked(IBinder token, boolean onlyRoot) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005866 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005867 TaskRecord lastTask = null;
5868 for (int i=0; i<N; i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005869 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005870 if (r.appToken == token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005871 if (!onlyRoot || lastTask != r.task) {
5872 return r.task.taskId;
5873 }
5874 return -1;
5875 }
5876 lastTask = r.task;
5877 }
5878
5879 return -1;
5880 }
5881
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005882 // =========================================================
5883 // THUMBNAILS
5884 // =========================================================
5885
5886 public void reportThumbnail(IBinder token,
5887 Bitmap thumbnail, CharSequence description) {
5888 //System.out.println("Report thumbnail for " + token + ": " + thumbnail);
5889 final long origId = Binder.clearCallingIdentity();
5890 sendPendingThumbnail(null, token, thumbnail, description, true);
5891 Binder.restoreCallingIdentity(origId);
5892 }
5893
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005894 final void sendPendingThumbnail(ActivityRecord r, IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005895 Bitmap thumbnail, CharSequence description, boolean always) {
5896 TaskRecord task = null;
5897 ArrayList receivers = null;
5898
5899 //System.out.println("Send pending thumbnail: " + r);
5900
5901 synchronized(this) {
5902 if (r == null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07005903 r = mMainStack.isInStackLocked(token);
5904 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005905 return;
5906 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005907 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005908 if (thumbnail == null && r.thumbHolder != null) {
5909 thumbnail = r.thumbHolder.lastThumbnail;
5910 description = r.thumbHolder.lastDescription;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005911 }
5912 if (thumbnail == null && !always) {
5913 // If there is no thumbnail, and this entry is not actually
5914 // going away, then abort for now and pick up the next
5915 // thumbnail we get.
5916 return;
5917 }
5918 task = r.task;
5919
5920 int N = mPendingThumbnails.size();
5921 int i=0;
5922 while (i<N) {
5923 PendingThumbnailsRecord pr =
5924 (PendingThumbnailsRecord)mPendingThumbnails.get(i);
5925 //System.out.println("Looking in " + pr.pendingRecords);
5926 if (pr.pendingRecords.remove(r)) {
5927 if (receivers == null) {
5928 receivers = new ArrayList();
5929 }
5930 receivers.add(pr);
5931 if (pr.pendingRecords.size() == 0) {
5932 pr.finished = true;
5933 mPendingThumbnails.remove(i);
5934 N--;
5935 continue;
5936 }
5937 }
5938 i++;
5939 }
5940 }
5941
5942 if (receivers != null) {
5943 final int N = receivers.size();
5944 for (int i=0; i<N; i++) {
5945 try {
5946 PendingThumbnailsRecord pr =
5947 (PendingThumbnailsRecord)receivers.get(i);
5948 pr.receiver.newThumbnail(
5949 task != null ? task.taskId : -1, thumbnail, description);
5950 if (pr.finished) {
5951 pr.receiver.finished();
5952 }
5953 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005954 Slog.w(TAG, "Exception thrown when sending thumbnail", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005955 }
5956 }
5957 }
5958 }
5959
5960 // =========================================================
5961 // CONTENT PROVIDERS
5962 // =========================================================
5963
Jeff Brown10e89712011-07-08 18:52:57 -07005964 private final List<ProviderInfo> generateApplicationProvidersLocked(ProcessRecord app) {
5965 List<ProviderInfo> providers = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005966 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005967 providers = AppGlobals.getPackageManager().
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005968 queryContentProviders(app.processName, app.uid,
Dianne Hackborn1655be42009-05-08 14:29:01 -07005969 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005970 } catch (RemoteException ex) {
5971 }
Amith Yamasani742a6712011-05-04 14:49:28 -07005972 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005973 Slog.v(TAG_MU, "generateApplicationProvidersLocked, app.info.uid = " + app.uid);
5974 int userId = app.userId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005975 if (providers != null) {
5976 final int N = providers.size();
5977 for (int i=0; i<N; i++) {
5978 ProviderInfo cpi =
5979 (ProviderInfo)providers.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005980
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07005981 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07005982 ContentProviderRecord cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005983 if (cpr == null) {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08005984 cpr = new ContentProviderRecord(this, cpi, app.info, comp);
Amith Yamasani742a6712011-05-04 14:49:28 -07005985 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005986 }
Amith Yamasani742a6712011-05-04 14:49:28 -07005987 if (DEBUG_MU)
5988 Slog.v(TAG_MU, "generateApplicationProvidersLocked, cpi.uid = " + cpr.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005989 app.pubProviders.put(cpi.name, cpr);
5990 app.addPackage(cpi.applicationInfo.packageName);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07005991 ensurePackageDexOpt(cpi.applicationInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005992 }
5993 }
5994 return providers;
5995 }
5996
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005997 /**
5998 * Check if {@link ProcessRecord} has a possible chance at accessing the
5999 * given {@link ProviderInfo}. Final permission checking is always done
6000 * in {@link ContentProvider}.
6001 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006002 private final String checkContentProviderPermissionLocked(
Dianne Hackbornb424b632010-08-18 15:59:05 -07006003 ProviderInfo cpi, ProcessRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006004 final int callingPid = (r != null) ? r.pid : Binder.getCallingPid();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006005 final int callingUid = (r != null) ? r.uid : Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006006 if (checkComponentPermission(cpi.readPermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006007 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006008 == PackageManager.PERMISSION_GRANTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006009 return null;
6010 }
6011 if (checkComponentPermission(cpi.writePermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006012 cpi.applicationInfo.uid, cpi.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006013 == PackageManager.PERMISSION_GRANTED) {
6014 return null;
6015 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006016
6017 PathPermission[] pps = cpi.pathPermissions;
6018 if (pps != null) {
6019 int i = pps.length;
6020 while (i > 0) {
6021 i--;
6022 PathPermission pp = pps[i];
6023 if (checkComponentPermission(pp.getReadPermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006024 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006025 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006026 return null;
6027 }
6028 if (checkComponentPermission(pp.getWritePermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006029 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006030 == PackageManager.PERMISSION_GRANTED) {
6031 return null;
6032 }
6033 }
6034 }
6035
Dianne Hackbornb424b632010-08-18 15:59:05 -07006036 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(callingUid);
6037 if (perms != null) {
6038 for (Map.Entry<Uri, UriPermission> uri : perms.entrySet()) {
6039 if (uri.getKey().getAuthority().equals(cpi.authority)) {
6040 return null;
6041 }
6042 }
6043 }
6044
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006045 String msg;
6046 if (!cpi.exported) {
6047 msg = "Permission Denial: opening provider " + cpi.name
6048 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6049 + ", uid=" + callingUid + ") that is not exported from uid "
6050 + cpi.applicationInfo.uid;
6051 } else {
6052 msg = "Permission Denial: opening provider " + cpi.name
6053 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6054 + ", uid=" + callingUid + ") requires "
6055 + cpi.readPermission + " or " + cpi.writePermission;
6056 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08006057 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006058 return msg;
6059 }
6060
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006061 boolean incProviderCount(ProcessRecord r, final ContentProviderRecord cpr,
6062 IBinder externalProcessToken) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006063 if (r != null) {
6064 Integer cnt = r.conProviders.get(cpr);
6065 if (DEBUG_PROVIDER) Slog.v(TAG,
6066 "Adding provider requested by "
6067 + r.processName + " from process "
6068 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
6069 + " cnt=" + (cnt == null ? 1 : cnt));
6070 if (cnt == null) {
6071 cpr.clients.add(r);
6072 r.conProviders.put(cpr, new Integer(1));
6073 return true;
6074 } else {
6075 r.conProviders.put(cpr, new Integer(cnt.intValue()+1));
6076 }
6077 } else {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006078 cpr.addExternalProcessHandleLocked(externalProcessToken);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006079 }
6080 return false;
6081 }
6082
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006083 boolean decProviderCount(ProcessRecord r, final ContentProviderRecord cpr,
6084 IBinder externalProcessToken) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006085 if (r != null) {
6086 Integer cnt = r.conProviders.get(cpr);
6087 if (DEBUG_PROVIDER) Slog.v(TAG,
6088 "Removing provider requested by "
6089 + r.processName + " from process "
6090 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
6091 + " cnt=" + cnt);
6092 if (cnt == null || cnt.intValue() <= 1) {
6093 cpr.clients.remove(r);
6094 r.conProviders.remove(cpr);
6095 return true;
6096 } else {
6097 r.conProviders.put(cpr, new Integer(cnt.intValue()-1));
6098 }
6099 } else {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006100 cpr.removeExternalProcessHandleLocked(externalProcessToken);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006101 }
6102 return false;
6103 }
6104
Amith Yamasani742a6712011-05-04 14:49:28 -07006105 private final ContentProviderHolder getContentProviderImpl(IApplicationThread caller,
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006106 String name, IBinder token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006107 ContentProviderRecord cpr;
6108 ProviderInfo cpi = null;
6109
6110 synchronized(this) {
6111 ProcessRecord r = null;
6112 if (caller != null) {
6113 r = getRecordForAppLocked(caller);
6114 if (r == null) {
6115 throw new SecurityException(
6116 "Unable to find app for caller " + caller
6117 + " (pid=" + Binder.getCallingPid()
6118 + ") when getting content provider " + name);
6119 }
6120 }
6121
6122 // First check if this content provider has been published...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006123 int userId = UserId.getUserId(r != null ? r.uid : Binder.getCallingUid());
Amith Yamasani742a6712011-05-04 14:49:28 -07006124 cpr = mProviderMap.getProviderByName(name, userId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006125 boolean providerRunning = cpr != null;
6126 if (providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006127 cpi = cpr.info;
Dianne Hackbornb424b632010-08-18 15:59:05 -07006128 String msg;
6129 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6130 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006131 }
6132
6133 if (r != null && cpr.canRunHere(r)) {
6134 // This provider has been published or is in the process
6135 // of being published... but it is also allowed to run
6136 // in the caller's process, so don't make a connection
6137 // and just let the caller instantiate its own instance.
6138 if (cpr.provider != null) {
6139 // don't give caller the provider object, it needs
6140 // to make its own.
6141 cpr = new ContentProviderRecord(cpr);
6142 }
6143 return cpr;
6144 }
6145
6146 final long origId = Binder.clearCallingIdentity();
6147
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006148 // In this case the provider instance already exists, so we can
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006149 // return it right away.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006150 final boolean countChanged = incProviderCount(r, cpr, token);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006151 if (countChanged) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006152 if (cpr.proc != null && r.setAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006153 // If this is a perceptible app accessing the provider,
Dianne Hackborn906497c2010-05-10 15:57:38 -07006154 // make sure to count it as being accessed and thus
6155 // back up on the LRU list. This is good because
6156 // content providers are often expensive to start.
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006157 updateLruProcessLocked(cpr.proc, false, true);
Dianne Hackborn906497c2010-05-10 15:57:38 -07006158 }
Dianne Hackborn6f86c0e2010-05-11 14:20:52 -07006159 }
6160
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006161 if (cpr.proc != null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006162 if (false) {
6163 if (cpr.name.flattenToShortString().equals(
6164 "com.android.providers.calendar/.CalendarProvider2")) {
6165 Slog.v(TAG, "****************** KILLING "
6166 + cpr.name.flattenToShortString());
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006167 Process.killProcess(cpr.proc.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006168 }
6169 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006170 boolean success = updateOomAdjLocked(cpr.proc);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006171 if (DEBUG_PROVIDER) Slog.i(TAG, "Adjust success: " + success);
6172 // NOTE: there is still a race here where a signal could be
6173 // pending on the process even though we managed to update its
6174 // adj level. Not sure what to do about this, but at least
6175 // the race is now smaller.
6176 if (!success) {
6177 // Uh oh... it looks like the provider's process
6178 // has been killed on us. We need to wait for a new
6179 // process to be started, and make sure its death
6180 // doesn't kill our process.
6181 Slog.i(TAG,
6182 "Existing provider " + cpr.name.flattenToShortString()
6183 + " is crashing; detaching " + r);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006184 boolean lastRef = decProviderCount(r, cpr, token);
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006185 appDiedLocked(cpr.proc, cpr.proc.pid, cpr.proc.thread);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006186 if (!lastRef) {
6187 // This wasn't the last ref our process had on
6188 // the provider... we have now been killed, bail.
6189 return null;
6190 }
6191 providerRunning = false;
6192 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006193 }
6194
6195 Binder.restoreCallingIdentity(origId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006196 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006197
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006198 if (!providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006199 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006200 cpi = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07006201 resolveContentProvider(name,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006202 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006203 } catch (RemoteException ex) {
6204 }
6205 if (cpi == null) {
6206 return null;
6207 }
Amith Yamasania4a54e22012-04-16 15:44:19 -07006208 if (isSingleton(cpi.processName, cpi.applicationInfo)) {
6209 userId = 0;
6210 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006211 cpi.applicationInfo = getAppInfoForUser(cpi.applicationInfo, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07006212
Dianne Hackbornb424b632010-08-18 15:59:05 -07006213 String msg;
6214 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6215 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006216 }
6217
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07006218 if (!mProcessesReady && !mDidUpdate && !mWaitingUpdate
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006219 && !cpi.processName.equals("system")) {
6220 // If this content provider does not run in the system
6221 // process, and the system is not yet ready to run other
6222 // processes, then fail fast instead of hanging.
6223 throw new IllegalArgumentException(
6224 "Attempt to launch content provider before system ready");
6225 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006226
6227 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani483f3b02012-03-13 16:08:00 -07006228 cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006229 final boolean firstClass = cpr == null;
6230 if (firstClass) {
6231 try {
6232 ApplicationInfo ai =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006233 AppGlobals.getPackageManager().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006234 getApplicationInfo(
6235 cpi.applicationInfo.packageName,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006236 STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006237 if (ai == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006238 Slog.w(TAG, "No package info for content provider "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006239 + cpi.name);
6240 return null;
6241 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006242 ai = getAppInfoForUser(ai, userId);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006243 cpr = new ContentProviderRecord(this, cpi, ai, comp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006244 } catch (RemoteException ex) {
6245 // pm is in same process, this will never happen.
6246 }
6247 }
6248
6249 if (r != null && cpr.canRunHere(r)) {
6250 // If this is a multiprocess provider, then just return its
6251 // info and allow the caller to instantiate it. Only do
6252 // this if the provider is the same user as the caller's
6253 // process, or can run as root (so can be in any process).
6254 return cpr;
6255 }
6256
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006257 if (DEBUG_PROVIDER) {
6258 RuntimeException e = new RuntimeException("here");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006259 Slog.w(TAG, "LAUNCHING REMOTE PROVIDER (myuid " + r.uid
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006260 + " pruid " + cpr.appInfo.uid + "): " + cpr.info.name, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006261 }
6262
6263 // This is single process, and our app is now connecting to it.
6264 // See if we are already in the process of launching this
6265 // provider.
6266 final int N = mLaunchingProviders.size();
6267 int i;
6268 for (i=0; i<N; i++) {
6269 if (mLaunchingProviders.get(i) == cpr) {
6270 break;
6271 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006272 }
6273
6274 // If the provider is not already being launched, then get it
6275 // started.
6276 if (i >= N) {
6277 final long origId = Binder.clearCallingIdentity();
Dianne Hackborne7f97212011-02-24 14:40:20 -08006278
6279 try {
6280 // Content provider is now in use, its package can't be stopped.
6281 try {
6282 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07006283 cpr.appInfo.packageName, false, userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006284 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006285 } catch (IllegalArgumentException e) {
6286 Slog.w(TAG, "Failed trying to unstop package "
6287 + cpr.appInfo.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006288 }
6289
6290 ProcessRecord proc = startProcessLocked(cpi.processName,
6291 cpr.appInfo, false, 0, "content provider",
6292 new ComponentName(cpi.applicationInfo.packageName,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006293 cpi.name), false, false);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006294 if (proc == null) {
6295 Slog.w(TAG, "Unable to launch app "
6296 + cpi.applicationInfo.packageName + "/"
6297 + cpi.applicationInfo.uid + " for provider "
6298 + name + ": process is bad");
6299 return null;
6300 }
6301 cpr.launchingApp = proc;
6302 mLaunchingProviders.add(cpr);
6303 } finally {
6304 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006305 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006306 }
6307
6308 // Make sure the provider is published (the same provider class
6309 // may be published under multiple names).
6310 if (firstClass) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006311 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006312 }
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006313
Amith Yamasani742a6712011-05-04 14:49:28 -07006314 mProviderMap.putProviderByName(name, cpr);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006315 incProviderCount(r, cpr, token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006316 }
6317 }
6318
6319 // Wait for the provider to be published...
6320 synchronized (cpr) {
6321 while (cpr.provider == null) {
6322 if (cpr.launchingApp == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006323 Slog.w(TAG, "Unable to launch app "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006324 + cpi.applicationInfo.packageName + "/"
6325 + cpi.applicationInfo.uid + " for provider "
6326 + name + ": launching app became null");
Doug Zongker2bec3d42009-12-04 12:52:44 -08006327 EventLog.writeEvent(EventLogTags.AM_PROVIDER_LOST_PROCESS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006328 cpi.applicationInfo.packageName,
6329 cpi.applicationInfo.uid, name);
6330 return null;
6331 }
6332 try {
Amith Yamasani742a6712011-05-04 14:49:28 -07006333 if (DEBUG_MU) {
6334 Slog.v(TAG_MU, "Waiting to start provider " + cpr + " launchingApp="
6335 + cpr.launchingApp);
6336 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006337 cpr.wait();
6338 } catch (InterruptedException ex) {
6339 }
6340 }
6341 }
6342 return cpr;
6343 }
6344
6345 public final ContentProviderHolder getContentProvider(
6346 IApplicationThread caller, String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006347 enforceNotIsolatedCaller("getContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006348 if (caller == null) {
6349 String msg = "null IApplicationThread when getting content provider "
6350 + name;
Joe Onorato8a9b2202010-02-26 18:56:32 -08006351 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006352 throw new SecurityException(msg);
6353 }
6354
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006355 return getContentProviderImpl(caller, name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006356 }
6357
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006358 public ContentProviderHolder getContentProviderExternal(String name, IBinder token) {
6359 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6360 "Do not have permission in call getContentProviderExternal()");
6361 return getContentProviderExternalUnchecked(name, token);
6362 }
6363
6364 private ContentProviderHolder getContentProviderExternalUnchecked(String name,IBinder token) {
6365 return getContentProviderImpl(null, name, token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006366 }
6367
6368 /**
6369 * Drop a content provider from a ProcessRecord's bookkeeping
6370 * @param cpr
6371 */
6372 public void removeContentProvider(IApplicationThread caller, String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006373 enforceNotIsolatedCaller("removeContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006374 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006375 int userId = UserId.getUserId(Binder.getCallingUid());
6376 ContentProviderRecord cpr = mProviderMap.getProviderByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006377 if(cpr == null) {
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006378 // remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006379 if (DEBUG_PROVIDER) Slog.v(TAG, name +
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006380 " provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006381 return;
6382 }
6383 final ProcessRecord r = getRecordForAppLocked(caller);
6384 if (r == null) {
6385 throw new SecurityException(
6386 "Unable to find app for caller " + caller +
6387 " when removing content provider " + name);
6388 }
6389 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006390 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006391 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp, userId);
6392 if (DEBUG_PROVIDER) Slog.v(TAG, "Removing provider requested by "
6393 + r.info.processName + " from process "
6394 + localCpr.appInfo.processName);
6395 if (localCpr.launchingApp == r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006396 //should not happen. taken care of as a local provider
Joe Onorato8a9b2202010-02-26 18:56:32 -08006397 Slog.w(TAG, "removeContentProvider called on local provider: "
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006398 + cpr.info.name + " in process " + r.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006399 return;
6400 } else {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006401 if (decProviderCount(r, localCpr, null)) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006402 updateOomAdjLocked();
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07006403 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006404 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006405 }
6406 }
6407
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006408 public void removeContentProviderExternal(String name, IBinder token) {
6409 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6410 "Do not have permission in call removeContentProviderExternal()");
6411 removeContentProviderExternalUnchecked(name, token);
6412 }
6413
6414 private void removeContentProviderExternalUnchecked(String name, IBinder token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006415 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006416 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
6417 Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006418 if(cpr == null) {
6419 //remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006420 if(localLOGV) Slog.v(TAG, name+" content provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006421 return;
6422 }
6423
6424 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006425 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006426 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp,
6427 Binder.getOrigCallingUser());
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006428 if (localCpr.hasExternalProcessHandles()) {
6429 if (localCpr.removeExternalProcessHandleLocked(token)) {
6430 updateOomAdjLocked();
6431 } else {
6432 Slog.e(TAG, "Attmpt to remove content provider " + localCpr
6433 + " with no external reference for token: "
6434 + token + ".");
6435 }
6436 } else {
6437 Slog.e(TAG, "Attmpt to remove content provider: " + localCpr
6438 + " with no external references.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006439 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006440 }
6441 }
6442
6443 public final void publishContentProviders(IApplicationThread caller,
6444 List<ContentProviderHolder> providers) {
6445 if (providers == null) {
6446 return;
6447 }
6448
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006449 enforceNotIsolatedCaller("publishContentProviders");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006450 synchronized(this) {
6451 final ProcessRecord r = getRecordForAppLocked(caller);
Amith Yamasani742a6712011-05-04 14:49:28 -07006452 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006453 Slog.v(TAG_MU, "ProcessRecord uid = " + r.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006454 if (r == null) {
6455 throw new SecurityException(
6456 "Unable to find app for caller " + caller
6457 + " (pid=" + Binder.getCallingPid()
6458 + ") when publishing content providers");
6459 }
6460
6461 final long origId = Binder.clearCallingIdentity();
6462
6463 final int N = providers.size();
6464 for (int i=0; i<N; i++) {
6465 ContentProviderHolder src = providers.get(i);
6466 if (src == null || src.info == null || src.provider == null) {
6467 continue;
6468 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07006469 ContentProviderRecord dst = r.pubProviders.get(src.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006470 if (DEBUG_MU)
6471 Slog.v(TAG_MU, "ContentProviderRecord uid = " + dst.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006472 if (dst != null) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006473 ComponentName comp = new ComponentName(dst.info.packageName, dst.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006474 mProviderMap.putProviderByClass(comp, dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006475 String names[] = dst.info.authority.split(";");
6476 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006477 mProviderMap.putProviderByName(names[j], dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006478 }
6479
6480 int NL = mLaunchingProviders.size();
6481 int j;
6482 for (j=0; j<NL; j++) {
6483 if (mLaunchingProviders.get(j) == dst) {
6484 mLaunchingProviders.remove(j);
6485 j--;
6486 NL--;
6487 }
6488 }
6489 synchronized (dst) {
6490 dst.provider = src.provider;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006491 dst.proc = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006492 dst.notifyAll();
6493 }
6494 updateOomAdjLocked(r);
6495 }
6496 }
6497
6498 Binder.restoreCallingIdentity(origId);
6499 }
6500 }
6501
6502 public static final void installSystemProviders() {
Jeff Brown10e89712011-07-08 18:52:57 -07006503 List<ProviderInfo> providers;
Josh Bartel2ecce342010-02-25 10:55:48 -06006504 synchronized (mSelf) {
6505 ProcessRecord app = mSelf.mProcessNames.get("system", Process.SYSTEM_UID);
6506 providers = mSelf.generateApplicationProvidersLocked(app);
Dianne Hackborn5c83a5f2010-03-12 16:46:46 -08006507 if (providers != null) {
6508 for (int i=providers.size()-1; i>=0; i--) {
6509 ProviderInfo pi = (ProviderInfo)providers.get(i);
6510 if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6511 Slog.w(TAG, "Not installing system proc provider " + pi.name
6512 + ": not system .apk");
6513 providers.remove(i);
6514 }
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006515 }
6516 }
6517 }
Josh Bartel2ecce342010-02-25 10:55:48 -06006518 if (providers != null) {
6519 mSystemThread.installSystemProviders(providers);
6520 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08006521
6522 mSelf.mCoreSettingsObserver = new CoreSettingsObserver(mSelf);
Mark Brophyc6350272011-08-05 16:16:39 +01006523
6524 mSelf.mUsageStatsService.monitorPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006525 }
6526
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006527 /**
6528 * Allows app to retrieve the MIME type of a URI without having permission
6529 * to access its content provider.
6530 *
6531 * CTS tests for this functionality can be run with "runtest cts-appsecurity".
6532 *
6533 * Test cases are at cts/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/
6534 * src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java
6535 */
6536 public String getProviderMimeType(Uri uri) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006537 enforceNotIsolatedCaller("getProviderMimeType");
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006538 final String name = uri.getAuthority();
6539 final long ident = Binder.clearCallingIdentity();
6540 ContentProviderHolder holder = null;
6541
6542 try {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006543 holder = getContentProviderExternalUnchecked(name, null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006544 if (holder != null) {
6545 return holder.provider.getType(uri);
6546 }
6547 } catch (RemoteException e) {
6548 Log.w(TAG, "Content provider dead retrieving " + uri, e);
6549 return null;
6550 } finally {
6551 if (holder != null) {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006552 removeContentProviderExternalUnchecked(name, null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006553 }
6554 Binder.restoreCallingIdentity(ident);
6555 }
6556
6557 return null;
6558 }
6559
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006560 // =========================================================
6561 // GLOBAL MANAGEMENT
6562 // =========================================================
6563
6564 final ProcessRecord newProcessRecordLocked(IApplicationThread thread,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006565 ApplicationInfo info, String customProcess, boolean isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006566 String proc = customProcess != null ? customProcess : info.processName;
6567 BatteryStatsImpl.Uid.Proc ps = null;
6568 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006569 int uid = info.uid;
6570 if (isolated) {
6571 int userId = UserId.getUserId(uid);
6572 int stepsLeft = Process.LAST_ISOLATED_UID - Process.FIRST_ISOLATED_UID + 1;
6573 uid = 0;
6574 while (true) {
6575 if (mNextIsolatedProcessUid < Process.FIRST_ISOLATED_UID
6576 || mNextIsolatedProcessUid > Process.LAST_ISOLATED_UID) {
6577 mNextIsolatedProcessUid = Process.FIRST_ISOLATED_UID;
6578 }
6579 uid = UserId.getUid(userId, mNextIsolatedProcessUid);
6580 mNextIsolatedProcessUid++;
6581 if (mIsolatedProcesses.indexOfKey(uid) < 0) {
6582 // No process for this uid, use it.
6583 break;
6584 }
6585 stepsLeft--;
6586 if (stepsLeft <= 0) {
6587 return null;
6588 }
6589 }
6590 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006591 synchronized (stats) {
6592 ps = stats.getProcessStatsLocked(info.uid, proc);
6593 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006594 return new ProcessRecord(ps, thread, info, proc, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006595 }
6596
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006597 final ProcessRecord addAppLocked(ApplicationInfo info, boolean isolated) {
6598 ProcessRecord app;
6599 if (!isolated) {
6600 app = getProcessRecordLocked(info.processName, info.uid);
6601 } else {
6602 app = null;
6603 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006604
6605 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006606 app = newProcessRecordLocked(null, info, null, isolated);
6607 mProcessNames.put(info.processName, app.uid, app);
6608 if (isolated) {
6609 mIsolatedProcesses.put(app.uid, app);
6610 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08006611 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006612 }
6613
Dianne Hackborne7f97212011-02-24 14:40:20 -08006614 // This package really, really can not be stopped.
6615 try {
6616 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07006617 info.packageName, false, UserId.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -08006618 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006619 } catch (IllegalArgumentException e) {
6620 Slog.w(TAG, "Failed trying to unstop package "
6621 + info.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006622 }
6623
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006624 if ((info.flags&(ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT))
6625 == (ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT)) {
6626 app.persistent = true;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07006627 app.maxAdj = ProcessList.PERSISTENT_PROC_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006628 }
6629 if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) {
6630 mPersistentStartingProcesses.add(app);
6631 startProcessLocked(app, "added application", app.processName);
6632 }
6633
6634 return app;
6635 }
6636
6637 public void unhandledBack() {
6638 enforceCallingPermission(android.Manifest.permission.FORCE_BACK,
6639 "unhandledBack()");
6640
6641 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006642 int count = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08006643 if (DEBUG_SWITCH) Slog.d(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006644 TAG, "Performing unhandledBack(): stack size = " + count);
6645 if (count > 1) {
6646 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006647 mMainStack.finishActivityLocked((ActivityRecord)mMainStack.mHistory.get(count-1),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006648 count-1, Activity.RESULT_CANCELED, null, "unhandled-back");
6649 Binder.restoreCallingIdentity(origId);
6650 }
6651 }
6652 }
6653
6654 public ParcelFileDescriptor openContentUri(Uri uri) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006655 enforceNotIsolatedCaller("openContentUri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006656 String name = uri.getAuthority();
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006657 ContentProviderHolder cph = getContentProviderExternalUnchecked(name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006658 ParcelFileDescriptor pfd = null;
6659 if (cph != null) {
6660 // We record the binder invoker's uid in thread-local storage before
6661 // going to the content provider to open the file. Later, in the code
6662 // that handles all permissions checks, we look for this uid and use
6663 // that rather than the Activity Manager's own uid. The effect is that
6664 // we do the check against the caller's permissions even though it looks
6665 // to the content provider like the Activity Manager itself is making
6666 // the request.
6667 sCallerIdentity.set(new Identity(
6668 Binder.getCallingPid(), Binder.getCallingUid()));
6669 try {
6670 pfd = cph.provider.openFile(uri, "r");
6671 } catch (FileNotFoundException e) {
6672 // do nothing; pfd will be returned null
6673 } finally {
6674 // Ensure that whatever happens, we clean up the identity state
6675 sCallerIdentity.remove();
6676 }
6677
6678 // We've got the fd now, so we're done with the provider.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006679 removeContentProviderExternalUnchecked(name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006680 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006681 Slog.d(TAG, "Failed to get provider for authority '" + name + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006682 }
6683 return pfd;
6684 }
6685
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006686 // Actually is sleeping or shutting down or whatever else in the future
6687 // is an inactive state.
6688 public boolean isSleeping() {
6689 return mSleeping || mShuttingDown;
6690 }
6691
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006692 public void goingToSleep() {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006693 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
6694 != PackageManager.PERMISSION_GRANTED) {
6695 throw new SecurityException("Requires permission "
6696 + android.Manifest.permission.DEVICE_POWER);
6697 }
6698
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006699 synchronized(this) {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006700 mWentToSleep = true;
Jeff Brownc042ee22012-05-08 13:03:42 -07006701 updateEventDispatchingLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006702
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006703 if (!mSleeping) {
6704 mSleeping = true;
6705 mMainStack.stopIfSleepingLocked();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006706
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006707 // Initialize the wake times of all processes.
6708 checkExcessivePowerUsageLocked(false);
6709 mHandler.removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
6710 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
6711 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
6712 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006713 }
6714 }
6715
Dianne Hackborn55280a92009-05-07 15:53:46 -07006716 public boolean shutdown(int timeout) {
6717 if (checkCallingPermission(android.Manifest.permission.SHUTDOWN)
6718 != PackageManager.PERMISSION_GRANTED) {
6719 throw new SecurityException("Requires permission "
6720 + android.Manifest.permission.SHUTDOWN);
6721 }
6722
6723 boolean timedout = false;
6724
6725 synchronized(this) {
6726 mShuttingDown = true;
Jeff Brownc042ee22012-05-08 13:03:42 -07006727 updateEventDispatchingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07006728
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006729 if (mMainStack.mResumedActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006730 mMainStack.stopIfSleepingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07006731 final long endTime = System.currentTimeMillis() + timeout;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006732 while (mMainStack.mResumedActivity != null
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08006733 || mMainStack.mPausingActivity != null) {
Dianne Hackborn55280a92009-05-07 15:53:46 -07006734 long delay = endTime - System.currentTimeMillis();
6735 if (delay <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006736 Slog.w(TAG, "Activity manager shutdown timed out");
Dianne Hackborn55280a92009-05-07 15:53:46 -07006737 timedout = true;
6738 break;
6739 }
6740 try {
6741 this.wait();
6742 } catch (InterruptedException e) {
6743 }
6744 }
6745 }
6746 }
6747
6748 mUsageStatsService.shutdown();
6749 mBatteryStatsService.shutdown();
6750
6751 return timedout;
6752 }
6753
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006754 public final void activitySlept(IBinder token) {
6755 if (localLOGV) Slog.v(
6756 TAG, "Activity slept: token=" + token);
6757
6758 ActivityRecord r = null;
6759
6760 final long origId = Binder.clearCallingIdentity();
6761
6762 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006763 r = mMainStack.isInStackLocked(token);
6764 if (r != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006765 mMainStack.activitySleptLocked(r);
6766 }
6767 }
6768
6769 Binder.restoreCallingIdentity(origId);
6770 }
6771
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006772 private void comeOutOfSleepIfNeededLocked() {
6773 if (!mWentToSleep && !mLockScreenShown) {
6774 if (mSleeping) {
6775 mSleeping = false;
6776 mMainStack.awakeFromSleepingLocked();
6777 mMainStack.resumeTopActivityLocked(null);
6778 }
6779 }
6780 }
6781
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006782 public void wakingUp() {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006783 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
6784 != PackageManager.PERMISSION_GRANTED) {
6785 throw new SecurityException("Requires permission "
6786 + android.Manifest.permission.DEVICE_POWER);
6787 }
6788
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006789 synchronized(this) {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006790 mWentToSleep = false;
Jeff Brownc042ee22012-05-08 13:03:42 -07006791 updateEventDispatchingLocked();
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006792 comeOutOfSleepIfNeededLocked();
6793 }
6794 }
6795
Jeff Brownc042ee22012-05-08 13:03:42 -07006796 private void updateEventDispatchingLocked() {
6797 mWindowManager.setEventDispatching(mBooted && !mWentToSleep && !mShuttingDown);
6798 }
6799
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006800 public void setLockScreenShown(boolean shown) {
6801 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
6802 != PackageManager.PERMISSION_GRANTED) {
6803 throw new SecurityException("Requires permission "
6804 + android.Manifest.permission.DEVICE_POWER);
6805 }
6806
6807 synchronized(this) {
6808 mLockScreenShown = shown;
6809 comeOutOfSleepIfNeededLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006810 }
6811 }
6812
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006813 public void stopAppSwitches() {
6814 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
6815 != PackageManager.PERMISSION_GRANTED) {
6816 throw new SecurityException("Requires permission "
6817 + android.Manifest.permission.STOP_APP_SWITCHES);
6818 }
6819
6820 synchronized(this) {
6821 mAppSwitchesAllowedTime = SystemClock.uptimeMillis()
6822 + APP_SWITCH_DELAY_TIME;
6823 mDidAppSwitch = false;
6824 mHandler.removeMessages(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
6825 Message msg = mHandler.obtainMessage(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
6826 mHandler.sendMessageDelayed(msg, APP_SWITCH_DELAY_TIME);
6827 }
6828 }
6829
6830 public void resumeAppSwitches() {
6831 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
6832 != PackageManager.PERMISSION_GRANTED) {
6833 throw new SecurityException("Requires permission "
6834 + android.Manifest.permission.STOP_APP_SWITCHES);
6835 }
6836
6837 synchronized(this) {
6838 // Note that we don't execute any pending app switches... we will
6839 // let those wait until either the timeout, or the next start
6840 // activity request.
6841 mAppSwitchesAllowedTime = 0;
6842 }
6843 }
6844
6845 boolean checkAppSwitchAllowedLocked(int callingPid, int callingUid,
6846 String name) {
6847 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
6848 return true;
6849 }
6850
6851 final int perm = checkComponentPermission(
6852 android.Manifest.permission.STOP_APP_SWITCHES, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006853 callingUid, -1, true);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006854 if (perm == PackageManager.PERMISSION_GRANTED) {
6855 return true;
6856 }
6857
Joe Onorato8a9b2202010-02-26 18:56:32 -08006858 Slog.w(TAG, name + " request from " + callingUid + " stopped");
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006859 return false;
6860 }
6861
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006862 public void setDebugApp(String packageName, boolean waitForDebugger,
6863 boolean persistent) {
6864 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
6865 "setDebugApp()");
6866
6867 // Note that this is not really thread safe if there are multiple
6868 // callers into it at the same time, but that's not a situation we
6869 // care about.
6870 if (persistent) {
6871 final ContentResolver resolver = mContext.getContentResolver();
6872 Settings.System.putString(
6873 resolver, Settings.System.DEBUG_APP,
6874 packageName);
6875 Settings.System.putInt(
6876 resolver, Settings.System.WAIT_FOR_DEBUGGER,
6877 waitForDebugger ? 1 : 0);
6878 }
6879
6880 synchronized (this) {
6881 if (!persistent) {
6882 mOrigDebugApp = mDebugApp;
6883 mOrigWaitForDebugger = mWaitForDebugger;
6884 }
6885 mDebugApp = packageName;
6886 mWaitForDebugger = waitForDebugger;
6887 mDebugTransient = !persistent;
6888 if (packageName != null) {
6889 final long origId = Binder.clearCallingIdentity();
Amith Yamasani483f3b02012-03-13 16:08:00 -07006890 forceStopPackageLocked(packageName, -1, false, false, true, true, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006891 Binder.restoreCallingIdentity(origId);
6892 }
6893 }
6894 }
6895
Siva Velusamy92a8b222012-03-09 16:24:04 -08006896 void setOpenGlTraceApp(ApplicationInfo app, String processName) {
6897 synchronized (this) {
6898 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
6899 if (!isDebuggable) {
6900 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
6901 throw new SecurityException("Process not debuggable: " + app.packageName);
6902 }
6903 }
6904
6905 mOpenGlTraceApp = processName;
6906 }
6907 }
6908
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07006909 void setProfileApp(ApplicationInfo app, String processName, String profileFile,
6910 ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
6911 synchronized (this) {
6912 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
6913 if (!isDebuggable) {
6914 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
6915 throw new SecurityException("Process not debuggable: " + app.packageName);
6916 }
6917 }
6918 mProfileApp = processName;
6919 mProfileFile = profileFile;
6920 if (mProfileFd != null) {
6921 try {
6922 mProfileFd.close();
6923 } catch (IOException e) {
6924 }
6925 mProfileFd = null;
6926 }
6927 mProfileFd = profileFd;
6928 mProfileType = 0;
6929 mAutoStopProfiler = autoStopProfiler;
6930 }
6931 }
6932
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006933 public void setAlwaysFinish(boolean enabled) {
6934 enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH,
6935 "setAlwaysFinish()");
6936
6937 Settings.System.putInt(
6938 mContext.getContentResolver(),
6939 Settings.System.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0);
6940
6941 synchronized (this) {
6942 mAlwaysFinishActivities = enabled;
6943 }
6944 }
6945
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006946 public void setActivityController(IActivityController controller) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006947 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006948 "setActivityController()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006949 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006950 mController = controller;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006951 }
6952 }
6953
Dianne Hackborn9327f4f2010-01-29 10:38:29 -08006954 public boolean isUserAMonkey() {
6955 // For now the fact that there is a controller implies
6956 // we have a monkey.
6957 synchronized (this) {
6958 return mController != null;
6959 }
6960 }
6961
Jeff Sharkeya4620792011-05-20 15:29:23 -07006962 public void registerProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08006963 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
6964 "registerProcessObserver()");
6965 synchronized (this) {
6966 mProcessObservers.register(observer);
6967 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07006968 }
6969
6970 public void unregisterProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08006971 synchronized (this) {
6972 mProcessObservers.unregister(observer);
6973 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07006974 }
6975
Daniel Sandler69a48172010-06-23 16:29:36 -04006976 public void setImmersive(IBinder token, boolean immersive) {
6977 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006978 ActivityRecord r = mMainStack.isInStackLocked(token);
6979 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04006980 throw new IllegalArgumentException();
6981 }
Daniel Sandler69a48172010-06-23 16:29:36 -04006982 r.immersive = immersive;
6983 }
6984 }
6985
6986 public boolean isImmersive(IBinder token) {
6987 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006988 ActivityRecord r = mMainStack.isInStackLocked(token);
6989 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04006990 throw new IllegalArgumentException();
6991 }
Daniel Sandler69a48172010-06-23 16:29:36 -04006992 return r.immersive;
6993 }
6994 }
6995
6996 public boolean isTopActivityImmersive() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006997 enforceNotIsolatedCaller("startActivity");
Daniel Sandler69a48172010-06-23 16:29:36 -04006998 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006999 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Daniel Sandler69a48172010-06-23 16:29:36 -04007000 return (r != null) ? r.immersive : false;
7001 }
7002 }
7003
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007004 public final void enterSafeMode() {
7005 synchronized(this) {
7006 // It only makes sense to do this before the system is ready
7007 // and started launching other packages.
7008 if (!mSystemReady) {
7009 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007010 AppGlobals.getPackageManager().enterSafeMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007011 } catch (RemoteException e) {
7012 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007013 }
7014 }
7015 }
7016
Jeff Brownb09abc12011-01-13 21:08:27 -08007017 public final void showSafeModeOverlay() {
7018 View v = LayoutInflater.from(mContext).inflate(
7019 com.android.internal.R.layout.safe_mode, null);
7020 WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
7021 lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
7022 lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
7023 lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
7024 lp.gravity = Gravity.BOTTOM | Gravity.LEFT;
7025 lp.format = v.getBackground().getOpacity();
7026 lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
7027 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
7028 ((WindowManager)mContext.getSystemService(
7029 Context.WINDOW_SERVICE)).addView(v, lp);
7030 }
7031
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007032 public void noteWakeupAlarm(IIntentSender sender) {
7033 if (!(sender instanceof PendingIntentRecord)) {
7034 return;
7035 }
7036 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
7037 synchronized (stats) {
7038 if (mBatteryStatsService.isOnBattery()) {
7039 mBatteryStatsService.enforceCallingPermission();
7040 PendingIntentRecord rec = (PendingIntentRecord)sender;
7041 int MY_UID = Binder.getCallingUid();
7042 int uid = rec.uid == MY_UID ? Process.SYSTEM_UID : rec.uid;
7043 BatteryStatsImpl.Uid.Pkg pkg =
7044 stats.getPackageStatsLocked(uid, rec.key.packageName);
7045 pkg.incWakeupsLocked();
7046 }
7047 }
7048 }
7049
Dianne Hackborn64825172011-03-02 21:32:58 -08007050 public boolean killPids(int[] pids, String pReason, boolean secure) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007051 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007052 throw new SecurityException("killPids only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007053 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007054 String reason = (pReason == null) ? "Unknown" : pReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007055 // XXX Note: don't acquire main activity lock here, because the window
7056 // manager calls in with its locks held.
7057
7058 boolean killed = false;
7059 synchronized (mPidsSelfLocked) {
7060 int[] types = new int[pids.length];
7061 int worstType = 0;
7062 for (int i=0; i<pids.length; i++) {
7063 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7064 if (proc != null) {
7065 int type = proc.setAdj;
7066 types[i] = type;
7067 if (type > worstType) {
7068 worstType = type;
7069 }
7070 }
7071 }
7072
Dianne Hackborn64825172011-03-02 21:32:58 -08007073 // If the worst oom_adj is somewhere in the hidden proc LRU range,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007074 // then constrain it so we will kill all hidden procs.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007075 if (worstType < ProcessList.HIDDEN_APP_MAX_ADJ
7076 && worstType > ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07007077 worstType = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007078 }
Dianne Hackborn64825172011-03-02 21:32:58 -08007079
7080 // If this is not a secure call, don't let it kill processes that
7081 // are important.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007082 if (!secure && worstType < ProcessList.SERVICE_ADJ) {
7083 worstType = ProcessList.SERVICE_ADJ;
Dianne Hackborn64825172011-03-02 21:32:58 -08007084 }
7085
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007086 Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007087 for (int i=0; i<pids.length; i++) {
7088 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7089 if (proc == null) {
7090 continue;
7091 }
7092 int adj = proc.setAdj;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007093 if (adj >= worstType && !proc.killedBackground) {
Dianne Hackborn8633e682010-04-22 16:03:41 -07007094 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007095 EventLog.writeEvent(EventLogTags.AM_KILL, proc.pid,
7096 proc.processName, adj, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007097 killed = true;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007098 proc.killedBackground = true;
7099 Process.killProcessQuiet(pids[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007100 }
7101 }
7102 }
7103 return killed;
7104 }
Jeff Sharkeyb9a07012012-03-22 17:00:04 -07007105
7106 @Override
7107 public boolean killProcessesBelowForeground(String reason) {
7108 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7109 throw new SecurityException("killProcessesBelowForeground() only available to system");
7110 }
7111
7112 return killProcessesBelowAdj(ProcessList.FOREGROUND_APP_ADJ, reason);
7113 }
7114
7115 private boolean killProcessesBelowAdj(int belowAdj, String reason) {
7116 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7117 throw new SecurityException("killProcessesBelowAdj() only available to system");
7118 }
7119
7120 boolean killed = false;
7121 synchronized (mPidsSelfLocked) {
7122 final int size = mPidsSelfLocked.size();
7123 for (int i = 0; i < size; i++) {
7124 final int pid = mPidsSelfLocked.keyAt(i);
7125 final ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7126 if (proc == null) continue;
7127
7128 final int adj = proc.setAdj;
7129 if (adj > belowAdj && !proc.killedBackground) {
7130 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
7131 EventLog.writeEvent(
7132 EventLogTags.AM_KILL, proc.pid, proc.processName, adj, reason);
7133 killed = true;
7134 proc.killedBackground = true;
7135 Process.killProcessQuiet(pid);
7136 }
7137 }
7138 }
7139 return killed;
7140 }
7141
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007142 public final void startRunning(String pkg, String cls, String action,
7143 String data) {
7144 synchronized(this) {
7145 if (mStartRunning) {
7146 return;
7147 }
7148 mStartRunning = true;
7149 mTopComponent = pkg != null && cls != null
7150 ? new ComponentName(pkg, cls) : null;
7151 mTopAction = action != null ? action : Intent.ACTION_MAIN;
7152 mTopData = data;
7153 if (!mSystemReady) {
7154 return;
7155 }
7156 }
7157
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007158 systemReady(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007159 }
7160
7161 private void retrieveSettings() {
7162 final ContentResolver resolver = mContext.getContentResolver();
7163 String debugApp = Settings.System.getString(
7164 resolver, Settings.System.DEBUG_APP);
7165 boolean waitForDebugger = Settings.System.getInt(
7166 resolver, Settings.System.WAIT_FOR_DEBUGGER, 0) != 0;
7167 boolean alwaysFinishActivities = Settings.System.getInt(
7168 resolver, Settings.System.ALWAYS_FINISH_ACTIVITIES, 0) != 0;
7169
7170 Configuration configuration = new Configuration();
7171 Settings.System.getConfiguration(resolver, configuration);
7172
7173 synchronized (this) {
7174 mDebugApp = mOrigDebugApp = debugApp;
7175 mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger;
7176 mAlwaysFinishActivities = alwaysFinishActivities;
7177 // This happens before any activities are started, so we can
7178 // change mConfiguration in-place.
Dianne Hackborn813075a62011-11-14 17:45:19 -08007179 updateConfigurationLocked(configuration, null, false, true);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007180 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Initial config: " + mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007181 }
7182 }
7183
7184 public boolean testIsSystemReady() {
7185 // no need to synchronize(this) just to read & return the value
7186 return mSystemReady;
7187 }
7188
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007189 private static File getCalledPreBootReceiversFile() {
7190 File dataDir = Environment.getDataDirectory();
7191 File systemDir = new File(dataDir, "system");
7192 File fname = new File(systemDir, "called_pre_boots.dat");
7193 return fname;
7194 }
Dianne Hackborn661cd522011-08-22 00:26:20 -07007195
7196 static final int LAST_DONE_VERSION = 10000;
7197
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007198 private static ArrayList<ComponentName> readLastDonePreBootReceivers() {
7199 ArrayList<ComponentName> lastDoneReceivers = new ArrayList<ComponentName>();
7200 File file = getCalledPreBootReceiversFile();
7201 FileInputStream fis = null;
7202 try {
7203 fis = new FileInputStream(file);
7204 DataInputStream dis = new DataInputStream(new BufferedInputStream(fis, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007205 int fvers = dis.readInt();
7206 if (fvers == LAST_DONE_VERSION) {
7207 String vers = dis.readUTF();
7208 String codename = dis.readUTF();
7209 String build = dis.readUTF();
7210 if (android.os.Build.VERSION.RELEASE.equals(vers)
7211 && android.os.Build.VERSION.CODENAME.equals(codename)
7212 && android.os.Build.VERSION.INCREMENTAL.equals(build)) {
7213 int num = dis.readInt();
7214 while (num > 0) {
7215 num--;
7216 String pkg = dis.readUTF();
7217 String cls = dis.readUTF();
7218 lastDoneReceivers.add(new ComponentName(pkg, cls));
7219 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007220 }
7221 }
7222 } catch (FileNotFoundException e) {
7223 } catch (IOException e) {
7224 Slog.w(TAG, "Failure reading last done pre-boot receivers", e);
7225 } finally {
7226 if (fis != null) {
7227 try {
7228 fis.close();
7229 } catch (IOException e) {
7230 }
7231 }
7232 }
7233 return lastDoneReceivers;
7234 }
7235
7236 private static void writeLastDonePreBootReceivers(ArrayList<ComponentName> list) {
7237 File file = getCalledPreBootReceiversFile();
7238 FileOutputStream fos = null;
7239 DataOutputStream dos = null;
7240 try {
7241 Slog.i(TAG, "Writing new set of last done pre-boot receivers...");
7242 fos = new FileOutputStream(file);
7243 dos = new DataOutputStream(new BufferedOutputStream(fos, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007244 dos.writeInt(LAST_DONE_VERSION);
7245 dos.writeUTF(android.os.Build.VERSION.RELEASE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007246 dos.writeUTF(android.os.Build.VERSION.CODENAME);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007247 dos.writeUTF(android.os.Build.VERSION.INCREMENTAL);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007248 dos.writeInt(list.size());
7249 for (int i=0; i<list.size(); i++) {
7250 dos.writeUTF(list.get(i).getPackageName());
7251 dos.writeUTF(list.get(i).getClassName());
7252 }
7253 } catch (IOException e) {
7254 Slog.w(TAG, "Failure writing last done pre-boot receivers", e);
7255 file.delete();
7256 } finally {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07007257 FileUtils.sync(fos);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007258 if (dos != null) {
7259 try {
7260 dos.close();
7261 } catch (IOException e) {
7262 // TODO Auto-generated catch block
7263 e.printStackTrace();
7264 }
7265 }
7266 }
7267 }
7268
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007269 public void systemReady(final Runnable goingCallback) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007270 synchronized(this) {
7271 if (mSystemReady) {
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007272 if (goingCallback != null) goingCallback.run();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007273 return;
7274 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007275
7276 // Check to see if there are any update receivers to run.
7277 if (!mDidUpdate) {
7278 if (mWaitingUpdate) {
7279 return;
7280 }
7281 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
7282 List<ResolveInfo> ris = null;
7283 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007284 ris = AppGlobals.getPackageManager().queryIntentReceivers(
Amith Yamasani483f3b02012-03-13 16:08:00 -07007285 intent, null, 0, 0);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007286 } catch (RemoteException e) {
7287 }
7288 if (ris != null) {
7289 for (int i=ris.size()-1; i>=0; i--) {
7290 if ((ris.get(i).activityInfo.applicationInfo.flags
7291 &ApplicationInfo.FLAG_SYSTEM) == 0) {
7292 ris.remove(i);
7293 }
7294 }
7295 intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007296
7297 ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers();
7298
7299 final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007300 for (int i=0; i<ris.size(); i++) {
7301 ActivityInfo ai = ris.get(i).activityInfo;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007302 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7303 if (lastDoneReceivers.contains(comp)) {
7304 ris.remove(i);
7305 i--;
7306 }
7307 }
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07007308
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007309 for (int i=0; i<ris.size(); i++) {
7310 ActivityInfo ai = ris.get(i).activityInfo;
7311 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7312 doneReceivers.add(comp);
7313 intent.setComponent(comp);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007314 IIntentReceiver finisher = null;
Dianne Hackbornd6847842010-01-12 18:14:19 -08007315 if (i == ris.size()-1) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007316 finisher = new IIntentReceiver.Stub() {
7317 public void performReceive(Intent intent, int resultCode,
Dianne Hackborn68d881c2009-10-05 13:58:17 -07007318 String data, Bundle extras, boolean ordered,
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007319 boolean sticky) {
7320 // The raw IIntentReceiver interface is called
7321 // with the AM lock held, so redispatch to
7322 // execute our code without the lock.
7323 mHandler.post(new Runnable() {
7324 public void run() {
7325 synchronized (ActivityManagerService.this) {
7326 mDidUpdate = true;
7327 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007328 writeLastDonePreBootReceivers(doneReceivers);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007329 showBootMessage(mContext.getText(
7330 R.string.android_upgrading_complete),
7331 false);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007332 systemReady(goingCallback);
7333 }
7334 });
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007335 }
7336 };
7337 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08007338 Slog.i(TAG, "Sending system update to: " + intent.getComponent());
Amith Yamasani742a6712011-05-04 14:49:28 -07007339 /* TODO: Send this to all users */
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007340 broadcastIntentLocked(null, null, intent, null, finisher,
Amith Yamasani742a6712011-05-04 14:49:28 -07007341 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID,
Amith Yamasanic600e21f2012-02-14 16:08:07 -08007342 0 /* UserId zero */);
Dianne Hackbornd6847842010-01-12 18:14:19 -08007343 if (finisher != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007344 mWaitingUpdate = true;
7345 }
7346 }
7347 }
7348 if (mWaitingUpdate) {
7349 return;
7350 }
7351 mDidUpdate = true;
7352 }
7353
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007354 mSystemReady = true;
7355 if (!mStartRunning) {
7356 return;
7357 }
7358 }
7359
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007360 ArrayList<ProcessRecord> procsToKill = null;
7361 synchronized(mPidsSelfLocked) {
7362 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
7363 ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7364 if (!isAllowedWhileBooting(proc.info)){
7365 if (procsToKill == null) {
7366 procsToKill = new ArrayList<ProcessRecord>();
7367 }
7368 procsToKill.add(proc);
7369 }
7370 }
7371 }
7372
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007373 synchronized(this) {
7374 if (procsToKill != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007375 for (int i=procsToKill.size()-1; i>=0; i--) {
7376 ProcessRecord proc = procsToKill.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007377 Slog.i(TAG, "Removing system update proc: " + proc);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007378 removeProcessLocked(proc, true, false, "system update done");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007379 }
7380 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007381
7382 // Now that we have cleaned up any update processes, we
7383 // are ready to start launching real processes and know that
7384 // we won't trample on them any more.
7385 mProcessesReady = true;
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007386 }
7387
Joe Onorato8a9b2202010-02-26 18:56:32 -08007388 Slog.i(TAG, "System now ready");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007389 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007390 SystemClock.uptimeMillis());
7391
7392 synchronized(this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007393 // Make sure we have no pre-ready processes sitting around.
7394
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007395 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
7396 ResolveInfo ri = mContext.getPackageManager()
7397 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST),
Dianne Hackborn1655be42009-05-08 14:29:01 -07007398 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007399 CharSequence errorMsg = null;
7400 if (ri != null) {
7401 ActivityInfo ai = ri.activityInfo;
7402 ApplicationInfo app = ai.applicationInfo;
7403 if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7404 mTopAction = Intent.ACTION_FACTORY_TEST;
7405 mTopData = null;
7406 mTopComponent = new ComponentName(app.packageName,
7407 ai.name);
7408 } else {
7409 errorMsg = mContext.getResources().getText(
7410 com.android.internal.R.string.factorytest_not_system);
7411 }
7412 } else {
7413 errorMsg = mContext.getResources().getText(
7414 com.android.internal.R.string.factorytest_no_action);
7415 }
7416 if (errorMsg != null) {
7417 mTopAction = null;
7418 mTopData = null;
7419 mTopComponent = null;
7420 Message msg = Message.obtain();
7421 msg.what = SHOW_FACTORY_ERROR_MSG;
7422 msg.getData().putCharSequence("msg", errorMsg);
7423 mHandler.sendMessage(msg);
7424 }
7425 }
7426 }
7427
7428 retrieveSettings();
7429
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007430 if (goingCallback != null) goingCallback.run();
7431
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007432 synchronized (this) {
7433 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
7434 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007435 List apps = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07007436 getPersistentApplications(STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007437 if (apps != null) {
7438 int N = apps.size();
7439 int i;
7440 for (i=0; i<N; i++) {
7441 ApplicationInfo info
7442 = (ApplicationInfo)apps.get(i);
7443 if (info != null &&
7444 !info.packageName.equals("android")) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007445 addAppLocked(info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007446 }
7447 }
7448 }
7449 } catch (RemoteException ex) {
7450 // pm is in same process, this will never happen.
7451 }
7452 }
7453
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007454 // Start up initial activity.
7455 mBooting = true;
7456
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007457 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007458 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007459 Message msg = Message.obtain();
7460 msg.what = SHOW_UID_ERROR_MSG;
7461 mHandler.sendMessage(msg);
7462 }
7463 } catch (RemoteException e) {
7464 }
7465
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007466 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007467 }
7468 }
7469
Dan Egnorb7f03672009-12-09 16:22:32 -08007470 private boolean makeAppCrashingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007471 String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007472 app.crashing = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007473 app.crashingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007474 ActivityManager.ProcessErrorStateInfo.CRASHED, null, shortMsg, longMsg, stackTrace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007475 startAppProblemLocked(app);
7476 app.stopFreezingAllLocked();
7477 return handleAppCrashLocked(app);
7478 }
7479
Dan Egnorb7f03672009-12-09 16:22:32 -08007480 private void makeAppNotRespondingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007481 String activity, String shortMsg, String longMsg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007482 app.notResponding = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007483 app.notRespondingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007484 ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING,
7485 activity, shortMsg, longMsg, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007486 startAppProblemLocked(app);
7487 app.stopFreezingAllLocked();
7488 }
7489
7490 /**
7491 * Generate a process error record, suitable for attachment to a ProcessRecord.
7492 *
7493 * @param app The ProcessRecord in which the error occurred.
7494 * @param condition Crashing, Application Not Responding, etc. Values are defined in
7495 * ActivityManager.AppErrorStateInfo
Dan Egnor60d87622009-12-16 16:32:58 -08007496 * @param activity The activity associated with the crash, if known.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007497 * @param shortMsg Short message describing the crash.
7498 * @param longMsg Long message describing the crash.
Dan Egnorb7f03672009-12-09 16:22:32 -08007499 * @param stackTrace Full crash stack trace, may be null.
7500 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007501 * @return Returns a fully-formed AppErrorStateInfo record.
7502 */
7503 private ActivityManager.ProcessErrorStateInfo generateProcessError(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007504 int condition, String activity, String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007505 ActivityManager.ProcessErrorStateInfo report = new ActivityManager.ProcessErrorStateInfo();
Dan Egnorb7f03672009-12-09 16:22:32 -08007506
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007507 report.condition = condition;
7508 report.processName = app.processName;
7509 report.pid = app.pid;
7510 report.uid = app.info.uid;
Dan Egnor60d87622009-12-16 16:32:58 -08007511 report.tag = activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007512 report.shortMsg = shortMsg;
7513 report.longMsg = longMsg;
Dan Egnorb7f03672009-12-09 16:22:32 -08007514 report.stackTrace = stackTrace;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007515
7516 return report;
7517 }
7518
Dan Egnor42471dd2010-01-07 17:25:22 -08007519 void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007520 synchronized (this) {
7521 app.crashing = false;
7522 app.crashingReport = null;
7523 app.notResponding = false;
7524 app.notRespondingReport = null;
7525 if (app.anrDialog == fromDialog) {
7526 app.anrDialog = null;
7527 }
7528 if (app.waitDialog == fromDialog) {
7529 app.waitDialog = null;
7530 }
7531 if (app.pid > 0 && app.pid != MY_PID) {
Dan Egnor42471dd2010-01-07 17:25:22 -08007532 handleAppCrashLocked(app);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007533 Slog.i(ActivityManagerService.TAG, "Killing " + app + ": user's request");
Dianne Hackborn8633e682010-04-22 16:03:41 -07007534 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
7535 app.processName, app.setAdj, "user's request after error");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007536 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007537 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007538 }
7539 }
Dan Egnor42471dd2010-01-07 17:25:22 -08007540
Dan Egnorb7f03672009-12-09 16:22:32 -08007541 private boolean handleAppCrashLocked(ProcessRecord app) {
Mike Lockwood86548c42011-09-13 17:21:46 -04007542 if (mHeadless) {
7543 Log.e(TAG, "handleAppCrashLocked: " + app.processName);
7544 return false;
7545 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007546 long now = SystemClock.uptimeMillis();
7547
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007548 Long crashTime;
7549 if (!app.isolated) {
7550 crashTime = mProcessCrashTimes.get(app.info.processName, app.uid);
7551 } else {
7552 crashTime = null;
7553 }
Dianne Hackborn7d608422011-08-07 16:24:18 -07007554 if (crashTime != null && now < crashTime+ProcessList.MIN_CRASH_INTERVAL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007555 // This process loses!
Joe Onorato8a9b2202010-02-26 18:56:32 -08007556 Slog.w(TAG, "Process " + app.info.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007557 + " has crashed too many times: killing!");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007558 EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007559 app.info.processName, app.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007560 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
7561 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007562 if (r.app == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007563 Slog.w(TAG, " Force finishing activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007564 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007565 r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED, null, "crashed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007566 }
7567 }
7568 if (!app.persistent) {
7569 // We don't want to start this process again until the user
7570 // explicitly does so... but for persistent process, we really
7571 // need to keep it running. If a persistent process is actually
7572 // repeatedly crashing, then badness for everyone.
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007573 EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007574 app.info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007575 if (!app.isolated) {
7576 // XXX We don't have a way to mark isolated processes
7577 // as bad, since they don't have a peristent identity.
7578 mBadProcesses.put(app.info.processName, app.uid, now);
7579 mProcessCrashTimes.remove(app.info.processName, app.uid);
7580 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007581 app.bad = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007582 app.removed = true;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07007583 // Don't let services in this process be restarted and potentially
7584 // annoy the user repeatedly. Unless it is persistent, since those
7585 // processes run critical code.
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007586 removeProcessLocked(app, false, false, "crash");
Dianne Hackborncb44d962011-03-10 17:02:27 -08007587 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007588 return false;
7589 }
Dianne Hackborncb44d962011-03-10 17:02:27 -08007590 mMainStack.resumeTopActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007591 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007592 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Kevin Hester-Chowd87a9be2012-03-05 08:01:00 -08007593 if (r != null && r.app == app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007594 // If the top running activity is from this crashing
7595 // process, then terminate it to avoid getting in a loop.
7596 Slog.w(TAG, " Force finishing activity "
7597 + r.intent.getComponent().flattenToShortString());
Dianne Hackbornbe707852011-11-11 14:32:10 -08007598 int index = mMainStack.indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007599 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007600 Activity.RESULT_CANCELED, null, "crashed");
Dianne Hackborn070783f2010-12-29 16:46:28 -08007601 // Also terminate any activities below it that aren't yet
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007602 // stopped, to avoid a situation where one will get
7603 // re-start our crashing activity once it gets resumed again.
7604 index--;
7605 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007606 r = (ActivityRecord)mMainStack.mHistory.get(index);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007607 if (r.state == ActivityState.RESUMED
7608 || r.state == ActivityState.PAUSING
7609 || r.state == ActivityState.PAUSED) {
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08007610 if (!r.isHomeActivity || mHomeProcess != r.app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007611 Slog.w(TAG, " Force finishing activity "
7612 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007613 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007614 Activity.RESULT_CANCELED, null, "crashed");
7615 }
7616 }
7617 }
7618 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007619 }
7620
7621 // Bump up the crash count of any services currently running in the proc.
7622 if (app.services.size() != 0) {
7623 // Any services running in the application need to be placed
7624 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -07007625 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007626 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07007627 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007628 sr.crashCount++;
7629 }
7630 }
Mattias Larssona4fd0072010-06-22 22:37:03 +02007631
7632 // If the crashing process is what we consider to be the "home process" and it has been
7633 // replaced by a third-party app, clear the package preferred activities from packages
7634 // with a home activity running in the process to prevent a repeatedly crashing app
7635 // from blocking the user to manually clear the list.
7636 if (app == mHomeProcess && mHomeProcess.activities.size() > 0
7637 && (mHomeProcess.info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
7638 Iterator it = mHomeProcess.activities.iterator();
7639 while (it.hasNext()) {
Jean-Baptiste Queru5ea89f72010-07-30 09:30:31 -07007640 ActivityRecord r = (ActivityRecord)it.next();
Mattias Larssona4fd0072010-06-22 22:37:03 +02007641 if (r.isHomeActivity) {
7642 Log.i(TAG, "Clearing package preferred activities from " + r.packageName);
7643 try {
7644 ActivityThread.getPackageManager()
7645 .clearPackagePreferredActivities(r.packageName);
7646 } catch (RemoteException c) {
7647 // pm is in same process, this will never happen.
7648 }
7649 }
7650 }
7651 }
7652
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007653 if (!app.isolated) {
7654 // XXX Can't keep track of crash times for isolated processes,
7655 // because they don't have a perisistent identity.
7656 mProcessCrashTimes.put(app.info.processName, app.uid, now);
7657 }
7658
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007659 return true;
7660 }
7661
7662 void startAppProblemLocked(ProcessRecord app) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08007663 app.errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver(
7664 mContext, app.info.packageName, app.info.flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007665 skipCurrentReceiverLocked(app);
7666 }
7667
7668 void skipCurrentReceiverLocked(ProcessRecord app) {
Christopher Tatef46723b2012-01-26 14:19:24 -08007669 for (BroadcastQueue queue : mBroadcastQueues) {
7670 queue.skipCurrentReceiverLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007671 }
7672 }
7673
Dan Egnor60d87622009-12-16 16:32:58 -08007674 /**
7675 * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes.
7676 * The application process will exit immediately after this call returns.
7677 * @param app object of the crashing app, null for the system server
7678 * @param crashInfo describing the exception
7679 */
7680 public void handleApplicationCrash(IBinder app, ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007681 ProcessRecord r = findAppProcess(app, "Crash");
Jeff Sharkeya353d262011-10-28 11:12:06 -07007682 final String processName = app == null ? "system_server"
7683 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08007684
7685 EventLog.writeEvent(EventLogTags.AM_CRASH, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07007686 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08007687 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08007688 crashInfo.exceptionClassName,
7689 crashInfo.exceptionMessage,
7690 crashInfo.throwFileName,
7691 crashInfo.throwLineNumber);
7692
Jeff Sharkeya353d262011-10-28 11:12:06 -07007693 addErrorToDropBox("crash", r, processName, null, null, null, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08007694
7695 crashApplication(r, crashInfo);
7696 }
7697
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007698 public void handleApplicationStrictModeViolation(
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007699 IBinder app,
7700 int violationMask,
7701 StrictMode.ViolationInfo info) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007702 ProcessRecord r = findAppProcess(app, "StrictMode");
7703 if (r == null) {
7704 return;
7705 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007706
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007707 if ((violationMask & StrictMode.PENALTY_DROPBOX) != 0) {
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08007708 Integer stackFingerprint = info.hashCode();
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007709 boolean logIt = true;
7710 synchronized (mAlreadyLoggedViolatedStacks) {
7711 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) {
7712 logIt = false;
7713 // TODO: sub-sample into EventLog for these, with
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007714 // the info.durationMillis? Then we'd get
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007715 // the relative pain numbers, without logging all
7716 // the stack traces repeatedly. We'd want to do
7717 // likewise in the client code, which also does
7718 // dup suppression, before the Binder call.
7719 } else {
7720 if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) {
7721 mAlreadyLoggedViolatedStacks.clear();
7722 }
7723 mAlreadyLoggedViolatedStacks.add(stackFingerprint);
7724 }
7725 }
7726 if (logIt) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007727 logStrictModeViolationToDropBox(r, info);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007728 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007729 }
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007730
7731 if ((violationMask & StrictMode.PENALTY_DIALOG) != 0) {
7732 AppErrorResult result = new AppErrorResult();
7733 synchronized (this) {
7734 final long origId = Binder.clearCallingIdentity();
7735
7736 Message msg = Message.obtain();
7737 msg.what = SHOW_STRICT_MODE_VIOLATION_MSG;
7738 HashMap<String, Object> data = new HashMap<String, Object>();
7739 data.put("result", result);
7740 data.put("app", r);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007741 data.put("violationMask", violationMask);
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007742 data.put("info", info);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007743 msg.obj = data;
7744 mHandler.sendMessage(msg);
7745
7746 Binder.restoreCallingIdentity(origId);
7747 }
7748 int res = result.get();
Dianne Hackbornb424b632010-08-18 15:59:05 -07007749 Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007750 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007751 }
7752
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007753 // Depending on the policy in effect, there could be a bunch of
7754 // these in quick succession so we try to batch these together to
7755 // minimize disk writes, number of dropbox entries, and maximize
7756 // compression, by having more fewer, larger records.
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007757 private void logStrictModeViolationToDropBox(
7758 ProcessRecord process,
7759 StrictMode.ViolationInfo info) {
7760 if (info == null) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007761 return;
7762 }
7763 final boolean isSystemApp = process == null ||
7764 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM |
7765 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07007766 final String processName = process == null ? "unknown" : process.processName;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007767 final String dropboxTag = isSystemApp ? "system_app_strictmode" : "data_app_strictmode";
7768 final DropBoxManager dbox = (DropBoxManager)
7769 mContext.getSystemService(Context.DROPBOX_SERVICE);
7770
7771 // Exit early if the dropbox isn't configured to accept this report type.
7772 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
7773
7774 boolean bufferWasEmpty;
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007775 boolean needsFlush;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007776 final StringBuilder sb = isSystemApp ? mStrictModeBuffer : new StringBuilder(1024);
7777 synchronized (sb) {
7778 bufferWasEmpty = sb.length() == 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07007779 appendDropBoxProcessHeaders(process, processName, sb);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007780 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
7781 sb.append("System-App: ").append(isSystemApp).append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007782 sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n");
7783 if (info.violationNumThisLoop != 0) {
7784 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n");
7785 }
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07007786 if (info.numAnimationsRunning != 0) {
7787 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n");
7788 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07007789 if (info.broadcastIntentAction != null) {
7790 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n");
7791 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08007792 if (info.durationMillis != -1) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007793 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n");
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007794 }
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08007795 if (info.numInstances != -1) {
7796 sb.append("Instance-Count: ").append(info.numInstances).append("\n");
7797 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08007798 if (info.tags != null) {
7799 for (String tag : info.tags) {
7800 sb.append("Span-Tag: ").append(tag).append("\n");
7801 }
7802 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007803 sb.append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007804 if (info.crashInfo != null && info.crashInfo.stackTrace != null) {
7805 sb.append(info.crashInfo.stackTrace);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007806 }
7807 sb.append("\n");
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007808
7809 // Only buffer up to ~64k. Various logging bits truncate
7810 // things at 128k.
7811 needsFlush = (sb.length() > 64 * 1024);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007812 }
7813
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007814 // Flush immediately if the buffer's grown too large, or this
7815 // is a non-system app. Non-system apps are isolated with a
7816 // different tag & policy and not batched.
7817 //
7818 // Batching is useful during internal testing with
7819 // StrictMode settings turned up high. Without batching,
7820 // thousands of separate files could be created on boot.
7821 if (!isSystemApp || needsFlush) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007822 new Thread("Error dump: " + dropboxTag) {
7823 @Override
7824 public void run() {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007825 String report;
7826 synchronized (sb) {
7827 report = sb.toString();
7828 sb.delete(0, sb.length());
7829 sb.trimToSize();
7830 }
7831 if (report.length() != 0) {
7832 dbox.addText(dropboxTag, report);
7833 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007834 }
7835 }.start();
7836 return;
7837 }
7838
7839 // System app batching:
7840 if (!bufferWasEmpty) {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007841 // An existing dropbox-writing thread is outstanding, so
7842 // we don't need to start it up. The existing thread will
7843 // catch the buffer appends we just did.
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007844 return;
7845 }
7846
7847 // Worker thread to both batch writes and to avoid blocking the caller on I/O.
7848 // (After this point, we shouldn't access AMS internal data structures.)
7849 new Thread("Error dump: " + dropboxTag) {
7850 @Override
7851 public void run() {
7852 // 5 second sleep to let stacks arrive and be batched together
7853 try {
7854 Thread.sleep(5000); // 5 seconds
7855 } catch (InterruptedException e) {}
7856
7857 String errorReport;
7858 synchronized (mStrictModeBuffer) {
7859 errorReport = mStrictModeBuffer.toString();
7860 if (errorReport.length() == 0) {
7861 return;
7862 }
7863 mStrictModeBuffer.delete(0, mStrictModeBuffer.length());
7864 mStrictModeBuffer.trimToSize();
7865 }
7866 dbox.addText(dropboxTag, errorReport);
7867 }
7868 }.start();
7869 }
7870
Dan Egnor60d87622009-12-16 16:32:58 -08007871 /**
7872 * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors.
7873 * @param app object of the crashing app, null for the system server
7874 * @param tag reported by the caller
7875 * @param crashInfo describing the context of the error
7876 * @return true if the process should exit immediately (WTF is fatal)
7877 */
7878 public boolean handleApplicationWtf(IBinder app, String tag,
Dan Egnorb7f03672009-12-09 16:22:32 -08007879 ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007880 ProcessRecord r = findAppProcess(app, "WTF");
Jeff Sharkeya353d262011-10-28 11:12:06 -07007881 final String processName = app == null ? "system_server"
7882 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08007883
7884 EventLog.writeEvent(EventLogTags.AM_WTF, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07007885 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08007886 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08007887 tag, crashInfo.exceptionMessage);
7888
Jeff Sharkeya353d262011-10-28 11:12:06 -07007889 addErrorToDropBox("wtf", r, processName, null, null, tag, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08007890
Dianne Hackborn1ab43772011-03-15 14:38:02 -07007891 if (r != null && r.pid != Process.myPid() &&
7892 Settings.Secure.getInt(mContext.getContentResolver(),
7893 Settings.Secure.WTF_IS_FATAL, 0) != 0) {
Dan Egnor60d87622009-12-16 16:32:58 -08007894 crashApplication(r, crashInfo);
7895 return true;
7896 } else {
7897 return false;
7898 }
7899 }
7900
7901 /**
7902 * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit})
7903 * @return the corresponding {@link ProcessRecord} object, or null if none could be found
7904 */
Dianne Hackborncb44d962011-03-10 17:02:27 -08007905 private ProcessRecord findAppProcess(IBinder app, String reason) {
Dan Egnor60d87622009-12-16 16:32:58 -08007906 if (app == null) {
7907 return null;
7908 }
7909
7910 synchronized (this) {
7911 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
7912 final int NA = apps.size();
7913 for (int ia=0; ia<NA; ia++) {
7914 ProcessRecord p = apps.valueAt(ia);
7915 if (p.thread != null && p.thread.asBinder() == app) {
7916 return p;
7917 }
7918 }
7919 }
7920
Dianne Hackborncb44d962011-03-10 17:02:27 -08007921 Slog.w(TAG, "Can't find mystery application for " + reason
7922 + " from pid=" + Binder.getCallingPid()
7923 + " uid=" + Binder.getCallingUid() + ": " + app);
Dan Egnor60d87622009-12-16 16:32:58 -08007924 return null;
7925 }
7926 }
7927
7928 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007929 * Utility function for addErrorToDropBox and handleStrictModeViolation's logging
7930 * to append various headers to the dropbox log text.
Dan Egnor60d87622009-12-16 16:32:58 -08007931 */
Jeff Sharkeya353d262011-10-28 11:12:06 -07007932 private void appendDropBoxProcessHeaders(ProcessRecord process, String processName,
7933 StringBuilder sb) {
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08007934 // Watchdog thread ends up invoking this function (with
7935 // a null ProcessRecord) to add the stack file to dropbox.
7936 // Do not acquire a lock on this (am) in such cases, as it
7937 // could cause a potential deadlock, if and when watchdog
7938 // is invoked due to unavailability of lock on am and it
7939 // would prevent watchdog from killing system_server.
7940 if (process == null) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07007941 sb.append("Process: ").append(processName).append("\n");
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08007942 return;
7943 }
Brad Fitzpatrick1e02d362010-09-10 09:19:50 -07007944 // Note: ProcessRecord 'process' is guarded by the service
7945 // instance. (notably process.pkgList, which could otherwise change
7946 // concurrently during execution of this method)
7947 synchronized (this) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07007948 sb.append("Process: ").append(processName).append("\n");
Dan Egnora455d192010-03-12 08:52:28 -08007949 int flags = process.info.flags;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007950 IPackageManager pm = AppGlobals.getPackageManager();
Dan Egnora455d192010-03-12 08:52:28 -08007951 sb.append("Flags: 0x").append(Integer.toString(flags, 16)).append("\n");
7952 for (String pkg : process.pkgList) {
7953 sb.append("Package: ").append(pkg);
Dan Egnor42471dd2010-01-07 17:25:22 -08007954 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07007955 PackageInfo pi = pm.getPackageInfo(pkg, 0, 0);
Dan Egnora455d192010-03-12 08:52:28 -08007956 if (pi != null) {
7957 sb.append(" v").append(pi.versionCode);
7958 if (pi.versionName != null) {
7959 sb.append(" (").append(pi.versionName).append(")");
7960 }
7961 }
7962 } catch (RemoteException e) {
7963 Slog.e(TAG, "Error getting package info: " + pkg, e);
Dan Egnor60d87622009-12-16 16:32:58 -08007964 }
Dan Egnora455d192010-03-12 08:52:28 -08007965 sb.append("\n");
Dan Egnor60d87622009-12-16 16:32:58 -08007966 }
Dan Egnora455d192010-03-12 08:52:28 -08007967 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007968 }
7969
7970 private static String processClass(ProcessRecord process) {
7971 if (process == null || process.pid == MY_PID) {
7972 return "system_server";
7973 } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
7974 return "system_app";
7975 } else {
7976 return "data_app";
7977 }
7978 }
7979
7980 /**
7981 * Write a description of an error (crash, WTF, ANR) to the drop box.
7982 * @param eventType to include in the drop box tag ("crash", "wtf", etc.)
7983 * @param process which caused the error, null means the system server
7984 * @param activity which triggered the error, null if unknown
7985 * @param parent activity related to the error, null if unknown
7986 * @param subject line related to the error, null if absent
7987 * @param report in long form describing the error, null if absent
7988 * @param logFile to include in the report, null if none
7989 * @param crashInfo giving an application stack trace, null if absent
7990 */
7991 public void addErrorToDropBox(String eventType,
Jeff Sharkeya353d262011-10-28 11:12:06 -07007992 ProcessRecord process, String processName, ActivityRecord activity,
7993 ActivityRecord parent, String subject,
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007994 final String report, final File logFile,
7995 final ApplicationErrorReport.CrashInfo crashInfo) {
7996 // NOTE -- this must never acquire the ActivityManagerService lock,
7997 // otherwise the watchdog may be prevented from resetting the system.
7998
7999 final String dropboxTag = processClass(process) + "_" + eventType;
8000 final DropBoxManager dbox = (DropBoxManager)
8001 mContext.getSystemService(Context.DROPBOX_SERVICE);
8002
8003 // Exit early if the dropbox isn't configured to accept this report type.
8004 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
8005
8006 final StringBuilder sb = new StringBuilder(1024);
Jeff Sharkeya353d262011-10-28 11:12:06 -07008007 appendDropBoxProcessHeaders(process, processName, sb);
Dan Egnora455d192010-03-12 08:52:28 -08008008 if (activity != null) {
8009 sb.append("Activity: ").append(activity.shortComponentName).append("\n");
8010 }
8011 if (parent != null && parent.app != null && parent.app.pid != process.pid) {
8012 sb.append("Parent-Process: ").append(parent.app.processName).append("\n");
8013 }
8014 if (parent != null && parent != activity) {
8015 sb.append("Parent-Activity: ").append(parent.shortComponentName).append("\n");
8016 }
8017 if (subject != null) {
8018 sb.append("Subject: ").append(subject).append("\n");
8019 }
8020 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
Christian Lindeberg03d2ca62010-09-28 14:52:20 +02008021 if (Debug.isDebuggerConnected()) {
8022 sb.append("Debugger: Connected\n");
8023 }
Dan Egnora455d192010-03-12 08:52:28 -08008024 sb.append("\n");
8025
8026 // Do the rest in a worker thread to avoid blocking the caller on I/O
8027 // (After this point, we shouldn't access AMS internal data structures.)
8028 Thread worker = new Thread("Error dump: " + dropboxTag) {
8029 @Override
8030 public void run() {
8031 if (report != null) {
8032 sb.append(report);
8033 }
8034 if (logFile != null) {
8035 try {
8036 sb.append(FileUtils.readTextFile(logFile, 128 * 1024, "\n\n[[TRUNCATED]]"));
8037 } catch (IOException e) {
8038 Slog.e(TAG, "Error reading " + logFile, e);
8039 }
8040 }
8041 if (crashInfo != null && crashInfo.stackTrace != null) {
8042 sb.append(crashInfo.stackTrace);
8043 }
8044
8045 String setting = Settings.Secure.ERROR_LOGCAT_PREFIX + dropboxTag;
8046 int lines = Settings.Secure.getInt(mContext.getContentResolver(), setting, 0);
8047 if (lines > 0) {
8048 sb.append("\n");
8049
8050 // Merge several logcat streams, and take the last N lines
8051 InputStreamReader input = null;
8052 try {
8053 java.lang.Process logcat = new ProcessBuilder("/system/bin/logcat",
8054 "-v", "time", "-b", "events", "-b", "system", "-b", "main",
8055 "-t", String.valueOf(lines)).redirectErrorStream(true).start();
8056
8057 try { logcat.getOutputStream().close(); } catch (IOException e) {}
8058 try { logcat.getErrorStream().close(); } catch (IOException e) {}
8059 input = new InputStreamReader(logcat.getInputStream());
8060
8061 int num;
8062 char[] buf = new char[8192];
8063 while ((num = input.read(buf)) > 0) sb.append(buf, 0, num);
8064 } catch (IOException e) {
8065 Slog.e(TAG, "Error running logcat", e);
8066 } finally {
8067 if (input != null) try { input.close(); } catch (IOException e) {}
8068 }
8069 }
8070
8071 dbox.addText(dropboxTag, sb.toString());
Dan Egnor60d87622009-12-16 16:32:58 -08008072 }
Dan Egnora455d192010-03-12 08:52:28 -08008073 };
8074
Dianne Hackborn56385cc2012-04-30 15:07:47 -07008075 if (process == null) {
8076 // If process is null, we are being called from some internal code
8077 // and may be about to die -- run this synchronously.
8078 worker.run();
Dan Egnora455d192010-03-12 08:52:28 -08008079 } else {
8080 worker.start();
Dan Egnor60d87622009-12-16 16:32:58 -08008081 }
8082 }
8083
8084 /**
8085 * Bring up the "unexpected error" dialog box for a crashing app.
8086 * Deal with edge cases (intercepts from instrumented applications,
8087 * ActivityController, error intent receivers, that sort of thing).
8088 * @param r the application crashing
8089 * @param crashInfo describing the failure
8090 */
8091 private void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008092 long timeMillis = System.currentTimeMillis();
8093 String shortMsg = crashInfo.exceptionClassName;
8094 String longMsg = crashInfo.exceptionMessage;
8095 String stackTrace = crashInfo.stackTrace;
8096 if (shortMsg != null && longMsg != null) {
8097 longMsg = shortMsg + ": " + longMsg;
8098 } else if (shortMsg != null) {
8099 longMsg = shortMsg;
8100 }
8101
Dan Egnor60d87622009-12-16 16:32:58 -08008102 AppErrorResult result = new AppErrorResult();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008103 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008104 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008105 try {
8106 String name = r != null ? r.processName : null;
8107 int pid = r != null ? r.pid : Binder.getCallingPid();
Dan Egnor60d87622009-12-16 16:32:58 -08008108 if (!mController.appCrashed(name, pid,
Dan Egnorb7f03672009-12-09 16:22:32 -08008109 shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008110 Slog.w(TAG, "Force-killing crashed app " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008111 + " at watcher's request");
8112 Process.killProcess(pid);
Dan Egnorb7f03672009-12-09 16:22:32 -08008113 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008114 }
8115 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008116 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008117 }
8118 }
8119
8120 final long origId = Binder.clearCallingIdentity();
8121
8122 // If this process is running instrumentation, finish it.
8123 if (r != null && r.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008124 Slog.w(TAG, "Error in app " + r.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008125 + " running instrumentation " + r.instrumentationClass + ":");
Joe Onorato8a9b2202010-02-26 18:56:32 -08008126 if (shortMsg != null) Slog.w(TAG, " " + shortMsg);
8127 if (longMsg != null) Slog.w(TAG, " " + longMsg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008128 Bundle info = new Bundle();
8129 info.putString("shortMsg", shortMsg);
8130 info.putString("longMsg", longMsg);
8131 finishInstrumentationLocked(r, Activity.RESULT_CANCELED, info);
8132 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008133 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008134 }
8135
Dan Egnor60d87622009-12-16 16:32:58 -08008136 // If we can't identify the process or it's already exceeded its crash quota,
8137 // quit right away without showing a crash dialog.
8138 if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008139 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008140 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008141 }
8142
8143 Message msg = Message.obtain();
8144 msg.what = SHOW_ERROR_MSG;
8145 HashMap data = new HashMap();
8146 data.put("result", result);
8147 data.put("app", r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008148 msg.obj = data;
8149 mHandler.sendMessage(msg);
8150
8151 Binder.restoreCallingIdentity(origId);
8152 }
8153
8154 int res = result.get();
8155
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008156 Intent appErrorIntent = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008157 synchronized (this) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008158 if (r != null && !r.isolated) {
8159 // XXX Can't keep track of crash time for isolated processes,
8160 // since they don't have a persistent identity.
8161 mProcessCrashTimes.put(r.info.processName, r.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008162 SystemClock.uptimeMillis());
8163 }
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008164 if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008165 appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008166 }
8167 }
8168
8169 if (appErrorIntent != null) {
8170 try {
8171 mContext.startActivity(appErrorIntent);
8172 } catch (ActivityNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008173 Slog.w(TAG, "bug report receiver dissappeared", e);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008174 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008175 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008176 }
Dan Egnorb7f03672009-12-09 16:22:32 -08008177
8178 Intent createAppErrorIntentLocked(ProcessRecord r,
8179 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
8180 ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008181 if (report == null) {
8182 return null;
8183 }
8184 Intent result = new Intent(Intent.ACTION_APP_ERROR);
8185 result.setComponent(r.errorReportReceiver);
8186 result.putExtra(Intent.EXTRA_BUG_REPORT, report);
8187 result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
8188 return result;
8189 }
8190
Dan Egnorb7f03672009-12-09 16:22:32 -08008191 private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r,
8192 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008193 if (r.errorReportReceiver == null) {
8194 return null;
8195 }
8196
8197 if (!r.crashing && !r.notResponding) {
8198 return null;
8199 }
8200
Dan Egnorb7f03672009-12-09 16:22:32 -08008201 ApplicationErrorReport report = new ApplicationErrorReport();
8202 report.packageName = r.info.packageName;
8203 report.installerPackageName = r.errorReportReceiver.getPackageName();
8204 report.processName = r.processName;
8205 report.time = timeMillis;
Jacek Surazskie0ee6ef2010-01-07 16:23:03 +01008206 report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008207
Dan Egnorb7f03672009-12-09 16:22:32 -08008208 if (r.crashing) {
8209 report.type = ApplicationErrorReport.TYPE_CRASH;
8210 report.crashInfo = crashInfo;
8211 } else if (r.notResponding) {
8212 report.type = ApplicationErrorReport.TYPE_ANR;
8213 report.anrInfo = new ApplicationErrorReport.AnrInfo();
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008214
Dan Egnorb7f03672009-12-09 16:22:32 -08008215 report.anrInfo.activity = r.notRespondingReport.tag;
8216 report.anrInfo.cause = r.notRespondingReport.shortMsg;
8217 report.anrInfo.info = r.notRespondingReport.longMsg;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008218 }
8219
Dan Egnorb7f03672009-12-09 16:22:32 -08008220 return report;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008221 }
8222
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008223 public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008224 enforceNotIsolatedCaller("getProcessesInErrorState");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008225 // assume our apps are happy - lazy create the list
8226 List<ActivityManager.ProcessErrorStateInfo> errList = null;
8227
8228 synchronized (this) {
8229
8230 // iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008231 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8232 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008233 if ((app.thread != null) && (app.crashing || app.notResponding)) {
8234 // This one's in trouble, so we'll generate a report for it
8235 // crashes are higher priority (in case there's a crash *and* an anr)
8236 ActivityManager.ProcessErrorStateInfo report = null;
8237 if (app.crashing) {
8238 report = app.crashingReport;
8239 } else if (app.notResponding) {
8240 report = app.notRespondingReport;
8241 }
8242
8243 if (report != null) {
8244 if (errList == null) {
8245 errList = new ArrayList<ActivityManager.ProcessErrorStateInfo>(1);
8246 }
8247 errList.add(report);
8248 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008249 Slog.w(TAG, "Missing app error report, app = " + app.processName +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008250 " crashing = " + app.crashing +
8251 " notResponding = " + app.notResponding);
8252 }
8253 }
8254 }
8255 }
8256
8257 return errList;
8258 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07008259
8260 static int oomAdjToImportance(int adj, ActivityManager.RunningAppProcessInfo currApp) {
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008261 if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008262 if (currApp != null) {
8263 currApp.lru = adj - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
8264 }
8265 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008266 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
8267 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008268 } else if (adj >= ProcessList.HOME_APP_ADJ) {
8269 if (currApp != null) {
8270 currApp.lru = 0;
8271 }
8272 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008273 } else if (adj >= ProcessList.SERVICE_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008274 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
8275 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
8276 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
8277 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
8278 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
8279 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
8280 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
8281 } else {
8282 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
8283 }
8284 }
8285
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008286 private void fillInProcMemInfo(ProcessRecord app,
8287 ActivityManager.RunningAppProcessInfo outInfo) {
8288 outInfo.pid = app.pid;
8289 outInfo.uid = app.info.uid;
8290 if (mHeavyWeightProcess == app) {
8291 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_CANT_SAVE_STATE;
8292 }
8293 if (app.persistent) {
8294 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_PERSISTENT;
8295 }
8296 outInfo.lastTrimLevel = app.trimMemoryLevel;
8297 int adj = app.curAdj;
8298 outInfo.importance = oomAdjToImportance(adj, outInfo);
8299 outInfo.importanceReasonCode = app.adjTypeCode;
8300 }
8301
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008302 public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008303 enforceNotIsolatedCaller("getRunningAppProcesses");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008304 // Lazy instantiation of list
8305 List<ActivityManager.RunningAppProcessInfo> runList = null;
8306 synchronized (this) {
8307 // Iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008308 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8309 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008310 if ((app.thread != null) && (!app.crashing && !app.notResponding)) {
8311 // Generate process state info for running application
8312 ActivityManager.RunningAppProcessInfo currApp =
8313 new ActivityManager.RunningAppProcessInfo(app.processName,
8314 app.pid, app.getPackageList());
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008315 fillInProcMemInfo(app, currApp);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008316 if (app.adjSource instanceof ProcessRecord) {
8317 currApp.importanceReasonPid = ((ProcessRecord)app.adjSource).pid;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008318 currApp.importanceReasonImportance = oomAdjToImportance(
8319 app.adjSourceOom, null);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008320 } else if (app.adjSource instanceof ActivityRecord) {
8321 ActivityRecord r = (ActivityRecord)app.adjSource;
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008322 if (r.app != null) currApp.importanceReasonPid = r.app.pid;
8323 }
8324 if (app.adjTarget instanceof ComponentName) {
8325 currApp.importanceReasonComponent = (ComponentName)app.adjTarget;
8326 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08008327 //Slog.v(TAG, "Proc " + app.processName + ": imp=" + currApp.importance
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008328 // + " lru=" + currApp.lru);
8329 if (runList == null) {
8330 runList = new ArrayList<ActivityManager.RunningAppProcessInfo>();
8331 }
8332 runList.add(currApp);
8333 }
8334 }
8335 }
8336 return runList;
8337 }
8338
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008339 public List<ApplicationInfo> getRunningExternalApplications() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008340 enforceNotIsolatedCaller("getRunningExternalApplications");
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008341 List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses();
8342 List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>();
8343 if (runningApps != null && runningApps.size() > 0) {
8344 Set<String> extList = new HashSet<String>();
8345 for (ActivityManager.RunningAppProcessInfo app : runningApps) {
8346 if (app.pkgList != null) {
8347 for (String pkg : app.pkgList) {
8348 extList.add(pkg);
8349 }
8350 }
8351 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008352 IPackageManager pm = AppGlobals.getPackageManager();
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008353 for (String pkg : extList) {
8354 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07008355 ApplicationInfo info = pm.getApplicationInfo(pkg, 0, UserId.getCallingUserId());
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008356 if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
8357 retList.add(info);
8358 }
8359 } catch (RemoteException e) {
8360 }
8361 }
8362 }
8363 return retList;
8364 }
8365
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008366 @Override
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008367 public void getMyMemoryState(ActivityManager.RunningAppProcessInfo outInfo) {
8368 enforceNotIsolatedCaller("getMyMemoryState");
8369 synchronized (this) {
8370 ProcessRecord proc;
8371 synchronized (mPidsSelfLocked) {
8372 proc = mPidsSelfLocked.get(Binder.getCallingPid());
8373 }
8374 fillInProcMemInfo(proc, outInfo);
8375 }
8376 }
8377
8378 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008379 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008380 if (checkCallingPermission(android.Manifest.permission.DUMP)
8381 != PackageManager.PERMISSION_GRANTED) {
8382 pw.println("Permission Denial: can't dump ActivityManager from from pid="
8383 + Binder.getCallingPid()
8384 + ", uid=" + Binder.getCallingUid()
8385 + " without permission "
8386 + android.Manifest.permission.DUMP);
8387 return;
8388 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008389
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008390 boolean dumpAll = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008391 boolean dumpClient = false;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008392 String dumpPackage = null;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008393
8394 int opti = 0;
8395 while (opti < args.length) {
8396 String opt = args[opti];
8397 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
8398 break;
8399 }
8400 opti++;
8401 if ("-a".equals(opt)) {
8402 dumpAll = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008403 } else if ("-c".equals(opt)) {
8404 dumpClient = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008405 } else if ("-h".equals(opt)) {
8406 pw.println("Activity manager dump options:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008407 pw.println(" [-a] [-c] [-h] [cmd] ...");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008408 pw.println(" cmd may be one of:");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008409 pw.println(" a[ctivities]: activity stack state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008410 pw.println(" b[roadcasts] [PACKAGE_NAME]: broadcast state");
8411 pw.println(" i[ntents] [PACKAGE_NAME]: pending intent state");
8412 pw.println(" p[rocesses] [PACKAGE_NAME]: process state");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008413 pw.println(" o[om]: out of memory management");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008414 pw.println(" prov[iders] [COMP_SPEC ...]: content provider state");
Marco Nelissen18cb2872011-11-15 11:19:53 -08008415 pw.println(" provider [COMP_SPEC]: provider client-side state");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008416 pw.println(" s[ervices] [COMP_SPEC ...]: service state");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008417 pw.println(" service [COMP_SPEC]: service client-side state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008418 pw.println(" package [PACKAGE_NAME]: all state related to given package");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008419 pw.println(" all: dump all activities");
8420 pw.println(" top: dump the top activity");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008421 pw.println(" cmd may also be a COMP_SPEC to dump activities.");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008422 pw.println(" COMP_SPEC may be a component name (com.foo/.myApp),");
8423 pw.println(" a partial substring in a component name, a");
8424 pw.println(" hex object identifier.");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008425 pw.println(" -a: include all available server state.");
8426 pw.println(" -c: include client state.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008427 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008428 } else {
8429 pw.println("Unknown argument: " + opt + "; use -h for help");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008430 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008431 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008432
8433 long origId = Binder.clearCallingIdentity();
8434 boolean more = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008435 // Is the caller requesting to dump a particular piece of data?
8436 if (opti < args.length) {
8437 String cmd = args[opti];
8438 opti++;
8439 if ("activities".equals(cmd) || "a".equals(cmd)) {
8440 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008441 dumpActivitiesLocked(fd, pw, args, opti, true, dumpClient, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008442 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008443 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008444 String[] newArgs;
8445 String name;
8446 if (opti >= args.length) {
8447 name = null;
8448 newArgs = EMPTY_STRING_ARRAY;
8449 } else {
8450 name = args[opti];
8451 opti++;
8452 newArgs = new String[args.length - opti];
8453 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8454 args.length - opti);
8455 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008456 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008457 dumpBroadcastsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008458 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008459 } else if ("intents".equals(cmd) || "i".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008460 String[] newArgs;
8461 String name;
8462 if (opti >= args.length) {
8463 name = null;
8464 newArgs = EMPTY_STRING_ARRAY;
8465 } else {
8466 name = args[opti];
8467 opti++;
8468 newArgs = new String[args.length - opti];
8469 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8470 args.length - opti);
8471 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008472 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008473 dumpPendingIntentsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008474 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008475 } else if ("processes".equals(cmd) || "p".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008476 String[] newArgs;
8477 String name;
8478 if (opti >= args.length) {
8479 name = null;
8480 newArgs = EMPTY_STRING_ARRAY;
8481 } else {
8482 name = args[opti];
8483 opti++;
8484 newArgs = new String[args.length - opti];
8485 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8486 args.length - opti);
8487 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008488 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008489 dumpProcessesLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008490 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008491 } else if ("oom".equals(cmd) || "o".equals(cmd)) {
8492 synchronized (this) {
8493 dumpOomLocked(fd, pw, args, opti, true);
8494 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08008495 } else if ("provider".equals(cmd)) {
8496 String[] newArgs;
8497 String name;
8498 if (opti >= args.length) {
8499 name = null;
8500 newArgs = EMPTY_STRING_ARRAY;
8501 } else {
8502 name = args[opti];
8503 opti++;
8504 newArgs = new String[args.length - opti];
8505 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
8506 }
8507 if (!dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) {
8508 pw.println("No providers match: " + name);
8509 pw.println("Use -h for help.");
8510 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008511 } else if ("providers".equals(cmd) || "prov".equals(cmd)) {
8512 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008513 dumpProvidersLocked(fd, pw, args, opti, true, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008514 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008515 } else if ("service".equals(cmd)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008516 String[] newArgs;
8517 String name;
8518 if (opti >= args.length) {
8519 name = null;
8520 newArgs = EMPTY_STRING_ARRAY;
8521 } else {
8522 name = args[opti];
8523 opti++;
8524 newArgs = new String[args.length - opti];
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008525 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8526 args.length - opti);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008527 }
8528 if (!dumpService(fd, pw, name, newArgs, 0, dumpAll)) {
8529 pw.println("No services match: " + name);
8530 pw.println("Use -h for help.");
8531 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008532 } else if ("package".equals(cmd)) {
8533 String[] newArgs;
8534 if (opti >= args.length) {
8535 pw.println("package: no package name specified");
8536 pw.println("Use -h for help.");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008537 } else {
8538 dumpPackage = args[opti];
8539 opti++;
8540 newArgs = new String[args.length - opti];
8541 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8542 args.length - opti);
8543 args = newArgs;
8544 opti = 0;
Amith Yamasani7463ada2012-04-11 15:02:39 -07008545 more = true;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008546 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008547 } else if ("services".equals(cmd) || "s".equals(cmd)) {
8548 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008549 dumpServicesLocked(fd, pw, args, opti, true, dumpClient, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008550 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07008551 } else {
8552 // Dumping a single activity?
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008553 if (!dumpActivity(fd, pw, cmd, args, opti, dumpAll)) {
8554 pw.println("Bad activity command, or no activities match: " + cmd);
8555 pw.println("Use -h for help.");
Dianne Hackborn625ac272010-09-17 18:29:22 -07008556 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008557 }
8558 if (!more) {
8559 Binder.restoreCallingIdentity(origId);
Dianne Hackborn30d71892010-12-11 10:37:55 -08008560 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008561 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008562 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008563
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008564 // No piece of data specified, dump everything.
8565 synchronized (this) {
8566 boolean needSep;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008567 needSep = dumpPendingIntentsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008568 if (needSep) {
8569 pw.println(" ");
8570 }
8571 if (dumpAll) {
8572 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008573 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008574 needSep = dumpBroadcastsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008575 if (needSep) {
8576 pw.println(" ");
8577 }
8578 if (dumpAll) {
8579 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008580 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008581 needSep = dumpProvidersLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008582 if (needSep) {
8583 pw.println(" ");
8584 }
8585 if (dumpAll) {
8586 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008587 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008588 needSep = dumpServicesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008589 if (needSep) {
8590 pw.println(" ");
8591 }
8592 if (dumpAll) {
8593 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008594 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008595 needSep = dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008596 if (needSep) {
8597 pw.println(" ");
8598 }
8599 if (dumpAll) {
8600 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008601 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008602 dumpProcessesLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008603 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008604 Binder.restoreCallingIdentity(origId);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008605 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008606
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008607 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008608 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008609 pw.println("ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
8610 pw.println(" Main stack:");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008611 dumpHistoryList(fd, pw, mMainStack.mHistory, " ", "Hist", true, !dumpAll, dumpClient,
8612 dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008613 pw.println(" ");
8614 pw.println(" Running activities (most recent first):");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008615 dumpHistoryList(fd, pw, mMainStack.mLRUActivities, " ", "Run", false, !dumpAll, false,
8616 dumpPackage);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008617 if (mMainStack.mWaitingVisibleActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008618 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008619 pw.println(" Activities waiting for another to become visible:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008620 dumpHistoryList(fd, pw, mMainStack.mWaitingVisibleActivities, " ", "Wait", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008621 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008622 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008623 if (mMainStack.mStoppingActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008624 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008625 pw.println(" Activities waiting to stop:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008626 dumpHistoryList(fd, pw, mMainStack.mStoppingActivities, " ", "Stop", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008627 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008628 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008629 if (mMainStack.mGoingToSleepActivities.size() > 0) {
8630 pw.println(" ");
8631 pw.println(" Activities waiting to sleep:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008632 dumpHistoryList(fd, pw, mMainStack.mGoingToSleepActivities, " ", "Sleep", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008633 !dumpAll, false, dumpPackage);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008634 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008635 if (mMainStack.mFinishingActivities.size() > 0) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008636 pw.println(" ");
8637 pw.println(" Activities waiting to finish:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008638 dumpHistoryList(fd, pw, mMainStack.mFinishingActivities, " ", "Fin", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008639 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008640 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008641
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008642 pw.println(" ");
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08008643 if (mMainStack.mPausingActivity != null) {
8644 pw.println(" mPausingActivity: " + mMainStack.mPausingActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008645 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008646 pw.println(" mResumedActivity: " + mMainStack.mResumedActivity);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008647 pw.println(" mFocusedActivity: " + mFocusedActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008648 if (dumpAll) {
8649 pw.println(" mLastPausedActivity: " + mMainStack.mLastPausedActivity);
8650 pw.println(" mSleepTimeout: " + mMainStack.mSleepTimeout);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07008651 pw.println(" mDismissKeyguardOnNextActivity: "
8652 + mMainStack.mDismissKeyguardOnNextActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008653 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008654
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008655 if (mRecentTasks.size() > 0) {
8656 pw.println();
8657 pw.println(" Recent tasks:");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008658
8659 final int N = mRecentTasks.size();
8660 for (int i=0; i<N; i++) {
8661 TaskRecord tr = mRecentTasks.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008662 if (dumpPackage != null) {
8663 if (tr.realActivity == null ||
8664 !dumpPackage.equals(tr.realActivity)) {
8665 continue;
8666 }
8667 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008668 pw.print(" * Recent #"); pw.print(i); pw.print(": ");
8669 pw.println(tr);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008670 if (dumpAll) {
8671 mRecentTasks.get(i).dump(pw, " ");
8672 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008673 }
8674 }
8675
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008676 if (dumpAll) {
8677 pw.println(" ");
8678 pw.println(" mCurTask: " + mCurTask);
8679 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008680
8681 return true;
8682 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008683
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008684 boolean dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008685 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008686 boolean needSep = false;
8687 int numPers = 0;
8688
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008689 pw.println("ACTIVITY MANAGER RUNNING PROCESSES (dumpsys activity processes)");
8690
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008691 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008692 for (SparseArray<ProcessRecord> procs : mProcessNames.getMap().values()) {
8693 final int NA = procs.size();
8694 for (int ia=0; ia<NA; ia++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008695 ProcessRecord r = procs.valueAt(ia);
8696 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8697 continue;
8698 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008699 if (!needSep) {
8700 pw.println(" All known processes:");
8701 needSep = true;
8702 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008703 pw.print(r.persistent ? " *PERS*" : " *APP*");
8704 pw.print(" UID "); pw.print(procs.keyAt(ia));
8705 pw.print(" "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008706 r.dump(pw, " ");
8707 if (r.persistent) {
8708 numPers++;
8709 }
8710 }
8711 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008712 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008713
8714 if (mIsolatedProcesses.size() > 0) {
8715 if (needSep) pw.println(" ");
8716 needSep = true;
8717 pw.println(" Isolated process list (sorted by uid):");
8718 for (int i=0; i<mIsolatedProcesses.size(); i++) {
8719 ProcessRecord r = mIsolatedProcesses.valueAt(i);
8720 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8721 continue;
8722 }
8723 pw.println(String.format("%sIsolated #%2d: %s",
8724 " ", i, r.toString()));
8725 }
8726 }
8727
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008728 if (mLruProcesses.size() > 0) {
8729 if (needSep) pw.println(" ");
8730 needSep = true;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008731 pw.println(" Process LRU list (sorted by oom_adj):");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008732 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008733 "Proc", "PERS", false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008734 needSep = true;
8735 }
8736
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008737 if (dumpAll) {
8738 synchronized (mPidsSelfLocked) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008739 boolean printed = false;
8740 for (int i=0; i<mPidsSelfLocked.size(); i++) {
8741 ProcessRecord r = mPidsSelfLocked.valueAt(i);
8742 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8743 continue;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008744 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008745 if (!printed) {
8746 if (needSep) pw.println(" ");
8747 needSep = true;
8748 pw.println(" PID mappings:");
8749 printed = true;
8750 }
8751 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i));
8752 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008753 }
8754 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008755 }
8756
8757 if (mForegroundProcesses.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008758 synchronized (mPidsSelfLocked) {
8759 boolean printed = false;
8760 for (int i=0; i<mForegroundProcesses.size(); i++) {
8761 ProcessRecord r = mPidsSelfLocked.get(
8762 mForegroundProcesses.valueAt(i).pid);
8763 if (dumpPackage != null && (r == null
8764 || !dumpPackage.equals(r.info.packageName))) {
8765 continue;
8766 }
8767 if (!printed) {
8768 if (needSep) pw.println(" ");
8769 needSep = true;
8770 pw.println(" Foreground Processes:");
8771 printed = true;
8772 }
8773 pw.print(" PID #"); pw.print(mForegroundProcesses.keyAt(i));
8774 pw.print(": "); pw.println(mForegroundProcesses.valueAt(i));
8775 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008776 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008777 }
8778
8779 if (mPersistentStartingProcesses.size() > 0) {
8780 if (needSep) pw.println(" ");
8781 needSep = true;
8782 pw.println(" Persisent processes that are starting:");
8783 dumpProcessList(pw, this, mPersistentStartingProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008784 "Starting Norm", "Restarting PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008785 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008786
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008787 if (mRemovedProcesses.size() > 0) {
8788 if (needSep) pw.println(" ");
8789 needSep = true;
8790 pw.println(" Processes that are being removed:");
8791 dumpProcessList(pw, this, mRemovedProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008792 "Removed Norm", "Removed PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008793 }
8794
8795 if (mProcessesOnHold.size() > 0) {
8796 if (needSep) pw.println(" ");
8797 needSep = true;
8798 pw.println(" Processes that are on old until the system is ready:");
8799 dumpProcessList(pw, this, mProcessesOnHold, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008800 "OnHold Norm", "OnHold PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008801 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008802
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008803 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008804
8805 if (mProcessCrashTimes.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008806 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008807 long now = SystemClock.uptimeMillis();
8808 for (Map.Entry<String, SparseArray<Long>> procs
8809 : mProcessCrashTimes.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008810 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008811 SparseArray<Long> uids = procs.getValue();
8812 final int N = uids.size();
8813 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008814 int puid = uids.keyAt(i);
8815 ProcessRecord r = mProcessNames.get(pname, puid);
8816 if (dumpPackage != null && (r == null
8817 || !dumpPackage.equals(r.info.packageName))) {
8818 continue;
8819 }
8820 if (!printed) {
8821 if (needSep) pw.println(" ");
8822 needSep = true;
8823 pw.println(" Time since processes crashed:");
8824 printed = true;
8825 }
8826 pw.print(" Process "); pw.print(pname);
8827 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008828 pw.print(": last crashed ");
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008829 TimeUtils.formatDuration(now-uids.valueAt(i), pw);
8830 pw.println(" ago");
Dianne Hackbornfd12af42009-08-27 00:44:33 -07008831 }
8832 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008833 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008834
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008835 if (mBadProcesses.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008836 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008837 for (Map.Entry<String, SparseArray<Long>> procs
8838 : mBadProcesses.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008839 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008840 SparseArray<Long> uids = procs.getValue();
8841 final int N = uids.size();
8842 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008843 int puid = uids.keyAt(i);
8844 ProcessRecord r = mProcessNames.get(pname, puid);
8845 if (dumpPackage != null && (r == null
8846 || !dumpPackage.equals(r.info.packageName))) {
8847 continue;
8848 }
8849 if (!printed) {
8850 if (needSep) pw.println(" ");
8851 needSep = true;
8852 pw.println(" Bad processes:");
8853 }
8854 pw.print(" Bad process "); pw.print(pname);
8855 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008856 pw.print(": crashed at time ");
8857 pw.println(uids.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008858 }
8859 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008860 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008861
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008862 pw.println();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008863 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07008864 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn50685602011-12-01 12:23:37 -08008865 if (dumpAll) {
8866 StringBuilder sb = new StringBuilder(128);
8867 sb.append(" mPreviousProcessVisibleTime: ");
8868 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
8869 pw.println(sb);
8870 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07008871 if (mHeavyWeightProcess != null) {
8872 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
8873 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008874 pw.println(" mConfiguration: " + mConfiguration);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008875 if (dumpAll) {
8876 pw.println(" mConfigWillChange: " + mMainStack.mConfigWillChange);
Dianne Hackborn3d0724d2011-05-12 15:39:41 -07008877 if (mCompatModePackages.getPackages().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008878 boolean printed = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07008879 for (Map.Entry<String, Integer> entry
8880 : mCompatModePackages.getPackages().entrySet()) {
8881 String pkg = entry.getKey();
8882 int mode = entry.getValue();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008883 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
8884 continue;
8885 }
8886 if (!printed) {
8887 pw.println(" mScreenCompatPackages:");
8888 printed = true;
8889 }
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07008890 pw.print(" "); pw.print(pkg); pw.print(": ");
8891 pw.print(mode); pw.println();
8892 }
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07008893 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008894 }
Dianne Hackbornff5b1582012-04-12 17:24:07 -07008895 if (mSleeping || mWentToSleep || mLockScreenShown) {
8896 pw.println(" mSleeping=" + mSleeping + " mWentToSleep=" + mWentToSleep
8897 + " mLockScreenShown " + mLockScreenShown);
8898 }
8899 if (mShuttingDown) {
8900 pw.println(" mShuttingDown=" + mShuttingDown);
8901 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008902 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
8903 || mOrigWaitForDebugger) {
8904 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp
8905 + " mDebugTransient=" + mDebugTransient
8906 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger);
8907 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08008908 if (mOpenGlTraceApp != null) {
8909 pw.println(" mOpenGlTraceApp=" + mOpenGlTraceApp);
8910 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07008911 if (mProfileApp != null || mProfileProc != null || mProfileFile != null
8912 || mProfileFd != null) {
8913 pw.println(" mProfileApp=" + mProfileApp + " mProfileProc=" + mProfileProc);
8914 pw.println(" mProfileFile=" + mProfileFile + " mProfileFd=" + mProfileFd);
8915 pw.println(" mProfileType=" + mProfileType + " mAutoStopProfiler="
8916 + mAutoStopProfiler);
8917 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008918 if (mAlwaysFinishActivities || mController != null) {
8919 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities
8920 + " mController=" + mController);
8921 }
8922 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008923 pw.println(" Total persistent processes: " + numPers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008924 pw.println(" mStartRunning=" + mStartRunning
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07008925 + " mProcessesReady=" + mProcessesReady
8926 + " mSystemReady=" + mSystemReady);
8927 pw.println(" mBooting=" + mBooting
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008928 + " mBooted=" + mBooted
8929 + " mFactoryTest=" + mFactoryTest);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008930 pw.print(" mLastPowerCheckRealtime=");
8931 TimeUtils.formatDuration(mLastPowerCheckRealtime, pw);
8932 pw.println("");
8933 pw.print(" mLastPowerCheckUptime=");
8934 TimeUtils.formatDuration(mLastPowerCheckUptime, pw);
8935 pw.println("");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008936 pw.println(" mGoingToSleep=" + mMainStack.mGoingToSleep);
8937 pw.println(" mLaunchingActivity=" + mMainStack.mLaunchingActivity);
Dianne Hackborn906497c2010-05-10 15:57:38 -07008938 pw.println(" mAdjSeq=" + mAdjSeq + " mLruSeq=" + mLruSeq);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008939 pw.println(" mNumServiceProcs=" + mNumServiceProcs
8940 + " mNewNumServiceProcs=" + mNewNumServiceProcs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008941 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008942
8943 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008944 }
8945
Dianne Hackborn287952c2010-09-22 22:34:31 -07008946 boolean dumpProcessesToGc(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008947 int opti, boolean needSep, boolean dumpAll, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07008948 if (mProcessesToGc.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008949 boolean printed = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -07008950 long now = SystemClock.uptimeMillis();
8951 for (int i=0; i<mProcessesToGc.size(); i++) {
8952 ProcessRecord proc = mProcessesToGc.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008953 if (dumpPackage != null && !dumpPackage.equals(proc.info.packageName)) {
8954 continue;
8955 }
8956 if (!printed) {
8957 if (needSep) pw.println(" ");
8958 needSep = true;
8959 pw.println(" Processes that are waiting to GC:");
8960 printed = true;
8961 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008962 pw.print(" Process "); pw.println(proc);
8963 pw.print(" lowMem="); pw.print(proc.reportLowMemory);
8964 pw.print(", last gced=");
8965 pw.print(now-proc.lastRequestedGc);
8966 pw.print(" ms ago, last lowMem=");
8967 pw.print(now-proc.lastLowMemory);
8968 pw.println(" ms ago");
8969
8970 }
8971 }
8972 return needSep;
8973 }
8974
8975 boolean dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args,
8976 int opti, boolean dumpAll) {
8977 boolean needSep = false;
8978
8979 if (mLruProcesses.size() > 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07008980 if (needSep) pw.println(" ");
8981 needSep = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -07008982 pw.println(" OOM levels:");
Dianne Hackborn7d608422011-08-07 16:24:18 -07008983 pw.print(" SYSTEM_ADJ: "); pw.println(ProcessList.SYSTEM_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008984 pw.print(" PERSISTENT_PROC_ADJ: "); pw.println(ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07008985 pw.print(" FOREGROUND_APP_ADJ: "); pw.println(ProcessList.FOREGROUND_APP_ADJ);
8986 pw.print(" VISIBLE_APP_ADJ: "); pw.println(ProcessList.VISIBLE_APP_ADJ);
8987 pw.print(" PERCEPTIBLE_APP_ADJ: "); pw.println(ProcessList.PERCEPTIBLE_APP_ADJ);
8988 pw.print(" HEAVY_WEIGHT_APP_ADJ: "); pw.println(ProcessList.HEAVY_WEIGHT_APP_ADJ);
8989 pw.print(" BACKUP_APP_ADJ: "); pw.println(ProcessList.BACKUP_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008990 pw.print(" SERVICE_ADJ: "); pw.println(ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07008991 pw.print(" HOME_APP_ADJ: "); pw.println(ProcessList.HOME_APP_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07008992 pw.print(" PREVIOUS_APP_ADJ: "); pw.println(ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008993 pw.print(" SERVICE_B_ADJ: "); pw.println(ProcessList.SERVICE_B_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07008994 pw.print(" HIDDEN_APP_MIN_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008995 pw.print(" HIDDEN_APP_MAX_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MAX_ADJ);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07008996
8997 if (needSep) pw.println(" ");
8998 needSep = true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07008999 pw.println(" Process OOM control:");
Dianne Hackborn905577f2011-09-07 18:31:28 -07009000 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009001 "Proc", "PERS", true, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009002 needSep = true;
9003 }
9004
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009005 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009006
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009007 pw.println();
Dianne Hackborn287952c2010-09-22 22:34:31 -07009008 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009009 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009010 if (mHeavyWeightProcess != null) {
9011 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
9012 }
9013
9014 return true;
9015 }
9016
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009017 /**
9018 * There are three ways to call this:
9019 * - no service specified: dump all the services
9020 * - a flattened component name that matched an existing service was specified as the
9021 * first arg: dump that one service
9022 * - the first arg isn't the flattened component name of an existing service:
9023 * dump all services whose component contains the first arg as a substring
9024 */
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009025 protected boolean dumpService(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9026 int opti, boolean dumpAll) {
9027 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009028
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009029 if ("all".equals(name)) {
Dianne Hackborn14bfa392010-07-24 19:58:06 -07009030 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07009031 try {
9032 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
9033 for (UserInfo user : users) {
9034 for (ServiceRecord r1 : mServiceMap.getAllServices(user.id)) {
9035 services.add(r1);
9036 }
9037 }
9038 } catch (RemoteException re) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009039 }
9040 }
9041 } else {
9042 ComponentName componentName = name != null
9043 ? ComponentName.unflattenFromString(name) : null;
9044 int objectId = 0;
9045 if (componentName == null) {
9046 // Not a '/' separated full component name; maybe an object ID?
9047 try {
9048 objectId = Integer.parseInt(name, 16);
9049 name = null;
9050 componentName = null;
9051 } catch (RuntimeException e) {
9052 }
9053 }
9054
9055 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07009056 try {
9057 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
9058 for (UserInfo user : users) {
9059 for (ServiceRecord r1 : mServiceMap.getAllServices(user.id)) {
9060 if (componentName != null) {
9061 if (r1.name.equals(componentName)) {
9062 services.add(r1);
9063 }
9064 } else if (name != null) {
9065 if (r1.name.flattenToString().contains(name)) {
9066 services.add(r1);
9067 }
9068 } else if (System.identityHashCode(r1) == objectId) {
9069 services.add(r1);
9070 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009071 }
Dianne Hackborn14bfa392010-07-24 19:58:06 -07009072 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009073 } catch (RemoteException re) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009074 }
9075 }
9076 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009077
9078 if (services.size() <= 0) {
9079 return false;
9080 }
9081
9082 boolean needSep = false;
9083 for (int i=0; i<services.size(); i++) {
9084 if (needSep) {
9085 pw.println();
9086 }
9087 needSep = true;
9088 dumpService("", fd, pw, services.get(i), args, dumpAll);
9089 }
9090 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009091 }
9092
9093 /**
9094 * Invokes IApplicationThread.dumpService() on the thread of the specified service if
9095 * there is a thread associated with the service.
9096 */
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009097 private void dumpService(String prefix, FileDescriptor fd, PrintWriter pw,
9098 final ServiceRecord r, String[] args, boolean dumpAll) {
9099 String innerPrefix = prefix + " ";
9100 synchronized (this) {
9101 pw.print(prefix); pw.print("SERVICE ");
9102 pw.print(r.shortName); pw.print(" ");
9103 pw.print(Integer.toHexString(System.identityHashCode(r)));
9104 pw.print(" pid=");
9105 if (r.app != null) pw.println(r.app.pid);
9106 else pw.println("(not running)");
9107 if (dumpAll) {
9108 r.dump(pw, innerPrefix);
9109 }
9110 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009111 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009112 pw.print(prefix); pw.println(" Client:");
9113 pw.flush();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009114 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009115 TransferPipe tp = new TransferPipe();
9116 try {
9117 r.app.thread.dumpService(tp.getWriteFd().getFileDescriptor(), r, args);
9118 tp.setBufferPrefix(prefix + " ");
9119 tp.go(fd);
9120 } finally {
9121 tp.kill();
9122 }
9123 } catch (IOException e) {
9124 pw.println(prefix + " Failure while dumping the service: " + e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009125 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009126 pw.println(prefix + " Got a RemoteException while dumping the service");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009127 }
9128 }
9129 }
9130
Marco Nelissen18cb2872011-11-15 11:19:53 -08009131 /**
9132 * There are three ways to call this:
9133 * - no provider specified: dump all the providers
9134 * - a flattened component name that matched an existing provider was specified as the
9135 * first arg: dump that one provider
9136 * - the first arg isn't the flattened component name of an existing provider:
9137 * dump all providers whose component contains the first arg as a substring
9138 */
9139 protected boolean dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9140 int opti, boolean dumpAll) {
Marco Nelissende7408c2012-02-08 14:57:38 -08009141 return mProviderMap.dumpProvider(fd, pw, name, args, opti, dumpAll);
Marco Nelissen18cb2872011-11-15 11:19:53 -08009142 }
9143
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009144 static class ItemMatcher {
9145 ArrayList<ComponentName> components;
9146 ArrayList<String> strings;
9147 ArrayList<Integer> objects;
9148 boolean all;
9149
9150 ItemMatcher() {
9151 all = true;
9152 }
9153
9154 void build(String name) {
9155 ComponentName componentName = ComponentName.unflattenFromString(name);
9156 if (componentName != null) {
9157 if (components == null) {
9158 components = new ArrayList<ComponentName>();
9159 }
9160 components.add(componentName);
9161 all = false;
9162 } else {
9163 int objectId = 0;
9164 // Not a '/' separated full component name; maybe an object ID?
9165 try {
9166 objectId = Integer.parseInt(name, 16);
9167 if (objects == null) {
9168 objects = new ArrayList<Integer>();
9169 }
9170 objects.add(objectId);
9171 all = false;
9172 } catch (RuntimeException e) {
9173 // Not an integer; just do string match.
9174 if (strings == null) {
9175 strings = new ArrayList<String>();
9176 }
9177 strings.add(name);
9178 all = false;
9179 }
9180 }
9181 }
9182
9183 int build(String[] args, int opti) {
9184 for (; opti<args.length; opti++) {
9185 String name = args[opti];
9186 if ("--".equals(name)) {
9187 return opti+1;
9188 }
9189 build(name);
9190 }
9191 return opti;
9192 }
9193
9194 boolean match(Object object, ComponentName comp) {
9195 if (all) {
9196 return true;
9197 }
9198 if (components != null) {
9199 for (int i=0; i<components.size(); i++) {
9200 if (components.get(i).equals(comp)) {
9201 return true;
9202 }
9203 }
9204 }
9205 if (objects != null) {
9206 for (int i=0; i<objects.size(); i++) {
9207 if (System.identityHashCode(object) == objects.get(i)) {
9208 return true;
9209 }
9210 }
9211 }
9212 if (strings != null) {
9213 String flat = comp.flattenToString();
9214 for (int i=0; i<strings.size(); i++) {
9215 if (flat.contains(strings.get(i))) {
9216 return true;
9217 }
9218 }
9219 }
9220 return false;
9221 }
9222 }
9223
Dianne Hackborn625ac272010-09-17 18:29:22 -07009224 /**
9225 * There are three things that cmd can be:
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009226 * - a flattened component name that matches an existing activity
Dianne Hackborn625ac272010-09-17 18:29:22 -07009227 * - the cmd arg isn't the flattened component name of an existing activity:
9228 * dump all activity whose component contains the cmd as a substring
9229 * - A hex number of the ActivityRecord object instance.
9230 */
9231 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9232 int opti, boolean dumpAll) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009233 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009234
9235 if ("all".equals(name)) {
9236 synchronized (this) {
9237 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009238 activities.add(r1);
9239 }
9240 }
Dianne Hackbornf9302322011-06-14 18:36:14 -07009241 } else if ("top".equals(name)) {
9242 synchronized (this) {
9243 final int N = mMainStack.mHistory.size();
9244 if (N > 0) {
9245 activities.add((ActivityRecord)mMainStack.mHistory.get(N-1));
9246 }
9247 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009248 } else {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009249 ItemMatcher matcher = new ItemMatcher();
9250 matcher.build(name);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009251
9252 synchronized (this) {
9253 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009254 if (matcher.match(r1, r1.intent.getComponent())) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009255 activities.add(r1);
9256 }
9257 }
9258 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009259 }
9260
9261 if (activities.size() <= 0) {
9262 return false;
9263 }
9264
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009265 String[] newArgs = new String[args.length - opti];
9266 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
9267
Dianne Hackborn30d71892010-12-11 10:37:55 -08009268 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009269 boolean needSep = false;
Dianne Hackborn30d71892010-12-11 10:37:55 -08009270 for (int i=activities.size()-1; i>=0; i--) {
9271 ActivityRecord r = (ActivityRecord)activities.get(i);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009272 if (needSep) {
9273 pw.println();
9274 }
9275 needSep = true;
9276 synchronized (this) {
9277 if (lastTask != r.task) {
9278 lastTask = r.task;
9279 pw.print("TASK "); pw.print(lastTask.affinity);
9280 pw.print(" id="); pw.println(lastTask.taskId);
9281 if (dumpAll) {
9282 lastTask.dump(pw, " ");
9283 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08009284 }
9285 }
9286 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009287 }
9288 return true;
9289 }
9290
9291 /**
9292 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
9293 * there is a thread associated with the activity.
9294 */
Dianne Hackborn30d71892010-12-11 10:37:55 -08009295 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009296 final ActivityRecord r, String[] args, boolean dumpAll) {
9297 String innerPrefix = prefix + " ";
Dianne Hackborn30d71892010-12-11 10:37:55 -08009298 synchronized (this) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009299 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
9300 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
9301 pw.print(" pid=");
Dianne Hackborn30d71892010-12-11 10:37:55 -08009302 if (r.app != null) pw.println(r.app.pid);
9303 else pw.println("(not running)");
9304 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009305 r.dump(pw, innerPrefix);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009306 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009307 }
9308 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009309 // flush anything that is already in the PrintWriter since the thread is going
9310 // to write to the file descriptor directly
9311 pw.flush();
Dianne Hackborn625ac272010-09-17 18:29:22 -07009312 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009313 TransferPipe tp = new TransferPipe();
9314 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009315 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9316 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009317 tp.go(fd);
9318 } finally {
9319 tp.kill();
9320 }
9321 } catch (IOException e) {
9322 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009323 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009324 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
Dianne Hackborn625ac272010-09-17 18:29:22 -07009325 }
9326 }
9327 }
9328
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009329 boolean dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009330 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009331 boolean needSep = false;
9332
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009333 pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009334 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009335 if (mRegisteredReceivers.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009336 boolean printed = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009337 Iterator it = mRegisteredReceivers.values().iterator();
9338 while (it.hasNext()) {
9339 ReceiverList r = (ReceiverList)it.next();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009340 if (dumpPackage != null && (r.app == null ||
9341 !dumpPackage.equals(r.app.info.packageName))) {
9342 continue;
9343 }
9344 if (!printed) {
9345 pw.println(" Registered Receivers:");
9346 needSep = true;
9347 printed = true;
9348 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009349 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009350 r.dump(pw, " ");
9351 }
9352 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009353
9354 if (mReceiverResolver.dump(pw, needSep ?
9355 "\n Receiver Resolver Table:" : " Receiver Resolver Table:",
9356 " ", dumpPackage, false)) {
9357 needSep = true;
9358 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009359 }
Christopher Tatef46723b2012-01-26 14:19:24 -08009360
9361 for (BroadcastQueue q : mBroadcastQueues) {
9362 needSep = q.dumpLocked(fd, pw, args, opti, dumpAll, dumpPackage, needSep);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009363 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009364
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009365 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009366
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009367 if (mStickyBroadcasts != null && dumpPackage == null) {
9368 if (needSep) {
9369 pw.println();
9370 }
9371 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009372 pw.println(" Sticky broadcasts:");
9373 StringBuilder sb = new StringBuilder(128);
9374 for (Map.Entry<String, ArrayList<Intent>> ent
9375 : mStickyBroadcasts.entrySet()) {
9376 pw.print(" * Sticky action "); pw.print(ent.getKey());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009377 if (dumpAll) {
9378 pw.println(":");
9379 ArrayList<Intent> intents = ent.getValue();
9380 final int N = intents.size();
9381 for (int i=0; i<N; i++) {
9382 sb.setLength(0);
9383 sb.append(" Intent: ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009384 intents.get(i).toShortString(sb, false, true, false, false);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009385 pw.println(sb.toString());
9386 Bundle bundle = intents.get(i).getExtras();
9387 if (bundle != null) {
9388 pw.print(" ");
9389 pw.println(bundle.toString());
9390 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009391 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009392 } else {
9393 pw.println("");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009394 }
9395 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009396 needSep = true;
9397 }
9398
9399 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009400 pw.println();
Christopher Tatef46723b2012-01-26 14:19:24 -08009401 for (BroadcastQueue queue : mBroadcastQueues) {
9402 pw.println(" mBroadcastsScheduled [" + queue.mQueueName + "]="
9403 + queue.mBroadcastsScheduled);
9404 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009405 pw.println(" mHandler:");
9406 mHandler.dump(new PrintWriterPrinter(pw), " ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009407 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009408 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009409
9410 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009411 }
9412
Marco Nelissen18cb2872011-11-15 11:19:53 -08009413 /**
9414 * Prints a list of ServiceRecords (dumpsys activity services)
9415 */
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009416 boolean dumpServicesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009417 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009418 boolean needSep = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009419
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009420 ItemMatcher matcher = new ItemMatcher();
9421 matcher.build(args, opti);
9422
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009423 pw.println("ACTIVITY MANAGER SERVICES (dumpsys activity services)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009424 try {
9425 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
9426 for (UserInfo user : users) {
9427 if (mServiceMap.getAllServices(user.id).size() > 0) {
9428 boolean printed = false;
9429 long nowReal = SystemClock.elapsedRealtime();
9430 Iterator<ServiceRecord> it = mServiceMap.getAllServices(
9431 user.id).iterator();
9432 needSep = false;
9433 while (it.hasNext()) {
9434 ServiceRecord r = it.next();
9435 if (!matcher.match(r, r.name)) {
9436 continue;
9437 }
9438 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9439 continue;
9440 }
9441 if (!printed) {
9442 pw.println(" Active services:");
9443 printed = true;
9444 }
9445 if (needSep) {
9446 pw.println();
9447 }
9448 pw.print(" * ");
9449 pw.println(r);
9450 if (dumpAll) {
9451 r.dump(pw, " ");
9452 needSep = true;
9453 } else {
9454 pw.print(" app=");
9455 pw.println(r.app);
9456 pw.print(" created=");
9457 TimeUtils.formatDuration(r.createTime, nowReal, pw);
9458 pw.print(" started=");
9459 pw.print(r.startRequested);
9460 pw.print(" connections=");
9461 pw.println(r.connections.size());
9462 if (r.connections.size() > 0) {
9463 pw.println(" Connections:");
9464 for (ArrayList<ConnectionRecord> clist : r.connections.values()) {
9465 for (int i = 0; i < clist.size(); i++) {
9466 ConnectionRecord conn = clist.get(i);
9467 pw.print(" ");
9468 pw.print(conn.binding.intent.intent.getIntent()
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009469 .toShortString(false, false, false, false));
Amith Yamasani742a6712011-05-04 14:49:28 -07009470 pw.print(" -> ");
9471 ProcessRecord proc = conn.binding.client;
9472 pw.println(proc != null ? proc.toShortString() : "null");
9473 }
9474 }
Dianne Hackborn8ec8d412011-11-14 18:27:24 -08009475 }
9476 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009477 if (dumpClient && r.app != null && r.app.thread != null) {
9478 pw.println(" Client:");
9479 pw.flush();
9480 try {
9481 TransferPipe tp = new TransferPipe();
9482 try {
9483 r.app.thread.dumpService(tp.getWriteFd().getFileDescriptor(),
9484 r, args);
9485 tp.setBufferPrefix(" ");
9486 // Short timeout, since blocking here can
9487 // deadlock with the application.
9488 tp.go(fd, 2000);
9489 } finally {
9490 tp.kill();
9491 }
9492 } catch (IOException e) {
9493 pw.println(" Failure while dumping the service: " + e);
9494 } catch (RemoteException e) {
9495 pw.println(" Got a RemoteException while dumping the service");
9496 }
9497 needSep = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009498 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009499 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009500 needSep = printed;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009501 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009502 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009503 } catch (RemoteException re) {
9504
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009505 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009506
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009507 if (mPendingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009508 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009509 for (int i=0; i<mPendingServices.size(); i++) {
9510 ServiceRecord r = mPendingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009511 if (!matcher.match(r, r.name)) {
9512 continue;
9513 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009514 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9515 continue;
9516 }
9517 if (!printed) {
9518 if (needSep) pw.println(" ");
9519 needSep = true;
9520 pw.println(" Pending services:");
9521 printed = true;
9522 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009523 pw.print(" * Pending "); pw.println(r);
9524 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009525 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009526 needSep = true;
9527 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009528
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009529 if (mRestartingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009530 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009531 for (int i=0; i<mRestartingServices.size(); i++) {
9532 ServiceRecord r = mRestartingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009533 if (!matcher.match(r, r.name)) {
9534 continue;
9535 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009536 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9537 continue;
9538 }
9539 if (!printed) {
9540 if (needSep) pw.println(" ");
9541 needSep = true;
9542 pw.println(" Restarting services:");
9543 printed = true;
9544 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009545 pw.print(" * Restarting "); pw.println(r);
9546 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009547 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009548 needSep = true;
9549 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009550
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009551 if (mStoppingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009552 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009553 for (int i=0; i<mStoppingServices.size(); i++) {
9554 ServiceRecord r = mStoppingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009555 if (!matcher.match(r, r.name)) {
9556 continue;
9557 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009558 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9559 continue;
9560 }
9561 if (!printed) {
9562 if (needSep) pw.println(" ");
9563 needSep = true;
9564 pw.println(" Stopping services:");
9565 printed = true;
9566 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009567 pw.print(" * Stopping "); pw.println(r);
9568 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009569 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009570 needSep = true;
9571 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009572
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009573 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009574 if (mServiceConnections.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009575 boolean printed = false;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009576 Iterator<ArrayList<ConnectionRecord>> it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009577 = mServiceConnections.values().iterator();
9578 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009579 ArrayList<ConnectionRecord> r = it.next();
9580 for (int i=0; i<r.size(); i++) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009581 ConnectionRecord cr = r.get(i);
9582 if (!matcher.match(cr.binding.service, cr.binding.service.name)) {
9583 continue;
9584 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009585 if (dumpPackage != null && (cr.binding.client == null
9586 || !dumpPackage.equals(cr.binding.client.info.packageName))) {
9587 continue;
9588 }
9589 if (!printed) {
9590 if (needSep) pw.println(" ");
9591 needSep = true;
9592 pw.println(" Connection bindings to services:");
9593 printed = true;
9594 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009595 pw.print(" * "); pw.println(cr);
9596 cr.dump(pw, " ");
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009597 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009598 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009599 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009600 }
9601 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009602
9603 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009604 }
9605
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009606 boolean dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009607 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07009608 boolean needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009609
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009610 ItemMatcher matcher = new ItemMatcher();
9611 matcher.build(args, opti);
9612
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009613 pw.println("ACTIVITY MANAGER CONTENT PROVIDERS (dumpsys activity providers)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009614
9615 mProviderMap.dumpProvidersLocked(pw, dumpAll);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009616
9617 if (mLaunchingProviders.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009618 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009619 for (int i=mLaunchingProviders.size()-1; i>=0; i--) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009620 ContentProviderRecord r = mLaunchingProviders.get(i);
9621 if (dumpPackage != null && !dumpPackage.equals(r.name.getPackageName())) {
9622 continue;
9623 }
9624 if (!printed) {
9625 if (needSep) pw.println(" ");
9626 needSep = true;
9627 pw.println(" Launching content providers:");
9628 printed = true;
9629 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009630 pw.print(" Launching #"); pw.print(i); pw.print(": ");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009631 pw.println(r);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009632 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009633 }
9634
9635 if (mGrantedUriPermissions.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009636 if (needSep) pw.println();
9637 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009638 pw.println("Granted Uri Permissions:");
9639 for (int i=0; i<mGrantedUriPermissions.size(); i++) {
9640 int uid = mGrantedUriPermissions.keyAt(i);
9641 HashMap<Uri, UriPermission> perms
9642 = mGrantedUriPermissions.valueAt(i);
9643 pw.print(" * UID "); pw.print(uid);
9644 pw.println(" holds:");
9645 for (UriPermission perm : perms.values()) {
9646 pw.print(" "); pw.println(perm);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009647 if (dumpAll) {
9648 perm.dump(pw, " ");
9649 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009650 }
9651 }
9652 needSep = true;
9653 }
9654
9655 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009656 }
9657
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009658 boolean dumpPendingIntentsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009659 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009660 boolean needSep = false;
9661
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009662 if (mIntentSenderRecords.size() > 0) {
9663 boolean printed = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009664 Iterator<WeakReference<PendingIntentRecord>> it
9665 = mIntentSenderRecords.values().iterator();
9666 while (it.hasNext()) {
9667 WeakReference<PendingIntentRecord> ref = it.next();
9668 PendingIntentRecord rec = ref != null ? ref.get(): null;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009669 if (dumpPackage != null && (rec == null
9670 || !dumpPackage.equals(rec.key.packageName))) {
9671 continue;
9672 }
9673 if (!printed) {
9674 pw.println("ACTIVITY MANAGER PENDING INTENTS (dumpsys activity intents)");
9675 printed = true;
9676 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009677 needSep = true;
9678 if (rec != null) {
9679 pw.print(" * "); pw.println(rec);
9680 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009681 rec.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009682 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009683 } else {
9684 pw.print(" * "); pw.println(ref);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009685 }
9686 }
9687 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009688
9689 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009690 }
9691
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009692 private static final void dumpHistoryList(FileDescriptor fd, PrintWriter pw, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009693 String prefix, String label, boolean complete, boolean brief, boolean client,
9694 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009695 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009696 boolean needNL = false;
9697 final String innerPrefix = prefix + " ";
9698 final String[] args = new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009699 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009700 final ActivityRecord r = (ActivityRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009701 if (dumpPackage != null && !dumpPackage.equals(r.packageName)) {
9702 continue;
9703 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07009704 final boolean full = !brief && (complete || !r.isInHistory());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009705 if (needNL) {
9706 pw.println(" ");
9707 needNL = false;
9708 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009709 if (lastTask != r.task) {
9710 lastTask = r.task;
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009711 pw.print(prefix);
9712 pw.print(full ? "* " : " ");
9713 pw.println(lastTask);
9714 if (full) {
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009715 lastTask.dump(pw, prefix + " ");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009716 } else if (complete) {
9717 // Complete + brief == give a summary. Isn't that obvious?!?
9718 if (lastTask.intent != null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009719 pw.print(prefix); pw.print(" ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009720 pw.println(lastTask.intent.toInsecureStringWithClip());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009721 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009722 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009723 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009724 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label);
9725 pw.print(" #"); pw.print(i); pw.print(": ");
9726 pw.println(r);
9727 if (full) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009728 r.dump(pw, innerPrefix);
9729 } else if (complete) {
9730 // Complete + brief == give a summary. Isn't that obvious?!?
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009731 pw.print(innerPrefix); pw.println(r.intent.toInsecureString());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009732 if (r.app != null) {
9733 pw.print(innerPrefix); pw.println(r.app);
9734 }
9735 }
9736 if (client && r.app != null && r.app.thread != null) {
9737 // flush anything that is already in the PrintWriter since the thread is going
9738 // to write to the file descriptor directly
9739 pw.flush();
9740 try {
9741 TransferPipe tp = new TransferPipe();
9742 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009743 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9744 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009745 // Short timeout, since blocking here can
9746 // deadlock with the application.
9747 tp.go(fd, 2000);
9748 } finally {
9749 tp.kill();
9750 }
9751 } catch (IOException e) {
9752 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
9753 } catch (RemoteException e) {
9754 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
9755 }
9756 needNL = true;
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009757 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009758 }
9759 }
9760
Dianne Hackborn09c916b2009-12-08 14:50:51 -08009761 private static String buildOomTag(String prefix, String space, int val, int base) {
9762 if (val == base) {
9763 if (space == null) return prefix;
9764 return prefix + " ";
9765 }
9766 return prefix + "+" + Integer.toString(val-base);
9767 }
9768
9769 private static final int dumpProcessList(PrintWriter pw,
9770 ActivityManagerService service, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009771 String prefix, String normalLabel, String persistentLabel,
9772 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009773 int numPers = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07009774 final int N = list.size()-1;
9775 for (int i=N; i>=0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009776 ProcessRecord r = (ProcessRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009777 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9778 continue;
9779 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009780 pw.println(String.format("%s%s #%2d: %s",
9781 prefix, (r.persistent ? persistentLabel : normalLabel),
9782 i, r.toString()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009783 if (r.persistent) {
9784 numPers++;
9785 }
9786 }
9787 return numPers;
9788 }
9789
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009790 private static final boolean dumpProcessOomList(PrintWriter pw,
Dianne Hackborn905577f2011-09-07 18:31:28 -07009791 ActivityManagerService service, List<ProcessRecord> origList,
Dianne Hackborn287952c2010-09-22 22:34:31 -07009792 String prefix, String normalLabel, String persistentLabel,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009793 boolean inclDetails, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009794
Dianne Hackborn905577f2011-09-07 18:31:28 -07009795 ArrayList<Pair<ProcessRecord, Integer>> list
9796 = new ArrayList<Pair<ProcessRecord, Integer>>(origList.size());
9797 for (int i=0; i<origList.size(); i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009798 ProcessRecord r = origList.get(i);
9799 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9800 continue;
9801 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07009802 list.add(new Pair<ProcessRecord, Integer>(origList.get(i), i));
9803 }
9804
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009805 if (list.size() <= 0) {
9806 return false;
9807 }
9808
Dianne Hackborn905577f2011-09-07 18:31:28 -07009809 Comparator<Pair<ProcessRecord, Integer>> comparator
9810 = new Comparator<Pair<ProcessRecord, Integer>>() {
9811 @Override
9812 public int compare(Pair<ProcessRecord, Integer> object1,
9813 Pair<ProcessRecord, Integer> object2) {
9814 if (object1.first.setAdj != object2.first.setAdj) {
9815 return object1.first.setAdj > object2.first.setAdj ? -1 : 1;
9816 }
9817 if (object1.second.intValue() != object2.second.intValue()) {
9818 return object1.second.intValue() > object2.second.intValue() ? -1 : 1;
9819 }
9820 return 0;
9821 }
9822 };
9823
9824 Collections.sort(list, comparator);
9825
Dianne Hackborn287952c2010-09-22 22:34:31 -07009826 final long curRealtime = SystemClock.elapsedRealtime();
9827 final long realtimeSince = curRealtime - service.mLastPowerCheckRealtime;
9828 final long curUptime = SystemClock.uptimeMillis();
9829 final long uptimeSince = curUptime - service.mLastPowerCheckUptime;
9830
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009831 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07009832 ProcessRecord r = list.get(i).first;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009833 String oomAdj;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009834 if (r.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07009835 oomAdj = buildOomTag("bak", " ", r.setAdj, ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009836 } else if (r.setAdj >= ProcessList.SERVICE_B_ADJ) {
9837 oomAdj = buildOomTag("svcb ", null, r.setAdj, ProcessList.SERVICE_B_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009838 } else if (r.setAdj >= ProcessList.PREVIOUS_APP_ADJ) {
9839 oomAdj = buildOomTag("prev ", null, r.setAdj, ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009840 } else if (r.setAdj >= ProcessList.HOME_APP_ADJ) {
9841 oomAdj = buildOomTag("home ", null, r.setAdj, ProcessList.HOME_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009842 } else if (r.setAdj >= ProcessList.SERVICE_ADJ) {
9843 oomAdj = buildOomTag("svc ", null, r.setAdj, ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009844 } else if (r.setAdj >= ProcessList.BACKUP_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08009845 oomAdj = buildOomTag("bkup ", null, r.setAdj, ProcessList.BACKUP_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009846 } else if (r.setAdj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
9847 oomAdj = buildOomTag("hvy ", null, r.setAdj, ProcessList.HEAVY_WEIGHT_APP_ADJ);
9848 } else if (r.setAdj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
9849 oomAdj = buildOomTag("prcp ", null, r.setAdj, ProcessList.PERCEPTIBLE_APP_ADJ);
9850 } else if (r.setAdj >= ProcessList.VISIBLE_APP_ADJ) {
9851 oomAdj = buildOomTag("vis ", null, r.setAdj, ProcessList.VISIBLE_APP_ADJ);
9852 } else if (r.setAdj >= ProcessList.FOREGROUND_APP_ADJ) {
9853 oomAdj = buildOomTag("fore ", null, r.setAdj, ProcessList.FOREGROUND_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009854 } else if (r.setAdj >= ProcessList.PERSISTENT_PROC_ADJ) {
9855 oomAdj = buildOomTag("pers ", null, r.setAdj, ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009856 } else if (r.setAdj >= ProcessList.SYSTEM_ADJ) {
9857 oomAdj = buildOomTag("sys ", null, r.setAdj, ProcessList.SYSTEM_ADJ);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009858 } else {
9859 oomAdj = Integer.toString(r.setAdj);
9860 }
9861 String schedGroup;
9862 switch (r.setSchedGroup) {
9863 case Process.THREAD_GROUP_BG_NONINTERACTIVE:
9864 schedGroup = "B";
9865 break;
9866 case Process.THREAD_GROUP_DEFAULT:
9867 schedGroup = "F";
9868 break;
9869 default:
9870 schedGroup = Integer.toString(r.setSchedGroup);
9871 break;
9872 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07009873 String foreground;
9874 if (r.foregroundActivities) {
9875 foreground = "A";
9876 } else if (r.foregroundServices) {
9877 foreground = "S";
9878 } else {
9879 foreground = " ";
9880 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07009881 pw.println(String.format("%s%s #%2d: adj=%s/%s%s trm=%2d %s (%s)",
Dianne Hackborn287952c2010-09-22 22:34:31 -07009882 prefix, (r.persistent ? persistentLabel : normalLabel),
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009883 (origList.size()-1)-list.get(i).second, oomAdj, schedGroup,
9884 foreground, r.trimMemoryLevel, r.toShortString(), r.adjType));
Dianne Hackborn287952c2010-09-22 22:34:31 -07009885 if (r.adjSource != null || r.adjTarget != null) {
9886 pw.print(prefix);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009887 pw.print(" ");
Dianne Hackborn287952c2010-09-22 22:34:31 -07009888 if (r.adjTarget instanceof ComponentName) {
9889 pw.print(((ComponentName)r.adjTarget).flattenToShortString());
9890 } else if (r.adjTarget != null) {
9891 pw.print(r.adjTarget.toString());
9892 } else {
9893 pw.print("{null}");
9894 }
9895 pw.print("<=");
9896 if (r.adjSource instanceof ProcessRecord) {
9897 pw.print("Proc{");
9898 pw.print(((ProcessRecord)r.adjSource).toShortString());
9899 pw.println("}");
9900 } else if (r.adjSource != null) {
9901 pw.println(r.adjSource.toString());
9902 } else {
9903 pw.println("{null}");
9904 }
9905 }
9906 if (inclDetails) {
9907 pw.print(prefix);
9908 pw.print(" ");
9909 pw.print("oom: max="); pw.print(r.maxAdj);
9910 pw.print(" hidden="); pw.print(r.hiddenAdj);
9911 pw.print(" curRaw="); pw.print(r.curRawAdj);
9912 pw.print(" setRaw="); pw.print(r.setRawAdj);
9913 pw.print(" cur="); pw.print(r.curAdj);
9914 pw.print(" set="); pw.println(r.setAdj);
9915 pw.print(prefix);
9916 pw.print(" ");
9917 pw.print("keeping="); pw.print(r.keeping);
9918 pw.print(" hidden="); pw.print(r.hidden);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009919 pw.print(" empty="); pw.print(r.empty);
9920 pw.print(" hasAboveClient="); pw.println(r.hasAboveClient);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009921
9922 if (!r.keeping) {
9923 if (r.lastWakeTime != 0) {
9924 long wtime;
9925 BatteryStatsImpl stats = service.mBatteryStatsService.getActiveStatistics();
9926 synchronized (stats) {
9927 wtime = stats.getProcessWakeTime(r.info.uid,
9928 r.pid, curRealtime);
9929 }
9930 long timeUsed = wtime - r.lastWakeTime;
9931 pw.print(prefix);
9932 pw.print(" ");
9933 pw.print("keep awake over ");
9934 TimeUtils.formatDuration(realtimeSince, pw);
9935 pw.print(" used ");
9936 TimeUtils.formatDuration(timeUsed, pw);
9937 pw.print(" (");
9938 pw.print((timeUsed*100)/realtimeSince);
9939 pw.println("%)");
9940 }
9941 if (r.lastCpuTime != 0) {
9942 long timeUsed = r.curCpuTime - r.lastCpuTime;
9943 pw.print(prefix);
9944 pw.print(" ");
9945 pw.print("run cpu over ");
9946 TimeUtils.formatDuration(uptimeSince, pw);
9947 pw.print(" used ");
9948 TimeUtils.formatDuration(timeUsed, pw);
9949 pw.print(" (");
9950 pw.print((timeUsed*100)/uptimeSince);
9951 pw.println("%)");
9952 }
9953 }
9954 }
9955 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009956 return true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009957 }
9958
Dianne Hackbornb437e092011-08-05 17:50:29 -07009959 ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, String[] args) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009960 ArrayList<ProcessRecord> procs;
9961 synchronized (this) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009962 if (args != null && args.length > start
9963 && args[start].charAt(0) != '-') {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009964 procs = new ArrayList<ProcessRecord>();
9965 int pid = -1;
9966 try {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009967 pid = Integer.parseInt(args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009968 } catch (NumberFormatException e) {
9969
9970 }
9971 for (int i=mLruProcesses.size()-1; i>=0; i--) {
9972 ProcessRecord proc = mLruProcesses.get(i);
9973 if (proc.pid == pid) {
9974 procs.add(proc);
Dianne Hackbornb437e092011-08-05 17:50:29 -07009975 } else if (proc.processName.equals(args[start])) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009976 procs.add(proc);
9977 }
9978 }
9979 if (procs.size() <= 0) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009980 pw.println("No process found for: " + args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009981 return null;
9982 }
9983 } else {
9984 procs = new ArrayList<ProcessRecord>(mLruProcesses);
9985 }
9986 }
9987 return procs;
9988 }
9989
9990 final void dumpGraphicsHardwareUsage(FileDescriptor fd,
9991 PrintWriter pw, String[] args) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009992 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009993 if (procs == null) {
9994 return;
9995 }
9996
9997 long uptime = SystemClock.uptimeMillis();
9998 long realtime = SystemClock.elapsedRealtime();
9999 pw.println("Applications Graphics Acceleration Info:");
10000 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10001
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010002 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10003 ProcessRecord r = procs.get(i);
Chet Haase9c1e23b2011-03-24 10:51:31 -070010004 if (r.thread != null) {
10005 pw.println("\n** Graphics info for pid " + r.pid + " [" + r.processName + "] **");
10006 pw.flush();
10007 try {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010008 TransferPipe tp = new TransferPipe();
10009 try {
10010 r.thread.dumpGfxInfo(tp.getWriteFd().getFileDescriptor(), args);
10011 tp.go(fd);
10012 } finally {
10013 tp.kill();
10014 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010015 } catch (IOException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010016 pw.println("Failure while dumping the app: " + r);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010017 pw.flush();
Chet Haase9c1e23b2011-03-24 10:51:31 -070010018 } catch (RemoteException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010019 pw.println("Got a RemoteException while dumping the app " + r);
Chet Haase9c1e23b2011-03-24 10:51:31 -070010020 pw.flush();
10021 }
10022 }
10023 }
Chet Haase9c1e23b2011-03-24 10:51:31 -070010024 }
10025
Jeff Brown6754ba22011-12-14 20:20:01 -080010026 final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) {
10027 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
10028 if (procs == null) {
10029 return;
10030 }
10031
10032 pw.println("Applications Database Info:");
10033
10034 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10035 ProcessRecord r = procs.get(i);
10036 if (r.thread != null) {
10037 pw.println("\n** Database info for pid " + r.pid + " [" + r.processName + "] **");
10038 pw.flush();
10039 try {
10040 TransferPipe tp = new TransferPipe();
10041 try {
10042 r.thread.dumpDbInfo(tp.getWriteFd().getFileDescriptor(), args);
10043 tp.go(fd);
10044 } finally {
10045 tp.kill();
10046 }
10047 } catch (IOException e) {
10048 pw.println("Failure while dumping the app: " + r);
10049 pw.flush();
10050 } catch (RemoteException e) {
10051 pw.println("Got a RemoteException while dumping the app " + r);
10052 pw.flush();
10053 }
10054 }
10055 }
10056 }
10057
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010058 final static class MemItem {
10059 final String label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010060 final String shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010061 final long pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010062 final int id;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010063 ArrayList<MemItem> subitems;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010064
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010065 public MemItem(String _label, String _shortLabel, long _pss, int _id) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010066 label = _label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010067 shortLabel = _shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010068 pss = _pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010069 id = _id;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010070 }
10071 }
10072
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010073 static final void dumpMemItems(PrintWriter pw, String prefix, ArrayList<MemItem> items,
Dianne Hackbornb437e092011-08-05 17:50:29 -070010074 boolean sort) {
10075 if (sort) {
10076 Collections.sort(items, new Comparator<MemItem>() {
10077 @Override
10078 public int compare(MemItem lhs, MemItem rhs) {
10079 if (lhs.pss < rhs.pss) {
10080 return 1;
10081 } else if (lhs.pss > rhs.pss) {
10082 return -1;
10083 }
10084 return 0;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010085 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010086 });
10087 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010088
10089 for (int i=0; i<items.size(); i++) {
10090 MemItem mi = items.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010091 pw.print(prefix); pw.printf("%7d kB: ", mi.pss); pw.println(mi.label);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010092 if (mi.subitems != null) {
10093 dumpMemItems(pw, prefix + " ", mi.subitems, true);
10094 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010095 }
10096 }
10097
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010098 // These are in KB.
10099 static final long[] DUMP_MEM_BUCKETS = new long[] {
10100 5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024,
10101 120*1024, 160*1024, 200*1024,
10102 250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024,
10103 1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024
10104 };
10105
Dianne Hackborn672342c2011-11-29 11:29:02 -080010106 static final void appendMemBucket(StringBuilder out, long memKB, String label,
10107 boolean stackLike) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010108 int start = label.lastIndexOf('.');
10109 if (start >= 0) start++;
10110 else start = 0;
10111 int end = label.length();
10112 for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) {
10113 if (DUMP_MEM_BUCKETS[i] >= memKB) {
10114 long bucket = DUMP_MEM_BUCKETS[i]/1024;
10115 out.append(bucket);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010116 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010117 out.append(label, start, end);
10118 return;
10119 }
10120 }
10121 out.append(memKB/1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010122 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010123 out.append(label, start, end);
10124 }
10125
10126 static final int[] DUMP_MEM_OOM_ADJ = new int[] {
10127 ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ, ProcessList.FOREGROUND_APP_ADJ,
10128 ProcessList.VISIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ,
10129 ProcessList.BACKUP_APP_ADJ, ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ,
10130 ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.HIDDEN_APP_MAX_ADJ
10131 };
10132 static final String[] DUMP_MEM_OOM_LABEL = new String[] {
10133 "System", "Persistent", "Foreground",
10134 "Visible", "Perceptible", "Heavy Weight",
10135 "Backup", "A Services", "Home", "Previous",
10136 "B Services", "Background"
10137 };
10138
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010139 final void dumpApplicationMemoryUsage(FileDescriptor fd,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010140 PrintWriter pw, String prefix, String[] args, boolean brief,
Dianne Hackborn672342c2011-11-29 11:29:02 -080010141 PrintWriter categoryPw, StringBuilder outTag, StringBuilder outStack) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010142 boolean dumpAll = false;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010143 boolean oomOnly = false;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010144
10145 int opti = 0;
10146 while (opti < args.length) {
10147 String opt = args[opti];
10148 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
10149 break;
10150 }
10151 opti++;
10152 if ("-a".equals(opt)) {
10153 dumpAll = true;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010154 } else if ("--oom".equals(opt)) {
10155 oomOnly = true;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010156 } else if ("-h".equals(opt)) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010157 pw.println("meminfo dump options: [-a] [--oom] [process]");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010158 pw.println(" -a: include all available information for each process.");
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010159 pw.println(" --oom: only show processes organized by oom adj.");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010160 pw.println("If [process] is specified it can be the name or ");
10161 pw.println("pid of a specific process to dump.");
10162 return;
10163 } else {
10164 pw.println("Unknown argument: " + opt + "; use -h for help");
10165 }
10166 }
10167
10168 ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010169 if (procs == null) {
10170 return;
10171 }
10172
Dianne Hackborn6447ca32009-04-07 19:50:08 -070010173 final boolean isCheckinRequest = scanArgs(args, "--checkin");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010174 long uptime = SystemClock.uptimeMillis();
10175 long realtime = SystemClock.elapsedRealtime();
Dianne Hackbornb437e092011-08-05 17:50:29 -070010176
10177 if (procs.size() == 1 || isCheckinRequest) {
10178 dumpAll = true;
10179 }
10180
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010181 if (isCheckinRequest) {
10182 // short checkin version
10183 pw.println(uptime + "," + realtime);
10184 pw.flush();
10185 } else {
10186 pw.println("Applications Memory Usage (kB):");
10187 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10188 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010189
Dianne Hackbornb437e092011-08-05 17:50:29 -070010190 String[] innerArgs = new String[args.length-opti];
10191 System.arraycopy(args, opti, innerArgs, 0, args.length-opti);
10192
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010193 ArrayList<MemItem> procMems = new ArrayList<MemItem>();
10194 long nativePss=0, dalvikPss=0, otherPss=0;
10195 long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
10196
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010197 long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length];
10198 ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[])
10199 new ArrayList[DUMP_MEM_OOM_LABEL.length];
Dianne Hackbornb437e092011-08-05 17:50:29 -070010200
10201 long totalPss = 0;
10202
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010203 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10204 ProcessRecord r = procs.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010205 if (r.thread != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010206 if (!isCheckinRequest && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010207 pw.println("\n** MEMINFO in pid " + r.pid + " [" + r.processName + "] **");
10208 pw.flush();
10209 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010210 Debug.MemoryInfo mi = null;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010211 if (dumpAll) {
10212 try {
10213 mi = r.thread.dumpMemInfo(fd, isCheckinRequest, dumpAll, innerArgs);
10214 } catch (RemoteException e) {
10215 if (!isCheckinRequest) {
10216 pw.println("Got RemoteException!");
10217 pw.flush();
10218 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010219 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010220 } else {
10221 mi = new Debug.MemoryInfo();
10222 Debug.getMemoryInfo(r.pid, mi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010223 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010224
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010225 if (!isCheckinRequest && mi != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010226 long myTotalPss = mi.getTotalPss();
10227 totalPss += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010228 MemItem pssItem = new MemItem(r.processName + " (pid " + r.pid + ")",
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010229 r.processName, myTotalPss, 0);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010230 procMems.add(pssItem);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010231
10232 nativePss += mi.nativePss;
10233 dalvikPss += mi.dalvikPss;
10234 otherPss += mi.otherPss;
10235 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
10236 long mem = mi.getOtherPss(j);
10237 miscPss[j] += mem;
10238 otherPss -= mem;
10239 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010240
10241 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010242 if (r.setAdj <= DUMP_MEM_OOM_ADJ[oomIndex]
10243 || oomIndex == (oomPss.length-1)) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010244 oomPss[oomIndex] += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010245 if (oomProcs[oomIndex] == null) {
10246 oomProcs[oomIndex] = new ArrayList<MemItem>();
10247 }
10248 oomProcs[oomIndex].add(pssItem);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010249 break;
10250 }
10251 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010252 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010253 }
10254 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010255
10256 if (!isCheckinRequest && procs.size() > 1) {
10257 ArrayList<MemItem> catMems = new ArrayList<MemItem>();
10258
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010259 catMems.add(new MemItem("Native", "Native", nativePss, -1));
10260 catMems.add(new MemItem("Dalvik", "Dalvik", dalvikPss, -2));
10261 catMems.add(new MemItem("Unknown", "Unknown", otherPss, -3));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010262 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010263 String label = Debug.MemoryInfo.getOtherLabel(j);
10264 catMems.add(new MemItem(label, label, miscPss[j], j));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010265 }
10266
Dianne Hackbornb437e092011-08-05 17:50:29 -070010267 ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
10268 for (int j=0; j<oomPss.length; j++) {
10269 if (oomPss[j] != 0) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010270 String label = DUMP_MEM_OOM_LABEL[j];
10271 MemItem item = new MemItem(label, label, oomPss[j],
10272 DUMP_MEM_OOM_ADJ[j]);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010273 item.subitems = oomProcs[j];
10274 oomMems.add(item);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010275 }
10276 }
10277
Dianne Hackborn672342c2011-11-29 11:29:02 -080010278 if (outTag != null || outStack != null) {
10279 if (outTag != null) {
10280 appendMemBucket(outTag, totalPss, "total", false);
10281 }
10282 if (outStack != null) {
10283 appendMemBucket(outStack, totalPss, "total", true);
10284 }
10285 boolean firstLine = true;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010286 for (int i=0; i<oomMems.size(); i++) {
10287 MemItem miCat = oomMems.get(i);
10288 if (miCat.subitems == null || miCat.subitems.size() < 1) {
10289 continue;
10290 }
10291 if (miCat.id < ProcessList.SERVICE_ADJ
10292 || miCat.id == ProcessList.HOME_APP_ADJ
10293 || miCat.id == ProcessList.PREVIOUS_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010294 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10295 outTag.append(" / ");
10296 }
10297 if (outStack != null) {
10298 if (miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10299 if (firstLine) {
10300 outStack.append(":");
10301 firstLine = false;
10302 }
10303 outStack.append("\n\t at ");
10304 } else {
10305 outStack.append("$");
10306 }
10307 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010308 for (int j=0; j<miCat.subitems.size(); j++) {
10309 MemItem mi = miCat.subitems.get(j);
10310 if (j > 0) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010311 if (outTag != null) {
10312 outTag.append(" ");
10313 }
10314 if (outStack != null) {
10315 outStack.append("$");
10316 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010317 }
Dianne Hackborn672342c2011-11-29 11:29:02 -080010318 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10319 appendMemBucket(outTag, mi.pss, mi.shortLabel, false);
10320 }
10321 if (outStack != null) {
10322 appendMemBucket(outStack, mi.pss, mi.shortLabel, true);
10323 }
10324 }
10325 if (outStack != null && miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10326 outStack.append("(");
10327 for (int k=0; k<DUMP_MEM_OOM_ADJ.length; k++) {
10328 if (DUMP_MEM_OOM_ADJ[k] == miCat.id) {
10329 outStack.append(DUMP_MEM_OOM_LABEL[k]);
10330 outStack.append(":");
10331 outStack.append(DUMP_MEM_OOM_ADJ[k]);
10332 }
10333 }
10334 outStack.append(")");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010335 }
10336 }
10337 }
10338 }
10339
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010340 if (!brief && !oomOnly) {
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010341 pw.println();
10342 pw.println("Total PSS by process:");
10343 dumpMemItems(pw, " ", procMems, true);
10344 pw.println();
10345 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010346 pw.println("Total PSS by OOM adjustment:");
10347 dumpMemItems(pw, " ", oomMems, false);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010348 if (!oomOnly) {
10349 PrintWriter out = categoryPw != null ? categoryPw : pw;
10350 out.println();
10351 out.println("Total PSS by category:");
10352 dumpMemItems(out, " ", catMems, true);
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010353 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010354 pw.println();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010355 pw.print("Total PSS: "); pw.print(totalPss); pw.println(" kB");
Dianne Hackbornd3e677b2012-04-05 14:58:18 -070010356 final int[] SINGLE_LONG_FORMAT = new int[] {
10357 Process.PROC_SPACE_TERM|Process.PROC_OUT_LONG
10358 };
10359 long[] longOut = new long[1];
10360 Process.readProcFile("/sys/kernel/mm/ksm/pages_shared",
10361 SINGLE_LONG_FORMAT, null, longOut, null);
10362 long shared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10363 longOut[0] = 0;
10364 Process.readProcFile("/sys/kernel/mm/ksm/pages_sharing",
10365 SINGLE_LONG_FORMAT, null, longOut, null);
10366 long sharing = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10367 longOut[0] = 0;
10368 Process.readProcFile("/sys/kernel/mm/ksm/pages_unshared",
10369 SINGLE_LONG_FORMAT, null, longOut, null);
10370 long unshared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10371 longOut[0] = 0;
10372 Process.readProcFile("/sys/kernel/mm/ksm/pages_volatile",
10373 SINGLE_LONG_FORMAT, null, longOut, null);
10374 long voltile = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10375 pw.print(" KSM: "); pw.print(sharing); pw.print(" kB saved from shared ");
10376 pw.print(shared); pw.println(" kB");
10377 pw.print(" "); pw.print(unshared); pw.print(" kB unshared; ");
10378 pw.print(voltile); pw.println(" kB volatile");
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010379 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010380 }
10381
10382 /**
10383 * Searches array of arguments for the specified string
10384 * @param args array of argument strings
10385 * @param value value to search for
10386 * @return true if the value is contained in the array
10387 */
10388 private static boolean scanArgs(String[] args, String value) {
10389 if (args != null) {
10390 for (String arg : args) {
10391 if (value.equals(arg)) {
10392 return true;
10393 }
10394 }
10395 }
10396 return false;
10397 }
10398
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010399 private final void killServicesLocked(ProcessRecord app,
10400 boolean allowRestart) {
10401 // Report disconnected services.
10402 if (false) {
10403 // XXX we are letting the client link to the service for
10404 // death notifications.
10405 if (app.services.size() > 0) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010406 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010407 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010408 ServiceRecord r = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010409 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010410 Iterator<ArrayList<ConnectionRecord>> jt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010411 = r.connections.values().iterator();
10412 while (jt.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010413 ArrayList<ConnectionRecord> cl = jt.next();
10414 for (int i=0; i<cl.size(); i++) {
10415 ConnectionRecord c = cl.get(i);
10416 if (c.binding.client != app) {
10417 try {
10418 //c.conn.connected(r.className, null);
10419 } catch (Exception e) {
10420 // todo: this should be asynchronous!
10421 Slog.w(TAG, "Exception thrown disconnected servce "
10422 + r.shortName
10423 + " from app " + app.processName, e);
10424 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010425 }
10426 }
10427 }
10428 }
10429 }
10430 }
10431 }
10432
10433 // Clean up any connections this application has to other services.
10434 if (app.connections.size() > 0) {
10435 Iterator<ConnectionRecord> it = app.connections.iterator();
10436 while (it.hasNext()) {
10437 ConnectionRecord r = it.next();
10438 removeConnectionLocked(r, app, null);
10439 }
10440 }
10441 app.connections.clear();
10442
10443 if (app.services.size() != 0) {
10444 // Any services running in the application need to be placed
10445 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -070010446 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010447 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010448 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010449 synchronized (sr.stats.getBatteryStats()) {
10450 sr.stats.stopLaunchedLocked();
10451 }
10452 sr.app = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010453 sr.isolatedProc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010454 sr.executeNesting = 0;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010455 if (mStoppingServices.remove(sr)) {
10456 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
10457 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010458
10459 boolean hasClients = sr.bindings.size() > 0;
10460 if (hasClients) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010461 Iterator<IntentBindRecord> bindings
10462 = sr.bindings.values().iterator();
10463 while (bindings.hasNext()) {
10464 IntentBindRecord b = bindings.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -080010465 if (DEBUG_SERVICE) Slog.v(TAG, "Killing binding " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010466 + ": shouldUnbind=" + b.hasBound);
10467 b.binder = null;
10468 b.requested = b.received = b.hasBound = false;
10469 }
10470 }
10471
Dianne Hackborn070783f2010-12-29 16:46:28 -080010472 if (sr.crashCount >= 2 && (sr.serviceInfo.applicationInfo.flags
10473 &ApplicationInfo.FLAG_PERSISTENT) == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010474 Slog.w(TAG, "Service crashed " + sr.crashCount
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010475 + " times, stopping: " + sr);
Doug Zongker2bec3d42009-12-04 12:52:44 -080010476 EventLog.writeEvent(EventLogTags.AM_SERVICE_CRASHED_TOO_MUCH,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010477 sr.crashCount, sr.shortName, app.pid);
10478 bringDownServiceLocked(sr, true);
10479 } else if (!allowRestart) {
10480 bringDownServiceLocked(sr, true);
10481 } else {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010482 boolean canceled = scheduleServiceRestartLocked(sr, true);
10483
10484 // Should the service remain running? Note that in the
10485 // extreme case of so many attempts to deliver a command
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010486 // that it failed we also will stop it here.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010487 if (sr.startRequested && (sr.stopIfKilled || canceled)) {
10488 if (sr.pendingStarts.size() == 0) {
10489 sr.startRequested = false;
10490 if (!hasClients) {
10491 // Whoops, no reason to restart!
10492 bringDownServiceLocked(sr, true);
10493 }
10494 }
10495 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010496 }
10497 }
10498
10499 if (!allowRestart) {
10500 app.services.clear();
10501 }
10502 }
10503
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010504 // Make sure we have no more records on the stopping list.
10505 int i = mStoppingServices.size();
10506 while (i > 0) {
10507 i--;
10508 ServiceRecord sr = mStoppingServices.get(i);
10509 if (sr.app == app) {
10510 mStoppingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010511 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010512 }
10513 }
10514
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010515 app.executingServices.clear();
10516 }
10517
10518 private final void removeDyingProviderLocked(ProcessRecord proc,
10519 ContentProviderRecord cpr) {
10520 synchronized (cpr) {
10521 cpr.launchingApp = null;
10522 cpr.notifyAll();
10523 }
10524
Amith Yamasani742a6712011-05-04 14:49:28 -070010525 mProviderMap.removeProviderByClass(cpr.name, UserId.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010526 String names[] = cpr.info.authority.split(";");
10527 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010528 mProviderMap.removeProviderByName(names[j], UserId.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010529 }
10530
10531 Iterator<ProcessRecord> cit = cpr.clients.iterator();
10532 while (cit.hasNext()) {
10533 ProcessRecord capp = cit.next();
10534 if (!capp.persistent && capp.thread != null
10535 && capp.pid != 0
10536 && capp.pid != MY_PID) {
Dianne Hackborn8633e682010-04-22 16:03:41 -070010537 Slog.i(TAG, "Kill " + capp.processName
10538 + " (pid " + capp.pid + "): provider " + cpr.info.name
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010539 + " in dying process " + (proc != null ? proc.processName : "??"));
Dianne Hackborn8633e682010-04-22 16:03:41 -070010540 EventLog.writeEvent(EventLogTags.AM_KILL, capp.pid,
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010541 capp.processName, capp.setAdj, "dying provider "
10542 + cpr.name.toShortString());
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070010543 Process.killProcessQuiet(capp.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010544 }
10545 }
10546
10547 mLaunchingProviders.remove(cpr);
10548 }
10549
10550 /**
10551 * Main code for cleaning up a process when it has gone away. This is
10552 * called both as a result of the process dying, or directly when stopping
10553 * a process when running in single process mode.
10554 */
10555 private final void cleanUpApplicationRecordLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010556 boolean restarting, boolean allowRestart, int index) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010557 if (index >= 0) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010558 mLruProcesses.remove(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010559 }
10560
Dianne Hackborn36124872009-10-08 16:22:03 -070010561 mProcessesToGc.remove(app);
10562
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010563 // Dismiss any open dialogs.
10564 if (app.crashDialog != null) {
10565 app.crashDialog.dismiss();
10566 app.crashDialog = null;
10567 }
10568 if (app.anrDialog != null) {
10569 app.anrDialog.dismiss();
10570 app.anrDialog = null;
10571 }
10572 if (app.waitDialog != null) {
10573 app.waitDialog.dismiss();
10574 app.waitDialog = null;
10575 }
10576
10577 app.crashing = false;
10578 app.notResponding = false;
10579
10580 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -070010581 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010582 app.thread = null;
10583 app.forcingToForeground = null;
10584 app.foregroundServices = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010585 app.foregroundActivities = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070010586 app.hasShownUi = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010587 app.hasAboveClient = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010588
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010589 killServicesLocked(app, allowRestart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010590
10591 boolean restart = false;
10592
10593 int NL = mLaunchingProviders.size();
10594
10595 // Remove published content providers.
10596 if (!app.pubProviders.isEmpty()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010597 Iterator<ContentProviderRecord> it = app.pubProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010598 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010599 ContentProviderRecord cpr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010600 cpr.provider = null;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010601 cpr.proc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010602
10603 // See if someone is waiting for this provider... in which
10604 // case we don't remove it, but just let it restart.
10605 int i = 0;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010606 if (!app.bad && allowRestart) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010607 for (; i<NL; i++) {
10608 if (mLaunchingProviders.get(i) == cpr) {
10609 restart = true;
10610 break;
10611 }
10612 }
10613 } else {
10614 i = NL;
10615 }
10616
10617 if (i >= NL) {
10618 removeDyingProviderLocked(app, cpr);
10619 NL = mLaunchingProviders.size();
10620 }
10621 }
10622 app.pubProviders.clear();
10623 }
10624
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010625 // Take care of any launching providers waiting for this process.
10626 if (checkAppInLaunchingProvidersLocked(app, false)) {
10627 restart = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010628 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010629
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010630 // Unregister from connected content providers.
10631 if (!app.conProviders.isEmpty()) {
Dianne Hackborn0c3154d2009-10-06 17:18:05 -070010632 Iterator it = app.conProviders.keySet().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010633 while (it.hasNext()) {
10634 ContentProviderRecord cpr = (ContentProviderRecord)it.next();
10635 cpr.clients.remove(app);
10636 }
10637 app.conProviders.clear();
10638 }
10639
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010640 // At this point there may be remaining entries in mLaunchingProviders
10641 // where we were the only one waiting, so they are no longer of use.
10642 // Look for these and clean up if found.
10643 // XXX Commented out for now. Trying to figure out a way to reproduce
10644 // the actual situation to identify what is actually going on.
10645 if (false) {
10646 for (int i=0; i<NL; i++) {
10647 ContentProviderRecord cpr = (ContentProviderRecord)
10648 mLaunchingProviders.get(i);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080010649 if (cpr.clients.size() <= 0 && !cpr.hasExternalProcessHandles()) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010650 synchronized (cpr) {
10651 cpr.launchingApp = null;
10652 cpr.notifyAll();
10653 }
10654 }
10655 }
10656 }
10657
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010658 skipCurrentReceiverLocked(app);
10659
10660 // Unregister any receivers.
10661 if (app.receivers.size() > 0) {
10662 Iterator<ReceiverList> it = app.receivers.iterator();
10663 while (it.hasNext()) {
10664 removeReceiverLocked(it.next());
10665 }
10666 app.receivers.clear();
10667 }
10668
Christopher Tate181fafa2009-05-14 11:12:14 -070010669 // If the app is undergoing backup, tell the backup manager about it
10670 if (mBackupTarget != null && app.pid == mBackupTarget.app.pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010671 if (DEBUG_BACKUP) Slog.d(TAG, "App " + mBackupTarget.appInfo + " died during backup");
Christopher Tate181fafa2009-05-14 11:12:14 -070010672 try {
10673 IBackupManager bm = IBackupManager.Stub.asInterface(
10674 ServiceManager.getService(Context.BACKUP_SERVICE));
10675 bm.agentDisconnected(app.info.packageName);
10676 } catch (RemoteException e) {
10677 // can't happen; backup manager is local
10678 }
10679 }
10680
Jeff Sharkey287bd832011-05-28 19:36:26 -070010681 mHandler.obtainMessage(DISPATCH_PROCESS_DIED, app.pid, app.info.uid, null).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010682
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010683 // If the caller is restarting this app, then leave it in its
10684 // current lists and let the caller take care of it.
10685 if (restarting) {
10686 return;
10687 }
10688
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010689 if (!app.persistent || app.isolated) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010690 if (DEBUG_PROCESSES) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010691 "Removing non-persistent process during cleanup: " + app);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010692 mProcessNames.remove(app.processName, app.uid);
10693 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -070010694 if (mHeavyWeightProcess == app) {
10695 mHeavyWeightProcess = null;
10696 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
10697 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010698 } else if (!app.removed) {
10699 // This app is persistent, so we need to keep its record around.
10700 // If it is not already on the pending app list, add it there
10701 // and start a new process for it.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010702 if (mPersistentStartingProcesses.indexOf(app) < 0) {
10703 mPersistentStartingProcesses.add(app);
10704 restart = true;
10705 }
10706 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070010707 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
10708 "Clean-up removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010709 mProcessesOnHold.remove(app);
10710
The Android Open Source Project4df24232009-03-05 14:34:35 -080010711 if (app == mHomeProcess) {
10712 mHomeProcess = null;
10713 }
Dianne Hackbornf35fe232011-11-01 19:25:20 -070010714 if (app == mPreviousProcess) {
10715 mPreviousProcess = null;
10716 }
10717
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010718 if (restart && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010719 // We have components that still need to be running in the
10720 // process, so re-launch it.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010721 mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010722 startProcessLocked(app, "restart", app.processName);
10723 } else if (app.pid > 0 && app.pid != MY_PID) {
10724 // Goodbye!
10725 synchronized (mPidsSelfLocked) {
10726 mPidsSelfLocked.remove(app.pid);
10727 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
10728 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010729 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010730 }
10731 }
10732
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010733 boolean checkAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) {
10734 // Look through the content providers we are waiting to have launched,
10735 // and if any run in this process then either schedule a restart of
10736 // the process or kill the client waiting for it if this process has
10737 // gone bad.
10738 int NL = mLaunchingProviders.size();
10739 boolean restart = false;
10740 for (int i=0; i<NL; i++) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010741 ContentProviderRecord cpr = mLaunchingProviders.get(i);
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010742 if (cpr.launchingApp == app) {
10743 if (!alwaysBad && !app.bad) {
10744 restart = true;
10745 } else {
10746 removeDyingProviderLocked(app, cpr);
10747 NL = mLaunchingProviders.size();
10748 }
10749 }
10750 }
10751 return restart;
10752 }
10753
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010754 // =========================================================
10755 // SERVICES
10756 // =========================================================
10757
10758 ActivityManager.RunningServiceInfo makeRunningServiceInfoLocked(ServiceRecord r) {
10759 ActivityManager.RunningServiceInfo info =
10760 new ActivityManager.RunningServiceInfo();
10761 info.service = r.name;
10762 if (r.app != null) {
10763 info.pid = r.app.pid;
10764 }
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010765 info.uid = r.appInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010766 info.process = r.processName;
10767 info.foreground = r.isForeground;
10768 info.activeSince = r.createTime;
10769 info.started = r.startRequested;
10770 info.clientCount = r.connections.size();
10771 info.crashCount = r.crashCount;
10772 info.lastActivityTime = r.lastActivity;
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010773 if (r.isForeground) {
10774 info.flags |= ActivityManager.RunningServiceInfo.FLAG_FOREGROUND;
10775 }
10776 if (r.startRequested) {
10777 info.flags |= ActivityManager.RunningServiceInfo.FLAG_STARTED;
10778 }
Dan Egnor42471dd2010-01-07 17:25:22 -080010779 if (r.app != null && r.app.pid == MY_PID) {
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010780 info.flags |= ActivityManager.RunningServiceInfo.FLAG_SYSTEM_PROCESS;
10781 }
10782 if (r.app != null && r.app.persistent) {
10783 info.flags |= ActivityManager.RunningServiceInfo.FLAG_PERSISTENT_PROCESS;
10784 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010785
10786 for (ArrayList<ConnectionRecord> connl : r.connections.values()) {
10787 for (int i=0; i<connl.size(); i++) {
10788 ConnectionRecord conn = connl.get(i);
10789 if (conn.clientLabel != 0) {
10790 info.clientPackage = conn.binding.client.info.packageName;
10791 info.clientLabel = conn.clientLabel;
10792 return info;
10793 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010794 }
10795 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010796 return info;
10797 }
10798
10799 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum,
10800 int flags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010801 enforceNotIsolatedCaller("getServices");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010802 synchronized (this) {
10803 ArrayList<ActivityManager.RunningServiceInfo> res
10804 = new ArrayList<ActivityManager.RunningServiceInfo>();
10805
Amith Yamasani742a6712011-05-04 14:49:28 -070010806 int userId = UserId.getUserId(Binder.getCallingUid());
10807 if (mServiceMap.getAllServices(userId).size() > 0) {
10808 Iterator<ServiceRecord> it
10809 = mServiceMap.getAllServices(userId).iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010810 while (it.hasNext() && res.size() < maxNum) {
10811 res.add(makeRunningServiceInfoLocked(it.next()));
10812 }
10813 }
10814
10815 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
10816 ServiceRecord r = mRestartingServices.get(i);
10817 ActivityManager.RunningServiceInfo info =
10818 makeRunningServiceInfoLocked(r);
10819 info.restarting = r.nextRestartTime;
10820 res.add(info);
10821 }
10822
10823 return res;
10824 }
10825 }
10826
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010827 public PendingIntent getRunningServiceControlPanel(ComponentName name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010828 enforceNotIsolatedCaller("getRunningServiceControlPanel");
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010829 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010830 int userId = UserId.getUserId(Binder.getCallingUid());
10831 ServiceRecord r = mServiceMap.getServiceByName(name, userId);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010832 if (r != null) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010833 for (ArrayList<ConnectionRecord> conn : r.connections.values()) {
10834 for (int i=0; i<conn.size(); i++) {
10835 if (conn.get(i).clientIntent != null) {
10836 return conn.get(i).clientIntent;
10837 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010838 }
10839 }
10840 }
10841 }
10842 return null;
10843 }
10844
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010845 private final ServiceRecord findServiceLocked(ComponentName name,
10846 IBinder token) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010847 ServiceRecord r = mServiceMap.getServiceByName(name, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010848 return r == token ? r : null;
10849 }
10850
10851 private final class ServiceLookupResult {
10852 final ServiceRecord record;
10853 final String permission;
10854
10855 ServiceLookupResult(ServiceRecord _record, String _permission) {
10856 record = _record;
10857 permission = _permission;
10858 }
10859 };
10860
10861 private ServiceLookupResult findServiceLocked(Intent service,
Amith Yamasani483f3b02012-03-13 16:08:00 -070010862 String resolvedType, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010863 ServiceRecord r = null;
10864 if (service.getComponent() != null) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070010865 r = mServiceMap.getServiceByName(service.getComponent(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010866 }
10867 if (r == null) {
10868 Intent.FilterComparison filter = new Intent.FilterComparison(service);
Amith Yamasani483f3b02012-03-13 16:08:00 -070010869 r = mServiceMap.getServiceByIntent(filter, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010870 }
10871
10872 if (r == null) {
10873 try {
10874 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070010875 AppGlobals.getPackageManager().resolveService(
Amith Yamasani483f3b02012-03-13 16:08:00 -070010876 service, resolvedType, 0, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010877 ServiceInfo sInfo =
10878 rInfo != null ? rInfo.serviceInfo : null;
10879 if (sInfo == null) {
10880 return null;
10881 }
10882
10883 ComponentName name = new ComponentName(
10884 sInfo.applicationInfo.packageName, sInfo.name);
Amith Yamasani742a6712011-05-04 14:49:28 -070010885 r = mServiceMap.getServiceByName(name, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010886 } catch (RemoteException ex) {
10887 // pm is in same process, this will never happen.
10888 }
10889 }
10890 if (r != null) {
10891 int callingPid = Binder.getCallingPid();
10892 int callingUid = Binder.getCallingUid();
10893 if (checkComponentPermission(r.permission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010894 callingPid, callingUid, r.appInfo.uid, r.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010895 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010896 if (!r.exported) {
10897 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
10898 + " from pid=" + callingPid
10899 + ", uid=" + callingUid
10900 + " that is not exported from uid " + r.appInfo.uid);
10901 return new ServiceLookupResult(null, "not exported from uid "
10902 + r.appInfo.uid);
10903 }
Joe Onorato8a9b2202010-02-26 18:56:32 -080010904 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010905 + " from pid=" + callingPid
10906 + ", uid=" + callingUid
10907 + " requires " + r.permission);
10908 return new ServiceLookupResult(null, r.permission);
10909 }
10910 return new ServiceLookupResult(r, null);
10911 }
10912 return null;
10913 }
10914
10915 private class ServiceRestarter implements Runnable {
10916 private ServiceRecord mService;
10917
10918 void setService(ServiceRecord service) {
10919 mService = service;
10920 }
10921
10922 public void run() {
10923 synchronized(ActivityManagerService.this) {
10924 performServiceRestartLocked(mService);
10925 }
10926 }
10927 }
10928
10929 private ServiceLookupResult retrieveServiceLocked(Intent service,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010930 String resolvedType, int callingPid, int callingUid, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010931 ServiceRecord r = null;
Amith Yamasani742a6712011-05-04 14:49:28 -070010932 if (DEBUG_SERVICE)
10933 Slog.v(TAG, "retrieveServiceLocked: " + service + " type=" + resolvedType
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010934 + " callingUid=" + callingUid);
Amith Yamasani742a6712011-05-04 14:49:28 -070010935
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010936 if (service.getComponent() != null) {
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010937 r = mServiceMap.getServiceByName(service.getComponent(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010938 }
Amith Yamasani742a6712011-05-04 14:49:28 -070010939 if (r == null) {
10940 Intent.FilterComparison filter = new Intent.FilterComparison(service);
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010941 r = mServiceMap.getServiceByIntent(filter, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -070010942 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010943 if (r == null) {
10944 try {
10945 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070010946 AppGlobals.getPackageManager().resolveService(
Amith Yamasani483f3b02012-03-13 16:08:00 -070010947 service, resolvedType, STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010948 ServiceInfo sInfo =
10949 rInfo != null ? rInfo.serviceInfo : null;
10950 if (sInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010951 Slog.w(TAG, "Unable to start service " + service +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010952 ": not found");
10953 return null;
10954 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010955 if (userId > 0) {
Amith Yamasania4a54e22012-04-16 15:44:19 -070010956 if (isSingleton(sInfo.processName, sInfo.applicationInfo)) {
10957 userId = 0;
10958 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010959 sInfo.applicationInfo = getAppInfoForUser(sInfo.applicationInfo, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -070010960 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010961 ComponentName name = new ComponentName(
10962 sInfo.applicationInfo.packageName, sInfo.name);
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010963 r = mServiceMap.getServiceByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010964 if (r == null) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010965 Intent.FilterComparison filter = new Intent.FilterComparison(
10966 service.cloneFilter());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010967 ServiceRestarter res = new ServiceRestarter();
10968 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
10969 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
10970 synchronized (stats) {
10971 ss = stats.getServiceStatsLocked(
10972 sInfo.applicationInfo.uid, sInfo.packageName,
10973 sInfo.name);
10974 }
Dianne Hackbornb1c4a2a2010-01-19 15:36:42 -080010975 r = new ServiceRecord(this, ss, name, filter, sInfo, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010976 res.setService(r);
Amith Yamasani742a6712011-05-04 14:49:28 -070010977 mServiceMap.putServiceByName(name, UserId.getUserId(r.appInfo.uid), r);
10978 mServiceMap.putServiceByIntent(filter, UserId.getUserId(r.appInfo.uid), r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010979
10980 // Make sure this component isn't in the pending list.
10981 int N = mPendingServices.size();
10982 for (int i=0; i<N; i++) {
10983 ServiceRecord pr = mPendingServices.get(i);
10984 if (pr.name.equals(name)) {
10985 mPendingServices.remove(i);
10986 i--;
10987 N--;
10988 }
10989 }
10990 }
10991 } catch (RemoteException ex) {
10992 // pm is in same process, this will never happen.
10993 }
10994 }
10995 if (r != null) {
10996 if (checkComponentPermission(r.permission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010997 callingPid, callingUid, r.appInfo.uid, r.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010998 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010999 if (!r.exported) {
11000 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
11001 + " from pid=" + callingPid
11002 + ", uid=" + callingUid
11003 + " that is not exported from uid " + r.appInfo.uid);
11004 return new ServiceLookupResult(null, "not exported from uid "
11005 + r.appInfo.uid);
11006 }
Joe Onorato8a9b2202010-02-26 18:56:32 -080011007 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011008 + " from pid=" + callingPid
11009 + ", uid=" + callingUid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011010 + " requires " + r.permission);
11011 return new ServiceLookupResult(null, r.permission);
11012 }
11013 return new ServiceLookupResult(r, null);
11014 }
11015 return null;
11016 }
11017
Dianne Hackborn287952c2010-09-22 22:34:31 -070011018 private final void bumpServiceExecutingLocked(ServiceRecord r, String why) {
11019 if (DEBUG_SERVICE) Log.v(TAG, ">>> EXECUTING "
11020 + why + " of " + r + " in app " + r.app);
11021 else if (DEBUG_SERVICE_EXECUTING) Log.v(TAG, ">>> EXECUTING "
11022 + why + " of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011023 long now = SystemClock.uptimeMillis();
11024 if (r.executeNesting == 0 && r.app != null) {
11025 if (r.app.executingServices.size() == 0) {
11026 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
11027 msg.obj = r.app;
11028 mHandler.sendMessageAtTime(msg, now+SERVICE_TIMEOUT);
11029 }
11030 r.app.executingServices.add(r);
11031 }
11032 r.executeNesting++;
11033 r.executingStart = now;
11034 }
11035
11036 private final void sendServiceArgsLocked(ServiceRecord r,
11037 boolean oomAdjusted) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011038 final int N = r.pendingStarts.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011039 if (N == 0) {
11040 return;
11041 }
11042
Dianne Hackborn39792d22010-08-19 18:01:52 -070011043 while (r.pendingStarts.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011044 try {
Dianne Hackborn39792d22010-08-19 18:01:52 -070011045 ServiceRecord.StartItem si = r.pendingStarts.remove(0);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011046 if (DEBUG_SERVICE) Slog.v(TAG, "Sending arguments to: "
11047 + r + " " + r.intent + " args=" + si.intent);
Dianne Hackborn3a28f222011-03-01 12:25:54 -080011048 if (si.intent == null && N > 1) {
11049 // If somehow we got a dummy null intent in the middle,
11050 // then skip it. DO NOT skip a null intent when it is
11051 // the only one in the list -- this is to support the
11052 // onStartCommand(null) case.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011053 continue;
11054 }
Dianne Hackborn39792d22010-08-19 18:01:52 -070011055 si.deliveredTime = SystemClock.uptimeMillis();
11056 r.deliveredStarts.add(si);
11057 si.deliveryCount++;
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011058 if (si.neededGrants != null) {
11059 grantUriPermissionUncheckedFromIntentLocked(si.neededGrants,
11060 si.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -070011061 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070011062 bumpServiceExecutingLocked(r, "start");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011063 if (!oomAdjusted) {
11064 oomAdjusted = true;
11065 updateOomAdjLocked(r.app);
11066 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011067 int flags = 0;
Dianne Hackbornd8f10242012-05-08 17:14:58 -070011068 if (si.deliveryCount > 1) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011069 flags |= Service.START_FLAG_RETRY;
11070 }
11071 if (si.doneExecutingCount > 0) {
11072 flags |= Service.START_FLAG_REDELIVERY;
11073 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011074 r.app.thread.scheduleServiceArgs(r, si.taskRemoved, si.id, flags, si.intent);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011075 } catch (RemoteException e) {
11076 // Remote process gone... we'll let the normal cleanup take
11077 // care of this.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011078 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while scheduling start: " + r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011079 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011080 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011081 Slog.w(TAG, "Unexpected exception", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011082 break;
11083 }
11084 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011085 }
11086
11087 private final boolean requestServiceBindingLocked(ServiceRecord r,
11088 IntentBindRecord i, boolean rebind) {
11089 if (r.app == null || r.app.thread == null) {
11090 // If service is not currently running, can't yet bind.
11091 return false;
11092 }
11093 if ((!i.requested || rebind) && i.apps.size() > 0) {
11094 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011095 bumpServiceExecutingLocked(r, "bind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011096 r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind);
11097 if (!rebind) {
11098 i.requested = true;
11099 }
11100 i.hasBound = true;
11101 i.doRebind = false;
11102 } catch (RemoteException e) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011103 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while binding " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011104 return false;
11105 }
11106 }
11107 return true;
11108 }
11109
11110 private final void requestServiceBindingsLocked(ServiceRecord r) {
11111 Iterator<IntentBindRecord> bindings = r.bindings.values().iterator();
11112 while (bindings.hasNext()) {
11113 IntentBindRecord i = bindings.next();
11114 if (!requestServiceBindingLocked(r, i, false)) {
11115 break;
11116 }
11117 }
11118 }
11119
11120 private final void realStartServiceLocked(ServiceRecord r,
11121 ProcessRecord app) throws RemoteException {
11122 if (app.thread == null) {
11123 throw new RemoteException();
11124 }
Amith Yamasani742a6712011-05-04 14:49:28 -070011125 if (DEBUG_MU)
11126 Slog.v(TAG_MU, "realStartServiceLocked, ServiceRecord.uid = " + r.appInfo.uid
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011127 + ", ProcessRecord.uid = " + app.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011128 r.app = app;
The Android Open Source Project10592532009-03-18 17:39:46 -070011129 r.restartTime = r.lastActivity = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011130
11131 app.services.add(r);
Dianne Hackborn287952c2010-09-22 22:34:31 -070011132 bumpServiceExecutingLocked(r, "create");
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011133 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011134
11135 boolean created = false;
11136 try {
Dianne Hackborna33e3f72009-09-29 17:28:24 -070011137 mStringBuilder.setLength(0);
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011138 r.intent.getIntent().toShortString(mStringBuilder, true, false, true, false);
Doug Zongker2bec3d42009-12-04 12:52:44 -080011139 EventLog.writeEvent(EventLogTags.AM_CREATE_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011140 System.identityHashCode(r), r.shortName,
Dianne Hackborna33e3f72009-09-29 17:28:24 -070011141 mStringBuilder.toString(), r.app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011142 synchronized (r.stats.getBatteryStats()) {
11143 r.stats.startLaunchedLocked();
11144 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -070011145 ensurePackageDexOpt(r.serviceInfo.packageName);
Dianne Hackborne2515ee2011-04-27 18:52:56 -040011146 app.thread.scheduleCreateService(r, r.serviceInfo,
11147 compatibilityInfoForPackageLocked(r.serviceInfo.applicationInfo));
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011148 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011149 created = true;
11150 } finally {
11151 if (!created) {
11152 app.services.remove(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011153 scheduleServiceRestartLocked(r, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011154 }
11155 }
11156
11157 requestServiceBindingsLocked(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011158
11159 // If the service is in the started state, and there are no
11160 // pending arguments, then fake up one so its onStartCommand() will
11161 // be called.
11162 if (r.startRequested && r.callStart && r.pendingStarts.size() == 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011163 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011164 null, null));
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011165 }
11166
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011167 sendServiceArgsLocked(r, true);
11168 }
11169
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011170 private final boolean scheduleServiceRestartLocked(ServiceRecord r,
11171 boolean allowCancel) {
11172 boolean canceled = false;
11173
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011174 final long now = SystemClock.uptimeMillis();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011175 long minDuration = SERVICE_RESTART_DURATION;
Dianne Hackborn6ccd2af2009-08-27 12:26:44 -070011176 long resetTime = SERVICE_RESET_RUN_DURATION;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011177
Dianne Hackborn070783f2010-12-29 16:46:28 -080011178 if ((r.serviceInfo.applicationInfo.flags
11179 &ApplicationInfo.FLAG_PERSISTENT) != 0) {
11180 minDuration /= 4;
11181 }
11182
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011183 // Any delivered but not yet finished starts should be put back
11184 // on the pending list.
11185 final int N = r.deliveredStarts.size();
11186 if (N > 0) {
11187 for (int i=N-1; i>=0; i--) {
11188 ServiceRecord.StartItem si = r.deliveredStarts.get(i);
Dianne Hackborn39792d22010-08-19 18:01:52 -070011189 si.removeUriPermissionsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011190 if (si.intent == null) {
11191 // We'll generate this again if needed.
11192 } else if (!allowCancel || (si.deliveryCount < ServiceRecord.MAX_DELIVERY_COUNT
11193 && si.doneExecutingCount < ServiceRecord.MAX_DONE_EXECUTING_COUNT)) {
11194 r.pendingStarts.add(0, si);
11195 long dur = SystemClock.uptimeMillis() - si.deliveredTime;
11196 dur *= 2;
11197 if (minDuration < dur) minDuration = dur;
11198 if (resetTime < dur) resetTime = dur;
11199 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011200 Slog.w(TAG, "Canceling start item " + si.intent + " in service "
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011201 + r.name);
11202 canceled = true;
11203 }
11204 }
11205 r.deliveredStarts.clear();
11206 }
11207
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011208 r.totalRestartCount++;
11209 if (r.restartDelay == 0) {
11210 r.restartCount++;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011211 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011212 } else {
11213 // If it has been a "reasonably long time" since the service
11214 // was started, then reset our restart duration back to
11215 // the beginning, so we don't infinitely increase the duration
11216 // on a service that just occasionally gets killed (which is
11217 // a normal case, due to process being killed to reclaim memory).
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011218 if (now > (r.restartTime+resetTime)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011219 r.restartCount = 1;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011220 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011221 } else {
Dianne Hackborn070783f2010-12-29 16:46:28 -080011222 if ((r.serviceInfo.applicationInfo.flags
11223 &ApplicationInfo.FLAG_PERSISTENT) != 0) {
11224 // Services in peristent processes will restart much more
11225 // quickly, since they are pretty important. (Think SystemUI).
11226 r.restartDelay += minDuration/2;
11227 } else {
11228 r.restartDelay *= SERVICE_RESTART_DURATION_FACTOR;
11229 if (r.restartDelay < minDuration) {
11230 r.restartDelay = minDuration;
11231 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011232 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011233 }
11234 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011235
11236 r.nextRestartTime = now + r.restartDelay;
11237
11238 // Make sure that we don't end up restarting a bunch of services
11239 // all at the same time.
11240 boolean repeat;
11241 do {
11242 repeat = false;
11243 for (int i=mRestartingServices.size()-1; i>=0; i--) {
11244 ServiceRecord r2 = mRestartingServices.get(i);
11245 if (r2 != r && r.nextRestartTime
11246 >= (r2.nextRestartTime-SERVICE_MIN_RESTART_TIME_BETWEEN)
11247 && r.nextRestartTime
11248 < (r2.nextRestartTime+SERVICE_MIN_RESTART_TIME_BETWEEN)) {
11249 r.nextRestartTime = r2.nextRestartTime + SERVICE_MIN_RESTART_TIME_BETWEEN;
11250 r.restartDelay = r.nextRestartTime - now;
11251 repeat = true;
11252 break;
11253 }
11254 }
11255 } while (repeat);
11256
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011257 if (!mRestartingServices.contains(r)) {
11258 mRestartingServices.add(r);
11259 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011260
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011261 r.cancelNotification();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011262
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011263 mHandler.removeCallbacks(r.restarter);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011264 mHandler.postAtTime(r.restarter, r.nextRestartTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011265 r.nextRestartTime = SystemClock.uptimeMillis() + r.restartDelay;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011266 Slog.w(TAG, "Scheduling restart of crashed service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011267 + r.shortName + " in " + r.restartDelay + "ms");
Doug Zongker2bec3d42009-12-04 12:52:44 -080011268 EventLog.writeEvent(EventLogTags.AM_SCHEDULE_SERVICE_RESTART,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011269 r.shortName, r.restartDelay);
11270
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011271 return canceled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011272 }
11273
11274 final void performServiceRestartLocked(ServiceRecord r) {
11275 if (!mRestartingServices.contains(r)) {
11276 return;
11277 }
11278 bringUpServiceLocked(r, r.intent.getIntent().getFlags(), true);
11279 }
11280
11281 private final boolean unscheduleServiceRestartLocked(ServiceRecord r) {
11282 if (r.restartDelay == 0) {
11283 return false;
11284 }
11285 r.resetRestartCounter();
11286 mRestartingServices.remove(r);
11287 mHandler.removeCallbacks(r.restarter);
11288 return true;
11289 }
11290
11291 private final boolean bringUpServiceLocked(ServiceRecord r,
11292 int intentFlags, boolean whileRestarting) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011293 //Slog.i(TAG, "Bring up service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011294 //r.dump(" ");
11295
Dianne Hackborn36124872009-10-08 16:22:03 -070011296 if (r.app != null && r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011297 sendServiceArgsLocked(r, false);
11298 return true;
11299 }
11300
11301 if (!whileRestarting && r.restartDelay > 0) {
11302 // If waiting for a restart, then do nothing.
11303 return true;
11304 }
11305
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011306 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing up " + r + " " + r.intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011307
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011308 // We are now bringing the service up, so no longer in the
11309 // restarting state.
11310 mRestartingServices.remove(r);
11311
Dianne Hackborne7f97212011-02-24 14:40:20 -080011312 // Service is now being launched, its package can't be stopped.
11313 try {
11314 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -070011315 r.packageName, false, r.userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -080011316 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080011317 } catch (IllegalArgumentException e) {
11318 Slog.w(TAG, "Failed trying to unstop package "
11319 + r.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080011320 }
11321
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011322 final boolean isolated = (r.serviceInfo.flags&ServiceInfo.FLAG_ISOLATED_PROCESS) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011323 final String appName = r.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011324 ProcessRecord app;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011325
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011326 if (!isolated) {
11327 app = getProcessRecordLocked(appName, r.appInfo.uid);
11328 if (DEBUG_MU)
11329 Slog.v(TAG_MU, "bringUpServiceLocked: appInfo.uid=" + r.appInfo.uid + " app=" + app);
11330 if (app != null && app.thread != null) {
11331 try {
11332 app.addPackage(r.appInfo.packageName);
11333 realStartServiceLocked(r, app);
11334 return true;
11335 } catch (RemoteException e) {
11336 Slog.w(TAG, "Exception when starting service " + r.shortName, e);
11337 }
11338
11339 // If a dead object exception was thrown -- fall through to
11340 // restart the application.
11341 }
11342 } else {
11343 // If this service runs in an isolated process, then each time
11344 // we call startProcessLocked() we will get a new isolated
11345 // process, starting another process if we are currently waiting
11346 // for a previous process to come up. To deal with this, we store
11347 // in the service any current isolated process it is running in or
11348 // waiting to have come up.
11349 app = r.isolatedProc;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011350 }
11351
Dianne Hackborn36124872009-10-08 16:22:03 -070011352 // Not running -- get it started, and enqueue this service record
11353 // to be executed when the app comes up.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011354 if (app == null) {
11355 if ((app=startProcessLocked(appName, r.appInfo, true, intentFlags,
11356 "service", r.name, false, isolated)) == null) {
11357 Slog.w(TAG, "Unable to launch app "
11358 + r.appInfo.packageName + "/"
11359 + r.appInfo.uid + " for service "
11360 + r.intent.getIntent() + ": process is bad");
11361 bringDownServiceLocked(r, true);
11362 return false;
11363 }
11364 if (isolated) {
11365 r.isolatedProc = app;
11366 }
Dianne Hackborn36124872009-10-08 16:22:03 -070011367 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011368
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011369 if (!mPendingServices.contains(r)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011370 mPendingServices.add(r);
11371 }
Dianne Hackborn36124872009-10-08 16:22:03 -070011372
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011373 return true;
11374 }
11375
11376 private final void bringDownServiceLocked(ServiceRecord r, boolean force) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011377 //Slog.i(TAG, "Bring down service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011378 //r.dump(" ");
11379
11380 // Does it still need to run?
11381 if (!force && r.startRequested) {
11382 return;
11383 }
11384 if (r.connections.size() > 0) {
11385 if (!force) {
11386 // XXX should probably keep a count of the number of auto-create
11387 // connections directly in the service.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011388 Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011389 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011390 ArrayList<ConnectionRecord> cr = it.next();
11391 for (int i=0; i<cr.size(); i++) {
11392 if ((cr.get(i).flags&Context.BIND_AUTO_CREATE) != 0) {
11393 return;
11394 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011395 }
11396 }
11397 }
11398
11399 // Report to all of the connections that the service is no longer
11400 // available.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011401 Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011402 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011403 ArrayList<ConnectionRecord> c = it.next();
11404 for (int i=0; i<c.size(); i++) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011405 ConnectionRecord cr = c.get(i);
11406 // There is still a connection to the service that is
11407 // being brought down. Mark it as dead.
11408 cr.serviceDead = true;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011409 try {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011410 cr.conn.connected(r.name, null);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011411 } catch (Exception e) {
11412 Slog.w(TAG, "Failure disconnecting service " + r.name +
11413 " to connection " + c.get(i).conn.asBinder() +
11414 " (in " + c.get(i).binding.client.processName + ")", e);
11415 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011416 }
11417 }
11418 }
11419
11420 // Tell the service that it has been unbound.
11421 if (r.bindings.size() > 0 && r.app != null && r.app.thread != null) {
11422 Iterator<IntentBindRecord> it = r.bindings.values().iterator();
11423 while (it.hasNext()) {
11424 IntentBindRecord ibr = it.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -080011425 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down binding " + ibr
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011426 + ": hasBound=" + ibr.hasBound);
11427 if (r.app != null && r.app.thread != null && ibr.hasBound) {
11428 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011429 bumpServiceExecutingLocked(r, "bring down unbind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011430 updateOomAdjLocked(r.app);
11431 ibr.hasBound = false;
11432 r.app.thread.scheduleUnbindService(r,
11433 ibr.intent.getIntent());
11434 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011435 Slog.w(TAG, "Exception when unbinding service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011436 + r.shortName, e);
11437 serviceDoneExecutingLocked(r, true);
11438 }
11439 }
11440 }
11441 }
11442
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011443 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down " + r + " " + r.intent);
Doug Zongker2bec3d42009-12-04 12:52:44 -080011444 EventLog.writeEvent(EventLogTags.AM_DESTROY_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011445 System.identityHashCode(r), r.shortName,
11446 (r.app != null) ? r.app.pid : -1);
11447
Amith Yamasani742a6712011-05-04 14:49:28 -070011448 mServiceMap.removeServiceByName(r.name, r.userId);
11449 mServiceMap.removeServiceByIntent(r.intent, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011450 r.totalRestartCount = 0;
11451 unscheduleServiceRestartLocked(r);
11452
11453 // Also make sure it is not on the pending list.
11454 int N = mPendingServices.size();
11455 for (int i=0; i<N; i++) {
11456 if (mPendingServices.get(i) == r) {
11457 mPendingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011458 if (DEBUG_SERVICE) Slog.v(TAG, "Removed pending: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011459 i--;
11460 N--;
11461 }
11462 }
11463
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011464 r.cancelNotification();
11465 r.isForeground = false;
11466 r.foregroundId = 0;
11467 r.foregroundNoti = null;
11468
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011469 // Clear start entries.
Dianne Hackborn39792d22010-08-19 18:01:52 -070011470 r.clearDeliveredStartsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011471 r.pendingStarts.clear();
11472
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011473 if (r.app != null) {
11474 synchronized (r.stats.getBatteryStats()) {
11475 r.stats.stopLaunchedLocked();
11476 }
11477 r.app.services.remove(r);
11478 if (r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011479 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011480 bumpServiceExecutingLocked(r, "stop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011481 mStoppingServices.add(r);
11482 updateOomAdjLocked(r.app);
11483 r.app.thread.scheduleStopService(r);
11484 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011485 Slog.w(TAG, "Exception when stopping service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011486 + r.shortName, e);
11487 serviceDoneExecutingLocked(r, true);
11488 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011489 updateServiceForegroundLocked(r.app, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011490 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011491 if (DEBUG_SERVICE) Slog.v(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011492 TAG, "Removed service that has no process: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011493 }
11494 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011495 if (DEBUG_SERVICE) Slog.v(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011496 TAG, "Removed service that is not running: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011497 }
Vairavan Srinivasana207ce22010-12-23 13:51:48 -080011498
11499 if (r.bindings.size() > 0) {
11500 r.bindings.clear();
11501 }
11502
11503 if (r.restarter instanceof ServiceRestarter) {
11504 ((ServiceRestarter)r.restarter).setService(null);
11505 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011506 }
11507
11508 ComponentName startServiceLocked(IApplicationThread caller,
11509 Intent service, String resolvedType,
11510 int callingPid, int callingUid) {
11511 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011512 if (DEBUG_SERVICE) Slog.v(TAG, "startService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011513 + " type=" + resolvedType + " args=" + service.getExtras());
11514
11515 if (caller != null) {
11516 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11517 if (callerApp == null) {
11518 throw new SecurityException(
11519 "Unable to find app for caller " + caller
11520 + " (pid=" + Binder.getCallingPid()
11521 + ") when starting service " + service);
11522 }
11523 }
11524
11525 ServiceLookupResult res =
11526 retrieveServiceLocked(service, resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011527 callingPid, callingUid, UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011528 if (res == null) {
11529 return null;
11530 }
11531 if (res.record == null) {
11532 return new ComponentName("!", res.permission != null
11533 ? res.permission : "private to package");
11534 }
11535 ServiceRecord r = res.record;
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011536 NeededUriGrants neededGrants = checkGrantUriPermissionFromIntentLocked(
11537 callingUid, r.packageName, service, service.getFlags(), null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011538 if (unscheduleServiceRestartLocked(r)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011539 if (DEBUG_SERVICE) Slog.v(TAG, "START SERVICE WHILE RESTART PENDING: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011540 }
11541 r.startRequested = true;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011542 r.callStart = false;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011543 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011544 service, neededGrants));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011545 r.lastActivity = SystemClock.uptimeMillis();
11546 synchronized (r.stats.getBatteryStats()) {
11547 r.stats.startRunningLocked();
11548 }
11549 if (!bringUpServiceLocked(r, service.getFlags(), false)) {
11550 return new ComponentName("!", "Service process is bad");
11551 }
11552 return r.name;
11553 }
11554 }
11555
11556 public ComponentName startService(IApplicationThread caller, Intent service,
11557 String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011558 enforceNotIsolatedCaller("startService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011559 // Refuse possible leaked file descriptors
11560 if (service != null && service.hasFileDescriptors() == true) {
11561 throw new IllegalArgumentException("File descriptors passed in Intent");
11562 }
11563
Amith Yamasani742a6712011-05-04 14:49:28 -070011564 if (DEBUG_SERVICE)
11565 Slog.v(TAG, "startService: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011566 synchronized(this) {
11567 final int callingPid = Binder.getCallingPid();
11568 final int callingUid = Binder.getCallingUid();
11569 final long origId = Binder.clearCallingIdentity();
11570 ComponentName res = startServiceLocked(caller, service,
11571 resolvedType, callingPid, callingUid);
11572 Binder.restoreCallingIdentity(origId);
11573 return res;
11574 }
11575 }
11576
11577 ComponentName startServiceInPackage(int uid,
11578 Intent service, String resolvedType) {
11579 synchronized(this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070011580 if (DEBUG_SERVICE)
11581 Slog.v(TAG, "startServiceInPackage: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011582 final long origId = Binder.clearCallingIdentity();
11583 ComponentName res = startServiceLocked(null, service,
11584 resolvedType, -1, uid);
11585 Binder.restoreCallingIdentity(origId);
11586 return res;
11587 }
11588 }
11589
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011590 private void stopServiceLocked(ServiceRecord service) {
11591 synchronized (service.stats.getBatteryStats()) {
11592 service.stats.stopRunningLocked();
11593 }
11594 service.startRequested = false;
11595 service.callStart = false;
11596 bringDownServiceLocked(service, false);
11597 }
11598
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011599 public int stopService(IApplicationThread caller, Intent service,
11600 String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011601 enforceNotIsolatedCaller("stopService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011602 // Refuse possible leaked file descriptors
11603 if (service != null && service.hasFileDescriptors() == true) {
11604 throw new IllegalArgumentException("File descriptors passed in Intent");
11605 }
11606
11607 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011608 if (DEBUG_SERVICE) Slog.v(TAG, "stopService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011609 + " type=" + resolvedType);
11610
11611 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11612 if (caller != null && callerApp == null) {
11613 throw new SecurityException(
11614 "Unable to find app for caller " + caller
11615 + " (pid=" + Binder.getCallingPid()
11616 + ") when stopping service " + service);
11617 }
11618
11619 // If this service is active, make sure it is stopped.
Amith Yamasani483f3b02012-03-13 16:08:00 -070011620 ServiceLookupResult r = findServiceLocked(service, resolvedType,
11621 callerApp == null ? UserId.getCallingUserId() : callerApp.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011622 if (r != null) {
11623 if (r.record != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011624 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011625 try {
11626 stopServiceLocked(r.record);
11627 } finally {
11628 Binder.restoreCallingIdentity(origId);
11629 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011630 return 1;
11631 }
11632 return -1;
11633 }
11634 }
11635
11636 return 0;
11637 }
11638
11639 public IBinder peekService(Intent service, String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011640 enforceNotIsolatedCaller("peekService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011641 // Refuse possible leaked file descriptors
11642 if (service != null && service.hasFileDescriptors() == true) {
11643 throw new IllegalArgumentException("File descriptors passed in Intent");
11644 }
11645
11646 IBinder ret = null;
11647
11648 synchronized(this) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070011649 ServiceLookupResult r = findServiceLocked(service, resolvedType,
11650 UserId.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011651
11652 if (r != null) {
11653 // r.record is null if findServiceLocked() failed the caller permission check
11654 if (r.record == null) {
11655 throw new SecurityException(
11656 "Permission Denial: Accessing service " + r.record.name
11657 + " from pid=" + Binder.getCallingPid()
11658 + ", uid=" + Binder.getCallingUid()
11659 + " requires " + r.permission);
11660 }
11661 IntentBindRecord ib = r.record.bindings.get(r.record.intent);
11662 if (ib != null) {
11663 ret = ib.binder;
11664 }
11665 }
11666 }
11667
11668 return ret;
11669 }
11670
11671 public boolean stopServiceToken(ComponentName className, IBinder token,
11672 int startId) {
11673 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011674 if (DEBUG_SERVICE) Slog.v(TAG, "stopServiceToken: " + className
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011675 + " " + token + " startId=" + startId);
11676 ServiceRecord r = findServiceLocked(className, token);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011677 if (r != null) {
11678 if (startId >= 0) {
11679 // Asked to only stop if done with all work. Note that
11680 // to avoid leaks, we will take this as dropping all
11681 // start items up to and including this one.
11682 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
11683 if (si != null) {
11684 while (r.deliveredStarts.size() > 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -070011685 ServiceRecord.StartItem cur = r.deliveredStarts.remove(0);
11686 cur.removeUriPermissionsLocked();
11687 if (cur == si) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011688 break;
11689 }
11690 }
11691 }
11692
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011693 if (r.getLastStartId() != startId) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011694 return false;
11695 }
11696
11697 if (r.deliveredStarts.size() > 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011698 Slog.w(TAG, "stopServiceToken startId " + startId
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011699 + " is last, but have " + r.deliveredStarts.size()
11700 + " remaining args");
11701 }
11702 }
11703
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011704 synchronized (r.stats.getBatteryStats()) {
11705 r.stats.stopRunningLocked();
11706 r.startRequested = false;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011707 r.callStart = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011708 }
11709 final long origId = Binder.clearCallingIdentity();
11710 bringDownServiceLocked(r, false);
11711 Binder.restoreCallingIdentity(origId);
11712 return true;
11713 }
11714 }
11715 return false;
11716 }
11717
11718 public void setServiceForeground(ComponentName className, IBinder token,
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011719 int id, Notification notification, boolean removeNotification) {
11720 final long origId = Binder.clearCallingIdentity();
11721 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011722 synchronized(this) {
11723 ServiceRecord r = findServiceLocked(className, token);
11724 if (r != null) {
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011725 if (id != 0) {
11726 if (notification == null) {
11727 throw new IllegalArgumentException("null notification");
11728 }
11729 if (r.foregroundId != id) {
11730 r.cancelNotification();
11731 r.foregroundId = id;
11732 }
11733 notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
11734 r.foregroundNoti = notification;
11735 r.isForeground = true;
11736 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011737 if (r.app != null) {
11738 updateServiceForegroundLocked(r.app, true);
11739 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011740 } else {
11741 if (r.isForeground) {
11742 r.isForeground = false;
11743 if (r.app != null) {
Dianne Hackborn8633e682010-04-22 16:03:41 -070011744 updateLruProcessLocked(r.app, false, true);
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011745 updateServiceForegroundLocked(r.app, true);
11746 }
11747 }
11748 if (removeNotification) {
11749 r.cancelNotification();
11750 r.foregroundId = 0;
11751 r.foregroundNoti = null;
11752 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011753 }
11754 }
11755 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011756 } finally {
11757 Binder.restoreCallingIdentity(origId);
11758 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011759 }
11760
11761 public void updateServiceForegroundLocked(ProcessRecord proc, boolean oomAdj) {
11762 boolean anyForeground = false;
Dianne Hackborn860755f2010-06-03 18:47:52 -070011763 for (ServiceRecord sr : proc.services) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011764 if (sr.isForeground) {
11765 anyForeground = true;
11766 break;
11767 }
11768 }
11769 if (anyForeground != proc.foregroundServices) {
11770 proc.foregroundServices = anyForeground;
11771 if (oomAdj) {
11772 updateOomAdjLocked();
11773 }
11774 }
11775 }
Amith Yamasania4a54e22012-04-16 15:44:19 -070011776
11777 boolean isSingleton(String componentProcessName, ApplicationInfo aInfo) {
11778 boolean result = false;
11779 if (UserId.getAppId(aInfo.uid) >= Process.FIRST_APPLICATION_UID) {
11780 result = false;
11781 } else if (componentProcessName == aInfo.packageName) {
11782 result = (aInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0;
11783 } else if ("system".equals(componentProcessName)) {
11784 result = true;
11785 }
11786 if (DEBUG_MU) {
11787 Slog.v(TAG, "isSingleton(" + componentProcessName + ", " + aInfo + ") = " + result);
11788 }
11789 return result;
11790 }
11791
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011792 public int bindService(IApplicationThread caller, IBinder token,
11793 Intent service, String resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011794 IServiceConnection connection, int flags, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011795 enforceNotIsolatedCaller("bindService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011796 // Refuse possible leaked file descriptors
11797 if (service != null && service.hasFileDescriptors() == true) {
11798 throw new IllegalArgumentException("File descriptors passed in Intent");
11799 }
11800
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011801 checkValidCaller(Binder.getCallingUid(), userId);
11802
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011803 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011804 if (DEBUG_SERVICE) Slog.v(TAG, "bindService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011805 + " type=" + resolvedType + " conn=" + connection.asBinder()
11806 + " flags=0x" + Integer.toHexString(flags));
Amith Yamasani742a6712011-05-04 14:49:28 -070011807 if (DEBUG_MU)
11808 Slog.i(TAG_MU, "bindService uid=" + Binder.getCallingUid() + " origUid="
11809 + Binder.getOrigCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011810 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11811 if (callerApp == null) {
11812 throw new SecurityException(
11813 "Unable to find app for caller " + caller
11814 + " (pid=" + Binder.getCallingPid()
11815 + ") when binding service " + service);
11816 }
11817
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011818 ActivityRecord activity = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011819 if (token != null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070011820 activity = mMainStack.isInStackLocked(token);
11821 if (activity == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011822 Slog.w(TAG, "Binding with unknown activity: " + token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011823 return 0;
11824 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011825 }
11826
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011827 int clientLabel = 0;
11828 PendingIntent clientIntent = null;
11829
11830 if (callerApp.info.uid == Process.SYSTEM_UID) {
11831 // Hacky kind of thing -- allow system stuff to tell us
11832 // what they are, so we can report this elsewhere for
11833 // others to know why certain services are running.
11834 try {
11835 clientIntent = (PendingIntent)service.getParcelableExtra(
11836 Intent.EXTRA_CLIENT_INTENT);
11837 } catch (RuntimeException e) {
11838 }
11839 if (clientIntent != null) {
11840 clientLabel = service.getIntExtra(Intent.EXTRA_CLIENT_LABEL, 0);
11841 if (clientLabel != 0) {
11842 // There are no useful extras in the intent, trash them.
11843 // System code calling with this stuff just needs to know
11844 // this will happen.
11845 service = service.cloneFilter();
11846 }
11847 }
11848 }
11849
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011850 ServiceLookupResult res =
11851 retrieveServiceLocked(service, resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011852 Binder.getCallingPid(), Binder.getCallingUid(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011853 if (res == null) {
11854 return 0;
11855 }
11856 if (res.record == null) {
11857 return -1;
11858 }
Amith Yamasania4a54e22012-04-16 15:44:19 -070011859 if (isSingleton(res.record.processName, res.record.appInfo)) {
11860 userId = 0;
11861 res = retrieveServiceLocked(service, resolvedType, Binder.getCallingPid(),
11862 Binder.getCallingUid(), 0);
11863 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011864 ServiceRecord s = res.record;
11865
11866 final long origId = Binder.clearCallingIdentity();
11867
11868 if (unscheduleServiceRestartLocked(s)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011869 if (DEBUG_SERVICE) Slog.v(TAG, "BIND SERVICE WHILE RESTART PENDING: "
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011870 + s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011871 }
11872
11873 AppBindRecord b = s.retrieveAppBindingLocked(service, callerApp);
11874 ConnectionRecord c = new ConnectionRecord(b, activity,
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011875 connection, flags, clientLabel, clientIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011876
11877 IBinder binder = connection.asBinder();
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011878 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
11879 if (clist == null) {
11880 clist = new ArrayList<ConnectionRecord>();
11881 s.connections.put(binder, clist);
11882 }
11883 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011884 b.connections.add(c);
11885 if (activity != null) {
11886 if (activity.connections == null) {
11887 activity.connections = new HashSet<ConnectionRecord>();
11888 }
11889 activity.connections.add(c);
11890 }
11891 b.client.connections.add(c);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070011892 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
11893 b.client.hasAboveClient = true;
11894 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011895 clist = mServiceConnections.get(binder);
11896 if (clist == null) {
11897 clist = new ArrayList<ConnectionRecord>();
11898 mServiceConnections.put(binder, clist);
11899 }
11900 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011901
11902 if ((flags&Context.BIND_AUTO_CREATE) != 0) {
11903 s.lastActivity = SystemClock.uptimeMillis();
11904 if (!bringUpServiceLocked(s, service.getFlags(), false)) {
11905 return 0;
11906 }
11907 }
11908
11909 if (s.app != null) {
11910 // This could have made the service more important.
11911 updateOomAdjLocked(s.app);
11912 }
11913
Joe Onorato8a9b2202010-02-26 18:56:32 -080011914 if (DEBUG_SERVICE) Slog.v(TAG, "Bind " + s + " with " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011915 + ": received=" + b.intent.received
11916 + " apps=" + b.intent.apps.size()
11917 + " doRebind=" + b.intent.doRebind);
11918
11919 if (s.app != null && b.intent.received) {
11920 // Service is already running, so we can immediately
11921 // publish the connection.
11922 try {
11923 c.conn.connected(s.name, b.intent.binder);
11924 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011925 Slog.w(TAG, "Failure sending service " + s.shortName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011926 + " to connection " + c.conn.asBinder()
11927 + " (in " + c.binding.client.processName + ")", e);
11928 }
11929
11930 // If this is the first app connected back to this binding,
11931 // and the service had previously asked to be told when
11932 // rebound, then do so.
11933 if (b.intent.apps.size() == 1 && b.intent.doRebind) {
11934 requestServiceBindingLocked(s, b.intent, true);
11935 }
11936 } else if (!b.intent.requested) {
11937 requestServiceBindingLocked(s, b.intent, false);
11938 }
11939
11940 Binder.restoreCallingIdentity(origId);
11941 }
11942
11943 return 1;
11944 }
11945
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070011946 void removeConnectionLocked(
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011947 ConnectionRecord c, ProcessRecord skipApp, ActivityRecord skipAct) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011948 IBinder binder = c.conn.asBinder();
11949 AppBindRecord b = c.binding;
11950 ServiceRecord s = b.service;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011951 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
11952 if (clist != null) {
11953 clist.remove(c);
11954 if (clist.size() == 0) {
11955 s.connections.remove(binder);
11956 }
11957 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011958 b.connections.remove(c);
11959 if (c.activity != null && c.activity != skipAct) {
11960 if (c.activity.connections != null) {
11961 c.activity.connections.remove(c);
11962 }
11963 }
11964 if (b.client != skipApp) {
11965 b.client.connections.remove(c);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070011966 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
11967 b.client.updateHasAboveClientLocked();
11968 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011969 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011970 clist = mServiceConnections.get(binder);
11971 if (clist != null) {
11972 clist.remove(c);
11973 if (clist.size() == 0) {
11974 mServiceConnections.remove(binder);
11975 }
11976 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011977
11978 if (b.connections.size() == 0) {
11979 b.intent.apps.remove(b.client);
11980 }
11981
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011982 if (!c.serviceDead) {
11983 if (DEBUG_SERVICE) Slog.v(TAG, "Disconnecting binding " + b.intent
11984 + ": shouldUnbind=" + b.intent.hasBound);
11985 if (s.app != null && s.app.thread != null && b.intent.apps.size() == 0
11986 && b.intent.hasBound) {
11987 try {
11988 bumpServiceExecutingLocked(s, "unbind");
11989 updateOomAdjLocked(s.app);
11990 b.intent.hasBound = false;
11991 // Assume the client doesn't want to know about a rebind;
11992 // we will deal with that later if it asks for one.
11993 b.intent.doRebind = false;
11994 s.app.thread.scheduleUnbindService(s, b.intent.intent.getIntent());
11995 } catch (Exception e) {
11996 Slog.w(TAG, "Exception when unbinding service " + s.shortName, e);
11997 serviceDoneExecutingLocked(s, true);
11998 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011999 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012000
12001 if ((c.flags&Context.BIND_AUTO_CREATE) != 0) {
12002 bringDownServiceLocked(s, false);
12003 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012004 }
12005 }
12006
12007 public boolean unbindService(IServiceConnection connection) {
12008 synchronized (this) {
12009 IBinder binder = connection.asBinder();
Joe Onorato8a9b2202010-02-26 18:56:32 -080012010 if (DEBUG_SERVICE) Slog.v(TAG, "unbindService: conn=" + binder);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012011 ArrayList<ConnectionRecord> clist = mServiceConnections.get(binder);
12012 if (clist == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012013 Slog.w(TAG, "Unbind failed: could not find connection for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012014 + connection.asBinder());
12015 return false;
12016 }
12017
12018 final long origId = Binder.clearCallingIdentity();
12019
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012020 while (clist.size() > 0) {
12021 ConnectionRecord r = clist.get(0);
12022 removeConnectionLocked(r, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012023
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012024 if (r.binding.service.app != null) {
12025 // This could have made the service less important.
12026 updateOomAdjLocked(r.binding.service.app);
12027 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012028 }
12029
12030 Binder.restoreCallingIdentity(origId);
12031 }
12032
12033 return true;
12034 }
12035
12036 public void publishService(IBinder token, Intent intent, IBinder service) {
12037 // Refuse possible leaked file descriptors
12038 if (intent != null && intent.hasFileDescriptors() == true) {
12039 throw new IllegalArgumentException("File descriptors passed in Intent");
12040 }
12041
12042 synchronized(this) {
12043 if (!(token instanceof ServiceRecord)) {
12044 throw new IllegalArgumentException("Invalid service token");
12045 }
12046 ServiceRecord r = (ServiceRecord)token;
12047
12048 final long origId = Binder.clearCallingIdentity();
12049
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012050 if (DEBUG_SERVICE) Slog.v(TAG, "PUBLISHING " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012051 + " " + intent + ": " + service);
12052 if (r != null) {
12053 Intent.FilterComparison filter
12054 = new Intent.FilterComparison(intent);
12055 IntentBindRecord b = r.bindings.get(filter);
12056 if (b != null && !b.received) {
12057 b.binder = service;
12058 b.requested = true;
12059 b.received = true;
12060 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012061 Iterator<ArrayList<ConnectionRecord>> it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012062 = r.connections.values().iterator();
12063 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012064 ArrayList<ConnectionRecord> clist = it.next();
12065 for (int i=0; i<clist.size(); i++) {
12066 ConnectionRecord c = clist.get(i);
12067 if (!filter.equals(c.binding.intent.intent)) {
12068 if (DEBUG_SERVICE) Slog.v(
12069 TAG, "Not publishing to: " + c);
12070 if (DEBUG_SERVICE) Slog.v(
12071 TAG, "Bound intent: " + c.binding.intent.intent);
12072 if (DEBUG_SERVICE) Slog.v(
12073 TAG, "Published intent: " + intent);
12074 continue;
12075 }
12076 if (DEBUG_SERVICE) Slog.v(TAG, "Publishing to: " + c);
12077 try {
12078 c.conn.connected(r.name, service);
12079 } catch (Exception e) {
12080 Slog.w(TAG, "Failure sending service " + r.name +
12081 " to connection " + c.conn.asBinder() +
12082 " (in " + c.binding.client.processName + ")", e);
12083 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012084 }
12085 }
12086 }
12087 }
12088
12089 serviceDoneExecutingLocked(r, mStoppingServices.contains(r));
12090
12091 Binder.restoreCallingIdentity(origId);
12092 }
12093 }
12094 }
12095
12096 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
12097 // Refuse possible leaked file descriptors
12098 if (intent != null && intent.hasFileDescriptors() == true) {
12099 throw new IllegalArgumentException("File descriptors passed in Intent");
12100 }
12101
12102 synchronized(this) {
12103 if (!(token instanceof ServiceRecord)) {
12104 throw new IllegalArgumentException("Invalid service token");
12105 }
12106 ServiceRecord r = (ServiceRecord)token;
12107
12108 final long origId = Binder.clearCallingIdentity();
12109
12110 if (r != null) {
12111 Intent.FilterComparison filter
12112 = new Intent.FilterComparison(intent);
12113 IntentBindRecord b = r.bindings.get(filter);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012114 if (DEBUG_SERVICE) Slog.v(TAG, "unbindFinished in " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012115 + " at " + b + ": apps="
12116 + (b != null ? b.apps.size() : 0));
Per Edelberg78f9fff2010-08-30 20:01:35 +020012117
12118 boolean inStopping = mStoppingServices.contains(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012119 if (b != null) {
Per Edelberg78f9fff2010-08-30 20:01:35 +020012120 if (b.apps.size() > 0 && !inStopping) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012121 // Applications have already bound since the last
12122 // unbind, so just rebind right here.
12123 requestServiceBindingLocked(r, b, true);
12124 } else {
12125 // Note to tell the service the next time there is
12126 // a new client.
12127 b.doRebind = true;
12128 }
12129 }
12130
Per Edelberg78f9fff2010-08-30 20:01:35 +020012131 serviceDoneExecutingLocked(r, inStopping);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012132
12133 Binder.restoreCallingIdentity(origId);
12134 }
12135 }
12136 }
12137
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012138 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012139 synchronized(this) {
12140 if (!(token instanceof ServiceRecord)) {
12141 throw new IllegalArgumentException("Invalid service token");
12142 }
12143 ServiceRecord r = (ServiceRecord)token;
12144 boolean inStopping = mStoppingServices.contains(token);
12145 if (r != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012146 if (r != token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012147 Slog.w(TAG, "Done executing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012148 + " with incorrect token: given " + token
12149 + ", expected " + r);
12150 return;
12151 }
12152
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012153 if (type == 1) {
12154 // This is a call from a service start... take care of
12155 // book-keeping.
12156 r.callStart = true;
12157 switch (res) {
12158 case Service.START_STICKY_COMPATIBILITY:
12159 case Service.START_STICKY: {
12160 // We are done with the associated start arguments.
12161 r.findDeliveredStart(startId, true);
12162 // Don't stop if killed.
12163 r.stopIfKilled = false;
12164 break;
12165 }
12166 case Service.START_NOT_STICKY: {
12167 // We are done with the associated start arguments.
12168 r.findDeliveredStart(startId, true);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070012169 if (r.getLastStartId() == startId) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012170 // There is no more work, and this service
12171 // doesn't want to hang around if killed.
12172 r.stopIfKilled = true;
12173 }
12174 break;
12175 }
12176 case Service.START_REDELIVER_INTENT: {
12177 // We'll keep this item until they explicitly
12178 // call stop for it, but keep track of the fact
12179 // that it was delivered.
12180 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
12181 if (si != null) {
12182 si.deliveryCount = 0;
12183 si.doneExecutingCount++;
12184 // Don't stop if killed.
12185 r.stopIfKilled = true;
12186 }
12187 break;
12188 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070012189 case Service.START_TASK_REMOVED_COMPLETE: {
12190 // Special processing for onTaskRemoved(). Don't
12191 // impact normal onStartCommand() processing.
12192 r.findDeliveredStart(startId, true);
12193 break;
12194 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012195 default:
12196 throw new IllegalArgumentException(
12197 "Unknown service start result: " + res);
12198 }
12199 if (res == Service.START_STICKY_COMPATIBILITY) {
12200 r.callStart = false;
12201 }
12202 }
Amith Yamasani742a6712011-05-04 14:49:28 -070012203 if (DEBUG_MU)
12204 Slog.v(TAG_MU, "before serviceDontExecutingLocked, uid="
12205 + Binder.getOrigCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012206 final long origId = Binder.clearCallingIdentity();
12207 serviceDoneExecutingLocked(r, inStopping);
12208 Binder.restoreCallingIdentity(origId);
12209 } else {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012210 Slog.w(TAG, "Done executing unknown service from pid "
12211 + Binder.getCallingPid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012212 }
12213 }
12214 }
12215
12216 public void serviceDoneExecutingLocked(ServiceRecord r, boolean inStopping) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012217 if (DEBUG_SERVICE) Slog.v(TAG, "<<< DONE EXECUTING " + r
12218 + ": nesting=" + r.executeNesting
12219 + ", inStopping=" + inStopping + ", app=" + r.app);
Dianne Hackborn287952c2010-09-22 22:34:31 -070012220 else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG, "<<< DONE EXECUTING " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012221 r.executeNesting--;
12222 if (r.executeNesting <= 0 && r.app != null) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012223 if (DEBUG_SERVICE) Slog.v(TAG,
12224 "Nesting at 0 of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012225 r.app.executingServices.remove(r);
12226 if (r.app.executingServices.size() == 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012227 if (DEBUG_SERVICE || DEBUG_SERVICE_EXECUTING) Slog.v(TAG,
12228 "No more executingServices of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012229 mHandler.removeMessages(SERVICE_TIMEOUT_MSG, r.app);
12230 }
12231 if (inStopping) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012232 if (DEBUG_SERVICE) Slog.v(TAG,
12233 "doneExecuting remove stopping " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012234 mStoppingServices.remove(r);
Mattias Petersson3996b412010-10-27 09:32:51 +020012235 r.bindings.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012236 }
12237 updateOomAdjLocked(r.app);
12238 }
12239 }
12240
12241 void serviceTimeout(ProcessRecord proc) {
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012242 String anrMessage = null;
12243
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012244 synchronized(this) {
12245 if (proc.executingServices.size() == 0 || proc.thread == null) {
12246 return;
12247 }
12248 long maxTime = SystemClock.uptimeMillis() - SERVICE_TIMEOUT;
12249 Iterator<ServiceRecord> it = proc.executingServices.iterator();
12250 ServiceRecord timeout = null;
12251 long nextTime = 0;
12252 while (it.hasNext()) {
12253 ServiceRecord sr = it.next();
12254 if (sr.executingStart < maxTime) {
12255 timeout = sr;
12256 break;
12257 }
12258 if (sr.executingStart > nextTime) {
12259 nextTime = sr.executingStart;
12260 }
12261 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012262 if (timeout != null && mLruProcesses.contains(proc)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012263 Slog.w(TAG, "Timeout executing service: " + timeout);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012264 anrMessage = "Executing service " + timeout.shortName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012265 } else {
12266 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
12267 msg.obj = proc;
12268 mHandler.sendMessageAtTime(msg, nextTime+SERVICE_TIMEOUT);
12269 }
12270 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012271
12272 if (anrMessage != null) {
12273 appNotResponding(proc, null, null, anrMessage);
12274 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012275 }
12276
12277 // =========================================================
Christopher Tate181fafa2009-05-14 11:12:14 -070012278 // BACKUP AND RESTORE
12279 // =========================================================
12280
12281 // Cause the target app to be launched if necessary and its backup agent
12282 // instantiated. The backup agent will invoke backupAgentCreated() on the
12283 // activity manager to announce its creation.
12284 public boolean bindBackupAgent(ApplicationInfo app, int backupMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012285 if (DEBUG_BACKUP) Slog.v(TAG, "startBackupAgent: app=" + app + " mode=" + backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070012286 enforceCallingPermission("android.permission.BACKUP", "startBackupAgent");
12287
12288 synchronized(this) {
12289 // !!! TODO: currently no check here that we're already bound
12290 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
12291 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
12292 synchronized (stats) {
12293 ss = stats.getServiceStatsLocked(app.uid, app.packageName, app.name);
12294 }
12295
Dianne Hackborne7f97212011-02-24 14:40:20 -080012296 // Backup agent is now in use, its package can't be stopped.
12297 try {
12298 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -070012299 app.packageName, false, UserId.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -080012300 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080012301 } catch (IllegalArgumentException e) {
12302 Slog.w(TAG, "Failed trying to unstop package "
12303 + app.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080012304 }
12305
Christopher Tate181fafa2009-05-14 11:12:14 -070012306 BackupRecord r = new BackupRecord(ss, app, backupMode);
Christopher Tate4a627c72011-04-01 14:43:32 -070012307 ComponentName hostingName = (backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL)
12308 ? new ComponentName(app.packageName, app.backupAgentName)
12309 : new ComponentName("android", "FullBackupAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -070012310 // startProcessLocked() returns existing proc's record if it's already running
12311 ProcessRecord proc = startProcessLocked(app.processName, app,
Dianne Hackborna0c283e2012-02-09 10:47:01 -080012312 false, 0, "backup", hostingName, false, false);
Christopher Tate181fafa2009-05-14 11:12:14 -070012313 if (proc == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012314 Slog.e(TAG, "Unable to start backup agent process " + r);
Christopher Tate181fafa2009-05-14 11:12:14 -070012315 return false;
12316 }
12317
12318 r.app = proc;
12319 mBackupTarget = r;
12320 mBackupAppName = app.packageName;
12321
Christopher Tate6fa95972009-06-05 18:43:55 -070012322 // Try not to kill the process during backup
12323 updateOomAdjLocked(proc);
12324
Christopher Tate181fafa2009-05-14 11:12:14 -070012325 // If the process is already attached, schedule the creation of the backup agent now.
12326 // If it is not yet live, this will be done when it attaches to the framework.
12327 if (proc.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012328 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc already running: " + proc);
Christopher Tate181fafa2009-05-14 11:12:14 -070012329 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040012330 proc.thread.scheduleCreateBackupAgent(app,
12331 compatibilityInfoForPackageLocked(app), backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070012332 } catch (RemoteException e) {
Christopher Tate436344a2009-09-30 16:17:37 -070012333 // Will time out on the backup manager side
Christopher Tate181fafa2009-05-14 11:12:14 -070012334 }
12335 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012336 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc not running, waiting for attach");
Christopher Tate181fafa2009-05-14 11:12:14 -070012337 }
12338 // Invariants: at this point, the target app process exists and the application
12339 // is either already running or in the process of coming up. mBackupTarget and
12340 // mBackupAppName describe the app, so that when it binds back to the AM we
12341 // know that it's scheduled for a backup-agent operation.
12342 }
12343
12344 return true;
12345 }
12346
12347 // A backup agent has just come up
12348 public void backupAgentCreated(String agentPackageName, IBinder agent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012349 if (DEBUG_BACKUP) Slog.v(TAG, "backupAgentCreated: " + agentPackageName
Christopher Tate181fafa2009-05-14 11:12:14 -070012350 + " = " + agent);
12351
12352 synchronized(this) {
12353 if (!agentPackageName.equals(mBackupAppName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012354 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
Christopher Tate181fafa2009-05-14 11:12:14 -070012355 return;
12356 }
Dianne Hackborn06740692010-09-22 22:46:21 -070012357 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012358
Dianne Hackborn06740692010-09-22 22:46:21 -070012359 long oldIdent = Binder.clearCallingIdentity();
12360 try {
12361 IBackupManager bm = IBackupManager.Stub.asInterface(
12362 ServiceManager.getService(Context.BACKUP_SERVICE));
12363 bm.agentConnected(agentPackageName, agent);
12364 } catch (RemoteException e) {
12365 // can't happen; the backup manager service is local
12366 } catch (Exception e) {
12367 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: ");
12368 e.printStackTrace();
12369 } finally {
12370 Binder.restoreCallingIdentity(oldIdent);
Christopher Tate181fafa2009-05-14 11:12:14 -070012371 }
12372 }
12373
12374 // done with this agent
12375 public void unbindBackupAgent(ApplicationInfo appInfo) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012376 if (DEBUG_BACKUP) Slog.v(TAG, "unbindBackupAgent: " + appInfo);
Christopher Tate8a27f922009-06-26 11:49:18 -070012377 if (appInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012378 Slog.w(TAG, "unbind backup agent for null app");
Christopher Tate8a27f922009-06-26 11:49:18 -070012379 return;
12380 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012381
12382 synchronized(this) {
Christopher Tate8a27f922009-06-26 11:49:18 -070012383 if (mBackupAppName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012384 Slog.w(TAG, "Unbinding backup agent with no active backup");
Christopher Tate8a27f922009-06-26 11:49:18 -070012385 return;
12386 }
12387
Christopher Tate181fafa2009-05-14 11:12:14 -070012388 if (!mBackupAppName.equals(appInfo.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012389 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
Christopher Tate181fafa2009-05-14 11:12:14 -070012390 return;
12391 }
12392
Christopher Tate6fa95972009-06-05 18:43:55 -070012393 ProcessRecord proc = mBackupTarget.app;
12394 mBackupTarget = null;
12395 mBackupAppName = null;
12396
12397 // Not backing this app up any more; reset its OOM adjustment
12398 updateOomAdjLocked(proc);
12399
Christopher Tatec7b31e32009-06-10 15:49:30 -070012400 // If the app crashed during backup, 'thread' will be null here
12401 if (proc.thread != null) {
12402 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040012403 proc.thread.scheduleDestroyBackupAgent(appInfo,
12404 compatibilityInfoForPackageLocked(appInfo));
Christopher Tatec7b31e32009-06-10 15:49:30 -070012405 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012406 Slog.e(TAG, "Exception when unbinding backup agent:");
Christopher Tatec7b31e32009-06-10 15:49:30 -070012407 e.printStackTrace();
12408 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012409 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012410 }
12411 }
12412 // =========================================================
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012413 // BROADCASTS
12414 // =========================================================
12415
Josh Bartel7f208742010-02-25 11:01:44 -060012416 private final List getStickiesLocked(String action, IntentFilter filter,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012417 List cur) {
12418 final ContentResolver resolver = mContext.getContentResolver();
12419 final ArrayList<Intent> list = mStickyBroadcasts.get(action);
12420 if (list == null) {
12421 return cur;
12422 }
12423 int N = list.size();
12424 for (int i=0; i<N; i++) {
12425 Intent intent = list.get(i);
12426 if (filter.match(resolver, intent, true, TAG) >= 0) {
12427 if (cur == null) {
12428 cur = new ArrayList<Intent>();
12429 }
12430 cur.add(intent);
12431 }
12432 }
12433 return cur;
12434 }
12435
Christopher Tatef46723b2012-01-26 14:19:24 -080012436 boolean isPendingBroadcastProcessLocked(int pid) {
12437 return mFgBroadcastQueue.isPendingBroadcastProcessLocked(pid)
12438 || mBgBroadcastQueue.isPendingBroadcastProcessLocked(pid);
12439 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012440
Christopher Tatef46723b2012-01-26 14:19:24 -080012441 void skipPendingBroadcastLocked(int pid) {
12442 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
12443 for (BroadcastQueue queue : mBroadcastQueues) {
12444 queue.skipPendingBroadcastLocked(pid);
12445 }
12446 }
12447
12448 // The app just attached; send any pending broadcasts that it should receive
12449 boolean sendPendingBroadcastsLocked(ProcessRecord app) {
12450 boolean didSomething = false;
12451 for (BroadcastQueue queue : mBroadcastQueues) {
12452 didSomething |= queue.sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012453 }
Christopher Tatef46723b2012-01-26 14:19:24 -080012454 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012455 }
12456
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012457 public Intent registerReceiver(IApplicationThread caller, String callerPackage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012458 IIntentReceiver receiver, IntentFilter filter, String permission) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012459 enforceNotIsolatedCaller("registerReceiver");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012460 synchronized(this) {
12461 ProcessRecord callerApp = null;
12462 if (caller != null) {
12463 callerApp = getRecordForAppLocked(caller);
12464 if (callerApp == null) {
12465 throw new SecurityException(
12466 "Unable to find app for caller " + caller
12467 + " (pid=" + Binder.getCallingPid()
12468 + ") when registering receiver " + receiver);
12469 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012470 if (callerApp.info.uid != Process.SYSTEM_UID &&
12471 !callerApp.pkgList.contains(callerPackage)) {
12472 throw new SecurityException("Given caller package " + callerPackage
12473 + " is not running in process " + callerApp);
12474 }
12475 } else {
12476 callerPackage = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012477 }
12478
12479 List allSticky = null;
12480
12481 // Look for any matching sticky broadcasts...
12482 Iterator actions = filter.actionsIterator();
12483 if (actions != null) {
12484 while (actions.hasNext()) {
12485 String action = (String)actions.next();
Josh Bartel7f208742010-02-25 11:01:44 -060012486 allSticky = getStickiesLocked(action, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012487 }
12488 } else {
Josh Bartel7f208742010-02-25 11:01:44 -060012489 allSticky = getStickiesLocked(null, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012490 }
12491
12492 // The first sticky in the list is returned directly back to
12493 // the client.
12494 Intent sticky = allSticky != null ? (Intent)allSticky.get(0) : null;
12495
Joe Onorato8a9b2202010-02-26 18:56:32 -080012496 if (DEBUG_BROADCAST) Slog.v(TAG, "Register receiver " + filter
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012497 + ": " + sticky);
12498
12499 if (receiver == null) {
12500 return sticky;
12501 }
12502
12503 ReceiverList rl
12504 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
12505 if (rl == null) {
12506 rl = new ReceiverList(this, callerApp,
12507 Binder.getCallingPid(),
12508 Binder.getCallingUid(), receiver);
12509 if (rl.app != null) {
12510 rl.app.receivers.add(rl);
12511 } else {
12512 try {
12513 receiver.asBinder().linkToDeath(rl, 0);
12514 } catch (RemoteException e) {
12515 return sticky;
12516 }
12517 rl.linkedToDeath = true;
12518 }
12519 mRegisteredReceivers.put(receiver.asBinder(), rl);
12520 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012521 BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage, permission);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012522 rl.add(bf);
12523 if (!bf.debugCheck()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012524 Slog.w(TAG, "==> For Dynamic broadast");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012525 }
12526 mReceiverResolver.addFilter(bf);
12527
12528 // Enqueue broadcasts for all existing stickies that match
12529 // this filter.
12530 if (allSticky != null) {
12531 ArrayList receivers = new ArrayList();
12532 receivers.add(bf);
12533
12534 int N = allSticky.size();
12535 for (int i=0; i<N; i++) {
12536 Intent intent = (Intent)allSticky.get(i);
Christopher Tatef46723b2012-01-26 14:19:24 -080012537 BroadcastQueue queue = broadcastQueueForIntent(intent);
12538 BroadcastRecord r = new BroadcastRecord(queue, intent, null,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012539 null, -1, -1, null, receivers, null, 0, null, null,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012540 false, true, true);
Christopher Tatef46723b2012-01-26 14:19:24 -080012541 queue.enqueueParallelBroadcastLocked(r);
12542 queue.scheduleBroadcastsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012543 }
12544 }
12545
12546 return sticky;
12547 }
12548 }
12549
12550 public void unregisterReceiver(IIntentReceiver receiver) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012551 if (DEBUG_BROADCAST) Slog.v(TAG, "Unregister receiver: " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012552
Christopher Tatef46723b2012-01-26 14:19:24 -080012553 final long origId = Binder.clearCallingIdentity();
12554 try {
12555 boolean doTrim = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012556
Christopher Tatef46723b2012-01-26 14:19:24 -080012557 synchronized(this) {
12558 ReceiverList rl
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012559 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
Christopher Tatef46723b2012-01-26 14:19:24 -080012560 if (rl != null) {
12561 if (rl.curBroadcast != null) {
12562 BroadcastRecord r = rl.curBroadcast;
12563 final boolean doNext = finishReceiverLocked(
12564 receiver.asBinder(), r.resultCode, r.resultData,
12565 r.resultExtras, r.resultAbort, true);
12566 if (doNext) {
12567 doTrim = true;
12568 r.queue.processNextBroadcast(false);
12569 }
12570 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012571
Christopher Tatef46723b2012-01-26 14:19:24 -080012572 if (rl.app != null) {
12573 rl.app.receivers.remove(rl);
12574 }
12575 removeReceiverLocked(rl);
12576 if (rl.linkedToDeath) {
12577 rl.linkedToDeath = false;
12578 rl.receiver.asBinder().unlinkToDeath(rl, 0);
12579 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012580 }
12581 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012582
Christopher Tatef46723b2012-01-26 14:19:24 -080012583 // If we actually concluded any broadcasts, we might now be able
12584 // to trim the recipients' apps from our working set
12585 if (doTrim) {
12586 trimApplications();
12587 return;
12588 }
12589
12590 } finally {
12591 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012592 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012593 }
12594
12595 void removeReceiverLocked(ReceiverList rl) {
12596 mRegisteredReceivers.remove(rl.receiver.asBinder());
12597 int N = rl.size();
12598 for (int i=0; i<N; i++) {
12599 mReceiverResolver.removeFilter(rl.get(i));
12600 }
12601 }
12602
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012603 private final void sendPackageBroadcastLocked(int cmd, String[] packages) {
12604 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
12605 ProcessRecord r = mLruProcesses.get(i);
12606 if (r.thread != null) {
12607 try {
12608 r.thread.dispatchPackageBroadcast(cmd, packages);
12609 } catch (RemoteException ex) {
12610 }
12611 }
12612 }
12613 }
12614
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012615 private final int broadcastIntentLocked(ProcessRecord callerApp,
12616 String callerPackage, Intent intent, String resolvedType,
12617 IIntentReceiver resultTo, int resultCode, String resultData,
12618 Bundle map, String requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070012619 boolean ordered, boolean sticky, int callingPid, int callingUid,
12620 int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012621 intent = new Intent(intent);
12622
Dianne Hackborne7f97212011-02-24 14:40:20 -080012623 // By default broadcasts do not go to stopped apps.
12624 intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
12625
Joe Onorato8a9b2202010-02-26 18:56:32 -080012626 if (DEBUG_BROADCAST_LIGHT) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012627 TAG, (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
Amith Yamasani13593602012-03-22 16:16:17 -070012628 + " ordered=" + ordered + " userid=" + userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012629 if ((resultTo != null) && !ordered) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012630 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012631 }
12632
12633 // Handle special intents: if this broadcast is from the package
12634 // manager about a package being removed, we need to remove all of
12635 // its activities from the history stack.
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012636 final boolean uidRemoved = Intent.ACTION_UID_REMOVED.equals(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012637 intent.getAction());
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012638 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())
12639 || Intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction())
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080012640 || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012641 || uidRemoved) {
12642 if (checkComponentPermission(
12643 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080012644 callingPid, callingUid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012645 == PackageManager.PERMISSION_GRANTED) {
12646 if (uidRemoved) {
12647 final Bundle intentExtras = intent.getExtras();
12648 final int uid = intentExtras != null
12649 ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
12650 if (uid >= 0) {
12651 BatteryStatsImpl bs = mBatteryStatsService.getActiveStatistics();
12652 synchronized (bs) {
12653 bs.removeUidStatsLocked(uid);
12654 }
12655 }
12656 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012657 // If resources are unvailble just force stop all
12658 // those packages and flush the attribute cache as well.
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080012659 if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012660 String list[] = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
12661 if (list != null && (list.length > 0)) {
12662 for (String pkg : list) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070012663 forceStopPackageLocked(pkg, -1, false, true, true, false, userId);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012664 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012665 sendPackageBroadcastLocked(
12666 IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE, list);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012667 }
12668 } else {
12669 Uri data = intent.getData();
12670 String ssp;
12671 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
12672 if (!intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false)) {
12673 forceStopPackageLocked(ssp,
Amith Yamasani483f3b02012-03-13 16:08:00 -070012674 intent.getIntExtra(Intent.EXTRA_UID, -1), false, true, true,
12675 false, userId);
Dianne Hackbornde7faf62009-06-30 13:27:30 -070012676 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012677 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012678 sendPackageBroadcastLocked(IApplicationThread.PACKAGE_REMOVED,
12679 new String[] {ssp});
12680 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012681 }
12682 }
12683 }
12684 } else {
12685 String msg = "Permission Denial: " + intent.getAction()
12686 + " broadcast from " + callerPackage + " (pid=" + callingPid
12687 + ", uid=" + callingUid + ")"
12688 + " requires "
12689 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012690 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012691 throw new SecurityException(msg);
12692 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012693
12694 // Special case for adding a package: by default turn on compatibility
12695 // mode.
12696 } else if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -070012697 Uri data = intent.getData();
12698 String ssp;
12699 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
12700 mCompatModePackages.handlePackageAddedLocked(ssp,
12701 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false));
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012702 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012703 }
12704
12705 /*
12706 * If this is the time zone changed action, queue up a message that will reset the timezone
12707 * of all currently running processes. This message will get queued up before the broadcast
12708 * happens.
12709 */
12710 if (intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) {
12711 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
12712 }
12713
Robert Greenwalt03595d02010-11-02 14:08:23 -070012714 if (intent.ACTION_CLEAR_DNS_CACHE.equals(intent.getAction())) {
12715 mHandler.sendEmptyMessage(CLEAR_DNS_CACHE);
12716 }
12717
Robert Greenwalt434203a2010-10-11 16:00:27 -070012718 if (Proxy.PROXY_CHANGE_ACTION.equals(intent.getAction())) {
12719 ProxyProperties proxy = intent.getParcelableExtra("proxy");
12720 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY, proxy));
12721 }
12722
Dianne Hackborn854060af2009-07-09 18:14:31 -070012723 /*
12724 * Prevent non-system code (defined here to be non-persistent
12725 * processes) from sending protected broadcasts.
12726 */
12727 if (callingUid == Process.SYSTEM_UID || callingUid == Process.PHONE_UID
12728 || callingUid == Process.SHELL_UID || callingUid == 0) {
12729 // Always okay.
12730 } else if (callerApp == null || !callerApp.persistent) {
12731 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012732 if (AppGlobals.getPackageManager().isProtectedBroadcast(
Dianne Hackborn854060af2009-07-09 18:14:31 -070012733 intent.getAction())) {
12734 String msg = "Permission Denial: not allowed to send broadcast "
12735 + intent.getAction() + " from pid="
12736 + callingPid + ", uid=" + callingUid;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012737 Slog.w(TAG, msg);
Dianne Hackborn854060af2009-07-09 18:14:31 -070012738 throw new SecurityException(msg);
12739 }
12740 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012741 Slog.w(TAG, "Remote exception", e);
Dianne Hackborna4972e92012-03-14 10:38:05 -070012742 return ActivityManager.BROADCAST_SUCCESS;
Dianne Hackborn854060af2009-07-09 18:14:31 -070012743 }
12744 }
12745
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012746 // Add to the sticky list if requested.
12747 if (sticky) {
12748 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
12749 callingPid, callingUid)
12750 != PackageManager.PERMISSION_GRANTED) {
12751 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
12752 + callingPid + ", uid=" + callingUid
12753 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012754 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012755 throw new SecurityException(msg);
12756 }
12757 if (requiredPermission != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012758 Slog.w(TAG, "Can't broadcast sticky intent " + intent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012759 + " and enforce permission " + requiredPermission);
Dianne Hackborna4972e92012-03-14 10:38:05 -070012760 return ActivityManager.BROADCAST_STICKY_CANT_HAVE_PERMISSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012761 }
12762 if (intent.getComponent() != null) {
12763 throw new SecurityException(
12764 "Sticky broadcasts can't target a specific component");
12765 }
12766 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
12767 if (list == null) {
12768 list = new ArrayList<Intent>();
12769 mStickyBroadcasts.put(intent.getAction(), list);
12770 }
12771 int N = list.size();
12772 int i;
12773 for (i=0; i<N; i++) {
12774 if (intent.filterEquals(list.get(i))) {
12775 // This sticky already exists, replace it.
12776 list.set(i, new Intent(intent));
12777 break;
12778 }
12779 }
12780 if (i >= N) {
12781 list.add(new Intent(intent));
12782 }
12783 }
12784
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012785 // Figure out who all will receive this broadcast.
12786 List receivers = null;
12787 List<BroadcastFilter> registeredReceivers = null;
12788 try {
12789 if (intent.getComponent() != null) {
12790 // Broadcast is going to one specific receiver class...
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012791 ActivityInfo ai = AppGlobals.getPackageManager().
Amith Yamasani483f3b02012-03-13 16:08:00 -070012792 getReceiverInfo(intent.getComponent(), STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012793 if (ai != null) {
12794 receivers = new ArrayList();
12795 ResolveInfo ri = new ResolveInfo();
Amith Yamasania4a54e22012-04-16 15:44:19 -070012796 if (isSingleton(ai.processName, ai.applicationInfo)) {
12797 ri.activityInfo = getActivityInfoForUser(ai, 0);
12798 } else {
12799 ri.activityInfo = getActivityInfoForUser(ai, userId);
12800 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012801 receivers.add(ri);
12802 }
12803 } else {
12804 // Need to resolve the intent to interested receivers...
12805 if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
12806 == 0) {
12807 receivers =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012808 AppGlobals.getPackageManager().queryIntentReceivers(
Amith Yamasani483f3b02012-03-13 16:08:00 -070012809 intent, resolvedType, STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012810 }
Amith Yamasani483f3b02012-03-13 16:08:00 -070012811 registeredReceivers = mReceiverResolver.queryIntent(intent, resolvedType, false,
12812 userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012813 }
12814 } catch (RemoteException ex) {
12815 // pm is in same process, this will never happen.
12816 }
12817
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012818 final boolean replacePending =
12819 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
12820
Joe Onorato8a9b2202010-02-26 18:56:32 -080012821 if (DEBUG_BROADCAST) Slog.v(TAG, "Enqueing broadcast: " + intent.getAction()
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012822 + " replacePending=" + replacePending);
12823
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012824 int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
12825 if (!ordered && NR > 0) {
12826 // If we are not serializing this broadcast, then send the
12827 // registered receivers separately so they don't wait for the
12828 // components to be launched.
Christopher Tatef46723b2012-01-26 14:19:24 -080012829 final BroadcastQueue queue = broadcastQueueForIntent(intent);
12830 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012831 callerPackage, callingPid, callingUid, requiredPermission,
12832 registeredReceivers, resultTo, resultCode, resultData, map,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012833 ordered, sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012834 if (DEBUG_BROADCAST) Slog.v(
Christopher Tatef46723b2012-01-26 14:19:24 -080012835 TAG, "Enqueueing parallel broadcast " + r);
12836 final boolean replaced = replacePending && queue.replaceParallelBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012837 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012838 queue.enqueueParallelBroadcastLocked(r);
12839 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012840 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012841 registeredReceivers = null;
12842 NR = 0;
12843 }
12844
12845 // Merge into one list.
12846 int ir = 0;
12847 if (receivers != null) {
12848 // A special case for PACKAGE_ADDED: do not allow the package
12849 // being added to see this broadcast. This prevents them from
12850 // using this as a back door to get run as soon as they are
12851 // installed. Maybe in the future we want to have a special install
12852 // broadcast or such for apps, but we'd like to deliberately make
12853 // this decision.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012854 String skipPackages[] = null;
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012855 if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
12856 || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
12857 || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012858 Uri data = intent.getData();
12859 if (data != null) {
12860 String pkgName = data.getSchemeSpecificPart();
12861 if (pkgName != null) {
12862 skipPackages = new String[] { pkgName };
12863 }
12864 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012865 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012866 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
The Android Open Source Project10592532009-03-18 17:39:46 -070012867 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012868 if (skipPackages != null && (skipPackages.length > 0)) {
12869 for (String skipPackage : skipPackages) {
12870 if (skipPackage != null) {
12871 int NT = receivers.size();
12872 for (int it=0; it<NT; it++) {
12873 ResolveInfo curt = (ResolveInfo)receivers.get(it);
12874 if (curt.activityInfo.packageName.equals(skipPackage)) {
12875 receivers.remove(it);
12876 it--;
12877 NT--;
12878 }
12879 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012880 }
12881 }
12882 }
12883
12884 int NT = receivers != null ? receivers.size() : 0;
12885 int it = 0;
12886 ResolveInfo curt = null;
12887 BroadcastFilter curr = null;
12888 while (it < NT && ir < NR) {
12889 if (curt == null) {
12890 curt = (ResolveInfo)receivers.get(it);
12891 }
12892 if (curr == null) {
12893 curr = registeredReceivers.get(ir);
12894 }
12895 if (curr.getPriority() >= curt.priority) {
12896 // Insert this broadcast record into the final list.
12897 receivers.add(it, curr);
12898 ir++;
12899 curr = null;
12900 it++;
12901 NT++;
12902 } else {
12903 // Skip to the next ResolveInfo in the final list.
12904 it++;
12905 curt = null;
12906 }
12907 }
12908 }
12909 while (ir < NR) {
12910 if (receivers == null) {
12911 receivers = new ArrayList();
12912 }
12913 receivers.add(registeredReceivers.get(ir));
12914 ir++;
12915 }
12916
12917 if ((receivers != null && receivers.size() > 0)
12918 || resultTo != null) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012919 BroadcastQueue queue = broadcastQueueForIntent(intent);
12920 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012921 callerPackage, callingPid, callingUid, requiredPermission,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012922 receivers, resultTo, resultCode, resultData, map, ordered,
12923 sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012924 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012925 TAG, "Enqueueing ordered broadcast " + r
Christopher Tatef46723b2012-01-26 14:19:24 -080012926 + ": prev had " + queue.mOrderedBroadcasts.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012927 if (DEBUG_BROADCAST) {
12928 int seq = r.intent.getIntExtra("seq", -1);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012929 Slog.i(TAG, "Enqueueing broadcast " + r.intent.getAction() + " seq=" + seq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012930 }
Christopher Tatef46723b2012-01-26 14:19:24 -080012931 boolean replaced = replacePending && queue.replaceOrderedBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012932 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012933 queue.enqueueOrderedBroadcastLocked(r);
12934 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012935 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012936 }
12937
Dianne Hackborna4972e92012-03-14 10:38:05 -070012938 return ActivityManager.BROADCAST_SUCCESS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012939 }
12940
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012941 final Intent verifyBroadcastLocked(Intent intent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012942 // Refuse possible leaked file descriptors
12943 if (intent != null && intent.hasFileDescriptors() == true) {
12944 throw new IllegalArgumentException("File descriptors passed in Intent");
12945 }
12946
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012947 int flags = intent.getFlags();
12948
12949 if (!mProcessesReady) {
12950 // if the caller really truly claims to know what they're doing, go
12951 // ahead and allow the broadcast without launching any receivers
12952 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
12953 intent = new Intent(intent);
12954 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
12955 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
12956 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
12957 + " before boot completion");
12958 throw new IllegalStateException("Cannot broadcast before boot completed");
12959 }
12960 }
12961
12962 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
12963 throw new IllegalArgumentException(
12964 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
12965 }
12966
12967 return intent;
12968 }
12969
12970 public final int broadcastIntent(IApplicationThread caller,
12971 Intent intent, String resolvedType, IIntentReceiver resultTo,
12972 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070012973 String requiredPermission, boolean serialized, boolean sticky, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012974 enforceNotIsolatedCaller("broadcastIntent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012975 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012976 intent = verifyBroadcastLocked(intent);
Dianne Hackborn9acc0302009-08-25 00:27:12 -070012977
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012978 final ProcessRecord callerApp = getRecordForAppLocked(caller);
12979 final int callingPid = Binder.getCallingPid();
12980 final int callingUid = Binder.getCallingUid();
12981 final long origId = Binder.clearCallingIdentity();
12982 int res = broadcastIntentLocked(callerApp,
12983 callerApp != null ? callerApp.info.packageName : null,
12984 intent, resolvedType, resultTo,
Amith Yamasani742a6712011-05-04 14:49:28 -070012985 resultCode, resultData, map, requiredPermission, serialized, sticky,
12986 callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012987 Binder.restoreCallingIdentity(origId);
12988 return res;
12989 }
12990 }
12991
12992 int broadcastIntentInPackage(String packageName, int uid,
12993 Intent intent, String resolvedType, IIntentReceiver resultTo,
12994 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070012995 String requiredPermission, boolean serialized, boolean sticky, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012996 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012997 intent = verifyBroadcastLocked(intent);
12998
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012999 final long origId = Binder.clearCallingIdentity();
13000 int res = broadcastIntentLocked(null, packageName, intent, resolvedType,
13001 resultTo, resultCode, resultData, map, requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070013002 serialized, sticky, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013003 Binder.restoreCallingIdentity(origId);
13004 return res;
13005 }
13006 }
13007
Amith Yamasani742a6712011-05-04 14:49:28 -070013008 // TODO: Use the userId; maybe mStickyBroadcasts need to be tied to the user.
13009 public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013010 // Refuse possible leaked file descriptors
13011 if (intent != null && intent.hasFileDescriptors() == true) {
13012 throw new IllegalArgumentException("File descriptors passed in Intent");
13013 }
13014
13015 synchronized(this) {
13016 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
13017 != PackageManager.PERMISSION_GRANTED) {
13018 String msg = "Permission Denial: unbroadcastIntent() from pid="
13019 + Binder.getCallingPid()
13020 + ", uid=" + Binder.getCallingUid()
13021 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080013022 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013023 throw new SecurityException(msg);
13024 }
13025 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
13026 if (list != null) {
13027 int N = list.size();
13028 int i;
13029 for (i=0; i<N; i++) {
13030 if (intent.filterEquals(list.get(i))) {
13031 list.remove(i);
13032 break;
13033 }
13034 }
13035 }
13036 }
13037 }
13038
13039 private final boolean finishReceiverLocked(IBinder receiver, int resultCode,
13040 String resultData, Bundle resultExtras, boolean resultAbort,
13041 boolean explicit) {
Christopher Tatef46723b2012-01-26 14:19:24 -080013042 final BroadcastRecord r = broadcastRecordForReceiverLocked(receiver);
13043 if (r == null) {
13044 Slog.w(TAG, "finishReceiver called but not found on queue");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013045 return false;
13046 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013047
Christopher Tatef46723b2012-01-26 14:19:24 -080013048 return r.queue.finishReceiverLocked(r, resultCode, resultData, resultExtras, resultAbort,
13049 explicit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013050 }
13051
13052 public void finishReceiver(IBinder who, int resultCode, String resultData,
13053 Bundle resultExtras, boolean resultAbort) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013054 if (DEBUG_BROADCAST) Slog.v(TAG, "Finish receiver: " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013055
13056 // Refuse possible leaked file descriptors
13057 if (resultExtras != null && resultExtras.hasFileDescriptors()) {
13058 throw new IllegalArgumentException("File descriptors passed in Bundle");
13059 }
13060
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013061 final long origId = Binder.clearCallingIdentity();
Christopher Tatef46723b2012-01-26 14:19:24 -080013062 try {
13063 boolean doNext = false;
13064 BroadcastRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013065
Christopher Tatef46723b2012-01-26 14:19:24 -080013066 synchronized(this) {
13067 r = broadcastRecordForReceiverLocked(who);
13068 if (r != null) {
13069 doNext = r.queue.finishReceiverLocked(r, resultCode,
13070 resultData, resultExtras, resultAbort, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013071 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013072 }
Jeff Brown4d94a762010-09-23 11:33:28 -070013073
Christopher Tatef46723b2012-01-26 14:19:24 -080013074 if (doNext) {
13075 r.queue.processNextBroadcast(false);
13076 }
13077 trimApplications();
13078 } finally {
13079 Binder.restoreCallingIdentity(origId);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070013080 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013081 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013082
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013083 // =========================================================
13084 // INSTRUMENTATION
13085 // =========================================================
13086
13087 public boolean startInstrumentation(ComponentName className,
13088 String profileFile, int flags, Bundle arguments,
13089 IInstrumentationWatcher watcher) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080013090 enforceNotIsolatedCaller("startInstrumentation");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013091 // Refuse possible leaked file descriptors
13092 if (arguments != null && arguments.hasFileDescriptors()) {
13093 throw new IllegalArgumentException("File descriptors passed in Bundle");
13094 }
13095
13096 synchronized(this) {
13097 InstrumentationInfo ii = null;
13098 ApplicationInfo ai = null;
13099 try {
13100 ii = mContext.getPackageManager().getInstrumentationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070013101 className, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013102 ai = mContext.getPackageManager().getApplicationInfo(
Amith Yamasani483f3b02012-03-13 16:08:00 -070013103 ii.targetPackage, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013104 } catch (PackageManager.NameNotFoundException e) {
13105 }
13106 if (ii == null) {
13107 reportStartInstrumentationFailure(watcher, className,
13108 "Unable to find instrumentation info for: " + className);
13109 return false;
13110 }
13111 if (ai == null) {
13112 reportStartInstrumentationFailure(watcher, className,
13113 "Unable to find instrumentation target package: " + ii.targetPackage);
13114 return false;
13115 }
13116
13117 int match = mContext.getPackageManager().checkSignatures(
13118 ii.targetPackage, ii.packageName);
13119 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
13120 String msg = "Permission Denial: starting instrumentation "
13121 + className + " from pid="
13122 + Binder.getCallingPid()
13123 + ", uid=" + Binder.getCallingPid()
13124 + " not allowed because package " + ii.packageName
13125 + " does not have a signature matching the target "
13126 + ii.targetPackage;
13127 reportStartInstrumentationFailure(watcher, className, msg);
13128 throw new SecurityException(msg);
13129 }
13130
Amith Yamasani483f3b02012-03-13 16:08:00 -070013131 int userId = UserId.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013132 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -070013133 // Instrumentation can kill and relaunch even persistent processes
Amith Yamasani483f3b02012-03-13 16:08:00 -070013134 forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true, userId);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013135 ProcessRecord app = addAppLocked(ai, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013136 app.instrumentationClass = className;
Dianne Hackborn1655be42009-05-08 14:29:01 -070013137 app.instrumentationInfo = ai;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013138 app.instrumentationProfileFile = profileFile;
13139 app.instrumentationArguments = arguments;
13140 app.instrumentationWatcher = watcher;
13141 app.instrumentationResultClass = className;
13142 Binder.restoreCallingIdentity(origId);
13143 }
13144
13145 return true;
13146 }
13147
13148 /**
13149 * Report errors that occur while attempting to start Instrumentation. Always writes the
13150 * error to the logs, but if somebody is watching, send the report there too. This enables
13151 * the "am" command to report errors with more information.
13152 *
13153 * @param watcher The IInstrumentationWatcher. Null if there isn't one.
13154 * @param cn The component name of the instrumentation.
13155 * @param report The error report.
13156 */
13157 private void reportStartInstrumentationFailure(IInstrumentationWatcher watcher,
13158 ComponentName cn, String report) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013159 Slog.w(TAG, report);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013160 try {
13161 if (watcher != null) {
13162 Bundle results = new Bundle();
13163 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
13164 results.putString("Error", report);
13165 watcher.instrumentationStatus(cn, -1, results);
13166 }
13167 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013168 Slog.w(TAG, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013169 }
13170 }
13171
13172 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
13173 if (app.instrumentationWatcher != null) {
13174 try {
13175 // NOTE: IInstrumentationWatcher *must* be oneway here
13176 app.instrumentationWatcher.instrumentationFinished(
13177 app.instrumentationClass,
13178 resultCode,
13179 results);
13180 } catch (RemoteException e) {
13181 }
13182 }
13183 app.instrumentationWatcher = null;
13184 app.instrumentationClass = null;
Dianne Hackborn1655be42009-05-08 14:29:01 -070013185 app.instrumentationInfo = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013186 app.instrumentationProfileFile = null;
13187 app.instrumentationArguments = null;
13188
Amith Yamasani483f3b02012-03-13 16:08:00 -070013189 forceStopPackageLocked(app.processName, -1, false, false, true, true, app.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013190 }
13191
13192 public void finishInstrumentation(IApplicationThread target,
13193 int resultCode, Bundle results) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070013194 int userId = UserId.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013195 // Refuse possible leaked file descriptors
13196 if (results != null && results.hasFileDescriptors()) {
13197 throw new IllegalArgumentException("File descriptors passed in Intent");
13198 }
13199
13200 synchronized(this) {
13201 ProcessRecord app = getRecordForAppLocked(target);
13202 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013203 Slog.w(TAG, "finishInstrumentation: no app for " + target);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013204 return;
13205 }
13206 final long origId = Binder.clearCallingIdentity();
13207 finishInstrumentationLocked(app, resultCode, results);
13208 Binder.restoreCallingIdentity(origId);
13209 }
13210 }
13211
13212 // =========================================================
13213 // CONFIGURATION
13214 // =========================================================
13215
13216 public ConfigurationInfo getDeviceConfigurationInfo() {
13217 ConfigurationInfo config = new ConfigurationInfo();
13218 synchronized (this) {
13219 config.reqTouchScreen = mConfiguration.touchscreen;
13220 config.reqKeyboardType = mConfiguration.keyboard;
13221 config.reqNavigation = mConfiguration.navigation;
Dianne Hackbornfae76f52009-07-16 13:41:23 -070013222 if (mConfiguration.navigation == Configuration.NAVIGATION_DPAD
13223 || mConfiguration.navigation == Configuration.NAVIGATION_TRACKBALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013224 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
13225 }
Dianne Hackbornfae76f52009-07-16 13:41:23 -070013226 if (mConfiguration.keyboard != Configuration.KEYBOARD_UNDEFINED
13227 && mConfiguration.keyboard != Configuration.KEYBOARD_NOKEYS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013228 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
13229 }
Jack Palevichb90d28c2009-07-22 15:35:24 -070013230 config.reqGlEsVersion = GL_ES_VERSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013231 }
13232 return config;
13233 }
13234
13235 public Configuration getConfiguration() {
13236 Configuration ci;
13237 synchronized(this) {
13238 ci = new Configuration(mConfiguration);
13239 }
13240 return ci;
13241 }
13242
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013243 public void updatePersistentConfiguration(Configuration values) {
13244 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
13245 "updateConfiguration()");
13246 enforceCallingPermission(android.Manifest.permission.WRITE_SETTINGS,
13247 "updateConfiguration()");
13248 if (values == null) {
13249 throw new NullPointerException("Configuration must not be null");
13250 }
13251
13252 synchronized(this) {
13253 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn813075a62011-11-14 17:45:19 -080013254 updateConfigurationLocked(values, null, true, false);
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013255 Binder.restoreCallingIdentity(origId);
13256 }
13257 }
13258
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013259 public void updateConfiguration(Configuration values) {
13260 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
13261 "updateConfiguration()");
13262
13263 synchronized(this) {
13264 if (values == null && mWindowManager != null) {
13265 // sentinel: fetch the current configuration from the window manager
13266 values = mWindowManager.computeNewConfiguration();
13267 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013268
13269 if (mWindowManager != null) {
13270 mProcessList.applyDisplaySize(mWindowManager);
13271 }
13272
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013273 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013274 if (values != null) {
13275 Settings.System.clearConfiguration(values);
13276 }
Dianne Hackborn813075a62011-11-14 17:45:19 -080013277 updateConfigurationLocked(values, null, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013278 Binder.restoreCallingIdentity(origId);
13279 }
13280 }
13281
13282 /**
13283 * Do either or both things: (1) change the current configuration, and (2)
13284 * make sure the given activity is running with the (now) current
13285 * configuration. Returns true if the activity has been left running, or
13286 * false if <var>starting</var> is being destroyed to match the new
13287 * configuration.
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013288 * @param persistent TODO
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013289 */
Dianne Hackborna573f6a2012-02-09 16:12:18 -080013290 boolean updateConfigurationLocked(Configuration values,
Dianne Hackborn813075a62011-11-14 17:45:19 -080013291 ActivityRecord starting, boolean persistent, boolean initLocale) {
Mike Lockwood3a74bd32011-08-12 13:55:22 -070013292 // do nothing if we are headless
13293 if (mHeadless) return true;
13294
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013295 int changes = 0;
13296
13297 boolean kept = true;
13298
13299 if (values != null) {
13300 Configuration newConfig = new Configuration(mConfiguration);
13301 changes = newConfig.updateFrom(values);
13302 if (changes != 0) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013303 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013304 Slog.i(TAG, "Updating configuration to: " + values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013305 }
13306
Doug Zongker2bec3d42009-12-04 12:52:44 -080013307 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013308
Dianne Hackborn813075a62011-11-14 17:45:19 -080013309 if (values.locale != null && !initLocale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013310 saveLocaleLocked(values.locale,
13311 !values.locale.equals(mConfiguration.locale),
13312 values.userSetLocale);
13313 }
13314
Dianne Hackborne36d6e22010-02-17 19:46:25 -080013315 mConfigurationSeq++;
13316 if (mConfigurationSeq <= 0) {
13317 mConfigurationSeq = 1;
13318 }
13319 newConfig.seq = mConfigurationSeq;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013320 mConfiguration = newConfig;
Joe Onorato8a9b2202010-02-26 18:56:32 -080013321 Slog.i(TAG, "Config changed: " + newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013322
13323 final Configuration configCopy = new Configuration(mConfiguration);
Joe Onorato54a4a412011-11-02 20:50:08 -070013324
13325 // TODO: If our config changes, should we auto dismiss any currently
13326 // showing dialogs?
13327 mShowDialogs = shouldShowDialogs(newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013328
Dianne Hackborn826d17c2009-11-12 12:55:51 -080013329 AttributeCache ac = AttributeCache.instance();
13330 if (ac != null) {
Dianne Hackborn813075a62011-11-14 17:45:19 -080013331 ac.updateConfiguration(configCopy);
Dianne Hackborn826d17c2009-11-12 12:55:51 -080013332 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013333
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070013334 // Make sure all resources in our process are updated
13335 // right now, so that anyone who is going to retrieve
13336 // resource values after we return will be sure to get
13337 // the new ones. This is especially important during
13338 // boot, where the first config change needs to guarantee
13339 // all resources have that config before following boot
13340 // code is executed.
Dianne Hackborn813075a62011-11-14 17:45:19 -080013341 mSystemThread.applyConfigurationToResources(configCopy);
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070013342
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013343 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080013344 Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013345 msg.obj = new Configuration(configCopy);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080013346 mHandler.sendMessage(msg);
13347 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013348
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013349 for (int i=mLruProcesses.size()-1; i>=0; i--) {
13350 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013351 try {
13352 if (app.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013353 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending to proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013354 + app.processName + " new config " + mConfiguration);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013355 app.thread.scheduleConfigurationChanged(configCopy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013356 }
13357 } catch (Exception e) {
13358 }
13359 }
13360 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080013361 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
13362 | Intent.FLAG_RECEIVER_REPLACE_PENDING);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013363 broadcastIntentLocked(null, null, intent, null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070013364 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080013365 if ((changes&ActivityInfo.CONFIG_LOCALE) != 0) {
13366 broadcastIntentLocked(null, null,
13367 new Intent(Intent.ACTION_LOCALE_CHANGED),
13368 null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070013369 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080013370 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013371 }
13372 }
13373
13374 if (changes != 0 && starting == null) {
13375 // If the configuration changed, and the caller is not already
13376 // in the process of starting an activity, then find the top
13377 // activity to check if its configuration needs to change.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013378 starting = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013379 }
13380
13381 if (starting != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013382 kept = mMainStack.ensureActivityConfigurationLocked(starting, changes);
Dianne Hackborn5f4d6432010-12-21 20:40:11 -080013383 // And we need to make sure at this point that all other activities
13384 // are made visible with the correct configuration.
13385 mMainStack.ensureActivitiesVisibleLocked(starting, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013386 }
13387
Dianne Hackborne36d6e22010-02-17 19:46:25 -080013388 if (values != null && mWindowManager != null) {
13389 mWindowManager.setNewConfiguration(mConfiguration);
13390 }
13391
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013392 return kept;
13393 }
Joe Onorato54a4a412011-11-02 20:50:08 -070013394
13395 /**
13396 * Decide based on the configuration whether we should shouw the ANR,
13397 * crash, etc dialogs. The idea is that if there is no affordnace to
13398 * press the on-screen buttons, we shouldn't show the dialog.
13399 *
13400 * A thought: SystemUI might also want to get told about this, the Power
13401 * dialog / global actions also might want different behaviors.
13402 */
13403 private static final boolean shouldShowDialogs(Configuration config) {
13404 return !(config.keyboard == Configuration.KEYBOARD_NOKEYS
13405 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH);
13406 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013407
13408 /**
13409 * Save the locale. You must be inside a synchronized (this) block.
13410 */
13411 private void saveLocaleLocked(Locale l, boolean isDiff, boolean isPersist) {
13412 if(isDiff) {
13413 SystemProperties.set("user.language", l.getLanguage());
13414 SystemProperties.set("user.region", l.getCountry());
13415 }
13416
13417 if(isPersist) {
13418 SystemProperties.set("persist.sys.language", l.getLanguage());
13419 SystemProperties.set("persist.sys.country", l.getCountry());
13420 SystemProperties.set("persist.sys.localevar", l.getVariant());
13421 }
13422 }
13423
Adam Powelldd8fab22012-03-22 17:47:27 -070013424 @Override
13425 public boolean targetTaskAffinityMatchesActivity(IBinder token, String destAffinity) {
13426 ActivityRecord srec = ActivityRecord.forToken(token);
Adam Powellb71a5bc2012-04-24 14:20:57 -070013427 return srec != null && srec.task.affinity != null &&
13428 srec.task.affinity.equals(destAffinity);
Adam Powelldd8fab22012-03-22 17:47:27 -070013429 }
13430
13431 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
13432 Intent resultData) {
13433 ComponentName dest = destIntent.getComponent();
13434
13435 synchronized (this) {
13436 ActivityRecord srec = ActivityRecord.forToken(token);
Adam Powellb71a5bc2012-04-24 14:20:57 -070013437 if (srec == null) {
13438 return false;
13439 }
Adam Powelldd8fab22012-03-22 17:47:27 -070013440 ArrayList<ActivityRecord> history = srec.stack.mHistory;
13441 final int start = history.indexOf(srec);
13442 if (start < 0) {
13443 // Current activity is not in history stack; do nothing.
13444 return false;
13445 }
13446 int finishTo = start - 1;
13447 ActivityRecord parent = null;
13448 boolean foundParentInTask = false;
13449 if (dest != null) {
13450 TaskRecord tr = srec.task;
13451 for (int i = start - 1; i >= 0; i--) {
13452 ActivityRecord r = history.get(i);
13453 if (tr != r.task) {
13454 // Couldn't find parent in the same task; stop at the one above this.
13455 // (Root of current task; in-app "home" behavior)
13456 // Always at least finish the current activity.
13457 finishTo = Math.min(start - 1, i + 1);
13458 parent = history.get(finishTo);
13459 break;
13460 } else if (r.info.packageName.equals(dest.getPackageName()) &&
13461 r.info.name.equals(dest.getClassName())) {
13462 finishTo = i;
13463 parent = r;
13464 foundParentInTask = true;
13465 break;
13466 }
13467 }
13468 }
13469
13470 if (mController != null) {
13471 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
13472 if (next != null) {
13473 // ask watcher if this is allowed
13474 boolean resumeOK = true;
13475 try {
13476 resumeOK = mController.activityResuming(next.packageName);
13477 } catch (RemoteException e) {
13478 mController = null;
13479 }
13480
13481 if (!resumeOK) {
13482 return false;
13483 }
13484 }
13485 }
13486 final long origId = Binder.clearCallingIdentity();
13487 for (int i = start; i > finishTo; i--) {
13488 ActivityRecord r = history.get(i);
13489 mMainStack.requestFinishActivityLocked(r.appToken, resultCode, resultData,
13490 "navigate-up");
13491 // Only return the supplied result for the first activity finished
13492 resultCode = Activity.RESULT_CANCELED;
13493 resultData = null;
13494 }
13495
13496 if (parent != null && foundParentInTask) {
13497 final int parentLaunchMode = parent.info.launchMode;
13498 final int destIntentFlags = destIntent.getFlags();
13499 if (parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE ||
13500 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TASK ||
13501 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TOP ||
13502 (destIntentFlags & Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
Adam Powell69de7e12012-05-07 18:42:24 -070013503 parent.deliverNewIntentLocked(srec.info.applicationInfo.uid, destIntent);
Adam Powelldd8fab22012-03-22 17:47:27 -070013504 } else {
13505 try {
13506 ActivityInfo aInfo = AppGlobals.getPackageManager().getActivityInfo(
13507 destIntent.getComponent(), 0, UserId.getCallingUserId());
13508 int res = mMainStack.startActivityLocked(srec.app.thread, destIntent,
13509 null, aInfo, parent.appToken, null,
13510 0, -1, parent.launchedFromUid, 0, null, true, null);
13511 foundParentInTask = res == ActivityManager.START_SUCCESS;
13512 } catch (RemoteException e) {
13513 foundParentInTask = false;
13514 }
13515 mMainStack.requestFinishActivityLocked(parent.appToken, resultCode,
13516 resultData, "navigate-up");
13517 }
13518 }
13519 Binder.restoreCallingIdentity(origId);
13520 return foundParentInTask;
13521 }
13522 }
13523
Dianne Hackborn5320eb82012-05-18 12:05:04 -070013524 public int getLaunchedFromUid(IBinder activityToken) {
13525 ActivityRecord srec = ActivityRecord.forToken(activityToken);
13526 if (srec == null) {
13527 return -1;
13528 }
13529 return srec.launchedFromUid;
13530 }
13531
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013532 // =========================================================
13533 // LIFETIME MANAGEMENT
13534 // =========================================================
13535
Christopher Tatef46723b2012-01-26 14:19:24 -080013536 // Returns which broadcast queue the app is the current [or imminent] receiver
13537 // on, or 'null' if the app is not an active broadcast recipient.
13538 private BroadcastQueue isReceivingBroadcast(ProcessRecord app) {
13539 BroadcastRecord r = app.curReceiver;
13540 if (r != null) {
13541 return r.queue;
13542 }
13543
13544 // It's not the current receiver, but it might be starting up to become one
13545 synchronized (this) {
13546 for (BroadcastQueue queue : mBroadcastQueues) {
13547 r = queue.mPendingBroadcast;
13548 if (r != null && r.curApp == app) {
13549 // found it; report which queue it's in
13550 return queue;
13551 }
13552 }
13553 }
13554
13555 return null;
13556 }
13557
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013558 private final int computeOomAdjLocked(ProcessRecord app, int hiddenAdj,
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013559 ProcessRecord TOP_APP, boolean recursed, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013560 if (mAdjSeq == app.adjSeq) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013561 // This adjustment has already been computed. If we are calling
13562 // from the top, we may have already computed our adjustment with
13563 // an earlier hidden adjustment that isn't really for us... if
13564 // so, use the new hidden adjustment.
13565 if (!recursed && app.hidden) {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013566 app.curAdj = app.curRawAdj = app.nonStoppingAdj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013567 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013568 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013569 }
13570
13571 if (app.thread == null) {
13572 app.adjSeq = mAdjSeq;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013573 app.curSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013574 return (app.curAdj=ProcessList.HIDDEN_APP_MAX_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013575 }
13576
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013577 app.adjTypeCode = ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN;
13578 app.adjSource = null;
13579 app.adjTarget = null;
13580 app.empty = false;
13581 app.hidden = false;
13582
13583 final int activitiesSize = app.activities.size();
13584
Dianne Hackborn7d608422011-08-07 16:24:18 -070013585 if (app.maxAdj <= ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013586 // The max adjustment doesn't allow this app to be anything
13587 // below foreground, so it is not worth doing work for it.
13588 app.adjType = "fixed";
13589 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013590 app.curRawAdj = app.nonStoppingAdj = app.maxAdj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013591 app.foregroundActivities = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013592 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013593 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013594 // System process can do UI, and when they do we want to have
13595 // them trim their memory after the user leaves the UI. To
13596 // facilitate this, here we need to determine whether or not it
13597 // is currently showing UI.
13598 app.systemNoUi = true;
13599 if (app == TOP_APP) {
13600 app.systemNoUi = false;
13601 } else if (activitiesSize > 0) {
13602 for (int j = 0; j < activitiesSize; j++) {
13603 final ActivityRecord r = app.activities.get(j);
13604 if (r.visible) {
13605 app.systemNoUi = false;
13606 break;
13607 }
13608 }
13609 }
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013610 return (app.curAdj=app.maxAdj);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013611 }
13612
13613 final boolean hadForegroundActivities = app.foregroundActivities;
13614
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013615 app.foregroundActivities = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013616 app.keeping = false;
13617 app.systemNoUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013618
The Android Open Source Project4df24232009-03-05 14:34:35 -080013619 // Determine the importance of the process, starting with most
13620 // important to least, and assign an appropriate OOM adjustment.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013621 int adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013622 int schedGroup;
Christopher Tatef46723b2012-01-26 14:19:24 -080013623 BroadcastQueue queue;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013624 if (app == TOP_APP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013625 // The last app on the list is the foreground app.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013626 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013627 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013628 app.adjType = "top-activity";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013629 app.foregroundActivities = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013630 } else if (app.instrumentationClass != null) {
13631 // Don't want to kill running instrumentation.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013632 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013633 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013634 app.adjType = "instrumentation";
Christopher Tatef46723b2012-01-26 14:19:24 -080013635 } else if ((queue = isReceivingBroadcast(app)) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013636 // An app that is currently receiving a broadcast also
Christopher Tatef46723b2012-01-26 14:19:24 -080013637 // counts as being in the foreground for OOM killer purposes.
13638 // It's placed in a sched group based on the nature of the
13639 // broadcast as reflected by which queue it's active in.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013640 adj = ProcessList.FOREGROUND_APP_ADJ;
Christopher Tatef46723b2012-01-26 14:19:24 -080013641 schedGroup = (queue == mFgBroadcastQueue)
13642 ? Process.THREAD_GROUP_DEFAULT : Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013643 app.adjType = "broadcast";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013644 } else if (app.executingServices.size() > 0) {
13645 // An app that is currently executing a service callback also
13646 // counts as being in the foreground.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013647 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013648 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013649 app.adjType = "exec-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013650 } else if (activitiesSize > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013651 // This app is in the background with paused activities.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013652 // We inspect activities to potentially upgrade adjustment further below.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013653 adj = hiddenAdj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013654 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013655 app.hidden = true;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013656 app.adjType = "bg-activities";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013657 } else {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013658 // A very not-needed process. If this is lower in the lru list,
13659 // we will push it in to the empty bucket.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013660 adj = hiddenAdj;
13661 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013662 app.hidden = true;
13663 app.empty = true;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013664 app.adjType = "bg-empty";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013665 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013666
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013667 boolean hasStoppingActivities = false;
13668
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013669 // Examine all activities if not already foreground.
13670 if (!app.foregroundActivities && activitiesSize > 0) {
13671 for (int j = 0; j < activitiesSize; j++) {
13672 final ActivityRecord r = app.activities.get(j);
13673 if (r.visible) {
13674 // App has a visible activity; only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013675 if (adj > ProcessList.VISIBLE_APP_ADJ) {
13676 adj = ProcessList.VISIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013677 app.adjType = "visible";
13678 }
13679 schedGroup = Process.THREAD_GROUP_DEFAULT;
13680 app.hidden = false;
13681 app.foregroundActivities = true;
13682 break;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013683 } else if (r.state == ActivityState.PAUSING || r.state == ActivityState.PAUSED) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013684 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13685 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013686 app.adjType = "pausing";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013687 }
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -080013688 app.hidden = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013689 app.foregroundActivities = true;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013690 } else if (r.state == ActivityState.STOPPING) {
13691 // We will apply the actual adjustment later, because
13692 // we want to allow this process to immediately go through
13693 // any memory trimming that is in effect.
13694 app.hidden = false;
13695 app.foregroundActivities = true;
13696 hasStoppingActivities = true;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013697 }
13698 }
13699 }
13700
Dianne Hackborn7d608422011-08-07 16:24:18 -070013701 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013702 if (app.foregroundServices) {
13703 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013704 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013705 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013706 app.adjType = "foreground-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013707 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013708 } else if (app.forcingToForeground != null) {
13709 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013710 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013711 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013712 app.adjType = "force-foreground";
13713 app.adjSource = app.forcingToForeground;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013714 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013715 }
13716 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013717
Dianne Hackborn7d608422011-08-07 16:24:18 -070013718 if (adj > ProcessList.HEAVY_WEIGHT_APP_ADJ && app == mHeavyWeightProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013719 // We don't want to kill the current heavy-weight process.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013720 adj = ProcessList.HEAVY_WEIGHT_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013721 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013722 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013723 app.adjType = "heavy";
13724 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013725
Dianne Hackborn7d608422011-08-07 16:24:18 -070013726 if (adj > ProcessList.HOME_APP_ADJ && app == mHomeProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013727 // This process is hosting what we currently consider to be the
13728 // home app, so we don't want to let it go into the background.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013729 adj = ProcessList.HOME_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013730 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013731 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013732 app.adjType = "home";
13733 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013734
Dianne Hackbornf35fe232011-11-01 19:25:20 -070013735 if (adj > ProcessList.PREVIOUS_APP_ADJ && app == mPreviousProcess
13736 && app.activities.size() > 0) {
13737 // This was the previous process that showed UI to the user.
13738 // We want to try to keep it around more aggressively, to give
13739 // a good experience around switching between two apps.
13740 adj = ProcessList.PREVIOUS_APP_ADJ;
13741 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
13742 app.hidden = false;
13743 app.adjType = "previous";
13744 }
13745
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013746 if (false) Slog.i(TAG, "OOM " + app + ": initial adj=" + adj
13747 + " reason=" + app.adjType);
13748
The Android Open Source Project4df24232009-03-05 14:34:35 -080013749 // By default, we use the computed adjustment. It may be changed if
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013750 // there are applications dependent on our services or providers, but
13751 // this gives us a baseline and makes sure we don't get into an
13752 // infinite recursion.
13753 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013754 app.curRawAdj = app.nonStoppingAdj = adj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013755
Christopher Tate6fa95972009-06-05 18:43:55 -070013756 if (mBackupTarget != null && app == mBackupTarget.app) {
13757 // If possible we want to avoid killing apps while they're being backed up
Dianne Hackborn7d608422011-08-07 16:24:18 -070013758 if (adj > ProcessList.BACKUP_APP_ADJ) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013759 if (DEBUG_BACKUP) Slog.v(TAG, "oom BACKUP_APP_ADJ for " + app);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013760 adj = ProcessList.BACKUP_APP_ADJ;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013761 app.adjType = "backup";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013762 app.hidden = false;
Christopher Tate6fa95972009-06-05 18:43:55 -070013763 }
13764 }
13765
Dianne Hackborn7d608422011-08-07 16:24:18 -070013766 if (app.services.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013767 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013768 final long now = SystemClock.uptimeMillis();
13769 // This process is more important if the top activity is
13770 // bound to the service.
Dianne Hackborn860755f2010-06-03 18:47:52 -070013771 Iterator<ServiceRecord> jt = app.services.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013772 while (jt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013773 ServiceRecord s = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013774 if (s.startRequested) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013775 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013776 // If this process has shown some UI, let it immediately
13777 // go to the LRU list because it may be pretty heavy with
13778 // UI stuff. We'll tag it with a label just to help
13779 // debug and understand what is going on.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013780 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013781 app.adjType = "started-bg-ui-services";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013782 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013783 } else {
13784 if (now < (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
13785 // This service has seen some activity within
13786 // recent memory, so we will keep its process ahead
13787 // of the background processes.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013788 if (adj > ProcessList.SERVICE_ADJ) {
13789 adj = ProcessList.SERVICE_ADJ;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013790 app.adjType = "started-services";
13791 app.hidden = false;
13792 }
13793 }
13794 // If we have let the service slide into the background
13795 // state, still have some text describing what it is doing
13796 // even though the service no longer has an impact.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013797 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013798 app.adjType = "started-bg-services";
13799 }
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080013800 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013801 // Don't kill this process because it is doing work; it
13802 // has said it is doing work.
13803 app.keeping = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013804 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013805 if (s.connections.size() > 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013806 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013807 Iterator<ArrayList<ConnectionRecord>> kt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013808 = s.connections.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013809 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013810 ArrayList<ConnectionRecord> clist = kt.next();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013811 for (int i=0; i<clist.size() && adj > ProcessList.FOREGROUND_APP_ADJ; i++) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013812 // XXX should compute this based on the max of
13813 // all connected clients.
13814 ConnectionRecord cr = clist.get(i);
13815 if (cr.binding.client == app) {
13816 // Binding to ourself is not interesting.
13817 continue;
13818 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013819 if ((cr.flags&Context.BIND_WAIVE_PRIORITY) == 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013820 ProcessRecord client = cr.binding.client;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013821 int clientAdj = adj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013822 int myHiddenAdj = hiddenAdj;
13823 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013824 if (client.hiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013825 myHiddenAdj = client.hiddenAdj;
13826 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013827 myHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013828 }
13829 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013830 clientAdj = computeOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013831 client, myHiddenAdj, TOP_APP, true, doingAll);
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013832 String adjType = null;
13833 if ((cr.flags&Context.BIND_ALLOW_OOM_MANAGEMENT) != 0) {
13834 // Not doing bind OOM management, so treat
13835 // this guy more like a started service.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013836 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013837 // If this process has shown some UI, let it immediately
13838 // go to the LRU list because it may be pretty heavy with
13839 // UI stuff. We'll tag it with a label just to help
13840 // debug and understand what is going on.
13841 if (adj > clientAdj) {
13842 adjType = "bound-bg-ui-services";
13843 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013844 app.hidden = false;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013845 clientAdj = adj;
13846 } else {
13847 if (now >= (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
13848 // This service has not seen activity within
13849 // recent memory, so allow it to drop to the
13850 // LRU list if there is no other reason to keep
13851 // it around. We'll also tag it with a label just
13852 // to help debug and undertand what is going on.
13853 if (adj > clientAdj) {
13854 adjType = "bound-bg-services";
13855 }
13856 clientAdj = adj;
13857 }
13858 }
13859 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013860 if (adj > clientAdj) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013861 // If this process has recently shown UI, and
13862 // the process that is binding to it is less
13863 // important than being visible, then we don't
13864 // care about the binding as much as we care
13865 // about letting this process get into the LRU
13866 // list to be killed and restarted if needed for
13867 // memory.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013868 if (app.hasShownUi && app != mHomeProcess
13869 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013870 adjType = "bound-bg-ui-services";
13871 } else {
13872 if ((cr.flags&(Context.BIND_ABOVE_CLIENT
13873 |Context.BIND_IMPORTANT)) != 0) {
13874 adj = clientAdj;
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070013875 } else if ((cr.flags&Context.BIND_NOT_VISIBLE) != 0
13876 && clientAdj < ProcessList.PERCEPTIBLE_APP_ADJ
13877 && adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13878 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13879 } else if (clientAdj > ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013880 adj = clientAdj;
13881 } else {
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070013882 app.pendingUiClean = true;
13883 if (adj > ProcessList.VISIBLE_APP_ADJ) {
13884 adj = ProcessList.VISIBLE_APP_ADJ;
13885 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013886 }
13887 if (!client.hidden) {
13888 app.hidden = false;
13889 }
13890 if (client.keeping) {
13891 app.keeping = true;
13892 }
13893 adjType = "service";
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013894 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013895 }
13896 if (adjType != null) {
13897 app.adjType = adjType;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013898 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13899 .REASON_SERVICE_IN_USE;
13900 app.adjSource = cr.binding.client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013901 app.adjSourceOom = clientAdj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013902 app.adjTarget = s.name;
13903 }
13904 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
13905 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
13906 schedGroup = Process.THREAD_GROUP_DEFAULT;
13907 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013908 }
13909 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013910 if ((cr.flags&Context.BIND_ADJUST_WITH_ACTIVITY) != 0) {
13911 ActivityRecord a = cr.activity;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013912 if (a != null && adj > ProcessList.FOREGROUND_APP_ADJ &&
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013913 (a.visible || a.state == ActivityState.RESUMED
13914 || a.state == ActivityState.PAUSING)) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013915 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013916 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
13917 schedGroup = Process.THREAD_GROUP_DEFAULT;
13918 }
13919 app.hidden = false;
13920 app.adjType = "service";
13921 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13922 .REASON_SERVICE_IN_USE;
13923 app.adjSource = a;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013924 app.adjSourceOom = adj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013925 app.adjTarget = s.name;
13926 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013927 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013928 }
13929 }
13930 }
13931 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013932
Dianne Hackborn287952c2010-09-22 22:34:31 -070013933 // Finally, if this process has active services running in it, we
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013934 // would like to avoid killing it unless it would prevent the current
13935 // application from running. By default we put the process in
13936 // with the rest of the background processes; as we scan through
13937 // its services we may bump it up from there.
13938 if (adj > hiddenAdj) {
13939 adj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013940 app.hidden = false;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013941 app.adjType = "bg-services";
13942 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013943 }
13944
Dianne Hackborn7d608422011-08-07 16:24:18 -070013945 if (app.pubProviders.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013946 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013947 Iterator<ContentProviderRecord> jt = app.pubProviders.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013948 while (jt.hasNext() && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013949 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013950 ContentProviderRecord cpr = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013951 if (cpr.clients.size() != 0) {
13952 Iterator<ProcessRecord> kt = cpr.clients.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013953 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013954 ProcessRecord client = kt.next();
The Android Open Source Project10592532009-03-18 17:39:46 -070013955 if (client == app) {
13956 // Being our own client is not interesting.
13957 continue;
13958 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013959 int myHiddenAdj = hiddenAdj;
13960 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013961 if (client.hiddenAdj > ProcessList.FOREGROUND_APP_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013962 myHiddenAdj = client.hiddenAdj;
13963 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013964 myHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013965 }
13966 }
13967 int clientAdj = computeOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013968 client, myHiddenAdj, TOP_APP, true, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013969 if (adj > clientAdj) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013970 if (app.hasShownUi && app != mHomeProcess
13971 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013972 app.adjType = "bg-ui-provider";
13973 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013974 adj = clientAdj > ProcessList.FOREGROUND_APP_ADJ
13975 ? clientAdj : ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013976 app.adjType = "provider";
13977 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013978 if (!client.hidden) {
13979 app.hidden = false;
13980 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013981 if (client.keeping) {
13982 app.keeping = true;
13983 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070013984 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13985 .REASON_PROVIDER_IN_USE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013986 app.adjSource = client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013987 app.adjSourceOom = clientAdj;
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070013988 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013989 }
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013990 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
13991 schedGroup = Process.THREAD_GROUP_DEFAULT;
13992 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013993 }
13994 }
13995 // If the provider has external (non-framework) process
13996 // dependencies, ensure that its adjustment is at least
13997 // FOREGROUND_APP_ADJ.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080013998 if (cpr.hasExternalProcessHandles()) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013999 if (adj > ProcessList.FOREGROUND_APP_ADJ) {
14000 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014001 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014002 app.hidden = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070014003 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070014004 app.adjType = "provider";
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070014005 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014006 }
14007 }
14008 }
14009 }
14010
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014011 if (adj == ProcessList.SERVICE_ADJ) {
14012 if (doingAll) {
14013 app.serviceb = mNewNumServiceProcs > (mNumServiceProcs/3);
14014 mNewNumServiceProcs++;
14015 }
14016 if (app.serviceb) {
14017 adj = ProcessList.SERVICE_B_ADJ;
14018 }
14019 } else {
14020 app.serviceb = false;
14021 }
14022
14023 app.nonStoppingAdj = adj;
14024
14025 if (hasStoppingActivities) {
14026 // Only upgrade adjustment.
14027 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
14028 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
14029 app.adjType = "stopping";
14030 }
14031 }
14032
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014033 app.curRawAdj = adj;
14034
Joe Onorato8a9b2202010-02-26 18:56:32 -080014035 //Slog.i(TAG, "OOM ADJ " + app + ": pid=" + app.pid +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014036 // " adj=" + adj + " curAdj=" + app.curAdj + " maxAdj=" + app.maxAdj);
14037 if (adj > app.maxAdj) {
14038 adj = app.maxAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070014039 if (app.maxAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014040 schedGroup = Process.THREAD_GROUP_DEFAULT;
14041 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014042 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070014043 if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070014044 app.keeping = true;
14045 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014046
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014047 if (app.hasAboveClient) {
14048 // If this process has bound to any services with BIND_ABOVE_CLIENT,
14049 // then we need to drop its adjustment to be lower than the service's
14050 // in order to honor the request. We want to drop it by one adjustment
14051 // level... but there is special meaning applied to various levels so
14052 // we will skip some of them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014053 if (adj < ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014054 // System process will not get dropped, ever
Dianne Hackborn7d608422011-08-07 16:24:18 -070014055 } else if (adj < ProcessList.VISIBLE_APP_ADJ) {
14056 adj = ProcessList.VISIBLE_APP_ADJ;
14057 } else if (adj < ProcessList.PERCEPTIBLE_APP_ADJ) {
14058 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
14059 } else if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
14060 adj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014061 } else if (adj < ProcessList.HIDDEN_APP_MAX_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014062 adj++;
14063 }
14064 }
14065
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014066 app.curAdj = adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014067 app.curSchedGroup = schedGroup;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070014068
14069 if (hadForegroundActivities != app.foregroundActivities) {
Jeff Sharkey287bd832011-05-28 19:36:26 -070014070 mHandler.obtainMessage(DISPATCH_FOREGROUND_ACTIVITIES_CHANGED, app.pid, app.info.uid,
14071 app.foregroundActivities).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070014072 }
14073
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014074 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014075 }
14076
14077 /**
14078 * Ask a given process to GC right now.
14079 */
14080 final void performAppGcLocked(ProcessRecord app) {
14081 try {
14082 app.lastRequestedGc = SystemClock.uptimeMillis();
14083 if (app.thread != null) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014084 if (app.reportLowMemory) {
14085 app.reportLowMemory = false;
14086 app.thread.scheduleLowMemory();
14087 } else {
14088 app.thread.processInBackground();
14089 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014090 }
14091 } catch (Exception e) {
14092 // whatever.
14093 }
14094 }
14095
14096 /**
14097 * Returns true if things are idle enough to perform GCs.
14098 */
Josh Bartel7f208742010-02-25 11:01:44 -060014099 private final boolean canGcNowLocked() {
Christopher Tatef46723b2012-01-26 14:19:24 -080014100 boolean processingBroadcasts = false;
14101 for (BroadcastQueue q : mBroadcastQueues) {
14102 if (q.mParallelBroadcasts.size() != 0 || q.mOrderedBroadcasts.size() != 0) {
14103 processingBroadcasts = true;
14104 }
14105 }
14106 return !processingBroadcasts
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014107 && (mSleeping || (mMainStack.mResumedActivity != null &&
14108 mMainStack.mResumedActivity.idle));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014109 }
14110
14111 /**
14112 * Perform GCs on all processes that are waiting for it, but only
14113 * if things are idle.
14114 */
14115 final void performAppGcsLocked() {
14116 final int N = mProcessesToGc.size();
14117 if (N <= 0) {
14118 return;
14119 }
Josh Bartel7f208742010-02-25 11:01:44 -060014120 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014121 while (mProcessesToGc.size() > 0) {
14122 ProcessRecord proc = mProcessesToGc.remove(0);
Dianne Hackborn7d608422011-08-07 16:24:18 -070014123 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014124 if ((proc.lastRequestedGc+GC_MIN_INTERVAL)
14125 <= SystemClock.uptimeMillis()) {
14126 // To avoid spamming the system, we will GC processes one
14127 // at a time, waiting a few seconds between each.
14128 performAppGcLocked(proc);
14129 scheduleAppGcsLocked();
14130 return;
14131 } else {
14132 // It hasn't been long enough since we last GCed this
14133 // process... put it in the list to wait for its time.
14134 addProcessToGcListLocked(proc);
14135 break;
14136 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014137 }
14138 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014139
14140 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014141 }
14142 }
14143
14144 /**
14145 * If all looks good, perform GCs on all processes waiting for them.
14146 */
14147 final void performAppGcsIfAppropriateLocked() {
Josh Bartel7f208742010-02-25 11:01:44 -060014148 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014149 performAppGcsLocked();
14150 return;
14151 }
14152 // Still not idle, wait some more.
14153 scheduleAppGcsLocked();
14154 }
14155
14156 /**
14157 * Schedule the execution of all pending app GCs.
14158 */
14159 final void scheduleAppGcsLocked() {
14160 mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014161
14162 if (mProcessesToGc.size() > 0) {
14163 // Schedule a GC for the time to the next process.
14164 ProcessRecord proc = mProcessesToGc.get(0);
14165 Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG);
14166
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014167 long when = proc.lastRequestedGc + GC_MIN_INTERVAL;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014168 long now = SystemClock.uptimeMillis();
14169 if (when < (now+GC_TIMEOUT)) {
14170 when = now + GC_TIMEOUT;
14171 }
14172 mHandler.sendMessageAtTime(msg, when);
14173 }
14174 }
14175
14176 /**
14177 * Add a process to the array of processes waiting to be GCed. Keeps the
14178 * list in sorted order by the last GC time. The process can't already be
14179 * on the list.
14180 */
14181 final void addProcessToGcListLocked(ProcessRecord proc) {
14182 boolean added = false;
14183 for (int i=mProcessesToGc.size()-1; i>=0; i--) {
14184 if (mProcessesToGc.get(i).lastRequestedGc <
14185 proc.lastRequestedGc) {
14186 added = true;
14187 mProcessesToGc.add(i+1, proc);
14188 break;
14189 }
14190 }
14191 if (!added) {
14192 mProcessesToGc.add(0, proc);
14193 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014194 }
14195
14196 /**
14197 * Set up to ask a process to GC itself. This will either do it
14198 * immediately, or put it on the list of processes to gc the next
14199 * time things are idle.
14200 */
14201 final void scheduleAppGcLocked(ProcessRecord app) {
14202 long now = SystemClock.uptimeMillis();
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014203 if ((app.lastRequestedGc+GC_MIN_INTERVAL) > now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014204 return;
14205 }
14206 if (!mProcessesToGc.contains(app)) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014207 addProcessToGcListLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014208 scheduleAppGcsLocked();
14209 }
14210 }
14211
Dianne Hackborn287952c2010-09-22 22:34:31 -070014212 final void checkExcessivePowerUsageLocked(boolean doKills) {
14213 updateCpuStatsNow();
14214
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014215 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborn287952c2010-09-22 22:34:31 -070014216 boolean doWakeKills = doKills;
14217 boolean doCpuKills = doKills;
14218 if (mLastPowerCheckRealtime == 0) {
14219 doWakeKills = false;
14220 }
14221 if (mLastPowerCheckUptime == 0) {
14222 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014223 }
14224 if (stats.isScreenOn()) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070014225 doWakeKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014226 }
14227 final long curRealtime = SystemClock.elapsedRealtime();
Dianne Hackborn287952c2010-09-22 22:34:31 -070014228 final long realtimeSince = curRealtime - mLastPowerCheckRealtime;
14229 final long curUptime = SystemClock.uptimeMillis();
14230 final long uptimeSince = curUptime - mLastPowerCheckUptime;
14231 mLastPowerCheckRealtime = curRealtime;
14232 mLastPowerCheckUptime = curUptime;
14233 if (realtimeSince < WAKE_LOCK_MIN_CHECK_DURATION) {
14234 doWakeKills = false;
14235 }
14236 if (uptimeSince < CPU_MIN_CHECK_DURATION) {
14237 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014238 }
14239 int i = mLruProcesses.size();
14240 while (i > 0) {
14241 i--;
14242 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn287952c2010-09-22 22:34:31 -070014243 if (!app.keeping) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014244 long wtime;
14245 synchronized (stats) {
14246 wtime = stats.getProcessWakeTime(app.info.uid,
14247 app.pid, curRealtime);
14248 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070014249 long wtimeUsed = wtime - app.lastWakeTime;
14250 long cputimeUsed = app.curCpuTime - app.lastCpuTime;
14251 if (DEBUG_POWER) {
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014252 StringBuilder sb = new StringBuilder(128);
14253 sb.append("Wake for ");
14254 app.toShortString(sb);
14255 sb.append(": over ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070014256 TimeUtils.formatDuration(realtimeSince, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014257 sb.append(" used ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070014258 TimeUtils.formatDuration(wtimeUsed, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014259 sb.append(" (");
Dianne Hackborn287952c2010-09-22 22:34:31 -070014260 sb.append((wtimeUsed*100)/realtimeSince);
14261 sb.append("%)");
14262 Slog.i(TAG, sb.toString());
14263 sb.setLength(0);
14264 sb.append("CPU for ");
14265 app.toShortString(sb);
14266 sb.append(": over ");
14267 TimeUtils.formatDuration(uptimeSince, sb);
14268 sb.append(" used ");
14269 TimeUtils.formatDuration(cputimeUsed, sb);
14270 sb.append(" (");
14271 sb.append((cputimeUsed*100)/uptimeSince);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014272 sb.append("%)");
14273 Slog.i(TAG, sb.toString());
14274 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014275 // If a process has held a wake lock for more
14276 // than 50% of the time during this period,
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014277 // that sounds bad. Kill!
Dianne Hackborn287952c2010-09-22 22:34:31 -070014278 if (doWakeKills && realtimeSince > 0
14279 && ((wtimeUsed*100)/realtimeSince) >= 50) {
14280 synchronized (stats) {
14281 stats.reportExcessiveWakeLocked(app.info.uid, app.processName,
14282 realtimeSince, wtimeUsed);
14283 }
14284 Slog.w(TAG, "Excessive wake lock in " + app.processName
14285 + " (pid " + app.pid + "): held " + wtimeUsed
14286 + " during " + realtimeSince);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014287 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14288 app.processName, app.setAdj, "excessive wake lock");
14289 Process.killProcessQuiet(app.pid);
Dianne Hackborn287952c2010-09-22 22:34:31 -070014290 } else if (doCpuKills && uptimeSince > 0
14291 && ((cputimeUsed*100)/uptimeSince) >= 50) {
14292 synchronized (stats) {
14293 stats.reportExcessiveCpuLocked(app.info.uid, app.processName,
14294 uptimeSince, cputimeUsed);
14295 }
14296 Slog.w(TAG, "Excessive CPU in " + app.processName
14297 + " (pid " + app.pid + "): used " + cputimeUsed
14298 + " during " + uptimeSince);
14299 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14300 app.processName, app.setAdj, "excessive cpu");
14301 Process.killProcessQuiet(app.pid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014302 } else {
14303 app.lastWakeTime = wtime;
Dianne Hackborn287952c2010-09-22 22:34:31 -070014304 app.lastCpuTime = app.curCpuTime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014305 }
14306 }
14307 }
14308 }
14309
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014310 private final boolean updateOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014311 ProcessRecord app, int hiddenAdj, ProcessRecord TOP_APP, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014312 app.hiddenAdj = hiddenAdj;
14313
14314 if (app.thread == null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014315 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014316 }
14317
Dianne Hackborn287952c2010-09-22 22:34:31 -070014318 final boolean wasKeeping = app.keeping;
14319
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014320 boolean success = true;
14321
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014322 computeOomAdjLocked(app, hiddenAdj, TOP_APP, false, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014323
Jeff Brown10e89712011-07-08 18:52:57 -070014324 if (app.curRawAdj != app.setRawAdj) {
Jeff Brown10e89712011-07-08 18:52:57 -070014325 if (wasKeeping && !app.keeping) {
14326 // This app is no longer something we want to keep. Note
14327 // its current wake lock time to later know to kill it if
14328 // it is not behaving well.
14329 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
14330 synchronized (stats) {
14331 app.lastWakeTime = stats.getProcessWakeTime(app.info.uid,
14332 app.pid, SystemClock.elapsedRealtime());
14333 }
14334 app.lastCpuTime = app.curCpuTime;
14335 }
14336
14337 app.setRawAdj = app.curRawAdj;
14338 }
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014339
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014340 if (app.curAdj != app.setAdj) {
14341 if (Process.setOomAdj(app.pid, app.curAdj)) {
Dianne Hackbornbbb09ac2011-11-30 11:31:29 -080014342 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014343 TAG, "Set " + app.pid + " " + app.processName +
14344 " adj " + app.curAdj + ": " + app.adjType);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014345 app.setAdj = app.curAdj;
Jeff Brown10e89712011-07-08 18:52:57 -070014346 } else {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014347 success = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014348 Slog.w(TAG, "Failed setting oom adj of " + app + " to " + app.curAdj);
Jeff Brown10e89712011-07-08 18:52:57 -070014349 }
14350 }
14351 if (app.setSchedGroup != app.curSchedGroup) {
14352 app.setSchedGroup = app.curSchedGroup;
14353 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
14354 "Setting process group of " + app.processName
14355 + " to " + app.curSchedGroup);
14356 if (app.waitingToKill != null &&
14357 app.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
14358 Slog.i(TAG, "Killing " + app.toShortString() + ": " + app.waitingToKill);
14359 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14360 app.processName, app.setAdj, app.waitingToKill);
14361 Process.killProcessQuiet(app.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014362 success = false;
Jeff Brown10e89712011-07-08 18:52:57 -070014363 } else {
14364 if (true) {
14365 long oldId = Binder.clearCallingIdentity();
14366 try {
14367 Process.setProcessGroup(app.pid, app.curSchedGroup);
14368 } catch (Exception e) {
14369 Slog.w(TAG, "Failed setting process group of " + app.pid
14370 + " to " + app.curSchedGroup);
14371 e.printStackTrace();
14372 } finally {
14373 Binder.restoreCallingIdentity(oldId);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014374 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014375 } else {
Jeff Brown10e89712011-07-08 18:52:57 -070014376 if (app.thread != null) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070014377 try {
Jeff Brown10e89712011-07-08 18:52:57 -070014378 app.thread.setSchedulingGroup(app.curSchedGroup);
14379 } catch (RemoteException e) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070014380 }
14381 }
14382 }
14383 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014384 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014385 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014386 }
14387
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014388 private final ActivityRecord resumedAppLocked() {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014389 ActivityRecord resumedActivity = mMainStack.mResumedActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014390 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -080014391 resumedActivity = mMainStack.mPausingActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014392 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014393 resumedActivity = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014394 }
14395 }
14396 return resumedActivity;
14397 }
14398
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014399 private final boolean updateOomAdjLocked(ProcessRecord app) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014400 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014401 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
14402 int curAdj = app.curAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070014403 final boolean wasHidden = curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
14404 && curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014405
14406 mAdjSeq++;
14407
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014408 boolean success = updateOomAdjLocked(app, app.hiddenAdj, TOP_APP, false);
Dianne Hackborn7d608422011-08-07 16:24:18 -070014409 final boolean nowHidden = app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
14410 && app.curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014411 if (nowHidden != wasHidden) {
14412 // Changed to/from hidden state, so apps after it in the LRU
14413 // list may also be changed.
14414 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014415 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014416 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014417 }
14418
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014419 final void updateOomAdjLocked() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014420 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014421 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
14422
14423 if (false) {
14424 RuntimeException e = new RuntimeException();
14425 e.fillInStackTrace();
Joe Onorato8a9b2202010-02-26 18:56:32 -080014426 Slog.i(TAG, "updateOomAdj: top=" + TOP_ACT, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014427 }
14428
14429 mAdjSeq++;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014430 mNewNumServiceProcs = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014431
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014432 // Let's determine how many processes we have running vs.
14433 // how many slots we have for background processes; we may want
14434 // to put multiple processes in a slot of there are enough of
14435 // them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014436 int numSlots = ProcessList.HIDDEN_APP_MAX_ADJ - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014437 int factor = (mLruProcesses.size()-4)/numSlots;
14438 if (factor < 1) factor = 1;
14439 int step = 0;
Dianne Hackborn8633e682010-04-22 16:03:41 -070014440 int numHidden = 0;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014441 int numTrimming = 0;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014442
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014443 // First update the OOM adjustment for each of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014444 // application processes based on their current state.
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014445 int i = mLruProcesses.size();
Dianne Hackborn7d608422011-08-07 16:24:18 -070014446 int curHiddenAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014447 while (i > 0) {
14448 i--;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014449 ProcessRecord app = mLruProcesses.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080014450 //Slog.i(TAG, "OOM " + app + ": cur hidden=" + curHiddenAdj);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014451 updateOomAdjLocked(app, curHiddenAdj, TOP_APP, true);
14452 if (curHiddenAdj < ProcessList.HIDDEN_APP_MAX_ADJ
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014453 && app.curAdj == curHiddenAdj) {
14454 step++;
14455 if (step >= factor) {
14456 step = 0;
14457 curHiddenAdj++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014458 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014459 }
14460 if (!app.killedBackground) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070014461 if (app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014462 numHidden++;
14463 if (numHidden > mProcessLimit) {
14464 Slog.i(TAG, "No longer want " + app.processName
14465 + " (pid " + app.pid + "): hidden #" + numHidden);
14466 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14467 app.processName, app.setAdj, "too many background");
14468 app.killedBackground = true;
14469 Process.killProcessQuiet(app.pid);
Dianne Hackborn8633e682010-04-22 16:03:41 -070014470 }
14471 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -080014472 if (!app.killedBackground && app.isolated && app.services.size() <= 0) {
14473 // If this is an isolated process, and there are no
14474 // services running in it, then the process is no longer
14475 // needed. We agressively kill these because we can by
14476 // definition not re-use the same process again, and it is
14477 // good to avoid having whatever code was running in them
14478 // left sitting around after no longer needed.
14479 Slog.i(TAG, "Isolated process " + app.processName
14480 + " (pid " + app.pid + ") no longer needed");
14481 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14482 app.processName, app.setAdj, "isolated not needed");
14483 app.killedBackground = true;
14484 Process.killProcessQuiet(app.pid);
14485 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014486 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
14487 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
14488 && !app.killedBackground) {
14489 numTrimming++;
14490 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014491 }
14492 }
14493
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014494 mNumServiceProcs = mNewNumServiceProcs;
14495
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014496 // Now determine the memory trimming level of background processes.
14497 // Unfortunately we need to start at the back of the list to do this
14498 // properly. We only do this if the number of background apps we
14499 // are managing to keep around is less than half the maximum we desire;
14500 // if we are keeping a good number around, we'll let them use whatever
14501 // memory they want.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014502 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/2)) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014503 final int N = mLruProcesses.size();
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014504 factor = numTrimming/3;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080014505 int minFactor = 2;
14506 if (mHomeProcess != null) minFactor++;
14507 if (mPreviousProcess != null) minFactor++;
14508 if (factor < minFactor) factor = minFactor;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014509 step = 0;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014510 int fgTrimLevel;
14511 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/5)) {
14512 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL;
14513 } else if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/3)) {
14514 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW;
14515 } else {
14516 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE;
14517 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014518 int curLevel = ComponentCallbacks2.TRIM_MEMORY_COMPLETE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014519 for (i=0; i<N; i++) {
14520 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014521 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
14522 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080014523 && !app.killedBackground) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014524 if (app.trimMemoryLevel < curLevel && app.thread != null) {
14525 try {
14526 app.thread.scheduleTrimMemory(curLevel);
14527 } catch (RemoteException e) {
14528 }
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080014529 if (false) {
14530 // For now we won't do this; our memory trimming seems
14531 // to be good enough at this point that destroying
14532 // activities causes more harm than good.
14533 if (curLevel >= ComponentCallbacks2.TRIM_MEMORY_COMPLETE
14534 && app != mHomeProcess && app != mPreviousProcess) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070014535 // Need to do this on its own message because the stack may not
14536 // be in a consistent state at this point.
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080014537 // For these apps we will also finish their activities
14538 // to help them free memory.
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070014539 mMainStack.scheduleDestroyActivities(app, false, "trim");
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080014540 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014541 }
14542 }
14543 app.trimMemoryLevel = curLevel;
14544 step++;
14545 if (step >= factor) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014546 step = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014547 switch (curLevel) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014548 case ComponentCallbacks2.TRIM_MEMORY_COMPLETE:
14549 curLevel = ComponentCallbacks2.TRIM_MEMORY_MODERATE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014550 break;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014551 case ComponentCallbacks2.TRIM_MEMORY_MODERATE:
14552 curLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014553 break;
14554 }
14555 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014556 } else if (app.nonStoppingAdj == ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014557 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014558 && app.thread != null) {
14559 try {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014560 app.thread.scheduleTrimMemory(
14561 ComponentCallbacks2.TRIM_MEMORY_BACKGROUND);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014562 } catch (RemoteException e) {
14563 }
14564 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014565 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014566 } else {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014567 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014568 && app.pendingUiClean) {
14569 // If this application is now in the background and it
14570 // had done UI, then give it the special trim level to
14571 // have it free UI resources.
14572 final int level = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
14573 if (app.trimMemoryLevel < level && app.thread != null) {
14574 try {
14575 app.thread.scheduleTrimMemory(level);
14576 } catch (RemoteException e) {
14577 }
14578 }
14579 app.pendingUiClean = false;
14580 }
14581 if (app.trimMemoryLevel < fgTrimLevel && app.thread != null) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014582 try {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014583 app.thread.scheduleTrimMemory(fgTrimLevel);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014584 } catch (RemoteException e) {
14585 }
14586 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014587 app.trimMemoryLevel = fgTrimLevel;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014588 }
14589 }
14590 } else {
14591 final int N = mLruProcesses.size();
14592 for (i=0; i<N; i++) {
14593 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014594 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014595 && app.pendingUiClean) {
14596 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
14597 && app.thread != null) {
14598 try {
14599 app.thread.scheduleTrimMemory(
14600 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
14601 } catch (RemoteException e) {
14602 }
14603 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014604 app.pendingUiClean = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014605 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014606 app.trimMemoryLevel = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014607 }
14608 }
14609
14610 if (mAlwaysFinishActivities) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070014611 // Need to do this on its own message because the stack may not
14612 // be in a consistent state at this point.
14613 mMainStack.scheduleDestroyActivities(null, false, "always-finish");
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014614 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014615 }
14616
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014617 final void trimApplications() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014618 synchronized (this) {
14619 int i;
14620
14621 // First remove any unused application processes whose package
14622 // has been removed.
14623 for (i=mRemovedProcesses.size()-1; i>=0; i--) {
14624 final ProcessRecord app = mRemovedProcesses.get(i);
14625 if (app.activities.size() == 0
14626 && app.curReceiver == null && app.services.size() == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080014627 Slog.i(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014628 TAG, "Exiting empty application process "
14629 + app.processName + " ("
14630 + (app.thread != null ? app.thread.asBinder() : null)
14631 + ")\n");
14632 if (app.pid > 0 && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070014633 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14634 app.processName, app.setAdj, "empty");
14635 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014636 } else {
14637 try {
14638 app.thread.scheduleExit();
14639 } catch (Exception e) {
14640 // Ignore exceptions.
14641 }
14642 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070014643 cleanUpApplicationRecordLocked(app, false, true, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014644 mRemovedProcesses.remove(i);
14645
14646 if (app.persistent) {
14647 if (app.persistent) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080014648 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014649 }
14650 }
14651 }
14652 }
14653
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014654 // Now update the oom adj for all processes.
14655 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014656 }
14657 }
14658
14659 /** This method sends the specified signal to each of the persistent apps */
14660 public void signalPersistentProcesses(int sig) throws RemoteException {
14661 if (sig != Process.SIGNAL_USR1) {
14662 throw new SecurityException("Only SIGNAL_USR1 is allowed");
14663 }
14664
14665 synchronized (this) {
14666 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
14667 != PackageManager.PERMISSION_GRANTED) {
14668 throw new SecurityException("Requires permission "
14669 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
14670 }
14671
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014672 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
14673 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014674 if (r.thread != null && r.persistent) {
14675 Process.sendSignal(r.pid, sig);
14676 }
14677 }
14678 }
14679 }
14680
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014681 private void stopProfilerLocked(ProcessRecord proc, String path, int profileType) {
14682 if (proc == null || proc == mProfileProc) {
14683 proc = mProfileProc;
14684 path = mProfileFile;
14685 profileType = mProfileType;
14686 clearProfilerLocked();
14687 }
14688 if (proc == null) {
14689 return;
14690 }
14691 try {
14692 proc.thread.profilerControl(false, path, null, profileType);
14693 } catch (RemoteException e) {
14694 throw new IllegalStateException("Process disappeared");
14695 }
14696 }
14697
14698 private void clearProfilerLocked() {
14699 if (mProfileFd != null) {
14700 try {
14701 mProfileFd.close();
14702 } catch (IOException e) {
14703 }
14704 }
14705 mProfileApp = null;
14706 mProfileProc = null;
14707 mProfileFile = null;
14708 mProfileType = 0;
14709 mAutoStopProfiler = false;
14710 }
14711
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014712 public boolean profileControl(String process, boolean start,
Romain Guy7eabe552011-07-21 14:56:34 -070014713 String path, ParcelFileDescriptor fd, int profileType) throws RemoteException {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014714
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014715 try {
14716 synchronized (this) {
14717 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14718 // its own permission.
14719 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14720 != PackageManager.PERMISSION_GRANTED) {
14721 throw new SecurityException("Requires permission "
14722 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014723 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014724
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014725 if (start && fd == null) {
14726 throw new IllegalArgumentException("null fd");
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014727 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014728
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014729 ProcessRecord proc = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014730 if (process != null) {
14731 try {
14732 int pid = Integer.parseInt(process);
14733 synchronized (mPidsSelfLocked) {
14734 proc = mPidsSelfLocked.get(pid);
14735 }
14736 } catch (NumberFormatException e) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014737 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014738
14739 if (proc == null) {
14740 HashMap<String, SparseArray<ProcessRecord>> all
14741 = mProcessNames.getMap();
14742 SparseArray<ProcessRecord> procs = all.get(process);
14743 if (procs != null && procs.size() > 0) {
14744 proc = procs.valueAt(0);
14745 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014746 }
14747 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014748
14749 if (start && (proc == null || proc.thread == null)) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014750 throw new IllegalArgumentException("Unknown process: " + process);
14751 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014752
14753 if (start) {
14754 stopProfilerLocked(null, null, 0);
14755 setProfileApp(proc.info, proc.processName, path, fd, false);
14756 mProfileProc = proc;
14757 mProfileType = profileType;
14758 try {
14759 fd = fd.dup();
14760 } catch (IOException e) {
14761 fd = null;
14762 }
14763 proc.thread.profilerControl(start, path, fd, profileType);
14764 fd = null;
14765 mProfileFd = null;
14766 } else {
14767 stopProfilerLocked(proc, path, profileType);
14768 if (fd != null) {
14769 try {
14770 fd.close();
14771 } catch (IOException e) {
14772 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014773 }
14774 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014775
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014776 return true;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014777 }
14778 } catch (RemoteException e) {
14779 throw new IllegalStateException("Process disappeared");
14780 } finally {
14781 if (fd != null) {
14782 try {
14783 fd.close();
14784 } catch (IOException e) {
14785 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014786 }
14787 }
14788 }
Andy McFadden824c5102010-07-09 16:26:57 -070014789
14790 public boolean dumpHeap(String process, boolean managed,
14791 String path, ParcelFileDescriptor fd) throws RemoteException {
14792
14793 try {
14794 synchronized (this) {
14795 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14796 // its own permission (same as profileControl).
14797 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14798 != PackageManager.PERMISSION_GRANTED) {
14799 throw new SecurityException("Requires permission "
14800 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
14801 }
14802
14803 if (fd == null) {
14804 throw new IllegalArgumentException("null fd");
14805 }
14806
14807 ProcessRecord proc = null;
14808 try {
14809 int pid = Integer.parseInt(process);
14810 synchronized (mPidsSelfLocked) {
14811 proc = mPidsSelfLocked.get(pid);
14812 }
14813 } catch (NumberFormatException e) {
14814 }
14815
14816 if (proc == null) {
14817 HashMap<String, SparseArray<ProcessRecord>> all
14818 = mProcessNames.getMap();
14819 SparseArray<ProcessRecord> procs = all.get(process);
14820 if (procs != null && procs.size() > 0) {
14821 proc = procs.valueAt(0);
14822 }
14823 }
14824
14825 if (proc == null || proc.thread == null) {
14826 throw new IllegalArgumentException("Unknown process: " + process);
14827 }
14828
Dianne Hackbornf02e57b2011-03-01 22:21:04 -080014829 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
14830 if (!isDebuggable) {
Andy McFadden824c5102010-07-09 16:26:57 -070014831 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
14832 throw new SecurityException("Process not debuggable: " + proc);
14833 }
14834 }
14835
14836 proc.thread.dumpHeap(managed, path, fd);
14837 fd = null;
14838 return true;
14839 }
14840 } catch (RemoteException e) {
14841 throw new IllegalStateException("Process disappeared");
14842 } finally {
14843 if (fd != null) {
14844 try {
14845 fd.close();
14846 } catch (IOException e) {
14847 }
14848 }
14849 }
14850 }
14851
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014852 /** In this method we try to acquire our lock to make sure that we have not deadlocked */
14853 public void monitor() {
14854 synchronized (this) { }
14855 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014856
Dianne Hackborna573f6a2012-02-09 16:12:18 -080014857 void onCoreSettingsChange(Bundle settings) {
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014858 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
14859 ProcessRecord processRecord = mLruProcesses.get(i);
14860 try {
14861 if (processRecord.thread != null) {
14862 processRecord.thread.setCoreSettings(settings);
14863 }
14864 } catch (RemoteException re) {
14865 /* ignore */
14866 }
14867 }
14868 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014869
14870 // Multi-user methods
14871
Amith Yamasani742a6712011-05-04 14:49:28 -070014872 private int mCurrentUserId;
14873 private SparseIntArray mLoggedInUsers = new SparseIntArray(5);
14874
14875 public boolean switchUser(int userId) {
14876 final int callingUid = Binder.getCallingUid();
14877 if (callingUid != 0 && callingUid != Process.myUid()) {
14878 Slog.e(TAG, "Trying to switch user from unauthorized app");
14879 return false;
14880 }
14881 if (mCurrentUserId == userId)
14882 return true;
14883
14884 synchronized (this) {
14885 // Check if user is already logged in, otherwise check if user exists first before
14886 // adding to the list of logged in users.
14887 if (mLoggedInUsers.indexOfKey(userId) < 0) {
14888 if (!userExists(userId)) {
14889 return false;
14890 }
14891 mLoggedInUsers.append(userId, userId);
14892 }
14893
14894 mCurrentUserId = userId;
14895 boolean haveActivities = mMainStack.switchUser(userId);
14896 if (!haveActivities) {
14897 startHomeActivityLocked(userId);
14898 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014899
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014900 }
Amith Yamasani13593602012-03-22 16:16:17 -070014901
14902 // Inform of user switch
14903 Intent addedIntent = new Intent(Intent.ACTION_USER_SWITCHED);
14904 addedIntent.putExtra(Intent.EXTRA_USERID, userId);
14905 mContext.sendBroadcast(addedIntent, android.Manifest.permission.MANAGE_ACCOUNTS);
14906
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014907 return true;
14908 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014909
Amith Yamasani52f1d752012-03-28 18:19:29 -070014910 @Override
14911 public UserInfo getCurrentUser() throws RemoteException {
14912 final int callingUid = Binder.getCallingUid();
14913 if (callingUid != 0 && callingUid != Process.myUid()) {
14914 Slog.e(TAG, "Trying to get user from unauthorized app");
14915 return null;
14916 }
14917 return AppGlobals.getPackageManager().getUser(mCurrentUserId);
14918 }
14919
Amith Yamasani13593602012-03-22 16:16:17 -070014920 private void onUserRemoved(Intent intent) {
14921 int extraUserId = intent.getIntExtra(Intent.EXTRA_USERID, -1);
14922 if (extraUserId < 1) return;
14923
14924 // Kill all the processes for the user
14925 ArrayList<Pair<String, Integer>> pkgAndUids = new ArrayList<Pair<String,Integer>>();
14926 synchronized (this) {
14927 HashMap<String,SparseArray<ProcessRecord>> map = mProcessNames.getMap();
14928 for (Entry<String, SparseArray<ProcessRecord>> uidMap : map.entrySet()) {
14929 SparseArray<ProcessRecord> uids = uidMap.getValue();
14930 for (int i = 0; i < uids.size(); i++) {
14931 if (UserId.getUserId(uids.keyAt(i)) == extraUserId) {
14932 pkgAndUids.add(new Pair<String,Integer>(uidMap.getKey(), uids.keyAt(i)));
14933 }
14934 }
14935 }
14936
14937 for (Pair<String,Integer> pkgAndUid : pkgAndUids) {
14938 forceStopPackageLocked(pkgAndUid.first, pkgAndUid.second,
14939 false, false, true, true, extraUserId);
14940 }
14941 }
14942 }
14943
Amith Yamasani742a6712011-05-04 14:49:28 -070014944 private boolean userExists(int userId) {
14945 try {
Amith Yamasani13593602012-03-22 16:16:17 -070014946 UserInfo user = AppGlobals.getPackageManager().getUser(userId);
14947 return user != null;
Amith Yamasani742a6712011-05-04 14:49:28 -070014948 } catch (RemoteException re) {
14949 // Won't happen, in same process
14950 }
14951
14952 return false;
14953 }
14954
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014955 private void checkValidCaller(int uid, int userId) {
14956 if (UserId.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) return;
14957
14958 throw new SecurityException("Caller uid=" + uid
14959 + " is not privileged to communicate with user=" + userId);
14960 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014961
14962 private int applyUserId(int uid, int userId) {
14963 return UserId.getUid(userId, uid);
14964 }
14965
14966 private ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080014967 if (info == null) return null;
Amith Yamasani742a6712011-05-04 14:49:28 -070014968 ApplicationInfo newInfo = new ApplicationInfo(info);
14969 newInfo.uid = applyUserId(info.uid, userId);
Amith Yamasania4a54e22012-04-16 15:44:19 -070014970 newInfo.dataDir = USER_DATA_DIR + userId + "/"
14971 + info.packageName;
Amith Yamasani742a6712011-05-04 14:49:28 -070014972 return newInfo;
14973 }
14974
14975 ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) {
Amith Yamasania4a54e22012-04-16 15:44:19 -070014976 if (aInfo == null
14977 || (userId < 1 && aInfo.applicationInfo.uid < UserId.PER_USER_RANGE)) {
Amith Yamasani742a6712011-05-04 14:49:28 -070014978 return aInfo;
14979 }
14980
14981 ActivityInfo info = new ActivityInfo(aInfo);
14982 info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId);
14983 return info;
14984 }
14985
14986 static class ServiceMap {
14987
14988 private final SparseArray<HashMap<ComponentName, ServiceRecord>> mServicesByNamePerUser
14989 = new SparseArray<HashMap<ComponentName, ServiceRecord>>();
14990 private final SparseArray<HashMap<Intent.FilterComparison, ServiceRecord>>
14991 mServicesByIntentPerUser = new SparseArray<
14992 HashMap<Intent.FilterComparison, ServiceRecord>>();
14993
14994 ServiceRecord getServiceByName(ComponentName name, int callingUser) {
14995 // TODO: Deal with global services
14996 if (DEBUG_MU)
14997 Slog.v(TAG_MU, "getServiceByName(" + name + "), callingUser = " + callingUser);
14998 return getServices(callingUser).get(name);
14999 }
15000
15001 ServiceRecord getServiceByName(ComponentName name) {
15002 return getServiceByName(name, -1);
15003 }
15004
15005 ServiceRecord getServiceByIntent(Intent.FilterComparison filter, int callingUser) {
15006 // TODO: Deal with global services
15007 if (DEBUG_MU)
15008 Slog.v(TAG_MU, "getServiceByIntent(" + filter + "), callingUser = " + callingUser);
15009 return getServicesByIntent(callingUser).get(filter);
15010 }
15011
15012 ServiceRecord getServiceByIntent(Intent.FilterComparison filter) {
15013 return getServiceByIntent(filter, -1);
15014 }
15015
15016 void putServiceByName(ComponentName name, int callingUser, ServiceRecord value) {
15017 // TODO: Deal with global services
15018 getServices(callingUser).put(name, value);
15019 }
15020
15021 void putServiceByIntent(Intent.FilterComparison filter, int callingUser,
15022 ServiceRecord value) {
15023 // TODO: Deal with global services
15024 getServicesByIntent(callingUser).put(filter, value);
15025 }
15026
15027 void removeServiceByName(ComponentName name, int callingUser) {
15028 // TODO: Deal with global services
15029 ServiceRecord removed = getServices(callingUser).remove(name);
15030 if (DEBUG_MU)
15031 Slog.v(TAG, "removeServiceByName user=" + callingUser + " name=" + name
15032 + " removed=" + removed);
15033 }
15034
15035 void removeServiceByIntent(Intent.FilterComparison filter, int callingUser) {
15036 // TODO: Deal with global services
15037 ServiceRecord removed = getServicesByIntent(callingUser).remove(filter);
15038 if (DEBUG_MU)
15039 Slog.v(TAG_MU, "removeServiceByIntent user=" + callingUser + " intent=" + filter
15040 + " removed=" + removed);
15041 }
15042
15043 Collection<ServiceRecord> getAllServices(int callingUser) {
15044 // TODO: Deal with global services
15045 return getServices(callingUser).values();
15046 }
15047
15048 private HashMap<ComponentName, ServiceRecord> getServices(int callingUser) {
15049 HashMap map = mServicesByNamePerUser.get(callingUser);
15050 if (map == null) {
15051 map = new HashMap<ComponentName, ServiceRecord>();
15052 mServicesByNamePerUser.put(callingUser, map);
15053 }
15054 return map;
15055 }
15056
15057 private HashMap<Intent.FilterComparison, ServiceRecord> getServicesByIntent(
15058 int callingUser) {
15059 HashMap map = mServicesByIntentPerUser.get(callingUser);
15060 if (map == null) {
15061 map = new HashMap<Intent.FilterComparison, ServiceRecord>();
15062 mServicesByIntentPerUser.put(callingUser, map);
15063 }
15064 return map;
15065 }
15066 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015067}